context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Telerik.JustMock.Core.Castle.Core.Logging;
using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;
using Telerik.JustMock.Core.Castle.DynamicProxy.Internal;
internal abstract class MembersCollector
{
private const BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
private ILogger logger = NullLogger.Instance;
private ICollection<MethodInfo> checkedMethods = new HashSet<MethodInfo>();
private readonly IDictionary<PropertyInfo, MetaProperty> properties = new Dictionary<PropertyInfo, MetaProperty>();
private readonly IDictionary<EventInfo, MetaEvent> events = new Dictionary<EventInfo, MetaEvent>();
private readonly IDictionary<MethodInfo, MetaMethod> methods = new Dictionary<MethodInfo, MetaMethod>();
protected readonly Type type;
protected MembersCollector(Type type)
{
this.type = type;
}
public ILogger Logger
{
get { return logger; }
set { logger = value; }
}
public IEnumerable<MetaMethod> Methods
{
get { return methods.Values; }
}
public IEnumerable<MetaProperty> Properties
{
get { return properties.Values; }
}
public IEnumerable<MetaEvent> Events
{
get { return events.Values; }
}
public virtual void CollectMembersToProxy(IProxyGenerationHook hook)
{
if (checkedMethods == null) // this method was already called!
{
throw new InvalidOperationException(
string.Format("Can't call 'CollectMembersToProxy' method twice. This usually signifies a bug in custom {0}.",
typeof(ITypeContributor)));
}
CollectProperties(hook);
CollectEvents(hook);
// Methods go last, because properties and events have methods too (getters/setters add/remove)
// and we don't want to get duplicates, so we collect property and event methods first
// then we collect methods, and add only these that aren't there yet
CollectMethods(hook);
checkedMethods = null; // this is ugly, should have a boolean flag for this or something
}
private void CollectProperties(IProxyGenerationHook hook)
{
var propertiesFound = type.GetProperties(Flags);
foreach (var property in propertiesFound)
{
AddProperty(property, hook);
}
}
private void CollectEvents(IProxyGenerationHook hook)
{
var eventsFound = type.GetEvents(Flags);
foreach (var @event in eventsFound)
{
AddEvent(@event, hook);
}
}
private void CollectMethods(IProxyGenerationHook hook)
{
var methodsFound = MethodFinder.GetAllInstanceMethods(type, Flags);
foreach (var method in methodsFound)
{
AddMethod(method, hook, true);
}
}
private void AddProperty(PropertyInfo property, IProxyGenerationHook hook)
{
MetaMethod getter = null;
MetaMethod setter = null;
if (property.CanRead)
{
var getMethod = property.GetGetMethod(true);
getter = AddMethod(getMethod, hook, false);
}
if (property.CanWrite)
{
var setMethod = property.GetSetMethod(true);
setter = AddMethod(setMethod, hook, false);
}
if (setter == null && getter == null)
{
return;
}
var nonInheritableAttributes = property.GetNonInheritableAttributes();
var arguments = property.GetIndexParameters();
properties[property] = new MetaProperty(property.Name,
property.PropertyType,
property.DeclaringType,
getter,
setter,
nonInheritableAttributes.Select(a => a.Builder),
arguments.Select(a => a.ParameterType).ToArray());
}
private void AddEvent(EventInfo @event, IProxyGenerationHook hook)
{
var addMethod = @event.GetAddMethod(true);
var removeMethod = @event.GetRemoveMethod(true);
MetaMethod adder = null;
MetaMethod remover = null;
if (addMethod != null)
{
adder = AddMethod(addMethod, hook, false);
}
if (removeMethod != null)
{
remover = AddMethod(removeMethod, hook, false);
}
if (adder == null && remover == null)
{
return;
}
events[@event] = new MetaEvent(@event.Name,
@event.DeclaringType, @event.EventHandlerType, adder, remover, EventAttributes.None);
}
private MetaMethod AddMethod(MethodInfo method, IProxyGenerationHook hook, bool isStandalone)
{
if (checkedMethods.Contains(method))
{
return null;
}
checkedMethods.Add(method);
if (methods.ContainsKey(method))
{
return null;
}
var methodToGenerate = GetMethodToGenerate(method, hook, isStandalone);
if (methodToGenerate != null)
{
methods[method] = methodToGenerate;
}
return methodToGenerate;
}
protected abstract MetaMethod GetMethodToGenerate(MethodInfo method, IProxyGenerationHook hook, bool isStandalone);
/// <summary>
/// Performs some basic screening and invokes the <see cref = "IProxyGenerationHook" />
/// to select methods.
/// </summary>
/// <param name = "method"></param>
/// <param name = "onlyVirtuals"></param>
/// <param name = "hook"></param>
/// <returns></returns>
protected bool AcceptMethod(MethodInfo method, bool onlyVirtuals, IProxyGenerationHook hook)
{
if (IsInternalAndNotVisibleToDynamicProxy(method))
{
return false;
}
var isOverridable = method.IsVirtual && !method.IsFinal;
if (onlyVirtuals && !isOverridable)
{
if (
#if FEATURE_REMOTING
method.DeclaringType != typeof(MarshalByRefObject) &&
#endif
method.IsGetType() == false &&
method.IsMemberwiseClone() == false)
{
Logger.DebugFormat("Excluded non-overridable method {0} on {1} because it cannot be intercepted.", method.Name,
method.DeclaringType.FullName);
hook.NonProxyableMemberNotification(type, method);
}
return false;
}
// we can never intercept a sealed (final) method
if (method.IsFinal)
{
Logger.DebugFormat("Excluded sealed method {0} on {1} because it cannot be intercepted.", method.Name,
method.DeclaringType.FullName);
return false;
}
//can only proxy methods that are public or protected (or internals that have already been checked above)
if ((method.IsPublic || method.IsFamily || method.IsAssembly || method.IsFamilyOrAssembly) == false)
{
return false;
}
#if FEATURE_REMOTING
if (method.DeclaringType == typeof(MarshalByRefObject))
{
return false;
}
#endif
if (method.IsFinalizer())
{
return false;
}
return hook.ShouldInterceptMethod(type, method);
}
private static bool IsInternalAndNotVisibleToDynamicProxy(MethodInfo method)
{
return ProxyUtil.IsInternal(method) &&
ProxyUtil.AreInternalsVisibleToDynamicProxy(method.DeclaringType.GetTypeInfo().Assembly) == false;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.Extensions.DependencyInjection;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.ResourceDefinitions.Reading
{
public sealed class ResourceDefinitionReadTests : IClassFixture<IntegrationTestContext<TestableStartup<UniverseDbContext>, UniverseDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<UniverseDbContext>, UniverseDbContext> _testContext;
private readonly UniverseFakers _fakers = new();
public ResourceDefinitionReadTests(IntegrationTestContext<TestableStartup<UniverseDbContext>, UniverseDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<StarsController>();
testContext.UseController<PlanetsController>();
testContext.UseController<MoonsController>();
testContext.ConfigureServicesAfterStartup(services =>
{
services.AddResourceDefinition<StarDefinition>();
services.AddResourceDefinition<PlanetDefinition>();
services.AddResourceDefinition<MoonDefinition>();
services.AddSingleton<IClientSettingsProvider, TestClientSettingsProvider>();
services.AddSingleton<ResourceDefinitionHitCounter>();
});
var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.IncludeTotalResourceCount = true;
var settingsProvider = (TestClientSettingsProvider)testContext.Factory.Services.GetRequiredService<IClientSettingsProvider>();
settingsProvider.ResetToDefaults();
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
hitCounter.Reset();
}
[Fact]
public async Task Include_from_resource_definition_is_blocked()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var settingsProvider = (TestClientSettingsProvider)_testContext.Factory.Services.GetRequiredService<IClientSettingsProvider>();
settingsProvider.BlockIncludePlanetMoons();
Planet planet = _fakers.Planet.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Planet>();
dbContext.Planets.Add(planet);
await dbContext.SaveChangesAsync();
});
const string route = "/planets?include=moons";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
error.Title.Should().Be("Including moons is not permitted.");
error.Detail.Should().BeNull();
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Planet), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyFilter),
(typeof(Planet), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyFilter),
(typeof(Planet), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyIncludes)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Include_from_resource_definition_is_added()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var settingsProvider = (TestClientSettingsProvider)_testContext.Factory.Services.GetRequiredService<IClientSettingsProvider>();
settingsProvider.AutoIncludeOrbitingPlanetForMoons();
Moon moon = _fakers.Moon.Generate();
moon.OrbitsAround = _fakers.Planet.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Moons.Add(moon);
await dbContext.SaveChangesAsync();
});
string route = $"/moons/{moon.StringId}";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.SingleValue.Should().NotBeNull();
responseDocument.Data.SingleValue.Relationships["orbitsAround"].Data.SingleValue.Type.Should().Be("planets");
responseDocument.Data.SingleValue.Relationships["orbitsAround"].Data.SingleValue.Id.Should().Be(moon.OrbitsAround.StringId);
responseDocument.Included.Should().HaveCount(1);
responseDocument.Included[0].Type.Should().Be("planets");
responseDocument.Included[0].Id.Should().Be(moon.OrbitsAround.StringId);
responseDocument.Included[0].Attributes["publicName"].Should().Be(moon.OrbitsAround.PublicName);
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Moon), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyIncludes)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Filter_from_resource_definition_is_applied()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var settingsProvider = (TestClientSettingsProvider)_testContext.Factory.Services.GetRequiredService<IClientSettingsProvider>();
settingsProvider.HidePlanetsWithPrivateName();
List<Planet> planets = _fakers.Planet.Generate(4);
planets[0].PrivateName = "A";
planets[2].PrivateName = "B";
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Planet>();
dbContext.Planets.AddRange(planets);
await dbContext.SaveChangesAsync();
});
const string route = "/planets";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(2);
responseDocument.Data.ManyValue[0].Id.Should().Be(planets[1].StringId);
responseDocument.Data.ManyValue[1].Id.Should().Be(planets[3].StringId);
((JsonElement)responseDocument.Meta["total"]).GetInt32().Should().Be(2);
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Planet), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyFilter),
(typeof(Planet), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyFilter),
(typeof(Planet), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyIncludes)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Filter_from_resource_definition_and_query_string_are_applied()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
var settingsProvider = (TestClientSettingsProvider)_testContext.Factory.Services.GetRequiredService<IClientSettingsProvider>();
settingsProvider.HidePlanetsWithPrivateName();
List<Planet> planets = _fakers.Planet.Generate(4);
planets[0].HasRingSystem = true;
planets[0].PrivateName = "A";
planets[1].HasRingSystem = false;
planets[1].PrivateName = "B";
planets[2].HasRingSystem = true;
planets[3].HasRingSystem = false;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Planet>();
dbContext.Planets.AddRange(planets);
await dbContext.SaveChangesAsync();
});
const string route = "/planets?filter=equals(hasRingSystem,'false')";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(1);
responseDocument.Data.ManyValue[0].Id.Should().Be(planets[3].StringId);
((JsonElement)responseDocument.Meta["total"]).GetInt32().Should().Be(1);
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Planet), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyFilter),
(typeof(Planet), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyFilter),
(typeof(Planet), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyIncludes)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Sort_from_resource_definition_is_applied()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
List<Star> stars = _fakers.Star.Generate(3);
stars[0].SolarMass = 500m;
stars[0].SolarRadius = 1m;
stars[1].SolarMass = 500m;
stars[1].SolarRadius = 10m;
stars[2].SolarMass = 50m;
stars[2].SolarRadius = 15m;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Star>();
dbContext.Stars.AddRange(stars);
await dbContext.SaveChangesAsync();
});
const string route = "/stars";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(3);
responseDocument.Data.ManyValue[0].Id.Should().Be(stars[1].StringId);
responseDocument.Data.ManyValue[1].Id.Should().Be(stars[0].StringId);
responseDocument.Data.ManyValue[2].Id.Should().Be(stars[2].StringId);
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyPagination),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySort),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Sort_from_query_string_is_applied()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
List<Star> stars = _fakers.Star.Generate(3);
stars[0].Name = "B";
stars[0].SolarRadius = 10m;
stars[1].Name = "B";
stars[1].SolarRadius = 1m;
stars[2].Name = "A";
stars[2].SolarRadius = 15m;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Star>();
dbContext.Stars.AddRange(stars);
await dbContext.SaveChangesAsync();
});
const string route = "/stars?sort=name,-solarRadius";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(3);
responseDocument.Data.ManyValue[0].Id.Should().Be(stars[2].StringId);
responseDocument.Data.ManyValue[1].Id.Should().Be(stars[0].StringId);
responseDocument.Data.ManyValue[2].Id.Should().Be(stars[1].StringId);
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyPagination),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySort),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Page_size_from_resource_definition_is_applied()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
List<Star> stars = _fakers.Star.Generate(10);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Star>();
dbContext.Stars.AddRange(stars);
await dbContext.SaveChangesAsync();
});
const string route = "/stars?page[size]=8";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(5);
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyPagination),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySort),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Attribute_inclusion_from_resource_definition_is_applied_for_omitted_query_string()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
Star star = _fakers.Star.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Stars.Add(star);
await dbContext.SaveChangesAsync();
});
string route = $"/stars/{star.StringId}";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.SingleValue.Should().NotBeNull();
responseDocument.Data.SingleValue.Id.Should().Be(star.StringId);
responseDocument.Data.SingleValue.Attributes["name"].Should().Be(star.Name);
responseDocument.Data.SingleValue.Attributes["kind"].Should().Be(star.Kind);
responseDocument.Data.SingleValue.Relationships.Should().NotBeNull();
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyPagination),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySort),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Attribute_inclusion_from_resource_definition_is_applied_for_fields_query_string()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
Star star = _fakers.Star.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Stars.Add(star);
await dbContext.SaveChangesAsync();
});
string route = $"/stars/{star.StringId}?fields[stars]=name,solarRadius";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.SingleValue.Should().NotBeNull();
responseDocument.Data.SingleValue.Id.Should().Be(star.StringId);
responseDocument.Data.SingleValue.Attributes.Should().HaveCount(2);
responseDocument.Data.SingleValue.Attributes["name"].Should().Be(star.Name);
responseDocument.Data.SingleValue.Attributes["solarRadius"].As<decimal>().Should().BeApproximately(star.SolarRadius);
responseDocument.Data.SingleValue.Relationships.Should().BeNull();
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyPagination),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySort),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Attribute_exclusion_from_resource_definition_is_applied_for_omitted_query_string()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
Star star = _fakers.Star.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Stars.Add(star);
await dbContext.SaveChangesAsync();
});
string route = $"/stars/{star.StringId}";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.SingleValue.Should().NotBeNull();
responseDocument.Data.SingleValue.Id.Should().Be(star.StringId);
responseDocument.Data.SingleValue.Attributes["name"].Should().Be(star.Name);
responseDocument.Data.SingleValue.Attributes.Should().NotContainKey("isVisibleFromEarth");
responseDocument.Data.SingleValue.Relationships.Should().NotBeNull();
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyPagination),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySort),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Attribute_exclusion_from_resource_definition_is_applied_for_fields_query_string()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
Star star = _fakers.Star.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Stars.Add(star);
await dbContext.SaveChangesAsync();
});
string route = $"/stars/{star.StringId}?fields[stars]=name,isVisibleFromEarth";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.SingleValue.Should().NotBeNull();
responseDocument.Data.SingleValue.Id.Should().Be(star.StringId);
responseDocument.Data.SingleValue.Attributes.Should().HaveCount(1);
responseDocument.Data.SingleValue.Attributes["name"].Should().Be(star.Name);
responseDocument.Data.SingleValue.Relationships.Should().BeNull();
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyPagination),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySort),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet),
(typeof(Star), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplySparseFieldSet)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Queryable_parameter_handler_from_resource_definition_is_applied()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
List<Moon> moons = _fakers.Moon.Generate(2);
moons[0].SolarRadius = .5m;
moons[1].SolarRadius = 50m;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Moon>();
dbContext.Moons.AddRange(moons);
await dbContext.SaveChangesAsync();
});
const string route = "/moons?isLargerThanTheSun=true";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(1);
responseDocument.Data.ManyValue[0].Id.Should().Be(moons[1].StringId);
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Moon), ResourceDefinitionHitCounter.ExtensibilityPoint.OnRegisterQueryableHandlersForQueryStringParameters),
(typeof(Moon), ResourceDefinitionHitCounter.ExtensibilityPoint.OnRegisterQueryableHandlersForQueryStringParameters),
(typeof(Moon), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyIncludes)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Queryable_parameter_handler_from_resource_definition_and_query_string_filter_are_applied()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
List<Moon> moons = _fakers.Moon.Generate(4);
moons[0].Name = "Alpha1";
moons[0].SolarRadius = 1m;
moons[1].Name = "Alpha2";
moons[1].SolarRadius = 5m;
moons[2].Name = "Beta1";
moons[2].SolarRadius = 1m;
moons[3].Name = "Beta2";
moons[3].SolarRadius = 5m;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Moon>();
dbContext.Moons.AddRange(moons);
await dbContext.SaveChangesAsync();
});
const string route = "/moons?isLargerThanTheSun=false&filter=startsWith(name,'B')";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(1);
responseDocument.Data.ManyValue[0].Id.Should().Be(moons[2].StringId);
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Moon), ResourceDefinitionHitCounter.ExtensibilityPoint.OnRegisterQueryableHandlersForQueryStringParameters),
(typeof(Moon), ResourceDefinitionHitCounter.ExtensibilityPoint.OnRegisterQueryableHandlersForQueryStringParameters),
(typeof(Moon), ResourceDefinitionHitCounter.ExtensibilityPoint.OnApplyIncludes)
}, options => options.WithStrictOrdering());
}
[Fact]
public async Task Queryable_parameter_handler_from_resource_definition_is_not_applied_on_secondary_request()
{
// Arrange
var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>();
Planet planet = _fakers.Planet.Generate();
planet.Moons = _fakers.Moon.Generate(1).ToHashSet();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Planets.Add(planet);
await dbContext.SaveChangesAsync();
});
string route = $"/planets/{planet.StringId}/moons?isLargerThanTheSun=false";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
error.Title.Should().Be("Custom query string parameters cannot be used on nested resource endpoints.");
error.Detail.Should().Be("Query string parameter 'isLargerThanTheSun' cannot be used on a nested resource endpoint.");
error.Source.Parameter.Should().Be("isLargerThanTheSun");
hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[]
{
(typeof(Moon), ResourceDefinitionHitCounter.ExtensibilityPoint.OnRegisterQueryableHandlersForQueryStringParameters)
}, options => options.WithStrictOrdering());
}
}
}
| |
using Discord.Audio;
using Discord.Rest;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using UserModel = Discord.API.User;
using MemberModel = Discord.API.GuildMember;
using PresenceModel = Discord.API.Presence;
namespace Discord.WebSocket
{
/// <summary>
/// Represents a WebSocket-based guild user.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class SocketGuildUser : SocketUser, IGuildUser
{
private long? _premiumSinceTicks;
private long? _joinedAtTicks;
private ImmutableArray<ulong> _roleIds;
internal override SocketGlobalUser GlobalUser { get; }
/// <summary>
/// Gets the guild the user is in.
/// </summary>
public SocketGuild Guild { get; }
/// <inheritdoc />
public string Nickname { get; private set; }
/// <inheritdoc />
public override bool IsBot { get { return GlobalUser.IsBot; } internal set { GlobalUser.IsBot = value; } }
/// <inheritdoc />
public override string Username { get { return GlobalUser.Username; } internal set { GlobalUser.Username = value; } }
/// <inheritdoc />
public override ushort DiscriminatorValue { get { return GlobalUser.DiscriminatorValue; } internal set { GlobalUser.DiscriminatorValue = value; } }
/// <inheritdoc />
public override string AvatarId { get { return GlobalUser.AvatarId; } internal set { GlobalUser.AvatarId = value; } }
/// <inheritdoc />
public GuildPermissions GuildPermissions => new GuildPermissions(Permissions.ResolveGuild(Guild, this));
internal override SocketPresence Presence { get; set; }
/// <inheritdoc />
public override bool IsWebhook => false;
/// <inheritdoc />
public bool IsSelfDeafened => VoiceState?.IsSelfDeafened ?? false;
/// <inheritdoc />
public bool IsSelfMuted => VoiceState?.IsSelfMuted ?? false;
/// <inheritdoc />
public bool IsSuppressed => VoiceState?.IsSuppressed ?? false;
/// <inheritdoc />
public bool IsDeafened => VoiceState?.IsDeafened ?? false;
/// <inheritdoc />
public bool IsMuted => VoiceState?.IsMuted ?? false;
/// <inheritdoc />
public bool IsStreaming => VoiceState?.IsStreaming ?? false;
/// <inheritdoc />
public DateTimeOffset? JoinedAt => DateTimeUtils.FromTicks(_joinedAtTicks);
/// <summary>
/// Returns a collection of roles that the user possesses.
/// </summary>
public IReadOnlyCollection<SocketRole> Roles
=> _roleIds.Select(id => Guild.GetRole(id)).Where(x => x != null).ToReadOnlyCollection(() => _roleIds.Length);
/// <summary>
/// Returns the voice channel the user is in, or <c>null</c> if none.
/// </summary>
public SocketVoiceChannel VoiceChannel => VoiceState?.VoiceChannel;
/// <inheritdoc />
public string VoiceSessionId => VoiceState?.VoiceSessionId ?? "";
/// <summary>
/// Gets the voice connection status of the user if any.
/// </summary>
/// <returns>
/// A <see cref="SocketVoiceState" /> representing the user's voice status; <c>null</c> if the user is not
/// connected to a voice channel.
/// </returns>
public SocketVoiceState? VoiceState => Guild.GetVoiceState(Id);
public AudioInStream AudioStream => Guild.GetAudioStream(Id);
/// <inheritdoc />
public DateTimeOffset? PremiumSince => DateTimeUtils.FromTicks(_premiumSinceTicks);
/// <summary>
/// Returns the position of the user within the role hierarchy.
/// </summary>
/// <remarks>
/// The returned value equal to the position of the highest role the user has, or
/// <see cref="int.MaxValue"/> if user is the server owner.
/// </remarks>
public int Hierarchy
{
get
{
if (Guild.OwnerId == Id)
return int.MaxValue;
int maxPos = 0;
for (int i = 0; i < _roleIds.Length; i++)
{
var role = Guild.GetRole(_roleIds[i]);
if (role != null && role.Position > maxPos)
maxPos = role.Position;
}
return maxPos;
}
}
internal SocketGuildUser(SocketGuild guild, SocketGlobalUser globalUser)
: base(guild.Discord, globalUser.Id)
{
Guild = guild;
GlobalUser = globalUser;
}
internal static SocketGuildUser Create(SocketGuild guild, ClientState state, UserModel model)
{
var entity = new SocketGuildUser(guild, guild.Discord.GetOrCreateUser(state, model));
entity.Update(state, model);
entity.UpdateRoles(new ulong[0]);
return entity;
}
internal static SocketGuildUser Create(SocketGuild guild, ClientState state, MemberModel model)
{
var entity = new SocketGuildUser(guild, guild.Discord.GetOrCreateUser(state, model.User));
entity.Update(state, model);
return entity;
}
internal static SocketGuildUser Create(SocketGuild guild, ClientState state, PresenceModel model)
{
var entity = new SocketGuildUser(guild, guild.Discord.GetOrCreateUser(state, model.User));
entity.Update(state, model, false);
return entity;
}
internal void Update(ClientState state, MemberModel model)
{
base.Update(state, model.User);
if (model.JoinedAt.IsSpecified)
_joinedAtTicks = model.JoinedAt.Value.UtcTicks;
if (model.Nick.IsSpecified)
Nickname = model.Nick.Value;
if (model.Roles.IsSpecified)
UpdateRoles(model.Roles.Value);
if (model.PremiumSince.IsSpecified)
_premiumSinceTicks = model.PremiumSince.Value?.UtcTicks;
}
internal void Update(ClientState state, PresenceModel model, bool updatePresence)
{
if (updatePresence)
{
Presence = SocketPresence.Create(model);
GlobalUser.Update(state, model);
}
if (model.Nick.IsSpecified)
Nickname = model.Nick.Value;
if (model.Roles.IsSpecified)
UpdateRoles(model.Roles.Value);
}
private void UpdateRoles(ulong[] roleIds)
{
var roles = ImmutableArray.CreateBuilder<ulong>(roleIds.Length + 1);
roles.Add(Guild.Id);
for (int i = 0; i < roleIds.Length; i++)
roles.Add(roleIds[i]);
_roleIds = roles.ToImmutable();
}
/// <inheritdoc />
public Task ModifyAsync(Action<GuildUserProperties> func, RequestOptions options = null)
=> UserHelper.ModifyAsync(this, Discord, func, options);
/// <inheritdoc />
public Task KickAsync(string reason = null, RequestOptions options = null)
=> UserHelper.KickAsync(this, Discord, reason, options);
/// <inheritdoc />
public Task AddRoleAsync(IRole role, RequestOptions options = null)
=> AddRolesAsync(new[] { role }, options);
/// <inheritdoc />
public Task AddRolesAsync(IEnumerable<IRole> roles, RequestOptions options = null)
=> UserHelper.AddRolesAsync(this, Discord, roles, options);
/// <inheritdoc />
public Task RemoveRoleAsync(IRole role, RequestOptions options = null)
=> RemoveRolesAsync(new[] { role }, options);
/// <inheritdoc />
public Task RemoveRolesAsync(IEnumerable<IRole> roles, RequestOptions options = null)
=> UserHelper.RemoveRolesAsync(this, Discord, roles, options);
/// <inheritdoc />
public ChannelPermissions GetPermissions(IGuildChannel channel)
=> new ChannelPermissions(Permissions.ResolveChannel(Guild, this, channel, GuildPermissions.RawValue));
private string DebuggerDisplay => $"{Username}#{Discriminator} ({Id}{(IsBot ? ", Bot" : "")}, Guild)";
internal new SocketGuildUser Clone() => MemberwiseClone() as SocketGuildUser;
//IGuildUser
/// <inheritdoc />
IGuild IGuildUser.Guild => Guild;
/// <inheritdoc />
ulong IGuildUser.GuildId => Guild.Id;
/// <inheritdoc />
IReadOnlyCollection<ulong> IGuildUser.RoleIds => _roleIds;
//IVoiceState
/// <inheritdoc />
IVoiceChannel IVoiceState.VoiceChannel => VoiceChannel;
}
}
| |
using Microsoft.Azure.ApplicationInsights.Query.Models;
using Microsoft.Rest;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Azure.ApplicationInsights.Query
{
public partial class Metrics : IServiceOperations<ApplicationInsightsDataClient>, IMetrics {
#region Metric Extensions
/// <summary>
/// Retrieve summary metric data
/// </summary>
/// <remarks>
/// Gets summary metric values for a single metric
/// </remarks>
/// <param name='appId'>
/// ID of the application. This is Application ID from the API Access settings
/// blade in the Azure portal.
/// </param>
/// <param name='metricId'>
/// ID of the metric. This is either a standard AI metric, or an
/// application-specific custom metric. Possible values include:
/// 'requests/count', 'requests/duration', 'requests/failed',
/// 'users/count', 'users/authenticated', 'pageViews/count',
/// 'pageViews/duration', 'client/processingDuration',
/// 'client/receiveDuration', 'client/networkDuration',
/// 'client/sendDuration', 'client/totalDuration',
/// 'dependencies/count', 'dependencies/failed',
/// 'dependencies/duration', 'exceptions/count', 'exceptions/browser',
/// 'exceptions/server', 'sessions/count',
/// 'performanceCounters/requestExecutionTime',
/// 'performanceCounters/requestsPerSecond',
/// 'performanceCounters/requestsInQueue',
/// 'performanceCounters/memoryAvailableBytes',
/// 'performanceCounters/exceptionsPerSecond',
/// 'performanceCounters/processCpuPercentage',
/// 'performanceCounters/processIOBytesPerSecond',
/// 'performanceCounters/processPrivateBytes',
/// 'performanceCounters/processorCpuPercentage',
/// 'availabilityResults/availabilityPercentage',
/// 'availabilityResults/duration', 'billing/telemetryCount',
/// 'customEvents/count'
/// </param>
/// <param name='timespan'>
/// The timespan over which to retrieve metric values. This is an
/// ISO8601 time period value. If timespan is omitted, a default time
/// range of `PT12H` ("last 12 hours") is used. The actual timespan
/// that is queried may be adjusted by the server based. In all cases,
/// the actual time span used for the query is included in the
/// response.
/// </param>
/// <param name='aggregation'>
/// The aggregation to use when computing the metric values. To
/// retrieve more than one aggregation at a time, separate them with a
/// comma. If no aggregation is specified, then the default aggregation
/// for the metric is used.
/// </param>
/// <param name='top'>
/// The number of segments to return. This value is only valid when
/// segment is specified.
/// </param>
/// <param name='orderby'>
/// The aggregation function and direction to sort the segments by.
/// This value is only valid when segment is specified.
/// </param>
/// <param name='filter'>
/// An expression used to filter the results. This value should be a
/// valid OData filter expression where the keys of each clause should
/// be applicable dimensions for the metric you are retrieving.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<MetricsSummaryResult>> GetMetricSummaryWithHttpMessagesAsync(string appId, string metricId, string timespan = default(string), IList<string> aggregation = default(IList<string>),
int? top = default(int?), string orderby = default(string), string filter = default(string), Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default(CancellationToken))
{
var realResult = await GetWithHttpMessagesAsync(appId, metricId, timespan, null, aggregation, null, top, orderby, filter, customHeaders, cancellationToken).ConfigureAwait(false);
var realBody = realResult.Body.Value;
return new HttpOperationResponse<MetricsSummaryResult>
{
Request = realResult.Request,
Response = realResult.Response,
Body = new MetricsSummaryResult
{
Start = realBody.Start,
End = realBody.End,
Sum = realBody.GetSum(),
Average = realBody.GetAverage(),
Min = realBody.GetMin(),
Max = realBody.GetMax(),
Count = realBody.GetCount()
}
};
}
/// <summary>
/// Retrieve metric data
/// </summary>
/// <remarks>
/// Gets metric values for a single metric
/// </remarks>
/// <param name='appId'>
/// ID of the application. This is Application ID from the API Access settings
/// blade in the Azure portal.
/// </param>
/// <param name='metricId'>
/// ID of the metric. This is either a standard AI metric, or an
/// application-specific custom metric. Possible values include:
/// 'requests/count', 'requests/duration', 'requests/failed',
/// 'users/count', 'users/authenticated', 'pageViews/count',
/// 'pageViews/duration', 'client/processingDuration',
/// 'client/receiveDuration', 'client/networkDuration',
/// 'client/sendDuration', 'client/totalDuration',
/// 'dependencies/count', 'dependencies/failed',
/// 'dependencies/duration', 'exceptions/count', 'exceptions/browser',
/// 'exceptions/server', 'sessions/count',
/// 'performanceCounters/requestExecutionTime',
/// 'performanceCounters/requestsPerSecond',
/// 'performanceCounters/requestsInQueue',
/// 'performanceCounters/memoryAvailableBytes',
/// 'performanceCounters/exceptionsPerSecond',
/// 'performanceCounters/processCpuPercentage',
/// 'performanceCounters/processIOBytesPerSecond',
/// 'performanceCounters/processPrivateBytes',
/// 'performanceCounters/processorCpuPercentage',
/// 'availabilityResults/availabilityPercentage',
/// 'availabilityResults/duration', 'billing/telemetryCount',
/// 'customEvents/count'
/// </param>
/// <param name='timespan'>
/// The timespan over which to retrieve metric values. This is an
/// ISO8601 time period value. If timespan is omitted, a default time
/// range of `PT12H` ("last 12 hours") is used. The actual timespan
/// that is queried may be adjusted by the server based. In all cases,
/// the actual time span used for the query is included in the
/// response.
/// </param>
/// <param name='interval'>
/// The time interval to use when retrieving metric values. This is an
/// ISO8601 duration. If interval is omitted, the metric value is
/// aggregated across the entire timespan. If interval is supplied, the
/// server may adjust the interval to a more appropriate size based on
/// the timespan used for the query. In all cases, the actual interval
/// used for the query is included in the response.
/// </param>
/// <param name='aggregation'>
/// The aggregation to use when computing the metric values. To
/// retrieve more than one aggregation at a time, separate them with a
/// comma. If no aggregation is specified, then the default aggregation
/// for the metric is used.
/// </param>
/// <param name='segment'>
/// The name of the dimension to segment the metric values by. This
/// dimension must be applicable to the metric you are retrieving. To
/// segment by more than one dimension at a time, separate them with a
/// comma (,). In this case, the metric data will be segmented in the
/// order the dimensions are listed in the parameter.
/// </param>
/// <param name='top'>
/// The number of segments to return. This value is only valid when
/// segment is specified.
/// </param>
/// <param name='orderby'>
/// The aggregation function and direction to sort the segments by.
/// This value is only valid when segment is specified.
/// </param>
/// <param name='filter'>
/// An expression used to filter the results. This value should be a
/// valid OData filter expression where the keys of each clause should
/// be applicable dimensions for the metric you are retrieving.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<MetricsIntervaledResult>> GetIntervaledMetricWithHttpMessagesAsync(string appId,
string metricId, string timespan = default(string),
System.TimeSpan? interval = default(System.TimeSpan?), IList<string> aggregation = default(IList<string>),
IList<string> segment = default(IList<string>), int? top = default(int?), string orderby = default(string),
string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
var realResult = await GetWithHttpMessagesAsync(appId, metricId, timespan, interval, aggregation, null, top, orderby, filter, customHeaders, cancellationToken).ConfigureAwait(false);
var realBody = realResult.Body.Value;
return new HttpOperationResponse<MetricsIntervaledResult>
{
Request = realResult.Request,
Response = realResult.Response,
Body = new MetricsIntervaledResult
{
Start = realBody.Start,
End = realBody.End,
Interval = realBody.Interval,
Intervals = realBody.Segments?.Select(inter =>
new MetricsIntervaledData
{
Sum = inter.GetSum(),
Average = inter.GetAverage(),
Min = inter.GetMin(),
Max = inter.GetMax(),
Count = inter.GetCount()
}
).ToList()
}
};
}
/// <summary>
/// Retrieve metric data
/// </summary>
/// <remarks>
/// Gets metric values for a single metric
/// </remarks>
/// <param name='appId'>
/// ID of the application. This is Application ID from the API Access settings
/// blade in the Azure portal.
/// </param>
/// <param name='metricId'>
/// ID of the metric. This is either a standard AI metric, or an
/// application-specific custom metric. Possible values include:
/// 'requests/count', 'requests/duration', 'requests/failed',
/// 'users/count', 'users/authenticated', 'pageViews/count',
/// 'pageViews/duration', 'client/processingDuration',
/// 'client/receiveDuration', 'client/networkDuration',
/// 'client/sendDuration', 'client/totalDuration',
/// 'dependencies/count', 'dependencies/failed',
/// 'dependencies/duration', 'exceptions/count', 'exceptions/browser',
/// 'exceptions/server', 'sessions/count',
/// 'performanceCounters/requestExecutionTime',
/// 'performanceCounters/requestsPerSecond',
/// 'performanceCounters/requestsInQueue',
/// 'performanceCounters/memoryAvailableBytes',
/// 'performanceCounters/exceptionsPerSecond',
/// 'performanceCounters/processCpuPercentage',
/// 'performanceCounters/processIOBytesPerSecond',
/// 'performanceCounters/processPrivateBytes',
/// 'performanceCounters/processorCpuPercentage',
/// 'availabilityResults/availabilityPercentage',
/// 'availabilityResults/duration', 'billing/telemetryCount',
/// 'customEvents/count'
/// </param>
/// <param name='timespan'>
/// The timespan over which to retrieve metric values. This is an
/// ISO8601 time period value. If timespan is omitted, a default time
/// range of `PT12H` ("last 12 hours") is used. The actual timespan
/// that is queried may be adjusted by the server based. In all cases,
/// the actual time span used for the query is included in the
/// response.
/// </param>
/// <param name='aggregation'>
/// The aggregation to use when computing the metric values. To
/// retrieve more than one aggregation at a time, separate them with a
/// comma. If no aggregation is specified, then the default aggregation
/// for the metric is used.
/// </param>
/// <param name='segment'>
/// The name of the dimension to segment the metric values by. This
/// dimension must be applicable to the metric you are retrieving. To
/// segment by more than one dimension at a time, separate them with a
/// comma (,). In this case, the metric data will be segmented in the
/// order the dimensions are listed in the parameter.
/// </param>
/// <param name='top'>
/// The number of segments to return. This value is only valid when
/// segment is specified.
/// </param>
/// <param name='orderby'>
/// The aggregation function and direction to sort the segments by.
/// This value is only valid when segment is specified.
/// </param>
/// <param name='filter'>
/// An expression used to filter the results. This value should be a
/// valid OData filter expression where the keys of each clause should
/// be applicable dimensions for the metric you are retrieving.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<MetricsSegmentedResult>> GetSegmentedMetricWithHttpMessagesAsync(string appId, string metricId,
string timespan = default(string), IList<string> aggregation = default(IList<string>),
IList<string> segment = default(IList<string>), int? top = default(int?), string orderby = default(string),
string filter = default(string), Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default(CancellationToken))
{
var realResult = await GetWithHttpMessagesAsync(appId, metricId, timespan, null, aggregation, segment, top, orderby, filter, customHeaders, cancellationToken);
var realBody = realResult.Body.Value;
return new HttpOperationResponse<MetricsSegmentedResult>
{
Request = realResult.Request,
Response = realResult.Response,
Body = new MetricsSegmentedResult
{
Start = realBody.Start,
End = realBody.End,
Segments= GetSegmentInfo(realBody.Segments),
}
};
}
private static IList<IMetricsBaseSegmentInfo> GetSegmentInfo(IList<MetricsSegmentInfo> segments)
{
return segments?.Select(seg =>
{
IMetricsBaseSegmentInfo result;
if (seg.Segments != null && seg.Segments.Count != 0)
{
result = new MetricsNestedSegment()
{
SegmentId = seg.SegmentId,
SegmentValue = seg.SegmentValue,
Segments = GetSegmentInfo(seg.Segments),
};
}
else
{
result = new MetricsSegmentedData
{
SegmentId = seg.SegmentId,
SegmentValue = seg.SegmentValue,
Sum = seg.GetSum(),
Average = seg.GetAverage(),
Min = seg.GetMin(),
Max = seg.GetMax(),
Count = seg.GetCount()
};
}
return result;
}).ToList();
}
/// <summary>
/// Retrieve metric data
/// </summary>
/// <remarks>
/// Gets metric values for a single metric
/// </remarks>
/// <param name='appId'>
/// ID of the application. This is Application ID from the API Access settings
/// blade in the Azure portal.
/// </param>
/// <param name='metricId'>
/// ID of the metric. This is either a standard AI metric, or an
/// application-specific custom metric. Possible values include:
/// 'requests/count', 'requests/duration', 'requests/failed',
/// 'users/count', 'users/authenticated', 'pageViews/count',
/// 'pageViews/duration', 'client/processingDuration',
/// 'client/receiveDuration', 'client/networkDuration',
/// 'client/sendDuration', 'client/totalDuration',
/// 'dependencies/count', 'dependencies/failed',
/// 'dependencies/duration', 'exceptions/count', 'exceptions/browser',
/// 'exceptions/server', 'sessions/count',
/// 'performanceCounters/requestExecutionTime',
/// 'performanceCounters/requestsPerSecond',
/// 'performanceCounters/requestsInQueue',
/// 'performanceCounters/memoryAvailableBytes',
/// 'performanceCounters/exceptionsPerSecond',
/// 'performanceCounters/processCpuPercentage',
/// 'performanceCounters/processIOBytesPerSecond',
/// 'performanceCounters/processPrivateBytes',
/// 'performanceCounters/processorCpuPercentage',
/// 'availabilityResults/availabilityPercentage',
/// 'availabilityResults/duration', 'billing/telemetryCount',
/// 'customEvents/count'
/// </param>
/// <param name='timespan'>
/// The timespan over which to retrieve metric values. This is an
/// ISO8601 time period value. If timespan is omitted, a default time
/// range of `PT12H` ("last 12 hours") is used. The actual timespan
/// that is queried may be adjusted by the server based. In all cases,
/// the actual time span used for the query is included in the
/// response.
/// </param>
/// <param name='interval'>
/// The time interval to use when retrieving metric values. This is an
/// ISO8601 duration. If interval is omitted, the metric value is
/// aggregated across the entire timespan. If interval is supplied, the
/// server may adjust the interval to a more appropriate size based on
/// the timespan used for the query. In all cases, the actual interval
/// used for the query is included in the response.
/// </param>
/// <param name='aggregation'>
/// The aggregation to use when computing the metric values. To
/// retrieve more than one aggregation at a time, separate them with a
/// comma. If no aggregation is specified, then the default aggregation
/// for the metric is used.
/// </param>
/// <param name='segment'>
/// The name of the dimension to segment the metric values by. This
/// dimension must be applicable to the metric you are retrieving. To
/// segment by more than one dimension at a time, separate them with a
/// comma (,). In this case, the metric data will be segmented in the
/// order the dimensions are listed in the parameter.
/// </param>
/// <param name='top'>
/// The number of segments to return. This value is only valid when
/// segment is specified.
/// </param>
/// <param name='orderby'>
/// The aggregation function and direction to sort the segments by.
/// This value is only valid when segment is specified.
/// </param>
/// <param name='filter'>
/// An expression used to filter the results. This value should be a
/// valid OData filter expression where the keys of each clause should
/// be applicable dimensions for the metric you are retrieving.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<MetricsIntervaledSegmentedResult>> GetIntervaledSegmentedMetricWithHttpMessagesAsync(
string appId, string metricId,
string timespan = default(string), System.TimeSpan? interval = default(System.TimeSpan?),
IList<string> aggregation = default(IList<string>), IList<string> segment = default(IList<string>),
int? top = default(int?), string orderby = default(string), string filter = default(string),
Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default(CancellationToken))
{
var realResult = await GetWithHttpMessagesAsync(appId, metricId, timespan, interval, aggregation, segment, top, orderby, filter, customHeaders, cancellationToken).ConfigureAwait(false);
var realBody = realResult.Body.Value;
return new HttpOperationResponse<MetricsIntervaledSegmentedResult>
{
Request = realResult.Request,
Response = realResult.Response,
Body = new MetricsIntervaledSegmentedResult
{
Start = realBody.Start,
End = realBody.End,
Interval = realBody.Interval,
Intervals = realBody.Segments?.Select(inter =>
new MetricsSegmentedIntervalData
{
Start = inter.Start,
End = inter.End,
Segments = GetSegmentInfo(inter.Segments),
}
).ToList()
}
};
}
#endregion
}
}
| |
// 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.Runtime.InteropServices.ComTypes;
using OpenLiveWriter.Mshtml.Mshtml_Interop;
using System.Runtime.InteropServices;
namespace OpenLiveWriter.PostEditor
{
[Guid("bcf019de-cd63-4b33-8ffe-1f5e5403f3b3")]
[ComVisible(true)]
public enum ContentEditorFeature
{
/// <summary>
/// Whether or not the blog provider supports uploading images through their API.
/// </summary>
ImageUpload = 1,
/// <summary>
/// Whether or not the blog provider allows scripts in the published HTML.
/// </summary>
Script = 2,
/// <summary>
/// Whether or not the blog provider allows embeds in the published HTML.
/// </summary>
Embeds = 3,
/// <summary>
/// Whether or not the blog provider requires valid XHTML.
/// </summary>
XHTML = 4,
/// <summary>
/// Unused.
/// </summary>
ImageClickThroughs = 5,
/// <summary>
/// By default, hitting tab starts a block quote. This flag forces the editor to insert an indent instead.
/// </summary>
TabAsIndent = 6,
/// <summary>
/// Unused.
/// </summary>
OpenDialogOnInsertLinkDialog = 7,
/// <summary>
/// Whether or not, in left-to-right languages, the option to change the reading direction of each paragraph
/// should be enabled. This functionality is always enabled for right-to-left languages.
/// </summary>
RTLFeatures = 8,
/// <summary>
/// Whether or not "Ignore Once" is enabled.
/// </summary>
SpellCheckIgnoreOnce = 9,
/// <summary>
/// Cleans up the whitespace at the start and end of the document
/// when it loads the html into the editor
/// </summary>
TidyWhitespace = 10,
/// <summary>
/// By default, images are centered by displaying the image as a block element and setting the left and right
/// margins to auto. This flag forces the editor to center an image by wrapping it in an HTML
/// <p align="center"> tag.
/// </summary>
CenterImageWithParagraph = 11,
/// <summary>
/// Whether or not the source code editing mode is enabled.
/// </summary>
SourceEditor = 12,
/// <summary>
/// Whether or not the WYSIWYG sidebar is enabled.
/// </summary>
EnableSidebar = 13,
/// <summary>
/// Whether or not the Paste Special command is allowed.
/// </summary>
SpecialPaste = 14,
UrlContentSourcePaste = 16,
Table = 17,
ShowAllLinkOptions = 18,
SupportsImageClickThroughs = 19,
ImageBorderInherit = 20,
DivNewLine = 21,
HideNonVisibleElements = 22,
ShadowImageForDrafts = 23,
RTLDirectionDefault = 24,
PlainTextEditor = 25,
PreviewMode = 26,
UnicodeEllipsis = 27,
CleanHtmlOnPaste = 31,
BrokenSmartContent = 32,
ShowLinkTooltipForImages = 34,
AlwaysInsertInlineImagesAsInline = 35,
ViewNormalEditorShortcut = 39,
AutoLinking = 41,
/// <summary>
/// Determines whether or not to reset the focus to body element after documentComplete to trigger IME notification in mshtml
/// </summary>
ResetFocusToFixIME
}
[Guid("9a98e1fd-8407-478b-af8a-ea0b1774dd07")]
[ComVisible(true)]
public enum ContentEditorOptions
{
TypographicReplacement = 1,
SmartQuotes = 2,
RealTimeWordCount = 3
}
[Guid("6a4c65cc-eb91-41af-9599-f5665e592df5")]
[ComVisible(true)]
public enum EditingMode
{
Wysiwyg = 1,
Preview = 2,
Source = 4,
PlainText = 8
}
[Flags]
[Guid("ac667254-1b9d-4db8-83da-b026c730eff2")]
[ComVisible(true)]
// Make sure this stays in sync with HtmlInsertionOptions
public enum HtmlInsertOptions
{
SuppressSpellCheck = 1,
Indent = 2,
MoveCursorAfter = 4,
InsertAtBeginning = 8,
InsertAtEnd = 16,
ClearUndoStack = 32,
PlainText = 64,
InsertNewLineBefore = 128,
ExternalContent = 256,
ApplyDefaultFont = 512,
SelectFirstControl = 1024,
AllowBlockBreakout = 2048
}
[Guid("b6a7c590-2229-4dba-bf82-2acd898cb3ca")]
[ComVisible(true)]
public enum SelectionPosition
{
BodyStart = 0,
BodyEnd = 1
}
[Guid("183376ce-fef3-48d4-bcc7-453228cdd1e5")]
[ComVisible(true)]
public enum HR_E_PHOTOMAIL
{
MISSINGIMAGES = unchecked((int)0x8CCC0001),
WPOSTXFILEMISSING = unchecked((int)0x8CCC0002),
SIGNED_OUT = unchecked((int)0x8CCC0003),
HTTPERROR_BASE = unchecked((int)0x8CCCC000),
HTTPERROR_415 = unchecked((int)0x8CCCC19F),
HTTPERROR_500 = unchecked((int)0x8CCCC1F4),
HTTPERROR_502 = unchecked((int)0x8CCCC1F6),
HTTPERROR_503 = unchecked((int)0x8CCCC1F7),
HTTPERROR_504 = unchecked((int)0x8CCCC1F8),
HTTPERROR_MAX = unchecked((int)0x8CCCCFFF),
SKYDRIVE_BASE = unchecked((int)0x8CCCD000),
SKYDRIVE_1 = unchecked((int)0x8CCCD001),
SKYDRIVE_5 = unchecked((int)0x8CCCD005),
SKYDRIVE_65 = unchecked((int)0x8CCCD041),
SKYDRIVE_67 = unchecked((int)0x8CCCD043),
SKYDRIVE_70 = unchecked((int)0x8CCCD046),
SKYDRIVE_73 = unchecked((int)0x8CCCD049),
SKYDRIVE_82 = unchecked((int)0x8CCCD052),
SKYDRIVE_MAX = unchecked((int)0x8CCCDFFF),
WEBERROR_BASE = unchecked((int)0x8CCCE000),
WEBERROR_MAX = unchecked((int)0x8CCCEFFF),
}
[Guid("26E9B42B-F4F5-4037-95A7-E5E8E9AA5C26")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComVisible(true)]
public interface IContentEditorFactory
{
/// <summary>
/// Creates and editor with a blank document
/// </summary>
/// <param name="contentEditorSite"></param>
/// <param name="internetSecurityManager"></param>
/// <param name="wysiwygHtml"></param>
/// <returns></returns>
IContentEditor CreateEditor(
IContentEditorSite contentEditorSite,
IInternetSecurityManager internetSecurityManager,
string wysiwygHtml,
int dlControlFlags);
/// <summary>
/// Creates an editor using the draft that was saved by the
/// Save() function earlier from a IContentEditor
/// </summary>
/// <param name="contentEditorSite"></param>
/// <param name="internetSecurityManager"></param>
/// <param name="wysiwygHtml"></param>
/// <param name="pathToDraftFile"></param>
/// <returns></returns>
//IContentEditor CreateEditorFromDraft(
// IContentEditorSite contentEditorSite,
// IInternetSecurityManager internetSecurityManager,
// string wysiwygHtml,
// string pathToDraftFile,
// int dlControlFlags);
/// <summary>
/// Creates a editor using a html document. The body will
/// become the editable region. Everything around the body
/// will become the template.
/// </summary>
/// <param name="contentEditorSite"></param>
/// <param name="internetSecurityManager"></param>
/// <param name="htmlDocument"></param>
/// If true, a new line will be added to the begining of the body.
/// If false, a new line will be added to the end of the body
/// </param>
/// <returns></returns>
IContentEditor CreateEditorFromMoniker(
IContentEditorSite contentEditorSite,
IInternetSecurityManager internetSecurityManager,
IMoniker htmlDocument,
uint codepage,
HtmlInsertOptions options,
string color,
int dlControlFlags,
string wpost);
/// <summary>
/// Initialize the factory with settings that apply to
/// all editors
/// </summary>
/// <param name="appDataPath">
/// Sets the path of where the ContentEditor can
/// save settings(log file, link glossary, etc...)
/// e.g. C:\Users\user\AppData\Roaming\Open Live Writer
/// </param>
/// <param name="registrySettingsPath">
/// Sets the path of where in the registry ContentEditor
/// can save settings.
/// e.g. HKEY_CURRENT_USER\Software\Open Live Writer\Writer
/// </param>
/// <param name="applicationName">
/// Localized name of the application, will be shown to user in error messages
/// </param>
void Initialize(
string registrySettingsPath,
IContentEditorLogger logger,
IContentTarget contentTarget,
ISettingsProvider settingsProvider);
/// <summary>
/// Does clean up, and removes temp files, and
/// disposes native resources
/// </summary>
void Shutdown();
/// <summary>
/// Preloads some of the costly work assoicated with creating a ContentEditor
/// </summary>
void DoPreloadWork();
}
/// <summary>
/// IContentEditorLogger is a call back to do logging.
/// This is not part of the IContentSite because
/// there will need to be logging done before a ContentEditor
/// is created and it is global to all ContentEditors
/// thus it must be passed in when the IContentEditorFactory
/// is created.
/// </summary>
[Guid("EB64D508-6B7E-404f-B832-A68E5C5D06F0")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComVisible(true)]
public interface IContentEditorLogger
{
void WriteLine(string message, int level);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
private sealed partial class WorkCoordinator
{
private sealed partial class IncrementalAnalyzerProcessor
{
private sealed class NormalPriorityProcessor : GlobalOperationAwareIdleProcessor
{
private const int MaxHighPriorityQueueCache = 29;
private readonly AsyncDocumentWorkItemQueue _workItemQueue;
private readonly Lazy<ImmutableArray<IIncrementalAnalyzer>> _lazyAnalyzers;
private readonly ConcurrentDictionary<DocumentId, IDisposable> _higherPriorityDocumentsNotProcessed;
private readonly HashSet<ProjectId> _currentSnapshotVersionTrackingSet;
private ProjectId _currentProjectProcessing;
private Solution _processingSolution;
private IDisposable _projectCache;
// whether this processor is running or not
private Task _running;
public NormalPriorityProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers,
IGlobalOperationNotificationService globalOperationNotificationService,
int backOffTimeSpanInMs,
CancellationToken shutdownToken) :
base(listener, processor, globalOperationNotificationService, backOffTimeSpanInMs, shutdownToken)
{
_lazyAnalyzers = lazyAnalyzers;
_running = SpecializedTasks.EmptyTask;
_workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter);
_higherPriorityDocumentsNotProcessed = new ConcurrentDictionary<DocumentId, IDisposable>(concurrencyLevel: 2, capacity: 20);
_currentProjectProcessing = default(ProjectId);
_processingSolution = null;
_currentSnapshotVersionTrackingSet = new HashSet<ProjectId>();
Start();
}
internal ImmutableArray<IIncrementalAnalyzer> Analyzers
{
get
{
return _lazyAnalyzers.Value;
}
}
public void Enqueue(WorkItem item)
{
Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item");
this.UpdateLastAccessTime();
var added = _workItemQueue.AddOrReplace(item);
Logger.Log(FunctionId.WorkCoordinator_DocumentWorker_Enqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added);
CheckHigherPriorityDocument(item);
SolutionCrawlerLogger.LogWorkItemEnqueue(
this.Processor._logAggregator, item.Language, item.DocumentId, item.InvocationReasons, item.IsLowPriority, item.ActiveMember, added);
}
private void CheckHigherPriorityDocument(WorkItem item)
{
if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.HighPriority))
{
return;
}
AddHigherPriorityDocument(item.DocumentId);
}
private void AddHigherPriorityDocument(DocumentId id)
{
var cache = GetHighPriorityQueueProjectCache(id);
if (!_higherPriorityDocumentsNotProcessed.TryAdd(id, cache))
{
// we already have the document in the queue.
cache?.Dispose();
}
SolutionCrawlerLogger.LogHigherPriority(this.Processor._logAggregator, id.Id);
}
private IDisposable GetHighPriorityQueueProjectCache(DocumentId id)
{
// NOTE: we have one potential issue where we can cache a lot of stuff in memory
// since we will cache all high prioirty work's projects in memory until they are processed.
//
// To mitigate that, we will turn off cache if we have too many items in high priority queue
// this shouldn't affect active file since we always enable active file cache from background compiler.
return _higherPriorityDocumentsNotProcessed.Count <= MaxHighPriorityQueueCache ? Processor.EnableCaching(id.ProjectId) : null;
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
if (!_workItemQueue.HasAnyWork)
{
DisposeProjectCache();
}
return _workItemQueue.WaitAsync(cancellationToken);
}
public Task Running
{
get
{
return _running;
}
}
public bool HasAnyWork
{
get
{
return _workItemQueue.HasAnyWork;
}
}
protected override async Task ExecuteAsync()
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var source = new TaskCompletionSource<object>();
try
{
// mark it as running
_running = source.Task;
await WaitForHigherPriorityOperationsAsync().ConfigureAwait(false);
// okay, there must be at least one item in the map
await ResetStatesAsync().ConfigureAwait(false);
if (await TryProcessOneHigherPriorityDocumentAsync().ConfigureAwait(false))
{
// successfully processed a high priority document.
return;
}
// process one of documents remaining
var documentCancellation = default(CancellationTokenSource);
WorkItem workItem;
if (!_workItemQueue.TryTakeAnyWork(_currentProjectProcessing, this.Processor.DependencyGraph, out workItem, out documentCancellation))
{
return;
}
// check whether we have been shutdown
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
// check whether we have moved to new project
SetProjectProcessing(workItem.ProjectId);
// process the new document
await ProcessDocumentAsync(this.Analyzers, workItem, documentCancellation).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// mark it as done running
source.SetResult(null);
}
}
protected override Task HigherQueueOperationTask
{
get
{
return this.Processor._highPriorityProcessor.Running;
}
}
protected override bool HigherQueueHasWorkItem
{
get
{
return this.Processor._highPriorityProcessor.HasAnyWork;
}
}
protected override void PauseOnGlobalOperation()
{
_workItemQueue.RequestCancellationOnRunningTasks();
}
private void SetProjectProcessing(ProjectId currentProject)
{
EnableProjectCacheIfNecessary(currentProject);
_currentProjectProcessing = currentProject;
}
private void EnableProjectCacheIfNecessary(ProjectId currentProject)
{
if (_projectCache != null && currentProject == _currentProjectProcessing)
{
return;
}
DisposeProjectCache();
_projectCache = Processor.EnableCaching(currentProject);
}
private static void DisposeProjectCache(IDisposable projectCache)
{
projectCache?.Dispose();
}
private void DisposeProjectCache()
{
DisposeProjectCache(_projectCache);
_projectCache = null;
}
private IEnumerable<DocumentId> GetPrioritizedPendingDocuments()
{
if (this.Processor._documentTracker != null)
{
// First the active document
var activeDocumentId = this.Processor._documentTracker.GetActiveDocument();
if (activeDocumentId != null && _higherPriorityDocumentsNotProcessed.ContainsKey(activeDocumentId))
{
yield return activeDocumentId;
}
// Now any visible documents
foreach (var visibleDocumentId in this.Processor._documentTracker.GetVisibleDocuments())
{
if (_higherPriorityDocumentsNotProcessed.ContainsKey(visibleDocumentId))
{
yield return visibleDocumentId;
}
}
}
// Any other high priority documents
foreach (var documentId in _higherPriorityDocumentsNotProcessed.Keys)
{
yield return documentId;
}
}
private async Task<bool> TryProcessOneHigherPriorityDocumentAsync()
{
try
{
// this is a best effort algorithm with some shortcomings.
//
// the most obvious issue is if there is a new work item (without a solution change - but very unlikely)
// for a opened document we already processed, the work item will be treated as a regular one rather than higher priority one
// (opened document)
CancellationTokenSource documentCancellation;
foreach (var documentId in this.GetPrioritizedPendingDocuments())
{
if (this.CancellationToken.IsCancellationRequested)
{
return true;
}
// see whether we have work item for the document
WorkItem workItem;
if (!_workItemQueue.TryTake(documentId, out workItem, out documentCancellation))
{
RemoveHigherPriorityDocument(documentId);
continue;
}
// okay now we have work to do
await ProcessDocumentAsync(this.Analyzers, workItem, documentCancellation).ConfigureAwait(false);
RemoveHigherPriorityDocument(documentId);
return true;
}
return false;
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void RemoveHigherPriorityDocument(DocumentId documentId)
{
// remove opened document processed
IDisposable projectCache;
if (_higherPriorityDocumentsNotProcessed.TryRemove(documentId, out projectCache))
{
DisposeProjectCache(projectCache);
}
}
private async Task ProcessDocumentAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source)
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var processedEverything = false;
var documentId = workItem.DocumentId;
try
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, source.Token))
{
var cancellationToken = source.Token;
var document = _processingSolution.GetDocument(documentId);
if (document != null)
{
await TrackSemanticVersionsAsync(document, workItem, cancellationToken).ConfigureAwait(false);
// if we are called because a document is opened, we invalidate the document so that
// it can be re-analyzed. otherwise, since newly opened document has same version as before
// analyzer will simply return same data back
if (workItem.MustRefresh && !workItem.IsRetry)
{
var isOpen = document.IsOpen();
await ProcessOpenDocumentIfNeeded(analyzers, workItem, document, isOpen, cancellationToken).ConfigureAwait(false);
await ProcessCloseDocumentIfNeeded(analyzers, workItem, document, isOpen, cancellationToken).ConfigureAwait(false);
}
// check whether we are having special reanalyze request
await ProcessReanalyzeDocumentAsync(workItem, document, cancellationToken).ConfigureAwait(false);
await ProcessDocumentAnalyzersAsync(document, analyzers, workItem, cancellationToken).ConfigureAwait(false);
}
else
{
SolutionCrawlerLogger.LogProcessDocumentNotExist(this.Processor._logAggregator);
RemoveDocument(documentId);
}
if (!cancellationToken.IsCancellationRequested)
{
processedEverything = true;
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// we got cancelled in the middle of processing the document.
// let's make sure newly enqueued work item has all the flag needed.
if (!processedEverything)
{
_workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem")));
}
SolutionCrawlerLogger.LogProcessDocument(this.Processor._logAggregator, documentId.Id, processedEverything);
// remove one that is finished running
_workItemQueue.RemoveCancellationSource(workItem.DocumentId);
}
}
private async Task TrackSemanticVersionsAsync(Document document, WorkItem workItem, CancellationToken cancellationToken)
{
if (workItem.IsRetry ||
workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentAdded) ||
!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
return;
}
var service = document.Project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>();
if (service == null)
{
return;
}
// we already reported about this project for same snapshot, don't need to do it again
if (_currentSnapshotVersionTrackingSet.Contains(document.Project.Id))
{
return;
}
await service.RecordSemanticVersionsAsync(document.Project, cancellationToken).ConfigureAwait(false);
// mark this project as already processed.
_currentSnapshotVersionTrackingSet.Add(document.Project.Id);
}
private async Task ProcessOpenDocumentIfNeeded(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, Document document, bool isOpen, CancellationToken cancellationToken)
{
if (!isOpen || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentOpened))
{
return;
}
SolutionCrawlerLogger.LogProcessOpenDocument(this.Processor._logAggregator, document.Id.Id);
await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.DocumentOpenAsync(d, c), cancellationToken).ConfigureAwait(false);
}
private async Task ProcessCloseDocumentIfNeeded(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, Document document, bool isOpen, CancellationToken cancellationToken)
{
if (isOpen || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentClosed))
{
return;
}
SolutionCrawlerLogger.LogProcessCloseDocument(this.Processor._logAggregator, document.Id.Id);
await RunAnalyzersAsync(analyzers, document, (a, d, c) => a.DocumentCloseAsync(d, c), cancellationToken).ConfigureAwait(false);
}
private async Task ProcessReanalyzeDocumentAsync(WorkItem workItem, Document document, CancellationToken cancellationToken)
{
try
{
#if DEBUG
Contract.Requires(!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.Reanalyze) || workItem.Analyzers.Count > 0);
#endif
// no-reanalyze request or we already have a request to re-analyze every thing
if (workItem.MustRefresh || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.Reanalyze))
{
return;
}
// First reset the document state in analyzers.
var reanalyzers = workItem.Analyzers.ToImmutableArray();
await RunAnalyzersAsync(reanalyzers, document, (a, d, c) => a.DocumentResetAsync(d, c), cancellationToken).ConfigureAwait(false);
// no request to re-run syntax change analysis. run it here
if (!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
await RunAnalyzersAsync(reanalyzers, document, (a, d, c) => a.AnalyzeSyntaxAsync(d, c), cancellationToken).ConfigureAwait(false);
}
// no request to re-run semantic change analysis. run it here
if (!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged))
{
await RunAnalyzersAsync(reanalyzers, document, (a, d, c) => a.AnalyzeDocumentAsync(d, null, c), cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void RemoveDocument(DocumentId documentId)
{
RemoveDocument(this.Analyzers, documentId);
}
private static void RemoveDocument(IEnumerable<IIncrementalAnalyzer> analyzers, DocumentId documentId)
{
foreach (var analyzer in analyzers)
{
analyzer.RemoveDocument(documentId);
}
}
private void ResetLogAggregatorIfNeeded(Solution currentSolution)
{
if (currentSolution == null || _processingSolution == null ||
currentSolution.Id == _processingSolution.Id)
{
return;
}
SolutionCrawlerLogger.LogIncrementalAnalyzerProcessorStatistics(
this.Processor._registration.CorrelationId, _processingSolution, this.Processor._logAggregator, this.Analyzers);
this.Processor.ResetLogAggregator();
}
private async Task ResetStatesAsync()
{
try
{
var currentSolution = this.Processor.CurrentSolution;
if (currentSolution != _processingSolution)
{
ResetLogAggregatorIfNeeded(currentSolution);
// clear version tracking set we already reported.
_currentSnapshotVersionTrackingSet.Clear();
_processingSolution = currentSolution;
await RunAnalyzersAsync(this.Analyzers, currentSolution, (a, s, c) => a.NewSolutionSnapshotAsync(s, c), this.CancellationToken).ConfigureAwait(false);
foreach (var id in this.Processor.GetOpenDocumentIds())
{
AddHigherPriorityDocument(id);
}
SolutionCrawlerLogger.LogResetStates(this.Processor._logAggregator);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public override void Shutdown()
{
base.Shutdown();
SolutionCrawlerLogger.LogIncrementalAnalyzerProcessorStatistics(this.Processor._registration.CorrelationId, _processingSolution, this.Processor._logAggregator, this.Analyzers);
_workItemQueue.Dispose();
if (_projectCache != null)
{
_projectCache.Dispose();
_projectCache = null;
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items)
{
CancellationTokenSource source = new CancellationTokenSource();
_processingSolution = this.Processor.CurrentSolution;
foreach (var item in items)
{
ProcessDocumentAsync(analyzers, item, source).Wait();
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly()
{
// this shouldn't happen. would like to get some diagnostic
while (_workItemQueue.HasAnyWork)
{
Environment.FailFast("How?");
}
}
}
}
}
}
}
| |
using RSG.Promises;
using System;
using System.Linq;
using RSG.Exceptions;
using Xunit;
namespace RSG.Tests
{
public class Promise_NonGeneric_Tests
{
[Fact]
public void can_resolve_simple_promise()
{
var promise = Promise.Resolved();
var completed = 0;
promise.Then(() => ++completed);
Assert.Equal(1, completed);
}
[Fact]
public void can_reject_simple_promise()
{
var ex = new Exception();
var promise = Promise.Rejected(ex);
var errors = 0;
promise.Catch(e =>
{
Assert.Equal(ex, e);
++errors;
});
Assert.Equal(1, errors);
}
[Fact]
public void exception_is_thrown_for_reject_after_reject()
{
var promise = new Promise();
promise.Reject(new Exception());
Assert.Throws<PromiseStateException>(() =>
promise.Reject(new Exception())
);
}
[Fact]
public void exception_is_thrown_for_reject_after_resolve()
{
var promise = new Promise();
promise.Resolve();
Assert.Throws<PromiseStateException>(() =>
promise.Reject(new Exception())
);
}
[Fact]
public void exception_is_thrown_for_resolve_after_reject()
{
var promise = new Promise();
promise.Reject(new Exception());
Assert.Throws<PromiseStateException>(() => promise.Resolve());
}
[Fact]
public void can_resolve_promise_and_trigger_then_handler()
{
var promise = new Promise();
var completed = 0;
promise.Then(() => ++completed);
promise.Resolve();
Assert.Equal(1, completed);
}
[Fact]
public void exception_is_thrown_for_resolve_after_resolve()
{
var promise = new Promise();
promise.Resolve();
Assert.Throws<PromiseStateException>(() => promise.Resolve());
}
[Fact]
public void can_resolve_promise_and_trigger_multiple_then_handlers_in_order()
{
var promise = new Promise();
var completed = 0;
promise.Then(() => Assert.Equal(1, ++completed));
promise.Then(() => Assert.Equal(2, ++completed));
promise.Resolve();
Assert.Equal(2, completed);
}
[Fact]
public void can_resolve_promise_and_trigger_then_handler_with_callback_registration_after_resolve()
{
var promise = new Promise();
var completed = 0;
promise.Resolve();
promise.Then(() => ++completed);
Assert.Equal(1, completed);
}
[Fact]
public void can_reject_promise_and_trigger_error_handler()
{
var promise = new Promise();
var ex = new Exception();
var completed = 0;
promise.Catch(e =>
{
Assert.Equal(ex, e);
++completed;
});
promise.Reject(ex);
Assert.Equal(1, completed);
}
[Fact]
public void can_reject_promise_and_trigger_multiple_error_handlers_in_order()
{
var promise = new Promise();
var ex = new Exception();
var completed = 0;
promise.Catch(e =>
{
Assert.Equal(ex, e);
Assert.Equal(1, ++completed);
});
promise.Catch(e =>
{
Assert.Equal(ex, e);
Assert.Equal(2, ++completed);
});
promise.Reject(ex);
Assert.Equal(2, completed);
}
[Fact]
public void can_reject_promise_and_trigger_error_handler_with_registration_after_reject()
{
var promise = new Promise();
var ex = new Exception();
promise.Reject(ex);
var completed = 0;
promise.Catch(e =>
{
Assert.Equal(ex, e);
++completed;
});
Assert.Equal(1, completed);
}
[Fact]
public void error_handler_is_not_invoked_for_resolved_promised()
{
var promise = new Promise();
promise.Catch(e => throw new Exception("This shouldn't happen"));
promise.Resolve();
}
[Fact]
public void then_handler_is_not_invoked_for_rejected_promise()
{
var promise = new Promise();
promise.Then(() => throw new Exception("This shouldn't happen"));
promise.Reject(new Exception("Rejection!"));
}
[Fact]
public void chain_multiple_promises_using_all()
{
var promise = new Promise();
var chainedPromise1 = new Promise();
var chainedPromise2 = new Promise();
var completed = 0;
TestHelpers.VerifyDoesntThrowUnhandledException(() =>
{
promise
.ThenAll(() => EnumerableExt.FromItems(chainedPromise1, chainedPromise2)
.Cast<IPromise>())
.Then(() => ++completed);
Assert.Equal(0, completed);
promise.Resolve();
Assert.Equal(0, completed);
chainedPromise1.Resolve();
Assert.Equal(0, completed);
chainedPromise2.Resolve();
Assert.Equal(1, completed);
});
}
[Fact]
public void chain_multiple_promises_using_all_that_are_resolved_out_of_order()
{
var promise = new Promise();
var chainedPromise1 = new Promise<int>();
var chainedPromise2 = new Promise<int>();
const int chainedResult1 = 10;
const int chainedResult2 = 15;
var completed = 0;
TestHelpers.VerifyDoesntThrowUnhandledException(() =>
{
promise
.ThenAll(() => EnumerableExt.FromItems(chainedPromise1, chainedPromise2)
.Cast<IPromise<int>>())
.Then(result =>
{
var items = result.ToArray();
Assert.Equal(2, items.Length);
Assert.Equal(chainedResult1, items[0]);
Assert.Equal(chainedResult2, items[1]);
++completed;
});
Assert.Equal(0, completed);
promise.Resolve();
Assert.Equal(0, completed);
chainedPromise1.Resolve(chainedResult1);
Assert.Equal(0, completed);
chainedPromise2.Resolve(chainedResult2);
Assert.Equal(1, completed);
});
}
[Fact]
public void chain_multiple_value_promises_using_all_resolved_out_of_order()
{
var promise = new Promise();
var chainedPromise1 = new Promise<int>();
var chainedPromise2 = new Promise<int>();
const int chainedResult1 = 10;
const int chainedResult2 = 15;
var completed = 0;
TestHelpers.VerifyDoesntThrowUnhandledException(() =>
{
promise
.ThenAll(() => EnumerableExt.FromItems(chainedPromise1, chainedPromise2)
.Cast<IPromise<int>>())
.Then(result =>
{
var items = result.ToArray();
Assert.Equal(2, items.Length);
Assert.Equal(chainedResult1, items[0]);
Assert.Equal(chainedResult2, items[1]);
++completed;
});
Assert.Equal(0, completed);
promise.Resolve();
Assert.Equal(0, completed);
chainedPromise2.Resolve(chainedResult2);
Assert.Equal(0, completed);
chainedPromise1.Resolve(chainedResult1);
Assert.Equal(1, completed);
});
}
[Fact]
public void combined_promise_is_resolved_when_children_are_resolved()
{
var promise1 = new Promise();
var promise2 = new Promise();
TestHelpers.VerifyDoesntThrowUnhandledException(() =>
{
var all = Promise.All(EnumerableExt.FromItems<IPromise>(promise1, promise2));
var completed = 0;
all.Then(() => ++completed);
promise1.Resolve();
promise2.Resolve();
Assert.Equal(1, completed);
});
}
[Fact]
public void combined_promise_is_rejected_when_first_promise_is_rejected()
{
var promise1 = new Promise();
var promise2 = new Promise();
TestHelpers.VerifyDoesntThrowUnhandledException(() =>
{
var all = Promise.All(EnumerableExt.FromItems<IPromise>(promise1, promise2));
var errors = 0;
all.Catch(e => ++errors);
promise1.Reject(new Exception("Error!"));
promise2.Resolve();
Assert.Equal(1, errors);
});
}
[Fact]
public void combined_promise_is_rejected_when_second_promise_is_rejected()
{
var promise1 = new Promise();
var promise2 = new Promise();
TestHelpers.VerifyDoesntThrowUnhandledException(() => {
var all = Promise.All(EnumerableExt.FromItems<IPromise>(promise1, promise2));
var errors = 0;
all.Catch(e => { ++errors; });
promise1.Resolve();
promise2.Reject(new Exception("Error!"));
Assert.Equal(1, errors);
});
}
[Fact]
public void combined_promise_is_rejected_when_both_promises_are_rejected()
{
var promise1 = new Promise();
var promise2 = new Promise();
TestHelpers.VerifyDoesntThrowUnhandledException(() =>
{
var all = Promise.All(EnumerableExt.FromItems<IPromise>(promise1, promise2));
var errors = 0;
all.Catch(e => ++errors);
promise1.Reject(new Exception("Error!"));
promise2.Reject(new Exception("Error!"));
Assert.Equal(1, errors);
});
}
[Fact]
public void combined_promise_is_resolved_if_there_are_no_promises()
{
TestHelpers.VerifyDoesntThrowUnhandledException(() =>
{
var all = Promise.All(Enumerable.Empty<IPromise>());
var completed = 0;
all.Then(() => ++completed);
Assert.Equal(1, completed);
});
}
[Fact]
public void combined_promise_is_resolved_when_all_promises_are_already_resolved()
{
var promise1 = Promise.Resolved();
var promise2 = Promise.Resolved();
TestHelpers.VerifyDoesntThrowUnhandledException(() =>
{
var all = Promise.All(EnumerableExt.FromItems(promise1, promise2));
var completed = 0;
all.Then(() => ++completed);
Assert.Equal(1, completed);
});
}
[Fact]
public void all_with_rejected_promise()
{
bool resolved = false;
bool rejected = false;
Exception caughtException = null;
Exception exception = new Exception();
var promiseA = new Promise();
var promise = Promise
.All(promiseA, Promise.Rejected(exception))
.Then(() => resolved = true)
.Catch(ex =>
{
caughtException = ex;
rejected = true;
});
promiseA.ReportProgress(0.5f);
promiseA.Resolve();
Assert.Equal(false, resolved);
Assert.Equal(true, rejected);
Assert.Equal(exception, caughtException);
}
[Fact]
public void exception_thrown_during_transform_rejects_promise()
{
var promise = new Promise();
var errors = 0;
var ex = new Exception();
promise
.Then(() => throw ex)
.Catch(e =>
{
Assert.Equal(ex, e);
++errors;
});
promise.Resolve();
Assert.Equal(1, errors);
}
[Fact]
public void can_chain_promise()
{
var promise = new Promise();
var chainedPromise = new Promise();
var completed = 0;
promise
.Then(() => chainedPromise)
.Then(() => ++completed);
promise.Resolve();
chainedPromise.Resolve();
Assert.Equal(1, completed);
}
[Fact]
public void can_chain_promise_and_convert_to_promise_that_yields_a_value()
{
var promise = new Promise();
var chainedPromise = new Promise<string>();
const string chainedPromiseValue = "some-value";
var completed = 0;
promise
.Then(() => chainedPromise)
.Then(v =>
{
Assert.Equal(chainedPromiseValue, v);
++completed;
});
promise.Resolve();
chainedPromise.Resolve(chainedPromiseValue);
Assert.Equal(1, completed);
}
[Fact]
public void exception_thrown_in_chain_rejects_resulting_promise()
{
var promise = new Promise();
var ex = new Exception();
var errors = 0;
promise
.Then(() => throw ex)
.Catch(e =>
{
Assert.Equal(ex, e);
++errors;
});
promise.Resolve();
Assert.Equal(1, errors);
}
[Fact]
public void rejection_of_source_promise_rejects_chained_promise()
{
var promise = new Promise();
var chainedPromise = new Promise();
var ex = new Exception();
var errors = 0;
promise
.Then(() => chainedPromise)
.Catch(e =>
{
Assert.Equal(ex, e);
++errors;
});
promise.Reject(ex);
Assert.Equal(1, errors);
}
[Fact]
public void race_is_resolved_when_first_promise_is_resolved_first()
{
var promise1 = new Promise();
var promise2 = new Promise();
var completed = 0;
TestHelpers.VerifyDoesntThrowUnhandledException(() =>
{
Promise
.Race(promise1, promise2)
.Then(() => ++completed);
promise1.Resolve();
Assert.Equal(1, completed);
});
}
[Fact]
public void race_is_resolved_when_second_promise_is_resolved_first()
{
var promise1 = new Promise();
var promise2 = new Promise();
var completed = 0;
TestHelpers.VerifyDoesntThrowUnhandledException(() =>
{
Promise
.Race(promise1, promise2)
.Then(() => ++completed);
promise2.Resolve();
Assert.Equal(1, completed);
});
}
[Fact]
public void race_is_rejected_when_first_promise_is_rejected_first()
{
var promise1 = new Promise();
var promise2 = new Promise();
Exception ex = null;
TestHelpers.VerifyDoesntThrowUnhandledException(() =>
{
Promise
.Race(promise1, promise2)
.Catch(e => ex = e);
var expected = new Exception();
promise1.Reject(expected);
Assert.Equal(expected, ex);
});
}
[Fact]
public void race_is_rejected_when_second_promise_is_rejected_first()
{
var promise1 = new Promise();
var promise2 = new Promise();
Exception ex = null;
TestHelpers.VerifyDoesntThrowUnhandledException(() =>
{
Promise
.Race(promise1, promise2)
.Catch(e => ex = e);
var expected = new Exception();
promise2.Reject(expected);
Assert.Equal(expected, ex);
});
}
[Fact]
public void sequence_with_no_operations_is_directly_resolved()
{
var completed = 0;
Promise
.Sequence()
.Then(() => ++completed);
Assert.Equal(1, completed);
}
[Fact]
public void sequenced_is_not_resolved_when_operation_is_not_resolved()
{
var completed = 0;
Promise
.Sequence(() => new Promise())
.Then(() => ++completed);
Assert.Equal(0, completed);
}
[Fact]
public void sequence_is_resolved_when_operation_is_resolved()
{
var completed = 0;
Promise
.Sequence(Promise.Resolved)
.Then(() => ++completed);
Assert.Equal(1, completed);
}
[Fact]
public void sequence_is_unresolved_when_some_operations_are_unresolved()
{
var completed = 0;
Promise
.Sequence(
Promise.Resolved,
() => new Promise()
)
.Then(() => ++completed);
Assert.Equal(0, completed);
}
[Fact]
public void sequence_is_resolved_when_all_operations_are_resolved()
{
var completed = 0;
Promise
.Sequence(Promise.Resolved, Promise.Resolved)
.Then(() => ++completed);
Assert.Equal(1, completed);
}
[Fact]
public void sequenced_operations_are_run_in_order_is_directly_resolved()
{
var order = 0;
Promise
.Sequence(
() =>
{
Assert.Equal(1, ++order);
return Promise.Resolved();
},
() =>
{
Assert.Equal(2, ++order);
return Promise.Resolved();
},
() =>
{
Assert.Equal(3, ++order);
return Promise.Resolved();
}
);
Assert.Equal(3, order);
}
[Fact]
public void exception_thrown_in_sequence_rejects_the_promise()
{
var errored = 0;
var completed = 0;
var ex = new Exception();
Promise
.Sequence(() => throw ex)
.Then(() => ++completed)
.Catch(e =>
{
Assert.Equal(ex, e);
++errored;
});
Assert.Equal(1, errored);
Assert.Equal(0, completed);
}
[Fact]
public void exception_thrown_in_sequence_stops_following_operations_from_being_invoked()
{
var completed = 0;
Promise
.Sequence(
() =>
{
++completed;
return Promise.Resolved();
},
() => throw new Exception(),
() =>
{
++completed;
return Promise.Resolved();
}
);
Assert.Equal(1, completed);
}
[Fact]
public void can_resolve_promise_via_resolver_function()
{
var promise = new Promise((resolve, reject) =>
{
resolve();
});
var completed = 0;
promise.Then(() =>
{
++completed;
});
Assert.Equal(1, completed);
}
[Fact]
public void can_reject_promise_via_reject_function()
{
var ex = new Exception();
var promise = new Promise((resolve, reject) =>
{
reject(ex);
});
var completed = 0;
promise.Catch(e =>
{
Assert.Equal(ex, e);
++completed;
});
Assert.Equal(1, completed);
}
[Fact]
public void exception_thrown_during_resolver_rejects_proimse()
{
var ex = new Exception();
var promise = new Promise((resolve, reject) => throw ex);
var completed = 0;
promise.Catch(e =>
{
Assert.Equal(ex, e);
++completed;
});
Assert.Equal(1, completed);
}
[Fact]
public void unhandled_exception_is_propagated_via_event()
{
var promise = new Promise();
var ex = new Exception();
var eventRaised = 0;
EventHandler<ExceptionEventArgs> handler = (s, e) =>
{
Assert.Equal(ex, e.Exception);
++eventRaised;
};
Promise.UnhandledException += handler;
try
{
promise
.Then(() => throw ex)
.Done();
promise.Resolve();
Assert.Equal(1, eventRaised);
}
finally
{
Promise.UnhandledException -= handler;
}
}
[Fact]
public void exception_in_done_callback_is_propagated_via_event()
{
var promise = new Promise();
var ex = new Exception();
var eventRaised = 0;
EventHandler<ExceptionEventArgs> handler = (s, e) =>
{
Assert.Equal(ex, e.Exception);
++eventRaised;
};
Promise.UnhandledException += handler;
try
{
promise
.Done(() => throw ex);
promise.Resolve();
Assert.Equal(1, eventRaised);
}
finally
{
Promise.UnhandledException -= handler;
}
}
[Fact]
public void handled_exception_is_not_propagated_via_event()
{
var promise = new Promise();
var ex = new Exception();
var eventRaised = 0;
EventHandler<ExceptionEventArgs> handler = (s, e) => ++eventRaised;
Promise.UnhandledException += handler;
try
{
promise
.Then(() => throw ex)
.Catch(_ =>
{
// Catch the error.
})
.Done();
promise.Resolve();
Assert.Equal(0, eventRaised);
}
finally
{
Promise.UnhandledException -= handler;
}
}
[Fact]
public void can_handle_Done_onResolved()
{
var promise = new Promise();
var callback = 0;
promise.Done(() => ++callback);
promise.Resolve();
Assert.Equal(1, callback);
}
[Fact]
public void can_handle_Done_onResolved_with_onReject()
{
var promise = new Promise();
var callback = 0;
var errorCallback = 0;
promise.Done(
() => ++callback,
ex => ++errorCallback
);
promise.Resolve();
Assert.Equal(1, callback);
Assert.Equal(0, errorCallback);
}
/*todo:
* Also want a test that exception thrown during Then triggers the error handler.
* How do Javascript promises work in this regard?
[Fact]
public void exception_during_Done_onResolved_triggers_error_hander()
{
var promise = new Promise();
var callback = 0;
var errorCallback = 0;
var expectedValue = 5;
var expectedException = new Exception();
promise.Done(
value =>
{
Assert.Equal(expectedValue, value);
++callback;
throw expectedException;
},
ex =>
{
Assert.Equal(expectedException, ex);
++errorCallback;
}
);
promise.Resolve(expectedValue);
Assert.Equal(1, callback);
Assert.Equal(1, errorCallback);
}
* */
[Fact]
public void exception_during_Then_onResolved_triggers_error_hander()
{
var promise = new Promise();
var callback = 0;
var errorCallback = 0;
var expectedException = new Exception();
promise
.Then(() => throw expectedException)
.Done(
() => ++callback,
ex =>
{
Assert.Equal(expectedException, ex);
++errorCallback;
}
);
promise.Resolve();
Assert.Equal(0, callback);
Assert.Equal(1, errorCallback);
}
[Fact]
public void inner_exception_handled_by_outer_promise()
{
var promise = new Promise();
var errorCallback = 0;
var expectedException = new Exception();
var eventRaised = 0;
EventHandler<ExceptionEventArgs> handler = (s, e) => ++eventRaised;
Promise.UnhandledException += handler;
try
{
promise
.Then(() => Promise.Resolved().Then(() => throw expectedException))
.Catch(ex =>
{
Assert.Equal(expectedException, ex);
++errorCallback;
});
promise.Resolve();
// No "done" in the chain, no generic event handler should be called
Assert.Equal(0, eventRaised);
// Instead the catch should have got the exception
Assert.Equal(1, errorCallback);
}
finally
{
Promise.UnhandledException -= handler;
}
}
[Fact]
public void inner_exception_handled_by_outer_promise_with_results()
{
var promise = new Promise<int>();
var errorCallback = 0;
var expectedException = new Exception();
var eventRaised = 0;
EventHandler<ExceptionEventArgs> handler = (s, e) => ++eventRaised;
Promise.UnhandledException += handler;
try
{
promise
.Then(_ => Promise<int>.Resolved(5).Then(__ => throw expectedException))
.Catch(ex =>
{
Assert.Equal(expectedException, ex);
++errorCallback;
});
promise.Resolve(2);
// No "done" in the chain, no generic event handler should be called
Assert.Equal(0, eventRaised);
// Instead the catch should have got the exception
Assert.Equal(1, errorCallback);
}
finally
{
Promise.UnhandledException -= handler;
}
}
[Fact]
public void promises_have_sequential_ids()
{
var promise1 = new Promise();
var promise2 = new Promise();
Assert.Equal(promise1.Id + 1, promise2.Id);
}
[Fact]
public void finally_is_called_after_resolve()
{
var promise = new Promise();
var callback = 0;
promise.Finally(() => ++callback);
promise.Resolve();
Assert.Equal(1, callback);
}
[Fact]
public void finally_is_called_after_reject()
{
var promise = new Promise();
var callback = 0;
promise.Finally(() => ++callback);
promise.Reject(new Exception());
Assert.Equal(1, callback);
}
[Fact]
public void resolved_chain_continues_after_finally()
{
var promise = new Promise();
var callback = 0;
promise.Finally(() => ++callback)
.Then(() => ++callback);
promise.Resolve();
Assert.Equal(2, callback);
}
[Fact]
public void rejected_chain_rejects_after_finally()
{
var promise = new Promise();
var callback = 0;
promise.Finally(() => ++callback)
.Catch(_ => ++callback);
promise.Reject(new Exception());
Assert.Equal(2, callback);
}
[Fact]
public void rejected_chain_continues_after_ContinueWith_returning_non_value_promise() {
var promise = new Promise();
var callback = 0;
promise.ContinueWith(() =>
{
++callback;
return Promise.Resolved();
})
.Then(() => ++callback);
promise.Reject(new Exception());
Assert.Equal(2, callback);
}
[Fact]
public void rejected_chain_continues_after_ContinueWith_returning_value_promise() {
var promise = new Promise();
var callback = 0;
const string expectedValue = "foo";
promise.ContinueWith(() => {
++callback;
return Promise<string>.Resolved("foo");
})
.Then(x => {
Assert.Equal(expectedValue, x);
++callback;
});
promise.Reject(new Exception());
Assert.Equal(2, callback);
}
[Fact]
//tc39 note: "a throw (or returning a rejected promise) in the finally callback will reject the new promise with that rejection reason."
public void exception_in_finally_callback_is_caught_by_chained_catch()
{
//NOTE: Also tests that the new exception is passed thru promise chain
var promise = new Promise();
var callback = 0;
var expectedException = new Exception("Expected");
promise.Finally(() =>
{
++callback;
throw expectedException;
})
.Catch(ex =>
{
Assert.Equal(expectedException, ex);
++callback;
});
promise.Reject(new Exception());
Assert.Equal(2, callback);
}
[Fact]
public void exception_in_ContinueWith_callback_returning_non_value_promise_is_caught_by_chained_catch()
{
//NOTE: Also tests that the new exception is passed thru promise chain
var promise = new Promise();
var callback = 0;
var expectedException = new Exception("Expected");
promise.ContinueWith(() =>
{
++callback;
throw expectedException;
})
.Catch(ex =>
{
Assert.Equal(expectedException, ex);
++callback;
});
promise.Reject(new Exception());
Assert.Equal(2, callback);
}
[Fact]
public void exception_in_ContinueWith_callback_returning_value_promise_is_caught_by_chained_catch()
{
//NOTE: Also tests that the new exception is passed through promise chain
var promise = new Promise();
var callback = 0;
var expectedException = new Exception("Expected");
promise.ContinueWith(new Func<IPromise<int>>(() =>
{
++callback;
throw expectedException;
}))
.Catch(ex =>
{
Assert.Equal(expectedException, ex);
++callback;
});
promise.Reject(new Exception());
Assert.Equal(2, callback);
}
[Fact]
public void can_chain_promise_after_ContinueWith()
{
var promise = new Promise();
const int expectedValue = 5;
var callback = 0;
promise.ContinueWith(() =>
{
++callback;
return Promise<int>.Resolved(expectedValue);
})
.Then(x =>
{
Assert.Equal(expectedValue, x);
++callback;
});
promise.Resolve();
Assert.Equal(2, callback);
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Collections.Generic;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Abstract class front end to <see cref="SharpDX.Direct3D11.Texture1D"/>.
/// </summary>
public abstract class Texture1DBase : Texture
{
protected readonly new Direct3D11.Texture1D Resource;
private DXGI.Surface dxgiSurface;
/// <summary>
/// Initializes a new instance of the <see cref="Texture1DBase" /> class.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="description1D">The description.</param>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
protected internal Texture1DBase(GraphicsDevice device, Texture1DDescription description1D)
: base(device, description1D)
{
Resource = new Direct3D11.Texture1D(device, description1D);
Initialize(Resource);
}
/// <summary>
/// Initializes a new instance of the <see cref="Texture1DBase" /> class.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="description1D">The description.</param>
/// <param name="dataBox">A variable-length parameters list containing data rectangles.</param>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
protected internal Texture1DBase(GraphicsDevice device, Texture1DDescription description1D, DataBox[] dataBox)
: base(device, description1D)
{
Resource = new Direct3D11.Texture1D(device, description1D, dataBox);
Initialize(Resource);
}
/// <summary>
/// Specialised constructor for use only by derived classes.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="texture">The texture.</param>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
protected internal Texture1DBase(GraphicsDevice device, Direct3D11.Texture1D texture)
: base(device, texture.Description)
{
Resource = texture;
Initialize(Resource);
}
/// <summary>
/// Return an equivalent staging texture CPU read-writable from this instance.
/// </summary>
/// <returns></returns>
public override Texture ToStaging()
{
return new Texture1D(this.GraphicsDevice, this.Description.ToStagingDescription());
}
internal override TextureView GetShaderResourceView(Format viewFormat, ViewType viewType, int arrayOrDepthSlice, int mipIndex)
{
if ((this.Description.BindFlags & BindFlags.ShaderResource) == 0)
return null;
int arrayCount;
int mipCount;
GetViewSliceBounds(viewType, ref arrayOrDepthSlice, ref mipIndex, out arrayCount, out mipCount);
var textureViewKey = new TextureViewKey(viewFormat, viewType, arrayOrDepthSlice, mipIndex);
lock (this.shaderResourceViews)
{
TextureView srv;
// Creates the shader resource view
if (!shaderResourceViews.TryGetValue(textureViewKey, out srv))
{
// Create the view
var srvDescription = new ShaderResourceViewDescription() { Format = this.Description.Format };
// Initialize for texture arrays or texture cube
if (this.Description.ArraySize > 1)
{
// Else regular Texture1D
srvDescription.Dimension = ShaderResourceViewDimension.Texture1DArray;
srvDescription.Texture1DArray.ArraySize = arrayCount;
srvDescription.Texture1DArray.FirstArraySlice = arrayOrDepthSlice;
srvDescription.Texture1DArray.MipLevels = mipCount;
srvDescription.Texture1DArray.MostDetailedMip = mipIndex;
}
else
{
srvDescription.Dimension = ShaderResourceViewDimension.Texture1D;
srvDescription.Texture1D.MipLevels = mipCount;
srvDescription.Texture1D.MostDetailedMip = mipIndex;
}
srv = new TextureView(this, new ShaderResourceView(this.GraphicsDevice, this.Resource, srvDescription));
this.shaderResourceViews.Add(textureViewKey, ToDispose(srv));
}
return srv;
}
}
internal override UnorderedAccessView GetUnorderedAccessView(int arrayOrDepthSlice, int mipIndex)
{
if ((this.Description.BindFlags & BindFlags.UnorderedAccess) == 0)
return null;
int arrayCount = 1;
// Use Full although we are binding to a single array/mimap slice, just to get the correct index
var uavIndex = GetViewIndex(ViewType.Full, arrayOrDepthSlice, mipIndex);
lock (this.unorderedAccessViews)
{
var uav = this.unorderedAccessViews[uavIndex];
// Creates the unordered access view
if (uav == null)
{
var uavDescription = new UnorderedAccessViewDescription() {
Format = this.Description.Format,
Dimension = this.Description.ArraySize > 1 ? UnorderedAccessViewDimension.Texture1DArray : UnorderedAccessViewDimension.Texture1D
};
if (this.Description.ArraySize > 1)
{
uavDescription.Texture1DArray.ArraySize = arrayCount;
uavDescription.Texture1DArray.FirstArraySlice = arrayOrDepthSlice;
uavDescription.Texture1DArray.MipSlice = mipIndex;
}
else
{
uavDescription.Texture1D.MipSlice = mipIndex;
}
uav = new UnorderedAccessView(GraphicsDevice, Resource, uavDescription) { Tag = this };
this.unorderedAccessViews[uavIndex] = ToDispose(uav);
}
return uav;
}
}
/// <summary>
/// <see cref="SharpDX.DXGI.Surface"/> casting operator.
/// </summary>
/// <param name="from">From the Texture1D.</param>
public static implicit operator SharpDX.DXGI.Surface(Texture1DBase from)
{
// Don't bother with multithreading here
return from == null ? null : from.dxgiSurface ?? (from.dxgiSurface = from.ToDispose(from.Resource.QueryInterface<DXGI.Surface>()));
}
protected override void InitializeViews()
{
// Creates the shader resource view
if ((this.Description.BindFlags & BindFlags.ShaderResource) != 0)
{
shaderResourceViews = new Dictionary<TextureViewKey, TextureView>();
// Pre initialize by default the view on the first array/mipmap
var viewFormat = Format;
if (!FormatHelper.IsTypeless(viewFormat))
{
// Only valid for non-typeless viewformat
defaultShaderResourceView = GetShaderResourceView(viewFormat, ViewType.Full, 0, 0);
}
}
// Creates the unordered access view
if ((this.Description.BindFlags & BindFlags.UnorderedAccess) != 0)
{
// Initialize the unordered access views
this.unorderedAccessViews = new UnorderedAccessView[GetViewCount()];
// Pre initialize by default the view on the first array/mipmap
GetUnorderedAccessView(0, 0);
}
}
protected static Texture1DDescription NewDescription(int width, PixelFormat format, TextureFlags textureFlags, int mipCount, int arraySize, ResourceUsage usage)
{
if ((textureFlags & TextureFlags.UnorderedAccess) != 0)
usage = ResourceUsage.Default;
var desc = new Texture1DDescription()
{
Width = width,
ArraySize = arraySize,
BindFlags = GetBindFlagsFromTextureFlags(textureFlags),
Format = format,
MipLevels = CalculateMipMapCount(mipCount, width),
Usage = usage,
CpuAccessFlags = GetCpuAccessFlagsFromUsage(usage),
OptionFlags = ResourceOptionFlags.None
};
// If the texture is a RenderTarget + ShaderResource + MipLevels > 1, then allow for GenerateMipMaps method
if ((desc.BindFlags & BindFlags.RenderTarget) != 0 && (desc.BindFlags & BindFlags.ShaderResource) != 0 && desc.MipLevels > 1)
{
desc.OptionFlags |= ResourceOptionFlags.GenerateMipMaps;
}
return desc;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Web;
using System.Web.UI.WebControls;
using ASC.Core.Tenants;
using ASC.Data.Storage;
using ASC.Web.Community.Modules.Wiki.Resources;
using ASC.Web.UserControls.Wiki.Data;
using ASC.Web.UserControls.Wiki.Handlers;
using IO = System.IO;
namespace ASC.Web.UserControls.Wiki.UC
{
public partial class EditFile : BaseUserControl
{
public string FileName
{
get
{
return ViewState["FileName"] == null ? string.Empty : ViewState["FileName"].ToString();
}
set { ViewState["FileName"] = value; }
}
private File _fileInfo;
protected File CurrentFile
{
get
{
if (_fileInfo == null)
{
if (string.IsNullOrEmpty(FileName))
return null;
_fileInfo = Wiki.GetFile(FileName);
}
return _fileInfo;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
if (CurrentFile != null && !string.IsNullOrEmpty(CurrentFile.FileName))
{
RisePublishVersionInfo(CurrentFile);
}
}
protected string GetUploadFileName()
{
return CurrentFile == null ? string.Empty : CurrentFile.UploadFileName;
}
protected string GetFileLink()
{
var file = Wiki.GetFile(FileName);
if (file == null)
{
RisePageEmptyEvent();
return string.Empty; // "nonefile.png";
}
var ext = file.FileLocation.Split('.')[file.FileLocation.Split('.').Length - 1];
if (!string.IsNullOrEmpty(ext) && !WikiFileHandler.ImageExtentions.Contains(ext.ToLower()))
{
return string.Format(@"<a class=""linkMedium"" href=""{0}"" title=""{1}"">{2}</a>",
ResolveUrl(string.Format(ImageHandlerUrlFormat, FileName)),
file.FileName,
WikiUCResource.wikiFileDownloadCaption);
}
return string.Format(@"<img src=""{0}"" style=""max-width:300px; max-height:200px"" />",
ResolveUrl(string.Format(ImageHandlerUrlFormat, FileName)));
}
private static string GetFileLocation(string fileName)
{
var letter = (byte)fileName[0];
var secondFolder = letter.ToString("x");
var firstFolder = secondFolder.Substring(0, 1);
var fileLocation = IO.Path.Combine(firstFolder, secondFolder);
fileLocation = IO.Path.Combine(fileLocation, EncodeSafeName(fileName)); //TODO: encode nameprep here
return fileLocation;
}
private static string EncodeSafeName(string fileName)
{
return fileName;
}
public static void DeleteTempContent(string fileName, string configLocation, WikiSection section, int tenantId, HttpContext context)
{
var storage = StorageFactory.GetStorage(tenantId.ToString(), section.DataStorage.ModuleName);
storage.Delete(section.DataStorage.TempDomain, fileName);
}
public static void DeleteContent(string fileName, string configLocation, WikiSection section, int tenantId, HttpContext context)
{
var storage = StorageFactory.GetStorage(tenantId.ToString(), section.DataStorage.ModuleName);
storage.Delete(section.DataStorage.DefaultDomain, fileName);
}
public static SaveResult MoveContentFromTemp(Guid userId, string fromFileName, string toFileName, string configLocation, WikiSection section, int tenantId, HttpContext context, string rootFile, out string _fileName)
{
var storage = StorageFactory.GetStorage(tenantId.ToString(), section.DataStorage.ModuleName);
var fileName = toFileName;
var fileLocation = GetFileLocation(fileName);
var file = new File
{
FileName = fileName,
UploadFileName = fileName,
UserID = userId,
FileLocation = fileLocation,
FileSize = (int)storage.GetFileSize(section.DataStorage.TempDomain, fromFileName),
};
var wiki = new WikiEngine();
wiki.SaveFile(file);
storage.Move(section.DataStorage.TempDomain, fromFileName, section.DataStorage.DefaultDomain, fileLocation);
_fileName = file.FileName;
return SaveResult.Ok;
}
public static SaveResult DirectFileSave(Guid userId, FileUpload fuFile, string rootFile, WikiSection section, string configLocation, int tenantId, HttpContext context)
{
if (!fuFile.HasFile)
return SaveResult.FileEmpty;
var wikiEngine = new WikiEngine();
File file = null;
try
{
file = wikiEngine.CreateOrUpdateFile(new File { FileName = fuFile.FileName, FileSize = fuFile.FileBytes.Length });
FileContentSave(file.FileLocation, fuFile.FileBytes, section, configLocation, tenantId, context);
}
catch (TenantQuotaException)
{
if (file != null)
wikiEngine.RemoveFile(file.FileName);
return SaveResult.FileSizeExceeded;
}
return SaveResult.Ok;
}
private static void FileContentSave(string location, byte[] fileContent, WikiSection section, string configLocation, int tenantId, HttpContext context)
{
var storage = StorageFactory.GetStorage(tenantId.ToString(), section.DataStorage.ModuleName);
FileContentSave(storage, location, fileContent, section);
}
private static void FileContentSave(string location, byte[] fileContent, WikiSection section, int tenantId)
{
var storage = StorageFactory.GetStorage(tenantId.ToString(), section.DataStorage.ModuleName);
FileContentSave(storage, location, fileContent, section);
}
private static void FileContentSave(IDataStore storage, string location, byte[] fileContent, WikiSection section)
{
using (var ms = new IO.MemoryStream(fileContent))
{
storage.Save(section.DataStorage.DefaultDomain, location, ms);
}
}
public SaveResult Save(Guid userId)
{
string fileName;
return Save(userId, out fileName);
}
public SaveResult Save(Guid userId, out string fileName)
{
fileName = string.Empty;
if (!fuFile.HasFile)
return SaveResult.FileEmpty;
var file = CurrentFile ?? new File { FileName = fuFile.FileName, UploadFileName = fuFile.FileName };
file.FileSize = fuFile.FileBytes.Length;
file = Wiki.CreateOrUpdateFile(file);
try
{
FileContentSave(file.FileLocation, fuFile.FileBytes, WikiSection.Section, TenantId);
}
catch (TenantQuotaException)
{
Wiki.RemoveFile(file.FileName);
return SaveResult.FileSizeExceeded;
}
_fileInfo = file;
RisePublishVersionInfo(file);
fileName = file.FileName;
return SaveResult.Ok;
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Gallio.Common.Splash.Native;
namespace Gallio.Common.Splash.Internal
{
/// <summary>
/// Internal structure with script information necessary for layout and display of a paragraph.
/// Includes script information for each run in the paragraph.
/// </summary>
/// <remarks>
/// We pool allocated script paragraph structures and cache them to improve performance
/// and reduce the number of memory allocations.
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct ScriptParagraph
{
private const int InitialCapacityForCharsPerParagraph = 64;
private const int InitialCapacityForScriptRunsPerParagraph = 8;
private const int InitialCapacityForGlyphsPerParagraph = 64 * 3 / 2 + 16;
public int CharIndex;
public int CharCount;
public int CharCapacity;
public ushort* CharLogicalClusters; // 1 element per character
public SCRIPT_LOGATTR* CharLogicalAttributes; // 1 element per character
public int ScriptRunCount;
public int ScriptRunCapacity;
public ScriptRun* ScriptRuns; // 1 element per script run
public int GlyphCount;
public int GlyphCapacity;
public ushort* Glyphs; // 1 element per glyph
public SCRIPT_VISATTR* GlyphVisualAttributes; // 1 element per glyph
public int* GlyphAdvanceWidths; // 1 element per glyph
public GOFFSET* GlyphOffsets; // 1 element per glyph
public char* Chars(char* charZero)
{
return charZero + CharIndex;
}
public void Initialize()
{
InitializeCharBuffers();
InitializeScriptRunBuffers();
InitializeGlyphBuffers();
}
public void Free()
{
FreeCharBuffers();
FreeScriptRunBuffers();
FreeGlyphBuffers();
}
public void EnsureCharCapacity(int capacity)
{
if (CharCapacity < capacity)
{
FreeCharBuffers();
CharCapacity = NewCapacity(CharCapacity, InitialCapacityForCharsPerParagraph, capacity);
AllocCharBuffers();
}
}
public void EnsureScriptRunCapacity(int capacity)
{
if (ScriptRunCapacity < capacity)
{
FreeScriptRunBuffers();
ScriptRunCapacity = NewCapacity(ScriptRunCapacity, InitialCapacityForScriptRunsPerParagraph, capacity);
AllocScriptRunBuffers();
}
}
public void EnsureGlyphCapacityAndPreserveContents(int capacity)
{
if (GlyphCapacity < capacity)
{
int newGlyphCapacity = NewCapacity(GlyphCapacity, InitialCapacityForGlyphsPerParagraph, capacity);
ReAllocGlyphBuffers(newGlyphCapacity);
GlyphCapacity = newGlyphCapacity;
}
}
private void InitializeCharBuffers()
{
CharCapacity = 0;
CharLogicalClusters = null;
CharLogicalAttributes = null;
}
private void AllocCharBuffers()
{
CharLogicalClusters = (ushort*)Memory.Alloc(CharCapacity * sizeof(ushort));
CharLogicalAttributes = (SCRIPT_LOGATTR*)Memory.Alloc(CharCapacity * sizeof(SCRIPT_LOGATTR));
}
private void FreeCharBuffers()
{
CharCapacity = 0;
if (CharLogicalClusters != null)
{
Memory.Free(CharLogicalClusters);
CharLogicalClusters = null;
}
if (CharLogicalAttributes != null)
{
Memory.Free(CharLogicalAttributes);
CharLogicalAttributes = null;
}
}
private void InitializeScriptRunBuffers()
{
ScriptRunCapacity = 0;
ScriptRuns = null;
}
private void AllocScriptRunBuffers()
{
ScriptRuns = (ScriptRun*)Memory.Alloc(ScriptRunCapacity * sizeof(ScriptRun));
}
private void FreeScriptRunBuffers()
{
ScriptRunCapacity = 0;
if (ScriptRuns != null)
{
Memory.Free(ScriptRuns);
ScriptRuns = null;
}
}
private void InitializeGlyphBuffers()
{
GlyphCapacity = 0;
Glyphs = null;
GlyphVisualAttributes = null;
GlyphAdvanceWidths = null;
GlyphOffsets = null;
}
private void ReAllocGlyphBuffers(int newGlyphCapacity)
{
Glyphs = (ushort*)Memory.ReAlloc(Glyphs, newGlyphCapacity * sizeof(ushort));
GlyphVisualAttributes = (SCRIPT_VISATTR*)Memory.ReAlloc(GlyphVisualAttributes, newGlyphCapacity * sizeof(SCRIPT_VISATTR));
GlyphAdvanceWidths = (int*)Memory.ReAlloc(GlyphAdvanceWidths, newGlyphCapacity * sizeof(int));
GlyphOffsets = (GOFFSET*)Memory.ReAlloc(GlyphOffsets, newGlyphCapacity * sizeof(GOFFSET));
}
private void FreeGlyphBuffers()
{
GlyphCapacity = 0;
if (Glyphs != null)
{
Memory.Free(Glyphs);
Glyphs = null;
}
if (GlyphVisualAttributes != null)
{
Memory.Free(GlyphVisualAttributes);
GlyphVisualAttributes = null;
}
if (GlyphAdvanceWidths != null)
{
Memory.Free(GlyphAdvanceWidths);
GlyphAdvanceWidths = null;
}
if (GlyphOffsets != null)
{
Memory.Free(GlyphOffsets);
GlyphOffsets = null;
}
}
private static int NewCapacity(int currentCapacity, int initialCapacity, int desiredCapacity)
{
int newCapacity = Math.Max(currentCapacity, initialCapacity);
while (newCapacity < desiredCapacity)
newCapacity *= 2;
return newCapacity;
}
}
}
| |
#if NET_2_0
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Security.Permissions;
using System.Web;
using System.Web.Profile;
using Spring.Context.Support;
namespace Spring.Web.Providers
{
/// <summary>
/// Wrapper for <see cref="System.Web.Profile.ProfileProvider"/> class.
/// </summary>
/// <remarks>
/// <p>
/// Configuration for this provider <b>requires</b> <c>providerId</c> element set in web.config file,
/// as the Id of wrapped provider (defined in the Spring context).
/// </p>
/// </remarks>
/// <author>Damjan Tomic</author>
[AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class ProfileProviderAdapter : ProfileProvider, IProfileProvider
{
#region Field
/// <summary>
/// Reference to wrapped provider (defined in Spring context).
/// </summary>
private ProfileProvider wrappedProvider;
#endregion
#region ProviderBase members
///<summary>
///Initializes the provider.
///</summary>
///
///<param name="config">A collection of the name/value pairs representing the provider-specific
/// attributes specified in the configuration for this provider.
/// The <c>providerId</c> attribute may be used to override the name being used for looking up an object definition.
/// </param>
///<param name="name">The friendly name of the provider.</param>
///<exception cref="T:System.ArgumentNullException">The <paramref name="name"/> or <paramref name="config"/> is null.</exception>
///<exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider has already been initialized.</exception>
///<exception cref="T:System.ArgumentException">The <paramref name="name"/> has a length of zero or providerId attribute is not set.</exception>
public override void Initialize(string name, NameValueCollection config)
{
lock (this)
{
if (config == null) throw new ArgumentNullException("config");
string providerId = config["providerId"];
if (String.IsNullOrEmpty(providerId))
providerId = name;
config.Remove("providerId");
this.wrappedProvider = (ProfileProvider)WebApplicationContext.GetRootContext().GetObject(providerId);
this.wrappedProvider.Initialize(name, config);
}
}
///<summary>
///Gets the friendly name used to refer to the provider during configuration.
///</summary>
///
///<returns>
///The friendly name used to refer to the provider during configuration.
///</returns>
public override string Name
{
get { return this.wrappedProvider.Name; }
}
///<summary>
///Gets a brief, friendly description suitable for display in administrative tools or other user interfaces (UIs).
///</summary>
///
///<returns>
///A brief, friendly description suitable for display in administrative tools or other UIs.
///</returns>
public override string Description
{
get { return this.wrappedProvider.Description; }
}
#endregion
#region System.Web.Profile.ProfileProvider members
///<summary>
///Returns the collection of settings property values for the specified application instance and settings property group.
///</summary>
///
///<returns>
///A <see cref="T:System.Configuration.SettingsPropertyValueCollection"></see> containing the values for the specified settings property group.
///</returns>
///
///<param name="context">A <see cref="T:System.Configuration.SettingsContext"></see> describing the current application use.</param>
///<param name="collection">A <see cref="T:System.Configuration.SettingsPropertyCollection"></see> containing the settings property group whose values are to be retrieved.</param><filterpriority>2</filterpriority>
public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context,
SettingsPropertyCollection collection)
{
return this.wrappedProvider.GetPropertyValues(context, collection);
}
///<summary>
///Sets the values of the specified group of property settings.
///</summary>
///
///<param name="context">A <see cref="T:System.Configuration.SettingsContext"></see> describing the current application usage.</param>
///<param name="collection">A <see cref="T:System.Configuration.SettingsPropertyValueCollection"></see> representing the group of property settings to set.</param><filterpriority>2</filterpriority>
public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
{
this.wrappedProvider.SetPropertyValues(context,collection);
}
///<summary>
///Gets or sets the name of the currently running application.
///</summary>
///
///<returns>
///A <see cref="T:System.String"></see> that contains the application's shortened name, which does not contain a full path or extension, for example, SimpleAppSettings.
///</returns>
///<filterpriority>2</filterpriority>
public override string ApplicationName
{
get { return this.wrappedProvider.ApplicationName; }
set { this.wrappedProvider.ApplicationName = value; }
}
///<summary>
///When overridden in a derived class, deletes profile properties and information for the supplied list of profiles.
///</summary>
///
///<returns>
///The number of profiles deleted from the data source.
///</returns>
///
///<param name="profiles">A <see cref="T:System.Web.Profile.ProfileInfoCollection"></see> of information about profiles that are to be deleted.</param>
public override int DeleteProfiles(ProfileInfoCollection profiles)
{
return this.wrappedProvider.DeleteProfiles(profiles);
}
///<summary>
///When overridden in a derived class, deletes profile properties and information for profiles that match the supplied list of user names.
///</summary>
///
///<returns>
///The number of profiles deleted from the data source.
///</returns>
///
///<param name="usernames">A string array of user names for profiles to be deleted.</param>
public override int DeleteProfiles(string[] usernames)
{
return this.wrappedProvider.DeleteProfiles(usernames);
}
///<summary>
///When overridden in a derived class, deletes all user-profile data for profiles in which the last activity date occurred before the specified date.
///</summary>
///
///<returns>
///The number of profiles deleted from the data source.
///</returns>
///
///<param name="authenticationOption">One of the <see cref="T:System.Web.Profile.ProfileAuthenticationOption"></see> values, specifying whether anonymous, authenticated, or both types of profiles are deleted.</param>
///<param name="userInactiveSinceDate">A <see cref="T:System.DateTime"></see> that identifies which user profiles are considered inactive. If the <see cref="P:System.Web.Profile.ProfileInfo.LastActivityDate"></see> value of a user profile occurs on or before this date and time, the profile is considered inactive.</param>
public override int DeleteInactiveProfiles(ProfileAuthenticationOption authenticationOption,
DateTime userInactiveSinceDate)
{
return this.wrappedProvider.DeleteInactiveProfiles(authenticationOption, userInactiveSinceDate);
}
///<summary>
///When overridden in a derived class, returns the number of profiles in which the last activity date occurred on or before the specified date.
///</summary>
///
///<returns>
///The number of profiles in which the last activity date occurred on or before the specified date.
///</returns>
///
///<param name="authenticationOption">One of the <see cref="T:System.Web.Profile.ProfileAuthenticationOption"></see> values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param>
///<param name="userInactiveSinceDate">A <see cref="T:System.DateTime"></see> that identifies which user profiles are considered inactive. If the <see cref="P:System.Web.Profile.ProfileInfo.LastActivityDate"></see> of a user profile occurs on or before this date and time, the profile is considered inactive.</param>
public override int GetNumberOfInactiveProfiles(ProfileAuthenticationOption authenticationOption,
DateTime userInactiveSinceDate)
{
return this.wrappedProvider.GetNumberOfInactiveProfiles(authenticationOption, userInactiveSinceDate);
}
///<summary>
///When overridden in a derived class, retrieves user profile data for all profiles in the data source.
///</summary>
///
///<returns>
///A <see cref="T:System.Web.Profile.ProfileInfoCollection"></see> containing user-profile information for all profiles in the data source.
///</returns>
///
///<param name="authenticationOption">One of the <see cref="T:System.Web.Profile.ProfileAuthenticationOption"></see> values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param>
///<param name="totalRecords">When this method returns, contains the total number of profiles.</param>
///<param name="pageIndex">The index of the page of results to return.</param>
///<param name="pageSize">The size of the page of results to return.</param>
public override ProfileInfoCollection GetAllProfiles(ProfileAuthenticationOption authenticationOption,
int pageIndex, int pageSize, out int totalRecords)
{
return this.wrappedProvider.GetAllProfiles(authenticationOption, pageIndex, pageSize, out totalRecords);
}
///<summary>
///When overridden in a derived class, retrieves user-profile data from the data source for profiles in which the last activity date occurred on or before the specified date.
///</summary>
///
///<returns>
///A <see cref="T:System.Web.Profile.ProfileInfoCollection"></see> containing user-profile information about the inactive profiles.
///</returns>
///
///<param name="authenticationOption">One of the <see cref="T:System.Web.Profile.ProfileAuthenticationOption"></see> values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param>
///<param name="userInactiveSinceDate">A <see cref="T:System.DateTime"></see> that identifies which user profiles are considered inactive. If the <see cref="P:System.Web.Profile.ProfileInfo.LastActivityDate"></see> of a user profile occurs on or before this date and time, the profile is considered inactive.</param>
///<param name="totalRecords">When this method returns, contains the total number of profiles.</param>
///<param name="pageIndex">The index of the page of results to return.</param>
///<param name="pageSize">The size of the page of results to return.</param>
public override ProfileInfoCollection GetAllInactiveProfiles(ProfileAuthenticationOption authenticationOption,
DateTime userInactiveSinceDate, int pageIndex,
int pageSize, out int totalRecords)
{
return
this.wrappedProvider.GetAllInactiveProfiles(authenticationOption, userInactiveSinceDate, pageIndex, pageSize,
out totalRecords);
}
///<summary>
///When overridden in a derived class, retrieves profile information for profiles in which the user name matches the specified user names.
///</summary>
///
///<returns>
///A <see cref="T:System.Web.Profile.ProfileInfoCollection"></see> containing user-profile information for profiles where the user name matches the supplied usernameToMatch parameter.
///</returns>
///
///<param name="authenticationOption">One of the <see cref="T:System.Web.Profile.ProfileAuthenticationOption"></see> values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param>
///<param name="totalRecords">When this method returns, contains the total number of profiles.</param>
///<param name="pageIndex">The index of the page of results to return.</param>
///<param name="usernameToMatch">The user name to search for.</param>
///<param name="pageSize">The size of the page of results to return.</param>
public override ProfileInfoCollection FindProfilesByUserName(ProfileAuthenticationOption authenticationOption,
string usernameToMatch, int pageIndex, int pageSize,
out int totalRecords)
{
return
this.wrappedProvider.FindProfilesByUserName(authenticationOption, usernameToMatch, pageIndex, pageSize,
out totalRecords);
}
///<summary>
///When overridden in a derived class, retrieves profile information for profiles in which the last activity date occurred on or before the specified date and the user name matches the specified user name.
///</summary>
///
///<returns>
///A <see cref="T:System.Web.Profile.ProfileInfoCollection"></see> containing user profile information for inactive profiles where the user name matches the supplied usernameToMatch parameter.
///</returns>
///
///<param name="authenticationOption">One of the <see cref="T:System.Web.Profile.ProfileAuthenticationOption"></see> values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param>
///<param name="userInactiveSinceDate">A <see cref="T:System.DateTime"></see> that identifies which user profiles are considered inactive. If the <see cref="P:System.Web.Profile.ProfileInfo.LastActivityDate"></see> value of a user profile occurs on or before this date and time, the profile is considered inactive.</param>
///<param name="totalRecords">When this method returns, contains the total number of profiles.</param>
///<param name="pageIndex">The index of the page of results to return.</param>
///<param name="usernameToMatch">The user name to search for.</param>
///<param name="pageSize">The size of the page of results to return.</param>
public override ProfileInfoCollection FindInactiveProfilesByUserName(
ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate,
int pageIndex, int pageSize, out int totalRecords)
{
return this.wrappedProvider.FindInactiveProfilesByUserName(authenticationOption, usernameToMatch, userInactiveSinceDate,
pageIndex, pageSize, out totalRecords);
}
#endregion
}
}
#endif
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace ASC.Mail.Net.STUN.Client
{
#region usings
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Message;
#endregion
/// <summary>
/// This class implements STUN client. Defined in RFC 3489.
/// </summary>
/// <example>
/// <code>
/// // Create new socket for STUN client.
/// Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
/// socket.Bind(new IPEndPoint(IPAddress.Any,0));
///
/// // Query STUN server
/// STUN_Result result = STUN_Client.Query("stunserver.org",3478,socket);
/// if(result.NetType != STUN_NetType.UdpBlocked){
/// // UDP blocked or !!!! bad STUN server
/// }
/// else{
/// IPEndPoint publicEP = result.PublicEndPoint;
/// // Do your stuff
/// }
/// </code>
/// </example>
public class STUN_Client
{
#region Methods
/// <summary>
/// Gets NAT info from STUN server.
/// </summary>
/// <param name="host">STUN server name or IP.</param>
/// <param name="port">STUN server port. Default port is 3478.</param>
/// <param name="socket">UDP socket to use.</param>
/// <returns>Returns UDP netwrok info.</returns>
/// <exception cref="Exception">Throws exception if unexpected error happens.</exception>
public static STUN_Result Query(string host, int port, Socket socket)
{
if (host == null)
{
throw new ArgumentNullException("host");
}
if (socket == null)
{
throw new ArgumentNullException("socket");
}
if (port < 1)
{
throw new ArgumentException("Port value must be >= 1 !");
}
if (socket.ProtocolType != ProtocolType.Udp)
{
throw new ArgumentException("Socket must be UDP socket !");
}
IPEndPoint remoteEndPoint = new IPEndPoint(Dns.GetHostAddresses(host)[0], port);
socket.ReceiveTimeout = 3000;
socket.SendTimeout = 3000;
/*
In test I, the client sends a STUN Binding Request to a server, without any flags set in the
CHANGE-REQUEST attribute, and without the RESPONSE-ADDRESS attribute. This causes the server
to send the response back to the address and port that the request came from.
In test II, the client sends a Binding Request with both the "change IP" and "change port" flags
from the CHANGE-REQUEST attribute set.
In test III, the client sends a Binding Request with only the "change port" flag set.
+--------+
| Test |
| I |
+--------+
|
|
V
/\ /\
N / \ Y / \ Y +--------+
UDP <-------/Resp\--------->/ IP \------------->| Test |
Blocked \ ? / \Same/ | II |
\ / \? / +--------+
\/ \/ |
| N |
| V
V /\
+--------+ Sym. N / \
| Test | UDP <---/Resp\
| II | Firewall \ ? /
+--------+ \ /
| \/
V |Y
/\ /\ |
Symmetric N / \ +--------+ N / \ V
NAT <--- / IP \<-----| Test |<--- /Resp\ Open
\Same/ | I | \ ? / Internet
\? / +--------+ \ /
\/ \/
| |Y
| |
| V
| Full
| Cone
V /\
+--------+ / \ Y
| Test |------>/Resp\---->Restricted
| III | \ ? /
+--------+ \ /
\/
|N
| Port
+------>Restricted
*/
// Test I
STUN_Message test1 = new STUN_Message();
test1.Type = STUN_MessageType.BindingRequest;
STUN_Message test1response = DoTransaction(test1, socket, remoteEndPoint);
// UDP blocked.
if (test1response == null)
{
return new STUN_Result(STUN_NetType.UdpBlocked, null);
}
else
{
// Test II
STUN_Message test2 = new STUN_Message();
test2.Type = STUN_MessageType.BindingRequest;
test2.ChangeRequest = new STUN_t_ChangeRequest(true, true);
// No NAT.
if (socket.LocalEndPoint.Equals(test1response.MappedAddress))
{
STUN_Message test2Response = DoTransaction(test2, socket, remoteEndPoint);
// Open Internet.
if (test2Response != null)
{
return new STUN_Result(STUN_NetType.OpenInternet, test1response.MappedAddress);
}
// Symmetric UDP firewall.
else
{
return new STUN_Result(STUN_NetType.SymmetricUdpFirewall, test1response.MappedAddress);
}
}
// NAT
else
{
STUN_Message test2Response = DoTransaction(test2, socket, remoteEndPoint);
// Full cone NAT.
if (test2Response != null)
{
return new STUN_Result(STUN_NetType.FullCone, test1response.MappedAddress);
}
else
{
/*
If no response is received, it performs test I again, but this time, does so to
the address and port from the CHANGED-ADDRESS attribute from the response to test I.
*/
// Test I(II)
STUN_Message test12 = new STUN_Message();
test12.Type = STUN_MessageType.BindingRequest;
STUN_Message test12Response = DoTransaction(test12,
socket,
test1response.ChangedAddress);
if (test12Response == null)
{
throw new Exception("STUN Test I(II) dind't get resonse !");
}
else
{
// Symmetric NAT
if (!test12Response.MappedAddress.Equals(test1response.MappedAddress))
{
return new STUN_Result(STUN_NetType.Symmetric, test1response.MappedAddress);
}
else
{
// Test III
STUN_Message test3 = new STUN_Message();
test3.Type = STUN_MessageType.BindingRequest;
test3.ChangeRequest = new STUN_t_ChangeRequest(false, true);
STUN_Message test3Response = DoTransaction(test3,
socket,
test1response.ChangedAddress);
// Restricted
if (test3Response != null)
{
return new STUN_Result(STUN_NetType.RestrictedCone,
test1response.MappedAddress);
}
// Port restricted
else
{
return new STUN_Result(STUN_NetType.PortRestrictedCone,
test1response.MappedAddress);
}
}
}
}
}
}
}
/// <summary>
/// Resolves local IP to public IP using STUN.
/// </summary>
/// <param name="stunServer">STUN server.</param>
/// <param name="port">STUN server port. Default port is 3478.</param>
/// <param name="localIP">Local IP address.</param>
/// <returns>Returns public IP address.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>stunServer</b> or <b>localIP</b> is null reference.</exception>
/// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
/// <exception cref="IOException">Is raised when no connection to STUN server.</exception>
public static IPAddress GetPublicIP(string stunServer, int port, IPAddress localIP)
{
if (stunServer == null)
{
throw new ArgumentNullException("stunServer");
}
if (stunServer == "")
{
throw new ArgumentException("Argument 'stunServer' value must be specified.");
}
if (port < 1)
{
throw new ArgumentException("Invalid argument 'port' value.");
}
if (localIP == null)
{
throw new ArgumentNullException("localIP");
}
if (!Core.IsPrivateIP(localIP))
{
return localIP;
}
STUN_Result result = Query(stunServer,
port,
Core.CreateSocket(new IPEndPoint(localIP, 0), ProtocolType.Udp));
if (result.PublicEndPoint != null)
{
return result.PublicEndPoint.Address;
}
else
{
throw new IOException(
"Failed to STUN public IP address. STUN server name is invalid or firewall blocks STUN.");
}
}
#endregion
#region Utility methods
/// <summary>
/// Does STUN transaction. Returns transaction response or null if transaction failed.
/// </summary>
/// <param name="request">STUN message.</param>
/// <param name="socket">Socket to use for send/receive.</param>
/// <param name="remoteEndPoint">Remote end point.</param>
/// <returns>Returns transaction response or null if transaction failed.</returns>
private static STUN_Message DoTransaction(STUN_Message request,
Socket socket,
IPEndPoint remoteEndPoint)
{
byte[] requestBytes = request.ToByteData();
DateTime startTime = DateTime.Now;
// We do it only 2 sec and retransmit with 100 ms.
while (startTime.AddSeconds(2) > DateTime.Now)
{
try
{
socket.SendTo(requestBytes, remoteEndPoint);
// We got response.
if (socket.Poll(100, SelectMode.SelectRead))
{
byte[] receiveBuffer = new byte[512];
socket.Receive(receiveBuffer);
// Parse message
STUN_Message response = new STUN_Message();
response.Parse(receiveBuffer);
// Check that transaction ID matches or not response what we want.
if (request.TransactionID.Equals(response.TransactionID))
{
return response;
}
}
}
catch {}
}
return null;
}
private void GetSharedSecret()
{
/*
*) Open TLS connection to STUN server.
*) Send Shared Secret request.
*/
/*
using(SocketEx socket = new SocketEx()){
socket.RawSocket.ReceiveTimeout = 5000;
socket.RawSocket.SendTimeout = 5000;
socket.Connect(host,port);
socket.SwitchToSSL_AsClient();
// Send Shared Secret request.
STUN_Message sharedSecretRequest = new STUN_Message();
sharedSecretRequest.Type = STUN_MessageType.SharedSecretRequest;
socket.Write(sharedSecretRequest.ToByteData());
// TODO: Parse message
// We must get "Shared Secret" or "Shared Secret Error" response.
byte[] receiveBuffer = new byte[256];
socket.RawSocket.Receive(receiveBuffer);
STUN_Message sharedSecretRequestResponse = new STUN_Message();
if(sharedSecretRequestResponse.Type == STUN_MessageType.SharedSecretResponse){
}
// Shared Secret Error or Unknown response, just try again.
else{
// TODO: Unknown response
}
}*/
}
#endregion
}
}
| |
//=================================================================================================
//
// MSAA Filtering 2.0 Sample
// by MJP
// http://mynameismjp.wordpress.com/
//
// All code licensed under the MIT license
//
//=================================================================================================
public class Settings
{
enum MSAAModes
{
[EnumLabel("None")]
MSAANone = 0,
[EnumLabel("2x")]
MSAA2x,
[EnumLabel("4x")]
MSAA4x,
[EnumLabel("8x")]
MSAA8x,
}
enum FilterTypes
{
Box = 0,
Triangle,
Gaussian,
BlackmanHarris,
Smoothstep,
BSpline,
CatmullRom,
Mitchell,
GeneralizedCubic,
Sinc,
}
enum Scenes
{
CornellBox,
DropBoxes,
Sponza,
}
enum JitterModes
{
None,
Uniform2x,
Hammersly16,
}
enum ShadingTech
{
Forward,
Clustered_Deferred,
}
public class AntiAliasing
{
MSAAModes MSAAMode = MSAAModes.MSAA4x;
FilterTypes FilterType = FilterTypes.Smoothstep;
[MinValue(0.0f)]
[MaxValue(6.0f)]
[StepSize(0.01f)]
float FilterSize = 2.0f;
[MinValue(0.01f)]
[MaxValue(1.0f)]
[StepSize(0.01f)]
float GaussianSigma = 0.5f;
[MinValue(0.0f)]
[MaxValue(1.0f)]
[StepSize(0.01f)]
float CubicB = 0.33f;
[MinValue(0.0f)]
[MaxValue(1.0f)]
[StepSize(0.01f)]
float CubicC = 0.33f;
bool UseStandardResolve = false;
bool InverseLuminanceFiltering = true;
bool UseExposureFiltering = true;
[MinValue(-16.0f)]
[MaxValue(16.0f)]
float ExposureFilterOffset = 2.0f;
bool UseGradientMipLevel = false;
[UseAsShaderConstant(false)]
bool CentroidSampling = true;
bool EnableTemporalAA = true;
[MinValue(0.0f)]
[MaxValue(1.0f)]
float TemporalAABlendFactor = 0.5f;
bool UseTemporalColorWeighting = true;
bool ClampPrevColor = true;
[UseAsShaderConstant(false)]
JitterModes JitterMode = JitterModes.Uniform2x;
[MinValue(0.0f)]
[MaxValue(100.0f)]
float LowFreqWeight = 0.25f;
[MinValue(0.0f)]
[MaxValue(100.0f)]
float HiFreqWeight = 0.85f;
[MinValue(0.0f)]
[MaxValue(1.0f)]
float SharpeningAmount = 0.0f;
}
public class SceneControls
{
Scenes CurrentScene = Scenes.CornellBox;
ShadingTech CurrentShadingTech = ShadingTech.Clustered_Deferred;
[DisplayName("Light Direction")]
[HelpText("The direction of the light")]
Direction LightDirection = new Direction(-0.75f, 0.977f, -0.4f);
[DisplayName("Light Color")]
[HelpText("The color of the light")]
[MinValue(0.0f)]
[MaxValue(50.0f)]
[StepSize(0.1f)]
[HDR(true)]
Color LightColor = new Color(20.0f, 16.0f, 10.0f);
[DisplayName("Sky Color")]
[HelpText("The color of the sky")]
[MinValue(0.0f)]
[MaxValue(20.0f)]
[StepSize(0.1f)]
[HDR(true)]
Color SkyColor = new Color(0.1f, 0.3f, 0.7f);
bool EnableSSR = false;
bool PauseSceneScript = false;
bool EnableDirectLighting = true;
bool EnableIndirectDiffuseLighting = true;
bool EnableIndirectSpecularLighting = true;
bool RenderBackground = true;
bool RenderSceneObjectBBox = false;
bool RenderProbeBBox = false;
bool RenderIrradianceVolumeProbes = false;
bool EnableShadows = true;
bool EnableNormalMaps = true;
bool EnableRealtimeCubemap = false;
[DisplayName("Diffuse GI Bounces")]
[HelpText("The bounces of Indirect diffuse from GI")]
[MinValue(1)]
[MaxValue(10)]
[StepSize(1)]
int DiffuseGIBounces = 1;
[DisplayName("GI Intensity")]
[HelpText("The intensity of Indirect diffuse from GI")]
[MinValue(0.0f)]
[MaxValue(10.0f)]
[StepSize(0.1f)]
float DiffuseGI_Intensity = 1.0f;
[MinValue(0.0f)]
[MaxValue(1.0f)]
float NormalMapIntensity = 1.0f;
[DisplayName("Diffuse Intensity")]
[MinValue(0.0f)]
[MaxValue(1.0f)]
[StepSize(0.001f)]
[HelpText("Diffuse albedo intensity parameter for the material")]
float DiffuseIntensity = 0.5f;
[MinValue(0.001f)]
[MaxValue(1.0f)]
[StepSize(0.001f)]
[HelpText("Specular roughness parameter for the material")]
[ConversionMode(ConversionMode.Square)]
float Roughness = 0.1f;
[DisplayName("Specular Intensity")]
[MinValue(0.0f)]
[MaxValue(1.0f)]
[StepSize(0.001f)]
[HelpText("Specular intensity parameter for the material")]
float SpecularIntensity = 0.05f;
[DisplayName("Emissive Intensity")]
[MinValue(0.0f)]
[MaxValue(1.0f)]
[StepSize(0.001f)]
[HelpText("Emissive parameter for the material")]
float EmissiveIntensity = 0.00f;
[DisplayName("Probe Index")]
[MinValue(0.0f)]
[MaxValue(50.0f)]
[StepSize(1.0f)]
float ProbeIndex = 0.0f;
[DisplayName("ProbeX")]
[MinValue(-100.0f)]
[MaxValue(100.0f)]
[StepSize(0.1f)]
float ProbeX = 0.0f;
[DisplayName("ProbeY")]
[MinValue(-100.0f)]
[MaxValue(100.0f)]
[StepSize(0.1f)]
float ProbeY = 0.0f;
[DisplayName("ProbeZ")]
[MinValue(-100.0f)]
[MaxValue(100.0f)]
[StepSize(0.1f)]
float ProbeZ = 0.0f;
[DisplayName("BoxSizeX")]
[MinValue(-100.0f)]
[MaxValue(100.0f)]
[StepSize(0.1f)]
float BoxSizeX = 1.0f;
[DisplayName("BoxSizeY")]
[MinValue(-100.0f)]
[MaxValue(100.0f)]
[StepSize(0.1f)]
float BoxSizeY = 1.0f;
[DisplayName("BoxSizeZ")]
[MinValue(-100.0f)]
[MaxValue(100.0f)]
[StepSize(0.1f)]
float BoxSizeZ = 1.0f;
// Orientation SceneOrientation = new Orientation(0.41f, -0.55f, -0.29f, 0.67f);
Orientation SceneOrientation = new Orientation(0.0f, 0.0f, 0.0f, 1.0f);
[MinValue(0.0f)]
[MaxValue(10.0f)]
[StepSize(0.01f)]
float ModelRotationSpeed = 0.0f;
bool DoubleSyncInterval = false;
[MinValue(-16.0f)]
[MaxValue(16.0f)]
float ExposureScale = 0.0f;
}
public class PostProcessing
{
[DisplayName("Bloom Exposure Offset")]
[MinValue(-10.0f)]
[MaxValue(0.0f)]
[StepSize(0.01f)]
[HelpText("Exposure offset applied to generate the input of the bloom pass")]
float BloomExposure = -4.0f;
[DisplayName("Bloom Magnitude")]
[MinValue(0.0f)]
[MaxValue(2.0f)]
[StepSize(0.01f)]
[HelpText("Scale factor applied to the bloom results when combined with tone-mapped result")]
float BloomMagnitude = 1.0f;
[DisplayName("Bloom Blur Sigma")]
[MinValue(0.5f)]
[MaxValue(5.0f)]
[StepSize(0.01f)]
[HelpText("Sigma parameter of the Gaussian filter used in the bloom pass")]
float BloomBlurSigma = 5.0f;
[MinValue(-10.0f)]
[MaxValue(10.0f)]
[StepSize(0.01f)]
[HelpText("Manual exposure value when auto-exposure is disabled")]
float ManualExposure = -2.5f;
}
// No auto-exposure for this sample
const bool EnableAutoExposure = false;
const float KeyValue = 0.115f;
const float AdaptationRate = 0.5f;
}
| |
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Banshee.Widgets;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Gui;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Banshee.Sources.Gui;
using Banshee.Web;
using Lastfm;
using Lastfm.Data;
namespace Banshee.Lastfm
{
public class LastfmSourceContents : Hyena.Widgets.ScrolledWindow, ISourceContents
{
private VBox main_box;
private LastfmSource lastfm;
private NumberedList recently_loved;
private NumberedList recently_played;
private NumberedList top_artists;
private Viewport viewport;
// "Coming Soon: Profile, Friends, Events etc")
public LastfmSourceContents () : base ()
{
HscrollbarPolicy = PolicyType.Never;
VscrollbarPolicy = PolicyType.Automatic;
viewport = new Viewport ();
viewport.ShadowType = ShadowType.None;
main_box = new VBox ();
main_box.Spacing = 6;
main_box.BorderWidth = 5;
main_box.ReallocateRedraws = true;
// Clamp the width, preventing horizontal scrolling
SizeAllocated += delegate (object o, SizeAllocatedArgs args) {
// TODO '- 10' worked for Nereid, but not for Cubano; properly calculate the right width we should request
main_box.WidthRequest = args.Allocation.Width - 30;
};
viewport.Add (main_box);
StyleSet += delegate {
viewport.ModifyBg (StateType.Normal, Style.Base (StateType.Normal));
viewport.ModifyFg (StateType.Normal, Style.Text (StateType.Normal));
};
AddWithFrame (viewport);
ShowAll ();
}
public bool SetSource (ISource src)
{
lastfm = src as LastfmSource;
if (lastfm == null) {
return false;
}
if (lastfm.Connection.Connected) {
UpdateForUser (lastfm.Account.UserName);
} else {
lastfm.Connection.StateChanged += HandleConnectionStateChanged;
}
return true;
}
public ISource Source {
get { return lastfm; }
}
public void ResetSource ()
{
lastfm = null;
}
public Widget Widget {
get { return this; }
}
public void Refresh ()
{
if (user != null) {
user.RecentLovedTracks.Refresh ();
user.RecentTracks.Refresh ();
user.GetTopArtists (TopType.Overall).Refresh ();
recently_loved.SetList (user.RecentLovedTracks);
recently_played.SetList (user.RecentTracks);
top_artists.SetList (user.GetTopArtists (TopType.Overall));
}
}
private string last_user;
private LastfmUserData user;
private void UpdateForUser (string username)
{
if (username == last_user) {
return;
}
last_user = username;
while (main_box.Children.Length != 0) {
main_box.Remove (main_box.Children[0]);
}
recently_loved = new NumberedList (lastfm, Catalog.GetString ("Recently Loved Tracks"));
recently_played = new NumberedList (lastfm, Catalog.GetString ("Recently Played Tracks"));
top_artists = new NumberedList (lastfm, Catalog.GetString ("My Top Artists"));
//recommended_artists = new NumberedList (Catalog.GetString ("Recommended Artists"));
main_box.PackStart (recently_loved, false, false, 0);
main_box.PackStart (new HSeparator (), false, false, 5);
main_box.PackStart (recently_played, false, false, 0);
main_box.PackStart (new HSeparator (), false, false, 5);
main_box.PackStart (top_artists, false, false, 0);
//PackStart (recommended_artists, true, true, 0);
user = new LastfmUserData (username);
recently_loved.SetList (user.RecentLovedTracks);
recently_played.SetList (user.RecentTracks);
top_artists.SetList (user.GetTopArtists (TopType.Overall));
ShowAll ();
}
private void HandleConnectionStateChanged (object sender, ConnectionStateChangedArgs args)
{
if (args.State == ConnectionState.Connected) {
ThreadAssist.ProxyToMain (delegate {
if (lastfm != null && lastfm.Account != null) {
UpdateForUser (lastfm.Account.UserName);
}
});
}
}
public class NumberedTileView : TileView
{
private int i = 1;
public NumberedTileView (int cols) : base (cols)
{
}
public new void ClearWidgets ()
{
i = 1;
base.ClearWidgets ();
}
public void AddNumberedWidget (Tile tile)
{
tile.PrimaryText = String.Format ("{0}. {1}", i++, tile.PrimaryText);
AddWidget (tile);
}
}
protected class NumberedList : TitledList
{
protected ArtworkManager artwork_manager = ServiceManager.Get<ArtworkManager> ();
protected LastfmSource lastfm;
protected NumberedTileView tile_view;
protected Dictionary<object, RecentTrack> widget_track_map = new Dictionary<object, RecentTrack> ();
public NumberedList (LastfmSource lastfm, string name) : base (name)
{
this.lastfm = lastfm;
artwork_manager.AddCachedSize(40);
tile_view = new NumberedTileView (1);
PackStart (tile_view, true, true, 0);
tile_view.Show ();
StyleSet += delegate {
tile_view.ModifyBg (StateType.Normal, Style.Base (StateType.Normal));
tile_view.ModifyFg (StateType.Normal, Style.Text (StateType.Normal));
};
}
// TODO generalize this
public void SetList (LastfmData<UserTopArtist> artists)
{
tile_view.ClearWidgets ();
foreach (UserTopArtist artist in artists) {
MenuTile tile = new MenuTile ();
tile.PrimaryText = artist.Name;
tile.SecondaryText = String.Format (Catalog.GetString ("{0} plays"), artist.PlayCount);
tile_view.AddNumberedWidget (tile);
}
tile_view.ShowAll ();
}
public void SetList (LastfmData<RecentTrack> tracks)
{
tile_view.ClearWidgets ();
foreach (RecentTrack track in tracks) {
MenuTile tile = new MenuTile ();
widget_track_map [tile] = track;
tile.PrimaryText = track.Name;
tile.SecondaryText = track.Artist;
tile.ButtonPressEvent += OnTileActivated;
// Unfortunately the recently loved list doesn't include what album the song is on
if (!String.IsNullOrEmpty (track.Album)) {
AlbumInfo album = new AlbumInfo (track.Album);
album.ArtistName = track.Artist;
Gdk.Pixbuf pb = artwork_manager == null ? null : artwork_manager.LookupScalePixbuf (album.ArtworkId, 40);
if (pb != null) {
tile.Pixbuf = pb;
}
}
tile_view.AddNumberedWidget (tile);
}
tile_view.ShowAll ();
}
private void OnTileActivated (object sender, EventArgs args)
{
(sender as Button).Relief = ReliefStyle.Normal;
RecentTrack track = widget_track_map [sender];
lastfm.Actions.CurrentArtist = track.Artist;
lastfm.Actions.CurrentAlbum = track.Album;
lastfm.Actions.CurrentTrack = track.Name;
Gtk.Menu menu = ServiceManager.Get<InterfaceActionService> ().UIManager.GetWidget ("/LastfmTrackPopup") as Menu;
// For an event
//menu.Append (new MenuItem ("Go to Last.fm Page"));
//menu.Append (new MenuItem ("Add to Google Calendar"));
// For a user
//menu.Append (new MenuItem ("Go to Last.fm Page"));
//menu.Append (new MenuItem ("Listen to Recommended Station"));
//menu.Append (new MenuItem ("Listen to Loved Station"));
//menu.Append (new MenuItem ("Listen to Neighbors Station"));
menu.ShowAll ();
menu.Popup (null, null, null, 0, Gtk.Global.CurrentEventTime);
menu.Deactivated += delegate {
(sender as Button).Relief = ReliefStyle.None;
};
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace UnityTest
{
[Serializable]
public class IntegrationTestsRunnerWindow : EditorWindow
{
[SerializeField]
private IntegrationTestRunnerRenderer renderer;
#region runner steerign vars
private List<TestResult> testsToRun;
private bool readyToRun;
private bool isRunning;
private bool isCompiling;
private bool isBuilding;
#endregion
public IntegrationTestsRunnerWindow ()
{
title = "Integration Tests Runner";
renderer = new IntegrationTestRunnerRenderer(RunTests);
EditorApplication.hierarchyWindowItemOnGUI += renderer.OnHierarchyWindowItemOnGui;
renderer.InvalidateTestList();
}
public void OnDestroy ()
{
EditorApplication.hierarchyWindowItemOnGUI -= renderer.OnHierarchyWindowItemOnGui;
}
public void OnSelectionChange()
{
if (isRunning || EditorApplication.isPlayingOrWillChangePlaymode)
return;
if (Selection.objects != null
&& Selection.objects.All (o => o is GameObject)
&& Selection.objects.All (o=> (o as GameObject).GetComponent<TestComponent>() != null))
{
renderer.SelectInHierarchy(Selection.objects.Select (o => o as GameObject));
Repaint ();
}
if (Selection.activeGameObject != null && Selection.activeGameObject.transform.parent != null)
{
var testGO = TestManager.FindTopGameObject(Selection.activeGameObject);
if(testGO.GetComponent<TestComponent>() != null)
renderer.SelectInHierarchy(new[] {testGO});
}
}
public void OnHierarchyChange()
{
renderer.OnHierarchyChange(isRunning);
if(renderer.forceRepaint) Repaint ();
if (TestManager.GetAllTestGameObjects().Any())
{
TestRunner.GetTestRunner();
}
}
private void RunTests(IList<GameObject> tests)
{
if (!tests.Any ())
return;
Focus ();
testsToRun = renderer.GetTestResultsForGO (tests).ToList ();
readyToRun = true;
TestManager.DisableAllTests ();
EditorApplication.isPlaying = true;
}
public void Update()
{
if (readyToRun && EditorApplication.isPlaying)
{
readyToRun = false;
var testRunner = TestRunner.GetTestRunner();
testRunner.TestRunnerCallback.Add (new RunnerCallback (this));
testRunner.InitRunner(testsToRun);
SetConsoleErrorPause (false);
isRunning = true;
if (renderer.blockUIWhenRunning)
EditorUtility.DisplayProgressBar("Integration Test Runner",
"Initializing",0);
}
if (EditorApplication.isCompiling)
{
isCompiling = true;
}
else if(isCompiling)
{
isCompiling = false;
renderer.InvalidateTestList ();
}
}
private void SetConsoleErrorPause (bool b)
{
Assembly assembly = Assembly.GetAssembly (typeof (SceneView));
Type type = assembly.GetType ("UnityEditorInternal.LogEntries");
MethodInfo method = type.GetMethod ("SetConsoleFlag");
method.Invoke (new object (), new object[] { 1 << 2, b });
}
public void OnDidOpenScene()
{
renderer.InvalidateTestList();
Repaint();
}
public void OnGUI()
{
if (isRunning)
{
Repaint ();
if (!EditorApplication.isPlaying)
{
isRunning = false;
Debug.Log ("Test run was interrupted. Reseting Test Runner.");
}
}
#if !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2
if (BuildPipeline.isBuildingPlayer)
{
isBuilding = true;
}
else if (isBuilding)
{
isBuilding = false;
renderer.InvalidateTestList();
Repaint ();
}
#endif
if (!TestManager.AnyTestsOnScene())
{
renderer.PrintHeadPanel(isRunning);
GUILayout.Label ("No tests found on the scene",
EditorStyles.boldLabel);
GUILayout.FlexibleSpace();
}
else
{
renderer.PrintHeadPanel(isRunning);
renderer.PrintTestList();
renderer.PrintSelectedTestDetails();
}
if (renderer.forceRepaint)
{
renderer.forceRepaint = false;
Repaint ();
}
}
public void OnInspectorUpdate ()
{
if(focusedWindow != this)
Repaint ();
}
public void RunSelectedTest()
{
if (Selection.activeGameObject != null)
{
var activeGO = Selection.activeGameObject;
var topActiveGO = TestManager.FindTopGameObject(activeGO);
if (topActiveGO.GetComponent<TestComponent>() != null)
RunTests(new List<GameObject>() { topActiveGO });
else
Debug.LogWarning("Selected object or it's parent has no TestComponent attached.");
}
else
{
Debug.LogWarning("No object is selected");
}
}
class RunnerCallback : IntegrationTestRunner.ITestRunnerCallback
{
private IntegrationTestsRunnerWindow integrationTestRunnerWindow;
private int testNumber=0;
private int currentTestNumber = 0;
public RunnerCallback(IntegrationTestsRunnerWindow integrationTestRunnerWindow)
{
this.integrationTestRunnerWindow = integrationTestRunnerWindow;
}
public void RunStarted (string platform, List<TestResult> testsToRun)
{
testNumber = testsToRun.Count;
testsToRun.ForEach (t => t.Reset ());
integrationTestRunnerWindow.renderer.UpdateResults (testsToRun);
}
public void RunFinished (List<TestResult> testResults)
{
integrationTestRunnerWindow.isRunning = false;
integrationTestRunnerWindow.renderer.OnTestRunFinished();
integrationTestRunnerWindow.Repaint ();
EditorApplication.isPlaying = false;
if (integrationTestRunnerWindow.renderer.blockUIWhenRunning)
EditorUtility.ClearProgressBar();
}
public void TestStarted (TestResult test)
{
if (integrationTestRunnerWindow.renderer.blockUIWhenRunning
&& EditorUtility.DisplayCancelableProgressBar("Integration Test Runner",
"Running " + test.go.name,
(float) currentTestNumber / testNumber))
{
integrationTestRunnerWindow.isRunning = false;
EditorApplication.isPlaying = false;
}
integrationTestRunnerWindow.renderer.UpdateResults (new List<TestResult> {test});
integrationTestRunnerWindow.Repaint();
}
public void TestFinished (TestResult test)
{
currentTestNumber++;
integrationTestRunnerWindow.renderer.UpdateResults(new List<TestResult> { test });
integrationTestRunnerWindow.Repaint();
}
public void TestRunInterrupted(List<TestResult> testsNotRun)
{
Debug.Log("Test run interrupted");
RunFinished(new List<TestResult>());
}
}
public void RunAllTests()
{
RunTests (renderer.GetVisibleNotIgnoredTests ());
}
[MenuItem("Unity Test Tools/Integration Test Runner %#&t")]
public static IntegrationTestsRunnerWindow ShowWindow()
{
var w = GetWindow(typeof(IntegrationTestsRunnerWindow));
w.Show();
return w as IntegrationTestsRunnerWindow;
}
[MenuItem("Unity Test Tools/Run all integration tests %#t")]
public static void RunAllTestsMenu()
{
var trw = ShowWindow();
trw.RunAllTests();
}
[MenuItem("Unity Test Tools/Run selected integration test %t")]
[MenuItem("CONTEXT/TestComponent/Run")]
public static void RunSelectedMenu()
{
var trw = ShowWindow();
trw.RunSelectedTest();
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_ASWBXML
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml;
using Microsoft.Protocols.TestTools;
/// <summary>
/// The implementation of MS-ASWBXML
/// </summary>
public class MS_ASWBXML
{
/// <summary>
/// WBXML version
/// </summary>
private const byte VersionByte = 0x03;
/// <summary>
/// Public Identifier
/// </summary>
private const byte PublicIdentifierByte = 0x01;
/// <summary>
/// Encoding. 0x6A == UTF-8
/// </summary>
private const byte CharsetByte = 0x6A;
/// <summary>
/// String table length. This is not used in MS-ASWBXML, so this value is always 0.
/// </summary>
private const byte StringTableLengthByte = 0x00;
/// <summary>
/// XmlDocument that contain the xml
/// </summary>
private XmlDocument xmlDoc = new XmlDocument();
/// <summary>
/// Code pages.
/// </summary>
private CodePage[] codePages;
/// <summary>
/// Current code page.
/// </summary>
private int currentCodePage = 0;
/// <summary>
/// Default code page.
/// </summary>
private int defaultCodePage = -1;
/// <summary>
/// The DataCollection in encoding process
/// </summary>
private Dictionary<string, int> encodeDataCollection = new Dictionary<string, int>();
/// <summary>
/// The DataCollection in decoding process
/// </summary>
private Dictionary<string, int> decodeDataCollection = new Dictionary<string, int>();
/// <summary>
/// An instance of interface ITestSite which provides logging, assertions, and adapters for test code onto its execution context.
/// </summary>
private ITestSite site;
/// <summary>
/// Initializes a new instance of the MS_ASWBXML class.
/// </summary>
/// <param name="site">An instance of interface ITestSite which provides logging, assertions, and adapters for test code onto its execution context.</param>
public MS_ASWBXML(ITestSite site)
{
this.site = site;
// Loads up code pages. There are 25 code pages as per MS-ASWBXML
this.codePages = new CodePage[25];
// Code Page 0: AirSync
this.codePages[0] = new CodePage { Namespace = "AirSync", Xmlns = "airsync" };
this.codePages[0].AddToken(0x05, "Sync");
this.codePages[0].AddToken(0x06, "Responses");
this.codePages[0].AddToken(0x07, "Add");
this.codePages[0].AddToken(0x08, "Change");
this.codePages[0].AddToken(0x09, "Delete");
this.codePages[0].AddToken(0x0A, "Fetch");
this.codePages[0].AddToken(0x0B, "SyncKey");
this.codePages[0].AddToken(0x0C, "ClientId");
this.codePages[0].AddToken(0x0D, "ServerId");
this.codePages[0].AddToken(0x0E, "Status");
this.codePages[0].AddToken(0x0F, "Collection");
this.codePages[0].AddToken(0x10, "Class");
this.codePages[0].AddToken(0x12, "CollectionId");
this.codePages[0].AddToken(0x13, "GetChanges");
this.codePages[0].AddToken(0x14, "MoreAvailable");
this.codePages[0].AddToken(0x15, "WindowSize");
this.codePages[0].AddToken(0x16, "Commands");
this.codePages[0].AddToken(0x17, "Options");
this.codePages[0].AddToken(0x18, "FilterType");
this.codePages[0].AddToken(0x1B, "Conflict");
this.codePages[0].AddToken(0x1C, "Collections");
this.codePages[0].AddToken(0x1D, "ApplicationData");
this.codePages[0].AddToken(0x1E, "DeletesAsMoves");
this.codePages[0].AddToken(0x20, "Supported");
this.codePages[0].AddToken(0x21, "SoftDelete");
this.codePages[0].AddToken(0x22, "MIMESupport");
this.codePages[0].AddToken(0x23, "MIMETruncation");
this.codePages[0].AddToken(0x24, "Wait");
this.codePages[0].AddToken(0x25, "Limit");
this.codePages[0].AddToken(0x26, "Partial");
this.codePages[0].AddToken(0x27, "ConversationMode");
this.codePages[0].AddToken(0x28, "MaxItems");
this.codePages[0].AddToken(0x29, "HeartbeatInterval");
// Code Page 1: Contacts
this.codePages[1] = new CodePage { Namespace = "Contacts", Xmlns = "contacts" };
this.codePages[1].AddToken(0x05, "Anniversary");
this.codePages[1].AddToken(0x06, "AssistantName");
this.codePages[1].AddToken(0x07, "AssistantPhoneNumber");
this.codePages[1].AddToken(0x08, "Birthday");
this.codePages[1].AddToken(0x0C, "Business2PhoneNumber");
this.codePages[1].AddToken(0x0D, "BusinessAddressCity");
this.codePages[1].AddToken(0x0E, "BusinessAddressCountry");
this.codePages[1].AddToken(0x0F, "BusinessAddressPostalCode");
this.codePages[1].AddToken(0x10, "BusinessAddressState");
this.codePages[1].AddToken(0x11, "BusinessAddressStreet");
this.codePages[1].AddToken(0x12, "BusinessFaxNumber");
this.codePages[1].AddToken(0x13, "BusinessPhoneNumber");
this.codePages[1].AddToken(0x14, "CarPhoneNumber");
this.codePages[1].AddToken(0x15, "Categories");
this.codePages[1].AddToken(0x16, "Category");
this.codePages[1].AddToken(0x17, "Children");
this.codePages[1].AddToken(0x18, "Child");
this.codePages[1].AddToken(0x19, "CompanyName");
this.codePages[1].AddToken(0x1A, "Department");
this.codePages[1].AddToken(0x1B, "Email1Address");
this.codePages[1].AddToken(0x1C, "Email2Address");
this.codePages[1].AddToken(0x1D, "Email3Address");
this.codePages[1].AddToken(0x1E, "FileAs");
this.codePages[1].AddToken(0x1F, "FirstName");
this.codePages[1].AddToken(0x20, "Home2PhoneNumber");
this.codePages[1].AddToken(0x21, "HomeAddressCity");
this.codePages[1].AddToken(0x22, "HomeAddressCountry");
this.codePages[1].AddToken(0x23, "HomeAddressPostalCode");
this.codePages[1].AddToken(0x24, "HomeAddressState");
this.codePages[1].AddToken(0x25, "HomeAddressStreet");
this.codePages[1].AddToken(0x26, "HomeFaxNumber");
this.codePages[1].AddToken(0x27, "HomePhoneNumber");
this.codePages[1].AddToken(0x28, "JobTitle");
this.codePages[1].AddToken(0x29, "LastName");
this.codePages[1].AddToken(0x2A, "MiddleName");
this.codePages[1].AddToken(0x2B, "MobilePhoneNumber");
this.codePages[1].AddToken(0x2C, "OfficeLocation");
this.codePages[1].AddToken(0x2D, "OtherAddressCity");
this.codePages[1].AddToken(0x2E, "OtherAddressCountry");
this.codePages[1].AddToken(0x2F, "OtherAddressPostalCode");
this.codePages[1].AddToken(0x30, "OtherAddressState");
this.codePages[1].AddToken(0x31, "OtherAddressStreet");
this.codePages[1].AddToken(0x32, "PagerNumber");
this.codePages[1].AddToken(0x33, "RadioPhoneNumber");
this.codePages[1].AddToken(0x34, "Spouse");
this.codePages[1].AddToken(0x35, "Suffix");
this.codePages[1].AddToken(0x36, "Title");
this.codePages[1].AddToken(0x37, "WebPage");
this.codePages[1].AddToken(0x38, "YomiCompanyName");
this.codePages[1].AddToken(0x39, "YomiFirstName");
this.codePages[1].AddToken(0x3A, "YomiLastName");
this.codePages[1].AddToken(0x3C, "Picture");
this.codePages[1].AddToken(0x3D, "Alias");
this.codePages[1].AddToken(0x3E, "WeightedRank");
// Code Page 2: Email
this.codePages[2] = new CodePage { Namespace = "Email", Xmlns = "email" };
this.codePages[2].AddToken(0x0F, "DateReceived");
this.codePages[2].AddToken(0x11, "DisplayTo");
this.codePages[2].AddToken(0x12, "Importance");
this.codePages[2].AddToken(0x13, "MessageClass");
this.codePages[2].AddToken(0x14, "Subject");
this.codePages[2].AddToken(0x15, "Read");
this.codePages[2].AddToken(0x16, "To");
this.codePages[2].AddToken(0x17, "Cc");
this.codePages[2].AddToken(0x18, "From");
this.codePages[2].AddToken(0x19, "ReplyTo");
this.codePages[2].AddToken(0x1A, "AllDayEvent");
this.codePages[2].AddToken(0x1B, "Categories");
this.codePages[2].AddToken(0x1C, "Category");
this.codePages[2].AddToken(0x1D, "DtStamp");
this.codePages[2].AddToken(0x1E, "EndTime");
this.codePages[2].AddToken(0x1F, "InstanceType");
this.codePages[2].AddToken(0x20, "BusyStatus");
this.codePages[2].AddToken(0x21, "Location");
this.codePages[2].AddToken(0x22, "MeetingRequest");
this.codePages[2].AddToken(0x23, "Organizer");
this.codePages[2].AddToken(0x24, "RecurrenceId");
this.codePages[2].AddToken(0x25, "Reminder");
this.codePages[2].AddToken(0x26, "ResponseRequested");
this.codePages[2].AddToken(0x27, "Recurrences");
this.codePages[2].AddToken(0x28, "Recurrence");
this.codePages[2].AddToken(0x29, "Type");
this.codePages[2].AddToken(0x2A, "Until");
this.codePages[2].AddToken(0x2B, "Occurrences");
this.codePages[2].AddToken(0x2C, "Interval");
this.codePages[2].AddToken(0x2D, "DayOfWeek");
this.codePages[2].AddToken(0x2E, "DayOfMonth");
this.codePages[2].AddToken(0x2F, "WeekOfMonth");
this.codePages[2].AddToken(0x30, "MonthOfYear");
this.codePages[2].AddToken(0x31, "StartTime");
this.codePages[2].AddToken(0x32, "Sensitivity");
this.codePages[2].AddToken(0x33, "TimeZone");
this.codePages[2].AddToken(0x34, "GlobalObjId");
this.codePages[2].AddToken(0x35, "ThreadTopic");
this.codePages[2].AddToken(0x39, "InternetCPID");
this.codePages[2].AddToken(0x3A, "Flag");
this.codePages[2].AddToken(0x3B, "Status");
this.codePages[2].AddToken(0x3C, "ContentClass");
this.codePages[2].AddToken(0x3D, "FlagType");
this.codePages[2].AddToken(0x3E, "CompleteTime");
this.codePages[2].AddToken(0x3F, "DisallowNewTimeProposal");
// Code Page 3: AirNotify
this.codePages[3] = new CodePage { Namespace = string.Empty, Xmlns = string.Empty };
// Code Page 4: Calendar
this.codePages[4] = new CodePage { Namespace = "Calendar", Xmlns = "calendar" };
this.codePages[4].AddToken(0x05, "Timezone");
this.codePages[4].AddToken(0x06, "AllDayEvent");
this.codePages[4].AddToken(0x07, "Attendees");
this.codePages[4].AddToken(0x08, "Attendee");
this.codePages[4].AddToken(0x09, "Email");
this.codePages[4].AddToken(0x0A, "Name");
this.codePages[4].AddToken(0x0D, "BusyStatus");
this.codePages[4].AddToken(0x0E, "Categories");
this.codePages[4].AddToken(0x0F, "Category");
this.codePages[4].AddToken(0x11, "DtStamp");
this.codePages[4].AddToken(0x12, "EndTime");
this.codePages[4].AddToken(0x13, "Exception");
this.codePages[4].AddToken(0x14, "Exceptions");
this.codePages[4].AddToken(0x15, "Deleted");
this.codePages[4].AddToken(0x16, "ExceptionStartTime");
this.codePages[4].AddToken(0x17, "Location");
this.codePages[4].AddToken(0x18, "MeetingStatus");
this.codePages[4].AddToken(0x19, "OrganizerEmail");
this.codePages[4].AddToken(0x1A, "OrganizerName");
this.codePages[4].AddToken(0x1B, "Recurrence");
this.codePages[4].AddToken(0x1C, "Type");
this.codePages[4].AddToken(0x1D, "Until");
this.codePages[4].AddToken(0x1E, "Occurrences");
this.codePages[4].AddToken(0x1F, "Interval");
this.codePages[4].AddToken(0x20, "DayOfWeek");
this.codePages[4].AddToken(0x21, "DayOfMonth");
this.codePages[4].AddToken(0x22, "WeekOfMonth");
this.codePages[4].AddToken(0x23, "MonthOfYear");
this.codePages[4].AddToken(0x24, "Reminder");
this.codePages[4].AddToken(0x25, "Sensitivity");
this.codePages[4].AddToken(0x26, "Subject");
this.codePages[4].AddToken(0x27, "StartTime");
this.codePages[4].AddToken(0x28, "UID");
this.codePages[4].AddToken(0x29, "AttendeeStatus");
this.codePages[4].AddToken(0x2A, "AttendeeType");
this.codePages[4].AddToken(0x33, "DisallowNewTimeProposal");
this.codePages[4].AddToken(0x34, "ResponseRequested");
this.codePages[4].AddToken(0x35, "AppointmentReplyTime");
this.codePages[4].AddToken(0x36, "ResponseType");
this.codePages[4].AddToken(0x37, "CalendarType");
this.codePages[4].AddToken(0x38, "IsLeapMonth");
this.codePages[4].AddToken(0x39, "FirstDayOfWeek");
this.codePages[4].AddToken(0x3A, "OnlineMeetingConfLink");
this.codePages[4].AddToken(0x3B, "OnlineMeetingExternalLink");
this.codePages[4].AddToken(0x3C, "ClientUid");
// Code Page 5: Move
this.codePages[5] = new CodePage { Namespace = "Move", Xmlns = "move" };
this.codePages[5].AddToken(0x05, "MoveItems");
this.codePages[5].AddToken(0x06, "Move");
this.codePages[5].AddToken(0x07, "SrcMsgId");
this.codePages[5].AddToken(0x08, "SrcFldId");
this.codePages[5].AddToken(0x09, "DstFldId");
this.codePages[5].AddToken(0x0A, "Response");
this.codePages[5].AddToken(0x0B, "Status");
this.codePages[5].AddToken(0x0C, "DstMsgId");
// Code Page 6: GetItemEstimate
this.codePages[6] = new CodePage { Namespace = "GetItemEstimate", Xmlns = "getitemestimate" };
this.codePages[6].AddToken(0x05, "GetItemEstimate");
this.codePages[6].AddToken(0x07, "Collections");
this.codePages[6].AddToken(0x08, "Collection");
this.codePages[6].AddToken(0x09, "Class");
this.codePages[6].AddToken(0x0A, "CollectionId");
this.codePages[6].AddToken(0x0C, "Estimate");
this.codePages[6].AddToken(0x0D, "Response");
this.codePages[6].AddToken(0x0E, "Status");
// Code Page 7: FolderHierarchy
this.codePages[7] = new CodePage { Namespace = "FolderHierarchy", Xmlns = "folderhierarchy" };
this.codePages[7].AddToken(0x05, "Folders");
this.codePages[7].AddToken(0x06, "Folder");
this.codePages[7].AddToken(0x07, "DisplayName");
this.codePages[7].AddToken(0x08, "ServerId");
this.codePages[7].AddToken(0x09, "ParentId");
this.codePages[7].AddToken(0x0A, "Type");
this.codePages[7].AddToken(0x0C, "Status");
this.codePages[7].AddToken(0x0E, "Changes");
this.codePages[7].AddToken(0x0F, "Add");
this.codePages[7].AddToken(0x10, "Delete");
this.codePages[7].AddToken(0x11, "Update");
this.codePages[7].AddToken(0x12, "SyncKey");
this.codePages[7].AddToken(0x13, "FolderCreate");
this.codePages[7].AddToken(0x14, "FolderDelete");
this.codePages[7].AddToken(0x15, "FolderUpdate");
this.codePages[7].AddToken(0x16, "FolderSync");
this.codePages[7].AddToken(0x17, "Count");
// Code Page 8: MeetingResponse
this.codePages[8] = new CodePage { Namespace = "MeetingResponse", Xmlns = "meetingresponse" };
this.codePages[8].AddToken(0x05, "CalendarId");
this.codePages[8].AddToken(0x06, "CollectionId");
this.codePages[8].AddToken(0x07, "MeetingResponse");
this.codePages[8].AddToken(0x08, "RequestId");
this.codePages[8].AddToken(0x09, "Request");
this.codePages[8].AddToken(0x0A, "Result");
this.codePages[8].AddToken(0x0B, "Status");
this.codePages[8].AddToken(0x0C, "UserResponse");
this.codePages[8].AddToken(0x0E, "InstanceId");
this.codePages[8].AddToken(0x12, "SendResponse");
// Code Page 9: Tasks
this.codePages[9] = new CodePage { Namespace = "Tasks", Xmlns = "tasks" };
this.codePages[9].AddToken(0x08, "Categories");
this.codePages[9].AddToken(0x09, "Category");
this.codePages[9].AddToken(0x0A, "Complete");
this.codePages[9].AddToken(0x0B, "DateCompleted");
this.codePages[9].AddToken(0x0C, "DueDate");
this.codePages[9].AddToken(0x0D, "UtcDueDate");
this.codePages[9].AddToken(0x0E, "Importance");
this.codePages[9].AddToken(0x0F, "Recurrence");
this.codePages[9].AddToken(0x10, "Type");
this.codePages[9].AddToken(0x11, "Start");
this.codePages[9].AddToken(0x12, "Until");
this.codePages[9].AddToken(0x13, "Occurrences");
this.codePages[9].AddToken(0x14, "Interval");
this.codePages[9].AddToken(0x15, "DayOfMonth");
this.codePages[9].AddToken(0x16, "DayOfWeek");
this.codePages[9].AddToken(0x17, "WeekOfMonth");
this.codePages[9].AddToken(0x18, "MonthOfYear");
this.codePages[9].AddToken(0x19, "Regenerate");
this.codePages[9].AddToken(0x1A, "DeadOccur");
this.codePages[9].AddToken(0x1B, "ReminderSet");
this.codePages[9].AddToken(0x1C, "ReminderTime");
this.codePages[9].AddToken(0x1D, "Sensitivity");
this.codePages[9].AddToken(0x1E, "StartDate");
this.codePages[9].AddToken(0x1F, "UtcStartDate");
this.codePages[9].AddToken(0x20, "Subject");
this.codePages[9].AddToken(0x22, "OrdinalDate");
this.codePages[9].AddToken(0x23, "SubOrdinalDate");
this.codePages[9].AddToken(0x24, "CalendarType");
this.codePages[9].AddToken(0x25, "IsLeapMonth");
this.codePages[9].AddToken(0x26, "FirstDayOfWeek");
// Code Page 10: ResolveRecipients
this.codePages[10] = new CodePage { Namespace = "ResolveRecipients", Xmlns = "resolverecipients" };
this.codePages[10].AddToken(0x05, "ResolveRecipients");
this.codePages[10].AddToken(0x06, "Response");
this.codePages[10].AddToken(0x07, "Status");
this.codePages[10].AddToken(0x08, "Type");
this.codePages[10].AddToken(0x09, "Recipient");
this.codePages[10].AddToken(0x0A, "DisplayName");
this.codePages[10].AddToken(0x0B, "EmailAddress");
this.codePages[10].AddToken(0x0C, "Certificates");
this.codePages[10].AddToken(0x0D, "Certificate");
this.codePages[10].AddToken(0x0E, "MiniCertificate");
this.codePages[10].AddToken(0x0F, "Options");
this.codePages[10].AddToken(0x10, "To");
this.codePages[10].AddToken(0x11, "CertificateRetrieval");
this.codePages[10].AddToken(0x12, "RecipientCount");
this.codePages[10].AddToken(0x13, "MaxCertificates");
this.codePages[10].AddToken(0x14, "MaxAmbiguousRecipients");
this.codePages[10].AddToken(0x15, "CertificateCount");
this.codePages[10].AddToken(0x16, "Availability");
this.codePages[10].AddToken(0x17, "StartTime");
this.codePages[10].AddToken(0x18, "EndTime");
this.codePages[10].AddToken(0x19, "MergedFreeBusy");
this.codePages[10].AddToken(0x1A, "Picture");
this.codePages[10].AddToken(0x1B, "MaxSize");
this.codePages[10].AddToken(0x1C, "Data");
this.codePages[10].AddToken(0x1D, "MaxPictures");
// Code Page 11: ValidateCert
this.codePages[11] = new CodePage { Namespace = "ValidateCert", Xmlns = "ValidateCert" };
this.codePages[11].AddToken(0x05, "ValidateCert");
this.codePages[11].AddToken(0x06, "Certificates");
this.codePages[11].AddToken(0x07, "Certificate");
this.codePages[11].AddToken(0x08, "CertificateChain");
this.codePages[11].AddToken(0x09, "CheckCrl");
this.codePages[11].AddToken(0x0A, "Status");
// Code Page 12: Contacts2
this.codePages[12] = new CodePage { Namespace = "Contacts2", Xmlns = "contacts2" };
this.codePages[12].AddToken(0x05, "CustomerId");
this.codePages[12].AddToken(0x06, "GovernmentId");
this.codePages[12].AddToken(0x07, "IMAddress");
this.codePages[12].AddToken(0x08, "IMAddress2");
this.codePages[12].AddToken(0x09, "IMAddress3");
this.codePages[12].AddToken(0x0A, "ManagerName");
this.codePages[12].AddToken(0x0B, "CompanyMainPhone");
this.codePages[12].AddToken(0x0C, "AccountName");
this.codePages[12].AddToken(0x0D, "NickName");
this.codePages[12].AddToken(0x0E, "MMS");
// Code Page 13: Ping
this.codePages[13] = new CodePage { Namespace = "Ping", Xmlns = "ping" };
this.codePages[13].AddToken(0x05, "Ping");
this.codePages[13].AddToken(0x07, "Status");
this.codePages[13].AddToken(0x08, "HeartbeatInterval");
this.codePages[13].AddToken(0x09, "Folders");
this.codePages[13].AddToken(0x0A, "Folder");
this.codePages[13].AddToken(0x0B, "Id");
this.codePages[13].AddToken(0x0C, "Class");
this.codePages[13].AddToken(0x0D, "MaxFolders");
// Code Page 14: Provision
this.codePages[14] = new CodePage { Namespace = "Provision", Xmlns = "provision" };
this.codePages[14].AddToken(0x05, "Provision");
this.codePages[14].AddToken(0x06, "Policies");
this.codePages[14].AddToken(0x07, "Policy");
this.codePages[14].AddToken(0x08, "PolicyType");
this.codePages[14].AddToken(0x09, "PolicyKey");
this.codePages[14].AddToken(0x0A, "Data");
this.codePages[14].AddToken(0x0B, "Status");
this.codePages[14].AddToken(0x0C, "RemoteWipe");
this.codePages[14].AddToken(0x0D, "EASProvisionDoc");
this.codePages[14].AddToken(0x0E, "DevicePasswordEnabled");
this.codePages[14].AddToken(0x0F, "AlphanumericDevicePasswordRequired");
this.codePages[14].AddToken(0x10, "RequireStorageCardEncryption");
this.codePages[14].AddToken(0x11, "PasswordRecoveryEnabled");
this.codePages[14].AddToken(0x13, "AttachmentsEnabled");
this.codePages[14].AddToken(0x14, "MinDevicePasswordLength");
this.codePages[14].AddToken(0x15, "MaxInactivityTimeDeviceLock");
this.codePages[14].AddToken(0x16, "MaxDevicePasswordFailedAttempts");
this.codePages[14].AddToken(0x17, "MaxAttachmentSize");
this.codePages[14].AddToken(0x18, "AllowSimpleDevicePassword");
this.codePages[14].AddToken(0x19, "DevicePasswordExpiration");
this.codePages[14].AddToken(0x1A, "DevicePasswordHistory");
this.codePages[14].AddToken(0x1B, "AllowStorageCard");
this.codePages[14].AddToken(0x1C, "AllowCamera");
this.codePages[14].AddToken(0x1D, "RequireDeviceEncryption");
this.codePages[14].AddToken(0x1E, "AllowUnsignedApplications");
this.codePages[14].AddToken(0x1F, "AllowUnsignedInstallationPackages");
this.codePages[14].AddToken(0x20, "MinDevicePasswordComplexCharacters");
this.codePages[14].AddToken(0x21, "AllowWiFi");
this.codePages[14].AddToken(0x22, "AllowTextMessaging");
this.codePages[14].AddToken(0x23, "AllowPOPIMAPEmail");
this.codePages[14].AddToken(0x24, "AllowBluetooth");
this.codePages[14].AddToken(0x25, "AllowIrDA");
this.codePages[14].AddToken(0x26, "RequireManualSyncWhenRoaming");
this.codePages[14].AddToken(0x27, "AllowDesktopSync");
this.codePages[14].AddToken(0x28, "MaxCalendarAgeFilter");
this.codePages[14].AddToken(0x29, "AllowHTMLEmail");
this.codePages[14].AddToken(0x2A, "MaxEmailAgeFilter");
this.codePages[14].AddToken(0x2B, "MaxEmailBodyTruncationSize");
this.codePages[14].AddToken(0x2C, "MaxEmailHTMLBodyTruncationSize");
this.codePages[14].AddToken(0x2D, "RequireSignedSMIMEMessages");
this.codePages[14].AddToken(0x2E, "RequireEncryptedSMIMEMessages");
this.codePages[14].AddToken(0x2F, "RequireSignedSMIMEAlgorithm");
this.codePages[14].AddToken(0x30, "RequireEncryptionSMIMEAlgorithm");
this.codePages[14].AddToken(0x31, "AllowSMIMEEncryptionAlgorithmNegotiation");
this.codePages[14].AddToken(0x32, "AllowSMIMESoftCerts");
this.codePages[14].AddToken(0x33, "AllowBrowser");
this.codePages[14].AddToken(0x34, "AllowConsumerEmail");
this.codePages[14].AddToken(0x35, "AllowRemoteDesktop");
this.codePages[14].AddToken(0x36, "AllowInternetSharing");
this.codePages[14].AddToken(0x37, "UnapprovedInROMApplicationList");
this.codePages[14].AddToken(0x38, "ApplicationName");
this.codePages[14].AddToken(0x39, "ApprovedApplicationList");
this.codePages[14].AddToken(0x3A, "Hash");
// Code Page 15: Search
this.codePages[15] = new CodePage { Namespace = "Search", Xmlns = "search" };
this.codePages[15].AddToken(0x05, "Search");
this.codePages[15].AddToken(0x07, "Store");
this.codePages[15].AddToken(0x08, "Name");
this.codePages[15].AddToken(0x09, "Query");
this.codePages[15].AddToken(0x0A, "Options");
this.codePages[15].AddToken(0x0B, "Range");
this.codePages[15].AddToken(0x0C, "Status");
this.codePages[15].AddToken(0x0D, "Response");
this.codePages[15].AddToken(0x0E, "Result");
this.codePages[15].AddToken(0x0F, "Properties");
this.codePages[15].AddToken(0x10, "Total");
this.codePages[15].AddToken(0x11, "EqualTo");
this.codePages[15].AddToken(0x12, "Value");
this.codePages[15].AddToken(0x13, "And");
this.codePages[15].AddToken(0x14, "Or");
this.codePages[15].AddToken(0x15, "FreeText");
this.codePages[15].AddToken(0x17, "DeepTraversal");
this.codePages[15].AddToken(0x18, "LongId");
this.codePages[15].AddToken(0x19, "RebuildResults");
this.codePages[15].AddToken(0x1A, "LessThan");
this.codePages[15].AddToken(0x1B, "GreaterThan");
this.codePages[15].AddToken(0x1E, "UserName");
this.codePages[15].AddToken(0x1F, "Password");
this.codePages[15].AddToken(0x20, "ConversationId");
this.codePages[15].AddToken(0x21, "Picture");
this.codePages[15].AddToken(0x22, "MaxSize");
this.codePages[15].AddToken(0x23, "MaxPictures");
// Code Page 16: GAL
this.codePages[16] = new CodePage { Namespace = "GAL", Xmlns = "gal" };
this.codePages[16].AddToken(0x05, "DisplayName");
this.codePages[16].AddToken(0x06, "Phone");
this.codePages[16].AddToken(0x07, "Office");
this.codePages[16].AddToken(0x08, "Title");
this.codePages[16].AddToken(0x09, "Company");
this.codePages[16].AddToken(0x0A, "Alias");
this.codePages[16].AddToken(0x0B, "FirstName");
this.codePages[16].AddToken(0x0C, "LastName");
this.codePages[16].AddToken(0x0D, "HomePhone");
this.codePages[16].AddToken(0x0E, "MobilePhone");
this.codePages[16].AddToken(0x0F, "EmailAddress");
this.codePages[16].AddToken(0x10, "Picture");
this.codePages[16].AddToken(0x11, "Status");
this.codePages[16].AddToken(0x12, "Data");
// Code Page 17: AirSyncBase
this.codePages[17] = new CodePage { Namespace = "AirSyncBase", Xmlns = "airsyncbase" };
this.codePages[17].AddToken(0x05, "BodyPreference");
this.codePages[17].AddToken(0x06, "Type");
this.codePages[17].AddToken(0x07, "TruncationSize");
this.codePages[17].AddToken(0x08, "AllOrNone");
this.codePages[17].AddToken(0x0A, "Body");
this.codePages[17].AddToken(0x0B, "Data");
this.codePages[17].AddToken(0x0C, "EstimatedDataSize");
this.codePages[17].AddToken(0x0D, "Truncated");
this.codePages[17].AddToken(0x0E, "Attachments");
this.codePages[17].AddToken(0x0F, "Attachment");
this.codePages[17].AddToken(0x10, "DisplayName");
this.codePages[17].AddToken(0x11, "FileReference");
this.codePages[17].AddToken(0x12, "Method");
this.codePages[17].AddToken(0x13, "ContentId");
this.codePages[17].AddToken(0x14, "ContentLocation");
this.codePages[17].AddToken(0x15, "IsInline");
this.codePages[17].AddToken(0x16, "NativeBodyType");
this.codePages[17].AddToken(0x17, "ContentType");
this.codePages[17].AddToken(0x18, "Preview");
this.codePages[17].AddToken(0x19, "BodyPartPreference");
this.codePages[17].AddToken(0x1A, "BodyPart");
this.codePages[17].AddToken(0x1B, "Status");
this.codePages[17].AddToken(0x1C, "Add");
this.codePages[17].AddToken(0x1D, "Delete");
this.codePages[17].AddToken(0x1E, "ClientId");
this.codePages[17].AddToken(0x1F, "Content");
this.codePages[17].AddToken(0x20, "Location");
this.codePages[17].AddToken(0x21, "Annotation");
this.codePages[17].AddToken(0x22, "Street");
this.codePages[17].AddToken(0x23, "City");
this.codePages[17].AddToken(0x24, "State");
this.codePages[17].AddToken(0x25, "Country");
this.codePages[17].AddToken(0x26, "PostalCode");
this.codePages[17].AddToken(0x27, "Latitude");
this.codePages[17].AddToken(0x28, "Longitude");
this.codePages[17].AddToken(0x29, "Accuracy");
this.codePages[17].AddToken(0x2A, "Altitude");
this.codePages[17].AddToken(0x2B, "AltitudeAccuracy");
this.codePages[17].AddToken(0x2C, "LocationUri");
this.codePages[17].AddToken(0x2D, "InstanceId");
// Code Page 18: Settings
this.codePages[18] = new CodePage { Namespace = "Settings", Xmlns = "settings" };
this.codePages[18].AddToken(0x05, "Settings");
this.codePages[18].AddToken(0x06, "Status");
this.codePages[18].AddToken(0x07, "Get");
this.codePages[18].AddToken(0x08, "Set");
this.codePages[18].AddToken(0x09, "Oof");
this.codePages[18].AddToken(0x0A, "OofState");
this.codePages[18].AddToken(0x0B, "StartTime");
this.codePages[18].AddToken(0x0C, "EndTime");
this.codePages[18].AddToken(0x0D, "OofMessage");
this.codePages[18].AddToken(0x0E, "AppliesToInternal");
this.codePages[18].AddToken(0x0F, "AppliesToExternalKnown");
this.codePages[18].AddToken(0x10, "AppliesToExternalUnknown");
this.codePages[18].AddToken(0x11, "Enabled");
this.codePages[18].AddToken(0x12, "ReplyMessage");
this.codePages[18].AddToken(0x13, "BodyType");
this.codePages[18].AddToken(0x14, "DevicePassword");
this.codePages[18].AddToken(0x15, "Password");
this.codePages[18].AddToken(0x16, "DeviceInformation");
this.codePages[18].AddToken(0x17, "Model");
this.codePages[18].AddToken(0x18, "IMEI");
this.codePages[18].AddToken(0x19, "FriendlyName");
this.codePages[18].AddToken(0x1A, "OS");
this.codePages[18].AddToken(0x1B, "OSLanguage");
this.codePages[18].AddToken(0x1C, "PhoneNumber");
this.codePages[18].AddToken(0x1D, "UserInformation");
this.codePages[18].AddToken(0x1E, "EmailAddresses");
this.codePages[18].AddToken(0x1F, "SMTPAddress");
this.codePages[18].AddToken(0x20, "UserAgent");
this.codePages[18].AddToken(0x21, "EnableOutboundSMS");
this.codePages[18].AddToken(0x22, "MobileOperator");
this.codePages[18].AddToken(0x23, "PrimarySmtpAddress");
this.codePages[18].AddToken(0x24, "Accounts");
this.codePages[18].AddToken(0x25, "Account");
this.codePages[18].AddToken(0x26, "AccountId");
this.codePages[18].AddToken(0x27, "AccountName");
this.codePages[18].AddToken(0x28, "UserDisplayName");
this.codePages[18].AddToken(0x29, "SendDisabled");
this.codePages[18].AddToken(0x2B, "RightsManagementInformation");
// Code Page 19: DocumentLibrary
this.codePages[19] = new CodePage { Namespace = "DocumentLibrary", Xmlns = "documentlibrary" };
this.codePages[19].AddToken(0x05, "LinkId");
this.codePages[19].AddToken(0x06, "DisplayName");
this.codePages[19].AddToken(0x07, "IsFolder");
this.codePages[19].AddToken(0x08, "CreationDate");
this.codePages[19].AddToken(0x09, "LastModifiedDate");
this.codePages[19].AddToken(0x0A, "IsHidden");
this.codePages[19].AddToken(0x0B, "ContentLength");
this.codePages[19].AddToken(0x0C, "ContentType");
// Code Page 20: ItemOperations
this.codePages[20] = new CodePage { Namespace = "ItemOperations", Xmlns = "itemoperations" };
this.codePages[20].AddToken(0x05, "ItemOperations");
this.codePages[20].AddToken(0x06, "Fetch");
this.codePages[20].AddToken(0x07, "Store");
this.codePages[20].AddToken(0x08, "Options");
this.codePages[20].AddToken(0x09, "Range");
this.codePages[20].AddToken(0x0A, "Total");
this.codePages[20].AddToken(0x0B, "Properties");
this.codePages[20].AddToken(0x0C, "Data");
this.codePages[20].AddToken(0x0D, "Status");
this.codePages[20].AddToken(0x0E, "Response");
this.codePages[20].AddToken(0x0F, "Version");
this.codePages[20].AddToken(0x10, "Schema");
this.codePages[20].AddToken(0x11, "Part");
this.codePages[20].AddToken(0x12, "EmptyFolderContents");
this.codePages[20].AddToken(0x13, "DeleteSubFolders");
this.codePages[20].AddToken(0x14, "UserName");
this.codePages[20].AddToken(0x15, "Password");
this.codePages[20].AddToken(0x16, "Move");
this.codePages[20].AddToken(0x17, "DstFldId");
this.codePages[20].AddToken(0x18, "ConversationId");
this.codePages[20].AddToken(0x19, "MoveAlways");
// Code Page 21: ComposeMail
this.codePages[21] = new CodePage { Namespace = "ComposeMail", Xmlns = "composemail" };
this.codePages[21].AddToken(0x05, "SendMail");
this.codePages[21].AddToken(0x06, "SmartForward");
this.codePages[21].AddToken(0x07, "SmartReply");
this.codePages[21].AddToken(0x08, "SaveInSentItems");
this.codePages[21].AddToken(0x09, "ReplaceMime");
this.codePages[21].AddToken(0x0B, "Source");
this.codePages[21].AddToken(0x0C, "FolderId");
this.codePages[21].AddToken(0x0D, "ItemId");
this.codePages[21].AddToken(0x0E, "LongId");
this.codePages[21].AddToken(0x0F, "InstanceId");
this.codePages[21].AddToken(0x10, "Mime");
this.codePages[21].AddToken(0x11, "ClientId");
this.codePages[21].AddToken(0x12, "Status");
this.codePages[21].AddToken(0x13, "AccountId");
this.codePages[21].AddToken(0x15, "Forwardees");
this.codePages[21].AddToken(0x16, "Forwardee");
this.codePages[21].AddToken(0x17, "ForwardeeName");
this.codePages[21].AddToken(0x18, "ForwardeeEmail");
// Code Page 22: Email2
this.codePages[22] = new CodePage { Namespace = "Email2", Xmlns = "email2" };
this.codePages[22].AddToken(0x05, "UmCallerID");
this.codePages[22].AddToken(0x06, "UmUserNotes");
this.codePages[22].AddToken(0x07, "UmAttDuration");
this.codePages[22].AddToken(0x08, "UmAttOrder");
this.codePages[22].AddToken(0x09, "ConversationId");
this.codePages[22].AddToken(0x0A, "ConversationIndex");
this.codePages[22].AddToken(0x0B, "LastVerbExecuted");
this.codePages[22].AddToken(0x0C, "LastVerbExecutionTime");
this.codePages[22].AddToken(0x0D, "ReceivedAsBcc");
this.codePages[22].AddToken(0x0E, "Sender");
this.codePages[22].AddToken(0x0F, "CalendarType");
this.codePages[22].AddToken(0x10, "IsLeapMonth");
this.codePages[22].AddToken(0x11, "AccountId");
this.codePages[22].AddToken(0x12, "FirstDayOfWeek");
this.codePages[22].AddToken(0x13, "MeetingMessageType");
this.codePages[22].AddToken(0x15, "IsDraft");
this.codePages[22].AddToken(0x16, "Bcc");
this.codePages[22].AddToken(0x17, "Send");
// Code Page 23: Notes
this.codePages[23] = new CodePage { Namespace = "Notes", Xmlns = "notes" };
this.codePages[23].AddToken(0x05, "Subject");
this.codePages[23].AddToken(0x06, "MessageClass");
this.codePages[23].AddToken(0x07, "LastModifiedDate");
this.codePages[23].AddToken(0x08, "Categories");
this.codePages[23].AddToken(0x09, "Category");
// Code Page 24: RightsManagement
this.codePages[24] = new CodePage { Namespace = "RightsManagement", Xmlns = "rightsmanagement" };
this.codePages[24].AddToken(0x05, "RightsManagementSupport");
this.codePages[24].AddToken(0x06, "RightsManagementTemplates");
this.codePages[24].AddToken(0x07, "RightsManagementTemplate");
this.codePages[24].AddToken(0x08, "RightsManagementLicense");
this.codePages[24].AddToken(0x09, "EditAllowed");
this.codePages[24].AddToken(0x0A, "ReplyAllowed");
this.codePages[24].AddToken(0x0B, "ReplyAllAllowed");
this.codePages[24].AddToken(0x0C, "ForwardAllowed");
this.codePages[24].AddToken(0x0D, "ModifyRecipientsAllowed");
this.codePages[24].AddToken(0x0E, "ExtractAllowed");
this.codePages[24].AddToken(0x0F, "PrintAllowed");
this.codePages[24].AddToken(0x10, "ExportAllowed");
this.codePages[24].AddToken(0x11, "ProgrammaticAccessAllowed");
this.codePages[24].AddToken(0x12, "Owner");
this.codePages[24].AddToken(0x13, "ContentExpiryDate");
this.codePages[24].AddToken(0x14, "TemplateID");
this.codePages[24].AddToken(0x15, "TemplateName");
this.codePages[24].AddToken(0x16, "TemplateDescription");
this.codePages[24].AddToken(0x17, "ContentOwner");
this.codePages[24].AddToken(0x18, "RemoveRightsManagementProtection");
}
/// <summary>
/// Gets the DataCollection in encoding process
/// </summary>
public Dictionary<string, int> EncodeDataCollection
{
get { return this.encodeDataCollection; }
}
/// <summary>
/// Gets the DataCollection in decoding process
/// </summary>
public Dictionary<string, int> DecodeDataCollection
{
get { return this.decodeDataCollection; }
}
/// <summary>
/// Loads byte array and decode to xml string.
/// </summary>
/// <param name="byteWBXML">The bytes to be decoded</param>
/// <returns>The decoded xml string.</returns>
public string DecodeToXml(byte[] byteWBXML)
{
this.xmlDoc = new XmlDocument();
ByteQueue bytes = new ByteQueue(byteWBXML);
// Remove the version from bytes
bytes.Dequeue();
// Remove public identifier from bytes
bytes.DequeueMultibyteInt();
// Gets the Character set from bytes
int charset = bytes.DequeueMultibyteInt();
if (charset != 0x6A)
{
return string.Empty;
}
// String table length. MS-ASWBXML does not use string tables, it should be 0.
int stringTableLength = bytes.DequeueMultibyteInt();
this.site.Assert.AreEqual<int>(0, stringTableLength, "MS-ASWBXML does not use string tables, therefore String table length should be 0.");
// Initializes the DecodeDataCollection and begins to record
if (null == this.decodeDataCollection)
{
this.decodeDataCollection = new Dictionary<string, int>();
}
else
{
this.decodeDataCollection.Clear();
}
// Adds the declaration
XmlDeclaration xmlDec = this.xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
this.xmlDoc.InsertBefore(xmlDec, null);
XmlNode currentNode = this.xmlDoc;
while (bytes.Count > 0)
{
byte currentByte = bytes.Dequeue();
switch ((GlobalTokens)currentByte)
{
case GlobalTokens.SWITCH_PAGE:
int newCodePage = (int)bytes.Dequeue();
if (newCodePage >= 0 && newCodePage < 25)
{
this.currentCodePage = newCodePage;
}
else
{
this.site.Assert.Fail("Code page value which defined in MS-ASWBXML should be between 0-24, the actual value is : {0}.", newCodePage);
}
break;
case GlobalTokens.END:
if (currentNode.ParentNode != null)
{
currentNode = currentNode.ParentNode;
}
else
{
return string.Empty;
}
break;
case GlobalTokens.OPAQUE:
int cdataLength = bytes.DequeueMultibyteInt();
XmlCDataSection newOpaqueNode;
if (currentNode.Name == "ConversationId"
|| currentNode.Name == "ConversationIndex")
{
newOpaqueNode = this.xmlDoc.CreateCDataSection(bytes.DequeueBase64String(cdataLength));
}
else
{
newOpaqueNode = this.xmlDoc.CreateCDataSection(bytes.DequeueString(cdataLength));
}
currentNode.AppendChild(newOpaqueNode);
break;
case GlobalTokens.STR_I:
XmlNode newTextNode = this.xmlDoc.CreateTextNode(bytes.DequeueString());
currentNode.AppendChild(newTextNode);
break;
case GlobalTokens.ENTITY:
case GlobalTokens.EXT_0:
case GlobalTokens.EXT_1:
case GlobalTokens.EXT_2:
case GlobalTokens.EXT_I_0:
case GlobalTokens.EXT_I_1:
case GlobalTokens.EXT_I_2:
case GlobalTokens.EXT_T_0:
case GlobalTokens.EXT_T_1:
case GlobalTokens.EXT_T_2:
case GlobalTokens.LITERAL:
case GlobalTokens.LITERAL_A:
case GlobalTokens.LITERAL_AC:
case GlobalTokens.LITERAL_C:
case GlobalTokens.PI:
case GlobalTokens.STR_T:
return string.Empty;
default:
bool hasAttributes = (currentByte & 0x80) > 0;
bool hasContent = (currentByte & 0x40) > 0;
byte token = (byte)(currentByte & 0x3F);
if (hasAttributes)
{
return string.Empty;
}
string strTag = this.codePages[this.currentCodePage].GetTag(token) ?? string.Format(CultureInfo.CurrentCulture, "UNKNOWN_TAG_{0,2:X}", token);
XmlNode newNode;
try
{
newNode = this.xmlDoc.CreateElement(this.codePages[this.currentCodePage].Xmlns, strTag, this.codePages[this.currentCodePage].Namespace);
}
catch (XmlException)
{
return string.Empty;
}
try
{
string codepageName = this.codePages[this.currentCodePage].Xmlns;
string combinedTagAndToken = string.Format(CultureInfo.CurrentCulture, @"{0}|{1}|{2}|{3}", this.decodeDataCollection.Count, codepageName, strTag, token);
this.decodeDataCollection.Add(combinedTagAndToken, this.currentCodePage);
}
catch (ArgumentException)
{
return string.Empty;
}
newNode.Prefix = string.Empty;
currentNode.AppendChild(newNode);
if (hasContent)
{
currentNode = newNode;
}
break;
}
}
using (StringWriter stringWriter = new StringWriter())
{
XmlTextWriter textWriter = new XmlTextWriter(stringWriter) { Formatting = Formatting.Indented };
this.xmlDoc.WriteTo(textWriter);
textWriter.Flush();
return stringWriter.ToString();
}
}
/// <summary>
/// Loads xml string and encodes to bytes.
/// </summary>
/// <param name="xmlValue">The xml string.</param>
/// <returns>The encoded bytes.</returns>
public byte[] EncodeToWBXML(string xmlValue)
{
this.xmlDoc.LoadXml(xmlValue);
List<byte> byteList = new List<byte>();
// Initializes the EncodeDataCollection
if (this.encodeDataCollection == null)
{
this.encodeDataCollection = new Dictionary<string, int>();
}
else
{
this.encodeDataCollection.Clear();
}
byteList.Add(VersionByte);
byteList.Add(PublicIdentifierByte);
byteList.Add(CharsetByte);
byteList.Add(StringTableLengthByte);
foreach (XmlNode node in this.xmlDoc.ChildNodes)
{
byteList.AddRange(this.EncodeNode(node));
}
return byteList.ToArray();
}
/// <summary>
/// Encodes a string.
/// </summary>
/// <param name="value">The string to encode.</param>
/// <returns>The encoded bytes.</returns>
private static byte[] EncodeString(string value)
{
List<byte> byteList = new List<byte>();
char[] charArray = value.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
byteList.Add((byte)charArray[i]);
}
byteList.Add(0x00);
return byteList.ToArray();
}
/// <summary>
/// Encodes multi byte integer
/// </summary>
/// <param name="value">Then integer to encode.</param>
/// <returns>The encoded bytes</returns>
private static byte[] EncodeMultibyteInteger(int value)
{
List<byte> byteList = new List<byte>();
while (value > 0)
{
byte addByte = (byte)(value & 0x7F);
if (byteList.Count > 0)
{
addByte |= 0x80;
}
byteList.Insert(0, addByte);
value >>= 7;
}
return byteList.ToArray();
}
/// <summary>
/// Encodes opaque data.
/// </summary>
/// <param name="opaqueBytes">The opaque data</param>
/// <returns>The encoded bytes.</returns>
private static byte[] EncodeOpaque(byte[] opaqueBytes)
{
List<byte> byteList = new List<byte>();
byteList.AddRange(EncodeMultibyteInteger(opaqueBytes.Length));
byteList.AddRange(opaqueBytes);
return byteList.ToArray();
}
/// <summary>
/// Encodes a node.
/// </summary>
/// <param name="node">The node need to encode.</param>
/// <returns>The encoded bytes.</returns>
private byte[] EncodeNode(XmlNode node)
{
List<byte> byteList = new List<byte>();
switch (node.NodeType)
{
case XmlNodeType.Element:
if (node.Attributes != null && node.Attributes.Count > 0)
{
this.ParseXmlnsAttributes(node);
}
if (this.SetCodePageByXmlns(node.NamespaceURI))
{
byteList.Add((byte)GlobalTokens.SWITCH_PAGE);
byteList.Add((byte)this.currentCodePage);
}
// Gets token in this.codePages
byte wbxmlMapToken = this.codePages[this.currentCodePage].GetToken(node.LocalName);
byte token = wbxmlMapToken;
if (node.HasChildNodes)
{
token |= 0x40;
}
byteList.Add(token);
string codepageName = this.codePages[this.currentCodePage].Xmlns;
string combinedTagAndToken = string.Format(CultureInfo.CurrentCulture, @"{0}|{1}|{2}|{3}", this.encodeDataCollection.Count, codepageName, node.LocalName, wbxmlMapToken);
this.encodeDataCollection.Add(combinedTagAndToken, this.currentCodePage);
if (node.HasChildNodes)
{
foreach (XmlNode child in node.ChildNodes)
{
byteList.AddRange(this.EncodeNode(child));
}
byteList.Add((byte)GlobalTokens.END);
}
break;
case XmlNodeType.Text:
byteList.Add((byte)GlobalTokens.STR_I);
byteList.AddRange(EncodeString(node.Value));
break;
case XmlNodeType.CDATA:
byteList.Add((byte)GlobalTokens.OPAQUE);
byte[] cdataValue = System.Text.Encoding.ASCII.GetBytes(node.Value);
if (node.ParentNode.Name == "ConversationId"
|| node.ParentNode.Name == "ConversationIndex")
{
cdataValue = System.Convert.FromBase64String(node.Value);
}
byteList.AddRange(EncodeOpaque(cdataValue));
break;
}
return byteList.ToArray();
}
/// <summary>
/// Gets code page index by namespace.
/// </summary>
/// <param name="nameSpace">The namespace</param>
/// <returns>The index of code page</returns>
private int GetCodePageByNamespace(string nameSpace)
{
for (int i = 0; i < this.codePages.Length; i++)
{
if (string.Equals(this.codePages[i].Namespace, nameSpace, StringComparison.CurrentCultureIgnoreCase))
{
return i;
}
}
return -1;
}
/// <summary>
/// Switches to the code page by prefix.
/// </summary>
/// <param name="namespaceUri">The prefix</param>
/// <returns>True, if successful.</returns>
private bool SetCodePageByXmlns(string namespaceUri)
{
if (string.IsNullOrEmpty(namespaceUri))
{
if (this.currentCodePage != this.defaultCodePage)
{
this.currentCodePage = this.defaultCodePage;
return true;
}
return false;
}
if (string.Equals(this.codePages[this.currentCodePage].Xmlns, namespaceUri, StringComparison.CurrentCultureIgnoreCase))
{
return false;
}
for (int i = 0; i < this.codePages.Length; i++)
{
if (string.Equals(this.codePages[i].Namespace, namespaceUri, StringComparison.CurrentCultureIgnoreCase))
{
this.currentCodePage = i;
return true;
}
}
throw new InvalidDataException(string.Format("Unknown Xmlns: {0}.", namespaceUri));
}
/// <summary>
/// Parses namespaceUri attribute
/// </summary>
/// <param name="node">The xml node to parse</param>
private void ParseXmlnsAttributes(XmlNode node)
{
if (node.Attributes == null)
{
return;
}
foreach (XmlAttribute attribute in node.Attributes)
{
int codePage = this.GetCodePageByNamespace(attribute.Value);
if (!string.IsNullOrEmpty(attribute.Value) && (attribute.Value.StartsWith("http://www.w3.org/2001/XMLSchema-instance", StringComparison.CurrentCultureIgnoreCase) || attribute.Value.StartsWith("http://www.w3.org/2001/XMLSchema", StringComparison.CurrentCultureIgnoreCase)))
{
break;
}
if (string.Equals(attribute.Name, "XMLNS", StringComparison.CurrentCultureIgnoreCase))
{
this.defaultCodePage = codePage;
}
else if (string.Equals(attribute.Prefix, "XMLNS", StringComparison.CurrentCultureIgnoreCase))
{
this.codePages[codePage].Xmlns = attribute.LocalName;
}
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management;
using Microsoft.WindowsAzure.Management.Models;
namespace Microsoft.WindowsAzure.Management
{
/// <summary>
/// The Service Management API provides programmatic access to much of the
/// functionality available through the Management Portal. The Service
/// Management API is a REST API. All API operations are performed over
/// SSL and are mutually authenticated using X.509 v3 certificates. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
/// more information)
/// </summary>
public static partial class AffinityGroupOperationsExtensions
{
/// <summary>
/// The Create Affinity Group operation creates a new affinity group
/// for the specified subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Affinity Group
/// operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Create(this IAffinityGroupOperations operations, AffinityGroupCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAffinityGroupOperations)s).CreateAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Create Affinity Group operation creates a new affinity group
/// for the specified subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Affinity Group
/// operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CreateAsync(this IAffinityGroupOperations operations, AffinityGroupCreateParameters parameters)
{
return operations.CreateAsync(parameters, CancellationToken.None);
}
/// <summary>
/// The Delete Affinity Group operation deletes an affinity group in
/// the specified subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
/// </param>
/// <param name='affinityGroupName'>
/// Required. The name of the affinity group.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IAffinityGroupOperations operations, string affinityGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAffinityGroupOperations)s).DeleteAsync(affinityGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Delete Affinity Group operation deletes an affinity group in
/// the specified subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
/// </param>
/// <param name='affinityGroupName'>
/// Required. The name of the affinity group.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IAffinityGroupOperations operations, string affinityGroupName)
{
return operations.DeleteAsync(affinityGroupName, CancellationToken.None);
}
/// <summary>
/// The Get Affinity Group Properties operation returns the system
/// properties associated with the specified affinity group. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
/// </param>
/// <param name='affinityGroupName'>
/// Required. The name of the desired affinity group as returned by the
/// name element of the List Affinity Groups operation.
/// </param>
/// <returns>
/// The Get Affinity Group operation response.
/// </returns>
public static AffinityGroupGetResponse Get(this IAffinityGroupOperations operations, string affinityGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAffinityGroupOperations)s).GetAsync(affinityGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Affinity Group Properties operation returns the system
/// properties associated with the specified affinity group. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
/// </param>
/// <param name='affinityGroupName'>
/// Required. The name of the desired affinity group as returned by the
/// name element of the List Affinity Groups operation.
/// </param>
/// <returns>
/// The Get Affinity Group operation response.
/// </returns>
public static Task<AffinityGroupGetResponse> GetAsync(this IAffinityGroupOperations operations, string affinityGroupName)
{
return operations.GetAsync(affinityGroupName, CancellationToken.None);
}
/// <summary>
/// The List Affinity Groups operation lists the affinity groups
/// associated with the specified subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
/// </param>
/// <returns>
/// The List Affinity Groups operation response.
/// </returns>
public static AffinityGroupListResponse List(this IAffinityGroupOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAffinityGroupOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List Affinity Groups operation lists the affinity groups
/// associated with the specified subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
/// </param>
/// <returns>
/// The List Affinity Groups operation response.
/// </returns>
public static Task<AffinityGroupListResponse> ListAsync(this IAffinityGroupOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
/// <summary>
/// The Update Affinity Group operation updates the label and/or the
/// description for an affinity group for the specified subscription.
/// (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
/// </param>
/// <param name='affinityGroupName'>
/// Required. The name of the affinity group.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Affinity Group
/// operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Update(this IAffinityGroupOperations operations, string affinityGroupName, AffinityGroupUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAffinityGroupOperations)s).UpdateAsync(affinityGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Update Affinity Group operation updates the label and/or the
/// description for an affinity group for the specified subscription.
/// (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
/// </param>
/// <param name='affinityGroupName'>
/// Required. The name of the affinity group.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Affinity Group
/// operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> UpdateAsync(this IAffinityGroupOperations operations, string affinityGroupName, AffinityGroupUpdateParameters parameters)
{
return operations.UpdateAsync(affinityGroupName, parameters, CancellationToken.None);
}
}
}
| |
// 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.
//Simple arithmatic manipulation of one 2D array elements
using System;
public class string1
{
public static Random rand;
public static int size;
public static double GenerateDbl()
{
int e;
int op1 = (int)((float)rand.Next() / Int32.MaxValue * 2);
if (op1 == 0)
e = -rand.Next(0, 14);
else
e = +rand.Next(0, 14);
return Math.Pow(2, e);
}
public static void Init2DMatrix(out String[,] m, out String[][] refm)
{
int i, j;
i = 0;
double temp;
m = new String[size, size];
refm = new String[size][];
for (int k = 0; k < refm.Length; k++)
refm[k] = new String[size];
while (i < size)
{
j = 0;
while (j < size)
{
temp = GenerateDbl();
m[i, j] = Convert.ToString(temp - 60);
refm[i][j] = Convert.ToString(temp - 60);
j++;
}
i++;
}
}
public static void Process2DArray(ref String[,] a)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
{
double temp = Convert.ToDouble(a[i, j]);
temp += Convert.ToDouble(a[0, j]) + Convert.ToDouble(a[1, j]);
temp *= Convert.ToDouble(a[i, j]) + Convert.ToDouble(a[2, j]);
temp -= Convert.ToDouble(a[i, j]) * Convert.ToDouble(a[3, j]);
temp /= Convert.ToDouble(a[i, j]) + Convert.ToDouble(a[4, j]);
for (int k = 5; k < size; k++)
temp += Convert.ToDouble(a[k, j]);
a[i, j] = Convert.ToString(temp);
}
}
public static void ProcessJagged2DArray(ref String[][] a)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
{
double temp = Convert.ToDouble(a[i][j]);
temp += Convert.ToDouble(a[0][j]) + Convert.ToDouble(a[1][j]);
temp *= Convert.ToDouble(a[i][j]) + Convert.ToDouble(a[2][j]);
temp -= Convert.ToDouble(a[i][j]) * Convert.ToDouble(a[3][j]);
temp /= Convert.ToDouble(a[i][j]) + Convert.ToDouble(a[4][j]);
for (int k = 5; k < size; k++)
temp += Convert.ToDouble(a[k][j]);
a[i][j] = Convert.ToString(temp);
}
}
public static void Init3DMatrix(String[,,] m, String[][] refm)
{
int i, j;
i = 0;
double temp;
while (i < size)
{
j = 0;
while (j < size)
{
temp = GenerateDbl();
m[i, size, j] = Convert.ToString(temp - 60);
refm[i][j] = Convert.ToString(temp - 60);
j++;
}
i++;
}
}
public static void Process3DArray(String[,,] a)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
{
double temp = Convert.ToDouble(a[i, size, j]);
temp += Convert.ToDouble(a[0, size, j]) + Convert.ToDouble(a[1, size, j]);
temp *= Convert.ToDouble(a[i, size, j]) + Convert.ToDouble(a[2, size, j]);
temp -= Convert.ToDouble(a[i, size, j]) * Convert.ToDouble(a[3, size, j]);
temp /= Convert.ToDouble(a[i, size, j]) + Convert.ToDouble(a[4, size, j]);
for (int k = 5; k < size; k++)
temp += Convert.ToDouble(a[k, size, j]);
a[i, size, j] = Convert.ToString(temp);
}
}
public static void ProcessJagged3DArray(String[][] a)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
{
double temp = Convert.ToDouble(a[i][j]);
temp += Convert.ToDouble(a[0][j]) + Convert.ToDouble(a[1][j]);
temp *= Convert.ToDouble(a[i][j]) + Convert.ToDouble(a[2][j]);
temp -= Convert.ToDouble(a[i][j]) * Convert.ToDouble(a[3][j]);
temp /= Convert.ToDouble(a[i][j]) + Convert.ToDouble(a[4][j]);
for (int k = 5; k < size; k++)
temp += Convert.ToDouble(a[k][j]);
a[i][j] = Convert.ToString(temp);
}
}
public static int Main()
{
bool pass = false;
rand = new Random();
size = rand.Next(5, 8);
Console.WriteLine();
Console.WriteLine("2D Array");
Console.WriteLine("Element manipulation of {0} by {0} matrices with different arithmatic operations", size);
Console.WriteLine("Matrix element stores string converted from random double");
Console.WriteLine("array set/get, ref/out param are used");
String[,] ima2d = new String[size, size];
String[][] refa2d = new String[size][];
Init2DMatrix(out ima2d, out refa2d);
int m = 0;
int n;
while (m < size)
{
n = 0;
while (n < size)
{
Process2DArray(ref ima2d);
ProcessJagged2DArray(ref refa2d);
n++;
}
m++;
}
pass = true;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (ima2d[i, j] != refa2d[i][j])
{
Console.WriteLine("i={0}, j={1}, imr[i,j] {2}!=refr[i][j] {3}", i, j, ima2d[i, j], refa2d[i][j]);
pass = false;
}
}
}
if (pass)
{
try
{
ima2d[0, -1] = "5";
pass = false;
}
catch (IndexOutOfRangeException)
{ }
}
Console.WriteLine();
Console.WriteLine("3D Array");
Console.WriteLine("Element manipulation of {0} by {1} by {0} matrices with different arithmatic operations", size, size + 1);
String[,,] ima3d = new String[size, size + 1, size];
String[][] refa3d = new String[size][];
for (int k = 0; k < refa3d.Length; k++)
refa3d[k] = new String[size];
Init3DMatrix(ima3d, refa3d);
m = 0;
n = 0;
while (m < size)
{
n = 0;
while (n < size)
{
Process3DArray(ima3d);
ProcessJagged3DArray(refa3d);
n++;
}
m++;
}
pass = true;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (ima3d[i, size, j] != refa3d[i][j])
{
Console.WriteLine("i={0}, j={1}, imr[i,{4},j] {2}!=refr[i][j] {3}", i, j, ima3d[i, size, j], refa3d[i][j], size);
pass = false;
}
}
}
if (pass)
{
try
{
ima3d[0, 100, 0] = "";
pass = false;
}
catch (IndexOutOfRangeException)
{ }
}
Console.WriteLine();
if (pass)
{
Console.WriteLine("PASSED");
return 100;
}
else
{
Console.WriteLine("FAILED");
return 1;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Sounds
//--------------------------------------------------------------------------
datablock SFXProfile(RyderFireSound)
{
filename = "art/sound/weapons/wpn_ryder_fire";
description = AudioClose3D;
preload = true;
};
datablock SFXProfile(RyderReloadSound)
{
filename = "art/sound/weapons/wpn_ryder_reload";
description = AudioClose3D;
preload = true;
};
datablock SFXProfile(RyderSwitchinSound)
{
filename = "art/sound/weapons/wpn_ryder_switchin";
description = AudioClose3D;
preload = true;
};
// ----------------------------------------------------------------------------
// Particles
// ----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Explosion
//-----------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Shell ejected during reload.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Projectile Object
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Ammo Item
//-----------------------------------------------------------------------------
datablock ItemData(RyderClip)
{
// Mission editor category
category = "AmmoClip";
// Add the Ammo namespace as a parent. The ammo namespace provides
// common ammo related functions and hooks into the inventory system.
className = "AmmoClip";
// Basic Item properties
shapeFile = "art/shapes/weapons/Ryder/TP_Ryder.DAE";
mass = 1;
elasticity = 0.2;
friction = 0.6;
// Dynamic properties defined by the scripts
pickUpName = "Ryder clip";
count = 1;
maxInventory = 10;
};
datablock ItemData(RyderAmmo)
{
// Mission editor category
category = "Ammo";
// Add the Ammo namespace as a parent. The ammo namespace provides
// common ammo related functions and hooks into the inventory system.
className = "Ammo";
// Basic Item properties
shapeFile = "art/shapes/weapons/Ryder/TP_Ryder.DAE";
mass = 1;
elasticity = 0.2;
friction = 0.6;
// Dynamic properties defined by the scripts
pickUpName = "Ryder bullet";
maxInventory = 8;
clip = RyderClip;
};
//--------------------------------------------------------------------------
// Weapon Item. This is the item that exists in the world, i.e. when it's
// been dropped, thrown or is acting as re-spawnable item. When the weapon
// is mounted onto a shape, the SoldierWeaponImage is used.
//-----------------------------------------------------------------------------
datablock ItemData(Ryder)
{
// Mission editor category
category = "Weapon";
// Hook into Item Weapon class hierarchy. The weapon namespace
// provides common weapon handling functions in addition to hooks
// into the inventory system.
className = "Weapon";
// Basic Item properties
shapeFile = "art/shapes/weapons/Ryder/TP_Ryder.DAE";
mass = 1;
elasticity = 0.2;
friction = 0.6;
emap = true;
PreviewImage = 'ryder.png';
// Dynamic properties defined by the scripts
pickUpName = "Ryder pistol";
description = "Ryder";
image = RyderWeaponImage;
reticle = "crossHair";
};
datablock ShapeBaseImageData(RyderWeaponImage)
{
// Basic Item properties
shapeFile = "art/shapes/weapons/Ryder/TP_Ryder.DAE";
shapeFileFP = "art/shapes/weapons/Ryder/FP_Ryder.DAE";
emap = true;
imageAnimPrefix = "Pistol";
imageAnimPrefixFP = "Pistol";
// Specify mount point & offset for 3rd person, and eye offset
// for first person rendering.
mountPoint = 0;
firstPerson = true;
useEyeNode = true;
animateOnServer = true;
// When firing from a point offset from the eye, muzzle correction
// will adjust the muzzle vector to point to the eye LOS point.
// Since this weapon doesn't actually fire from the muzzle point,
// we need to turn this off.
correctMuzzleVector = true;
// Add the WeaponImage namespace as a parent, WeaponImage namespace
// provides some hooks into the inventory system.
class = "WeaponImage";
className = "WeaponImage";
// Projectiles and Ammo.
item = Ryder;
ammo = RyderAmmo;
clip = RyderClip;
projectile = BulletProjectile;
projectileType = Projectile;
projectileSpread = "0.0";
altProjectile = GrenadeLauncherProjectile;
altProjectileSpread = "0.02";
casing = BulletShell;
shellExitDir = "1.0 0.3 1.0";
shellExitOffset = "0.15 -0.56 -0.1";
shellExitVariance = 15.0;
shellVelocity = 3.0;
// Weapon lights up while firing
lightType = "WeaponFireLight";
lightColor = "0.992126 0.968504 0.700787 1";
lightRadius = "4";
lightDuration = "100";
lightBrightness = 2;
// Shake camera while firing.
shakeCamera = "1";
camShakeFreq = "10 10 10";
camShakeAmp = "5 5 5";
// Images have a state system which controls how the animations
// are run, which sounds are played, script callbacks, etc. This
// state system is downloaded to the client so that clients can
// predict state changes and animate accordingly. The following
// system supports basic ready->fire->reload transitions as
// well as a no-ammo->dryfire idle state.
useRemainderDT = true;
// Initial start up state
stateName[0] = "Preactivate";
stateTransitionOnLoaded[0] = "Activate";
stateTransitionOnNoAmmo[0] = "NoAmmo";
// Activating the gun. Called when the weapon is first
// mounted and there is ammo.
stateName[1] = "Activate";
stateTransitionGeneric0In[1] = "SprintEnter";
stateTransitionOnTimeout[1] = "Ready";
stateTimeoutValue[1] = 1.5;
stateSequence[1] = "switch_in";
stateSound[1] = RyderSwitchinSound;
// Ready to fire, just waiting for the trigger
stateName[2] = "Ready";
stateTransitionGeneric0In[2] = "SprintEnter";
stateTransitionOnMotion[2] = "ReadyMotion";
stateScaleAnimation[2] = false;
stateScaleAnimationFP[2] = false;
stateTransitionOnNoAmmo[2] = "NoAmmo";
stateTransitionOnTriggerDown[2] = "Fire";
stateSequence[2] = "idle";
// Ready to fire with player moving
stateName[3] = "ReadyMotion";
stateTransitionGeneric0In[3] = "SprintEnter";
stateTransitionOnNoMotion[3] = "Ready";
stateWaitForTimeout[3] = false;
stateScaleAnimation[3] = false;
stateScaleAnimationFP[3] = false;
stateSequenceTransitionIn[3] = true;
stateSequenceTransitionOut[3] = true;
stateTransitionOnNoAmmo[3] = "NoAmmo";
stateTransitionOnTriggerDown[3] = "Fire";
stateSequence[3] = "run";
// Fire the weapon. Calls the fire script which does
// the actual work.
stateName[4] = "Fire";
stateTransitionGeneric0In[4] = "SprintEnter";
stateTransitionOnTimeout[4] = "WaitForRelease";
stateTimeoutValue[4] = 0.23;
stateWaitForTimeout[4] = true;
stateFire[4] = true;
stateRecoil[4] = "";
stateAllowImageChange[4] = false;
stateSequence[4] = "fire";
stateScaleAnimation[4] = true;
stateSequenceNeverTransition[4] = true;
stateSequenceRandomFlash[4] = true; // use muzzle flash sequence
stateScript[4] = "onFire";
stateEmitter[4] = GunFireSmokeEmitter;
stateEmitterTime[4] = 0.025;
stateEjectShell[4] = true;
stateSound[4] = RyderFireSound;
// Wait for the player to release the trigger
stateName[5] = "WaitForRelease";
stateTransitionGeneric0In[5] = "SprintEnter";
stateTransitionOnTriggerUp[5] = "NewRound";
stateTimeoutValue[5] = 0.05;
stateWaitForTimeout[5] = true;
stateAllowImageChange[5] = false;
// Put another round in the chamber
stateName[6] = "NewRound";
stateTransitionGeneric0In[6] = "SprintEnter";
stateTransitionOnNoAmmo[6] = "NoAmmo";
stateTransitionOnTimeout[6] = "Ready";
stateWaitForTimeout[6] = "0";
stateTimeoutValue[6] = 0.05;
stateAllowImageChange[6] = false;
// No ammo in the weapon, just idle until something
// shows up. Play the dry fire sound if the trigger is
// pulled.
stateName[7] = "NoAmmo";
stateTransitionGeneric0In[7] = "SprintEnter";
stateTransitionOnMotion[7] = "NoAmmoMotion";
stateTransitionOnAmmo[7] = "ReloadClip";
stateTimeoutValue[7] = 0.1; // Slight pause to allow script to run when trigger is still held down from Fire state
stateScript[7] = "onClipEmpty";
stateTransitionOnTriggerDown[7] = "DryFire";
stateSequence[7] = "idle";
stateScaleAnimation[7] = false;
stateScaleAnimationFP[7] = false;
stateName[8] = "NoAmmoMotion";
stateTransitionGeneric0In[8] = "SprintEnter";
stateTransitionOnNoMotion[8] = "NoAmmo";
stateWaitForTimeout[8] = false;
stateScaleAnimation[8] = false;
stateScaleAnimationFP[8] = false;
stateSequenceTransitionIn[8] = true;
stateSequenceTransitionOut[8] = true;
stateTransitionOnAmmo[8] = "ReloadClip";
stateTransitionOnTriggerDown[8] = "DryFire";
stateSequence[8] = "run";
// No ammo dry fire
stateName[9] = "DryFire";
stateTransitionGeneric0In[9] = "SprintEnter";
stateTransitionOnAmmo[9] = "ReloadClip";
stateWaitForTimeout[9] = "0";
stateTimeoutValue[9] = 0.7;
stateTransitionOnTimeout[9] = "NoAmmo";
stateScript[9] = "onDryFire";
// Play the reload clip animation
stateName[10] = "ReloadClip";
stateTransitionGeneric0In[10] = "SprintEnter";
stateTransitionOnTimeout[10] = "Ready";
stateWaitForTimeout[10] = true;
stateTimeoutValue[10] = 2.0;
stateReload[10] = true;
stateSequence[10] = "reload";
stateShapeSequence[10] = "Reload";
stateScaleShapeSequence[10] = true;
stateSound[10] = RyderReloadSound;
// Start Sprinting
stateName[11] = "SprintEnter";
stateTransitionGeneric0Out[11] = "SprintExit";
stateTransitionOnTimeout[11] = "Sprinting";
stateWaitForTimeout[11] = false;
stateTimeoutValue[11] = 0.5;
stateWaitForTimeout[11] = false;
stateScaleAnimation[11] = false;
stateScaleAnimationFP[11] = false;
stateSequenceTransitionIn[11] = true;
stateSequenceTransitionOut[11] = true;
stateAllowImageChange[11] = false;
stateSequence[11] = "sprint";
// Sprinting
stateName[12] = "Sprinting";
stateTransitionGeneric0Out[12] = "SprintExit";
stateWaitForTimeout[12] = false;
stateScaleAnimation[12] = false;
stateScaleAnimationFP[12] = false;
stateSequenceTransitionIn[12] = true;
stateSequenceTransitionOut[12] = true;
stateAllowImageChange[12] = false;
stateSequence[12] = "sprint";
// Stop Sprinting
stateName[13] = "SprintExit";
stateTransitionGeneric0In[13] = "SprintEnter";
stateTransitionOnTimeout[13] = "Ready";
stateWaitForTimeout[13] = false;
stateTimeoutValue[13] = 0.5;
stateSequenceTransitionIn[13] = true;
stateSequenceTransitionOut[13] = true;
stateAllowImageChange[13] = false;
stateSequence[13] = "sprint";
camShakeDuration = "0.2";
};
| |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.RabbitMqTransport
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using Configuration;
using Configuration.Configurators;
using NewIdFormatters;
using RabbitMQ.Client;
using Topology;
using Util;
public static class RabbitMqAddressExtensions
{
static readonly INewIdFormatter _formatter = new ZBase32Formatter();
static readonly Regex _regex = new Regex(@"^[A-Za-z0-9\-_\.:]+$");
public static string GetTemporaryQueueName(this IRabbitMqBusFactoryConfigurator configurator, string prefix)
{
var sb = new StringBuilder(prefix);
var host = HostMetadataCache.Host;
foreach (char c in host.MachineName)
{
if (char.IsLetterOrDigit(c))
sb.Append(c);
else if (c == '.' || c == '_' || c == '-' || c == ':')
sb.Append(c);
}
sb.Append('-');
foreach (char c in host.ProcessName)
{
if (char.IsLetterOrDigit(c))
sb.Append(c);
else if (c == '.' || c == '_' || c == '-' || c == ':')
sb.Append(c);
}
sb.Append('-');
sb.Append(NewId.Next().ToString(_formatter));
return sb.ToString();
}
public static Uri GetInputAddress(this RabbitMqHostSettings hostSettings, ReceiveSettings receiveSettings)
{
var builder = new UriBuilder
{
Scheme = "rabbitmq",
Host = hostSettings.Host,
Port = hostSettings.Port,
Path = (string.IsNullOrWhiteSpace(hostSettings.VirtualHost) || hostSettings.VirtualHost == "/")
? receiveSettings.QueueName
: string.Join("/", hostSettings.VirtualHost, receiveSettings.QueueName)
};
builder.Query += string.Join("&", GetQueryStringOptions(receiveSettings));
return builder.Uri;
}
public static Uri GetQueueAddress(this RabbitMqHostSettings hostSettings, string queueName)
{
UriBuilder builder = GetHostUriBuilder(hostSettings, queueName);
return builder.Uri;
}
/// <summary>
/// Returns a UriBuilder for the host and entity specified
/// </summary>
/// <param name="hostSettings">The host settings</param>
/// <param name="entityName">The entity name (queue/exchange)</param>
/// <returns>A UriBuilder</returns>
static UriBuilder GetHostUriBuilder(RabbitMqHostSettings hostSettings, string entityName)
{
return new UriBuilder
{
Scheme = "rabbitmq",
Host = hostSettings.Host,
Port = hostSettings.Port,
Path = (string.IsNullOrWhiteSpace(hostSettings.VirtualHost) || hostSettings.VirtualHost == "/")
? entityName
: string.Join("/", hostSettings.VirtualHost, entityName)
};
}
/// <summary>
/// Return a send address for the exchange
/// </summary>
/// <param name="host">The RabbitMQ host</param>
/// <param name="exchangeName">The exchange name</param>
/// <param name="configure">An optional configuration for the exchange to set type, durable, etc.</param>
/// <returns></returns>
public static Uri GetSendAddress(this IRabbitMqHost host, string exchangeName, Action<IExchangeConfigurator> configure = null)
{
var builder = GetHostUriBuilder(host.Settings, exchangeName);
var sendSettings = new RabbitMqSendSettings(exchangeName, ExchangeType.Fanout, true, false);
configure?.Invoke(sendSettings);
builder.Query += string.Join("&", GetQueryStringOptions(sendSettings));
return builder.Uri;
}
public static Uri GetSendAddress(this RabbitMqHostSettings hostSettings, SendSettings sendSettings)
{
var builder = new UriBuilder
{
Scheme = "rabbitmq",
Host = hostSettings.Host,
Port = hostSettings.Port,
Path = hostSettings.VirtualHost != "/"
? string.Join("/", hostSettings.VirtualHost, sendSettings.ExchangeName)
: sendSettings.ExchangeName
};
builder.Query += string.Join("&", GetQueryStringOptions(sendSettings));
return builder.Uri;
}
static IEnumerable<string> GetQueryStringOptions(ReceiveSettings settings)
{
if (!settings.Durable)
yield return "durable=false";
if (settings.AutoDelete)
yield return "autodelete=true";
if (settings.Exclusive)
yield return "exclusive=true";
if (settings.PrefetchCount != 0)
yield return "prefetch=" + settings.PrefetchCount;
}
static IEnumerable<string> GetQueryStringOptions(SendSettings settings)
{
if (!settings.Durable)
yield return "durable=false";
if (settings.AutoDelete)
yield return "autodelete=true";
if (settings.BindToQueue)
yield return "bind=true";
if (!string.IsNullOrWhiteSpace(settings.QueueName))
yield return "queue=" + WebUtility.UrlEncode(settings.QueueName);
if (settings.ExchangeType != ExchangeType.Fanout)
yield return "type=" + settings.ExchangeType;
if (settings.ExchangeArguments != null && settings.ExchangeArguments.ContainsKey("x-delayed-type"))
yield return "delayedType=" + settings.ExchangeArguments["x-delayed-type"];
foreach (var binding in settings.ExchangeBindings)
{
yield return $"bindexchange={binding.Exchange.ExchangeName}";
}
}
public static ReceiveSettings GetReceiveSettings(this Uri address)
{
if (string.Compare("rabbitmq", address.Scheme, StringComparison.OrdinalIgnoreCase) != 0)
throw new RabbitMqAddressException("The invalid scheme was specified: " + address.Scheme);
var connectionFactory = new ConnectionFactory
{
HostName = address.Host,
UserName = "guest",
Password = "guest",
};
if (address.IsDefaultPort)
connectionFactory.Port = 5672;
else if (!address.IsDefaultPort)
connectionFactory.Port = address.Port;
string name = address.AbsolutePath.Substring(1);
string[] pathSegments = name.Split('/');
if (pathSegments.Length == 2)
{
connectionFactory.VirtualHost = pathSegments[0];
name = pathSegments[1];
}
ushort heartbeat = address.Query.GetValueFromQueryString("heartbeat", connectionFactory.RequestedHeartbeat);
connectionFactory.RequestedHeartbeat = heartbeat;
if (name == "*")
{
string uri = address.GetLeftPart(UriPartial.Path);
if (uri.EndsWith("*"))
{
name = NewId.Next().ToString("NS");
uri = uri.Remove(uri.Length - 1) + name;
var builder = new UriBuilder(uri);
builder.Query = string.IsNullOrEmpty(address.Query) ? "" : address.Query.Substring(1);
address = builder.Uri;
}
else
throw new InvalidOperationException("Uri is not properly formed");
}
else
VerifyQueueOrExchangeNameIsLegal(name);
ushort prefetch = address.Query.GetValueFromQueryString("prefetch", (ushort)Math.Max(Environment.ProcessorCount, 16));
int timeToLive = address.Query.GetValueFromQueryString("ttl", 0);
bool isTemporary = address.Query.GetValueFromQueryString("temporary", false);
bool durable = address.Query.GetValueFromQueryString("durable", !isTemporary);
bool exclusive = address.Query.GetValueFromQueryString("exclusive", isTemporary);
bool autoDelete = address.Query.GetValueFromQueryString("autodelete", isTemporary);
ReceiveSettings settings = new RabbitMqReceiveSettings
{
AutoDelete = autoDelete,
Durable = durable,
Exclusive = exclusive,
QueueName = name,
PrefetchCount = prefetch,
};
if (timeToLive > 0)
settings.QueueArguments.Add("x-message-ttl", timeToLive.ToString("F0", CultureInfo.InvariantCulture));
return settings;
}
/// <summary>
/// Return the send settings for the address
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public static SendSettings GetSendSettings(this Uri address)
{
if (string.Compare("rabbitmq", address.Scheme, StringComparison.OrdinalIgnoreCase) != 0)
throw new RabbitMqAddressException("The invalid scheme was specified: " + address.Scheme);
string name = address.AbsolutePath.Substring(1);
string[] pathSegments = name.Split('/');
if (pathSegments.Length == 2)
name = pathSegments[1];
if (name == "*")
throw new ArgumentException("Cannot send to a dynamic address");
VerifyQueueOrExchangeNameIsLegal(name);
bool isTemporary = address.Query.GetValueFromQueryString("temporary", false);
bool durable = address.Query.GetValueFromQueryString("durable", !isTemporary);
bool autoDelete = address.Query.GetValueFromQueryString("autodelete", isTemporary);
string exchangeType = address.Query.GetValueFromQueryString("type") ?? ExchangeType.Fanout;
var settings = new RabbitMqSendSettings(name, exchangeType, durable, autoDelete);
bool bindToQueue = address.Query.GetValueFromQueryString("bind", false);
if (bindToQueue)
{
string queueName = WebUtility.UrlDecode(address.Query.GetValueFromQueryString("queue"));
settings.BindToQueue(queueName);
}
string delayedType = address.Query.GetValueFromQueryString("delayedType");
if (!string.IsNullOrWhiteSpace(delayedType))
settings.SetExchangeArgument("x-delayed-type", delayedType);
string bindExchange = address.Query.GetValueFromQueryString("bindexchange");
if (!string.IsNullOrWhiteSpace(bindExchange))
settings.BindToExchange(bindExchange);
return settings;
}
[Obsolete]
public static SendSettings GetSendSettings(this IRabbitMqHost host, Type messageType)
{
return GetSendSettings(host.Settings, messageType);
}
public static SendSettings GetSendSettings(this RabbitMqHostSettings hostSettings, Type messageType)
{
bool isTemporary = messageType.IsTemporaryMessageType();
bool durable = !isTemporary;
bool autoDelete = isTemporary;
string name = hostSettings.MessageNameFormatter.GetMessageName(messageType).ToString();
return new RabbitMqSendSettings(name, ExchangeType.Fanout, durable, autoDelete);
}
public static ConnectionFactory GetConnectionFactory(this RabbitMqHostSettings settings)
{
var factory = new ConnectionFactory
{
AutomaticRecoveryEnabled = false,
NetworkRecoveryInterval = TimeSpan.FromSeconds(1),
TopologyRecoveryEnabled = false,
HostName = settings.Host,
Port = settings.Port,
VirtualHost = settings.VirtualHost ?? "/",
RequestedHeartbeat = settings.Heartbeat
};
if (settings.ClusterMembers != null && settings.ClusterMembers.Any())
{
factory.HostName = null;
factory.HostnameSelector = settings.HostNameSelector;
}
if (settings.UseClientCertificateAsAuthenticationIdentity)
{
factory.AuthMechanisms.Clear();
factory.AuthMechanisms.Add(new ExternalMechanismFactory());
factory.UserName = "";
factory.Password = "";
}
else
{
if (!string.IsNullOrWhiteSpace(settings.Username))
factory.UserName = settings.Username;
if (!string.IsNullOrWhiteSpace(settings.Password))
factory.Password = settings.Password;
}
factory.Ssl.Enabled = settings.Ssl;
factory.Ssl.Version = settings.SslProtocol;
factory.Ssl.AcceptablePolicyErrors = settings.AcceptablePolicyErrors;
factory.Ssl.ServerName = settings.SslServerName;
factory.Ssl.Certs = settings.ClientCertificate == null ? null : new X509Certificate2Collection {settings.ClientCertificate};
if (string.IsNullOrWhiteSpace(factory.Ssl.ServerName))
factory.Ssl.AcceptablePolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
if (string.IsNullOrEmpty(settings.ClientCertificatePath))
{
factory.Ssl.CertPath = "";
factory.Ssl.CertPassphrase = "";
}
else
{
factory.Ssl.CertPath = settings.ClientCertificatePath;
factory.Ssl.CertPassphrase = settings.ClientCertificatePassphrase;
}
factory.ClientProperties = factory.ClientProperties ?? new Dictionary<string, object>();
HostInfo hostInfo = HostMetadataCache.Host;
factory.ClientProperties["client_api"] = "MassTransit";
factory.ClientProperties["masstransit_version"] = hostInfo.MassTransitVersion;
factory.ClientProperties["net_version"] = hostInfo.FrameworkVersion;
factory.ClientProperties["hostname"] = hostInfo.MachineName;
factory.ClientProperties["connected"] = DateTimeOffset.Now.ToString("R");
factory.ClientProperties["process_id"] = hostInfo.ProcessId.ToString();
factory.ClientProperties["process_name"] = hostInfo.ProcessName;
if (hostInfo.Assembly != null)
factory.ClientProperties["assembly"] = hostInfo.Assembly;
if (hostInfo.AssemblyVersion != null)
factory.ClientProperties["assembly_version"] = hostInfo.AssemblyVersion;
return factory;
}
public static RabbitMqHostSettings GetHostSettings(this Uri address)
{
return GetConfigurationHostSettings(address);
}
internal static ConfigurationHostSettings GetConfigurationHostSettings(this Uri address)
{
if (string.Compare("rabbitmq", address.Scheme, StringComparison.OrdinalIgnoreCase) != 0)
throw new RabbitMqAddressException("The invalid scheme was specified: " + address.Scheme);
var hostSettings = new ConfigurationHostSettings
{
Host = address.Host,
Username = "",
Password = "",
Port = address.IsDefaultPort ? 5672 : address.Port
};
if (!string.IsNullOrEmpty(address.UserInfo))
{
string[] parts = address.UserInfo.Split(':');
hostSettings.Username = parts[0];
if (parts.Length >= 2)
hostSettings.Password = parts[1];
}
string name = address.AbsolutePath.Substring(1);
string[] pathSegments = name.Split('/');
hostSettings.VirtualHost = pathSegments.Length == 2 ? pathSegments[0] : "/";
hostSettings.Heartbeat = address.Query.GetValueFromQueryString("heartbeat", (ushort)0);
return hostSettings;
}
static void VerifyQueueOrExchangeNameIsLegal(string queueName)
{
if (string.IsNullOrWhiteSpace(queueName))
throw new RabbitMqAddressException("The queue name must not be null or empty");
bool success = IsValidQueueName(queueName);
if (!success)
{
throw new RabbitMqAddressException(
"The queueName must be a sequence of these characters: letters, digits, hyphen, underscore, period, or colon.");
}
}
public static bool IsValidQueueName(string queueName)
{
Match match = _regex.Match(queueName);
bool success = match.Success;
return success;
}
}
}
| |
using System.Windows.Forms;
namespace XLG.Pipeliner
{
partial class GloveMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GloveMain));
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.NewScriptFile = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.generateCheckedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.generateSelectedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.regenerateCheckedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.regenerateSelectedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.autoRegenOnChangedXSLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.customizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.MetadataSources = new System.Windows.Forms.ListView();
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.label9 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.textConnectionName = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.textAppXlgXsl = new System.Windows.Forms.TextBox();
this.buttonChooseXlgFileXsl = new System.Windows.Forms.Button();
this.buttonEditXlgXslFile = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.checkRegenerateOnly = new System.Windows.Forms.CheckBox();
this.label12 = new System.Windows.Forms.Label();
this.textOutputXml = new System.Windows.Forms.TextBox();
this.buttonChoosetextOutputXml = new System.Windows.Forms.Button();
this.buttonViewtextOutputXml = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.textXlgFile = new System.Windows.Forms.TextBox();
this.buttonChooseXlgFile = new System.Windows.Forms.Button();
this.buttonEditXlgFile = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.textOutput = new System.Windows.Forms.TextBox();
this.buttonChooseOutput = new System.Windows.Forms.Button();
this.buttonViewOutputFolder = new System.Windows.Forms.Button();
this.label5 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.comboProviderName = new System.Windows.Forms.ComboBox();
this.label7 = new System.Windows.Forms.Label();
this.textConnectionStringName = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.textConnectionString = new System.Windows.Forms.TextBox();
this.buttonEditConnectionString = new System.Windows.Forms.Button();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStripButton6 = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton2 = new System.Windows.Forms.ToolStripButton();
this.autoRegenToolbarButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripButton4 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton5 = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.EditClipScript = new System.Windows.Forms.ToolStripButton();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.SuspendLayout();
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
//
// menuStrip1
//
this.menuStrip1.Dock = System.Windows.Forms.DockStyle.None;
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.toolsToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(159, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.NewScriptFile,
this.openToolStripMenuItem,
this.toolStripSeparator,
this.saveToolStripMenuItem,
this.saveAsToolStripMenuItem,
this.toolStripSeparator1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// NewScriptFile
//
this.NewScriptFile.Image = ((System.Drawing.Image)(resources.GetObject("NewScriptFile.Image")));
this.NewScriptFile.ImageTransparentColor = System.Drawing.Color.Magenta;
this.NewScriptFile.Name = "NewScriptFile";
this.NewScriptFile.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.NewScriptFile.Size = new System.Drawing.Size(146, 22);
this.NewScriptFile.Text = "&New";
this.NewScriptFile.Click += new System.EventHandler(this.NewScriptFile_Click);
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image")));
this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.openToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.openToolStripMenuItem.Text = "&Open";
this.openToolStripMenuItem.Click += new System.EventHandler(this.buttonLoad_Click);
//
// toolStripSeparator
//
this.toolStripSeparator.Name = "toolStripSeparator";
this.toolStripSeparator.Size = new System.Drawing.Size(143, 6);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image")));
this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.saveToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.saveToolStripMenuItem.Text = "&Save";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.buttonSave_Click);
//
// saveAsToolStripMenuItem
//
this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.saveAsToolStripMenuItem.Text = "Save &As";
this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveAsToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(143, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.generateCheckedToolStripMenuItem,
this.generateSelectedToolStripMenuItem,
this.regenerateCheckedToolStripMenuItem,
this.regenerateSelectedToolStripMenuItem,
this.toolStripSeparator2,
this.autoRegenOnChangedXSLToolStripMenuItem,
this.toolStripSeparator3,
this.customizeToolStripMenuItem,
this.optionsToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size(61, 20);
this.toolsToolStripMenuItem.Text = "S&ettings";
//
// generateCheckedToolStripMenuItem
//
this.generateCheckedToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("generateCheckedToolStripMenuItem.Image")));
this.generateCheckedToolStripMenuItem.Name = "generateCheckedToolStripMenuItem";
this.generateCheckedToolStripMenuItem.Size = new System.Drawing.Size(237, 22);
this.generateCheckedToolStripMenuItem.Text = "&Generate Checked";
this.generateCheckedToolStripMenuItem.Click += new System.EventHandler(this.buttonGo_Click);
//
// generateSelectedToolStripMenuItem
//
this.generateSelectedToolStripMenuItem.Enabled = false;
this.generateSelectedToolStripMenuItem.Name = "generateSelectedToolStripMenuItem";
this.generateSelectedToolStripMenuItem.Size = new System.Drawing.Size(237, 22);
this.generateSelectedToolStripMenuItem.Text = "Generate &Selected";
this.generateSelectedToolStripMenuItem.Click += new System.EventHandler(this.generateSelectedToolStripMenuItem_Click);
//
// regenerateCheckedToolStripMenuItem
//
this.regenerateCheckedToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("regenerateCheckedToolStripMenuItem.Image")));
this.regenerateCheckedToolStripMenuItem.Name = "regenerateCheckedToolStripMenuItem";
this.regenerateCheckedToolStripMenuItem.Size = new System.Drawing.Size(237, 22);
this.regenerateCheckedToolStripMenuItem.Text = "&Regenerate Checked";
this.regenerateCheckedToolStripMenuItem.Click += new System.EventHandler(this.buttonRegenerate_Click);
//
// regenerateSelectedToolStripMenuItem
//
this.regenerateSelectedToolStripMenuItem.Enabled = false;
this.regenerateSelectedToolStripMenuItem.Name = "regenerateSelectedToolStripMenuItem";
this.regenerateSelectedToolStripMenuItem.Size = new System.Drawing.Size(237, 22);
this.regenerateSelectedToolStripMenuItem.Text = "Regenerate Selected";
this.regenerateSelectedToolStripMenuItem.Click += new System.EventHandler(this.regenerateSelectedToolStripMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(234, 6);
//
// autoRegenOnChangedXSLToolStripMenuItem
//
this.autoRegenOnChangedXSLToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("autoRegenOnChangedXSLToolStripMenuItem.Image")));
this.autoRegenOnChangedXSLToolStripMenuItem.Name = "autoRegenOnChangedXSLToolStripMenuItem";
this.autoRegenOnChangedXSLToolStripMenuItem.Size = new System.Drawing.Size(237, 22);
this.autoRegenOnChangedXSLToolStripMenuItem.Text = "Auto Regen when XSL changes";
this.autoRegenOnChangedXSLToolStripMenuItem.Click += new System.EventHandler(this.buttonAutoGen_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(234, 6);
//
// customizeToolStripMenuItem
//
this.customizeToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("customizeToolStripMenuItem.Image")));
this.customizeToolStripMenuItem.Name = "customizeToolStripMenuItem";
this.customizeToolStripMenuItem.Size = new System.Drawing.Size(237, 22);
this.customizeToolStripMenuItem.Text = "&Add Step / Database Target";
this.customizeToolStripMenuItem.Click += new System.EventHandler(this.buttonAdd_Click);
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("optionsToolStripMenuItem.Image")));
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(237, 22);
this.optionsToolStripMenuItem.Text = "Delete Step / Database Target";
this.optionsToolStripMenuItem.Click += new System.EventHandler(this.buttonDelete_Click);
//
// MetadataSources
//
this.MetadataSources.CheckBoxes = true;
this.MetadataSources.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1});
this.MetadataSources.Dock = System.Windows.Forms.DockStyle.Fill;
this.MetadataSources.FullRowSelect = true;
this.MetadataSources.GridLines = true;
this.MetadataSources.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.MetadataSources.HideSelection = false;
this.MetadataSources.Location = new System.Drawing.Point(0, 0);
this.MetadataSources.MultiSelect = false;
this.MetadataSources.Name = "MetadataSources";
this.MetadataSources.ShowGroups = false;
this.MetadataSources.Size = new System.Drawing.Size(159, 349);
this.MetadataSources.TabIndex = 0;
this.MetadataSources.UseCompatibleStateImageBehavior = false;
this.MetadataSources.View = System.Windows.Forms.View.Details;
this.MetadataSources.ItemChecked += new System.Windows.Forms.ItemCheckedEventHandler(this.MetadataSources_ItemChecked);
this.MetadataSources.SelectedIndexChanged += new System.EventHandler(this.MetadataSources_SelectedIndexChanged);
//
// columnHeader1
//
this.columnHeader1.Text = "Steps / Targets";
this.columnHeader1.Width = 150;
//
// splitContainer1
//
this.splitContainer1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.toolStripContainer1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.flowLayoutPanel1);
this.splitContainer1.Panel2.Controls.Add(this.toolStrip1);
this.splitContainer1.Size = new System.Drawing.Size(907, 377);
this.splitContainer1.SplitterDistance = 163;
this.splitContainer1.TabIndex = 8;
//
// toolStripContainer1
//
this.toolStripContainer1.BottomToolStripPanelVisible = false;
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.Controls.Add(this.MetadataSources);
this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(159, 349);
this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer1.LeftToolStripPanelVisible = false;
this.toolStripContainer1.Location = new System.Drawing.Point(0, 0);
this.toolStripContainer1.Name = "toolStripContainer1";
this.toolStripContainer1.RightToolStripPanelVisible = false;
this.toolStripContainer1.Size = new System.Drawing.Size(159, 373);
this.toolStripContainer1.TabIndex = 11;
this.toolStripContainer1.Text = "toolStripContainer1";
//
// toolStripContainer1.TopToolStripPanel
//
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.menuStrip1);
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.BackColor = System.Drawing.SystemColors.Control;
this.flowLayoutPanel1.Controls.Add(this.label9);
this.flowLayoutPanel1.Controls.Add(this.label8);
this.flowLayoutPanel1.Controls.Add(this.textConnectionName);
this.flowLayoutPanel1.Controls.Add(this.label2);
this.flowLayoutPanel1.Controls.Add(this.textAppXlgXsl);
this.flowLayoutPanel1.Controls.Add(this.buttonChooseXlgFileXsl);
this.flowLayoutPanel1.Controls.Add(this.buttonEditXlgXslFile);
this.flowLayoutPanel1.Controls.Add(this.label4);
this.flowLayoutPanel1.Controls.Add(this.checkRegenerateOnly);
this.flowLayoutPanel1.Controls.Add(this.label12);
this.flowLayoutPanel1.Controls.Add(this.textOutputXml);
this.flowLayoutPanel1.Controls.Add(this.buttonChoosetextOutputXml);
this.flowLayoutPanel1.Controls.Add(this.buttonViewtextOutputXml);
this.flowLayoutPanel1.Controls.Add(this.label1);
this.flowLayoutPanel1.Controls.Add(this.textXlgFile);
this.flowLayoutPanel1.Controls.Add(this.buttonChooseXlgFile);
this.flowLayoutPanel1.Controls.Add(this.buttonEditXlgFile);
this.flowLayoutPanel1.Controls.Add(this.label3);
this.flowLayoutPanel1.Controls.Add(this.textOutput);
this.flowLayoutPanel1.Controls.Add(this.buttonChooseOutput);
this.flowLayoutPanel1.Controls.Add(this.buttonViewOutputFolder);
this.flowLayoutPanel1.Controls.Add(this.label5);
this.flowLayoutPanel1.Controls.Add(this.label13);
this.flowLayoutPanel1.Controls.Add(this.comboProviderName);
this.flowLayoutPanel1.Controls.Add(this.label7);
this.flowLayoutPanel1.Controls.Add(this.textConnectionStringName);
this.flowLayoutPanel1.Controls.Add(this.label6);
this.flowLayoutPanel1.Controls.Add(this.textConnectionString);
this.flowLayoutPanel1.Controls.Add(this.buttonEditConnectionString);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 31);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Padding = new System.Windows.Forms.Padding(10);
this.flowLayoutPanel1.Size = new System.Drawing.Size(736, 342);
this.flowLayoutPanel1.TabIndex = 8;
//
// label9
//
this.flowLayoutPanel1.SetFlowBreak(this.label9, true);
this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label9.Location = new System.Drawing.Point(13, 10);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(111, 20);
this.label9.TabIndex = 1;
this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label8
//
this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label8.Location = new System.Drawing.Point(13, 30);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(111, 20);
this.label8.TabIndex = 1;
this.label8.Text = "Step Name";
this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textConnectionName
//
this.flowLayoutPanel1.SetFlowBreak(this.textConnectionName, true);
this.textConnectionName.Location = new System.Drawing.Point(130, 33);
this.textConnectionName.Name = "textConnectionName";
this.textConnectionName.Size = new System.Drawing.Size(487, 20);
this.textConnectionName.TabIndex = 0;
//
// label2
//
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(13, 56);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(111, 20);
this.label2.TabIndex = 1;
this.label2.Text = "XSL TemplateName";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textAppXlgXsl
//
this.textAppXlgXsl.Location = new System.Drawing.Point(130, 59);
this.textAppXlgXsl.Name = "textAppXlgXsl";
this.textAppXlgXsl.Size = new System.Drawing.Size(487, 20);
this.textAppXlgXsl.TabIndex = 1;
//
// buttonChooseXlgFileXsl
//
this.buttonChooseXlgFileXsl.Location = new System.Drawing.Point(623, 59);
this.buttonChooseXlgFileXsl.Name = "buttonChooseXlgFileXsl";
this.buttonChooseXlgFileXsl.Size = new System.Drawing.Size(28, 23);
this.buttonChooseXlgFileXsl.TabIndex = 2;
this.buttonChooseXlgFileXsl.Text = "...";
this.buttonChooseXlgFileXsl.UseVisualStyleBackColor = true;
this.buttonChooseXlgFileXsl.Click += new System.EventHandler(this.buttonChooseXlgFileXsl_Click);
//
// buttonEditXlgXslFile
//
this.flowLayoutPanel1.SetFlowBreak(this.buttonEditXlgXslFile, true);
this.buttonEditXlgXslFile.Location = new System.Drawing.Point(657, 59);
this.buttonEditXlgXslFile.Name = "buttonEditXlgXslFile";
this.buttonEditXlgXslFile.Size = new System.Drawing.Size(37, 23);
this.buttonEditXlgXslFile.TabIndex = 3;
this.buttonEditXlgXslFile.Text = "Edit";
this.buttonEditXlgXslFile.UseVisualStyleBackColor = true;
this.buttonEditXlgXslFile.Click += new System.EventHandler(this.buttonEditXlgXslFile_Click);
//
// label4
//
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(13, 85);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(111, 16);
this.label4.TabIndex = 1;
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// checkRegenerateOnly
//
this.flowLayoutPanel1.SetFlowBreak(this.checkRegenerateOnly, true);
this.checkRegenerateOnly.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkRegenerateOnly.Location = new System.Drawing.Point(130, 88);
this.checkRegenerateOnly.Name = "checkRegenerateOnly";
this.checkRegenerateOnly.Size = new System.Drawing.Size(354, 17);
this.checkRegenerateOnly.TabIndex = 4;
this.checkRegenerateOnly.Text = "Regenerate by default (don\'t overwrite Target XML)";
this.checkRegenerateOnly.UseVisualStyleBackColor = true;
//
// label12
//
this.label12.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label12.Location = new System.Drawing.Point(13, 108);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(111, 20);
this.label12.TabIndex = 1;
this.label12.Text = "Target XML";
this.label12.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textOutputXml
//
this.textOutputXml.Anchor = System.Windows.Forms.AnchorStyles.None;
this.textOutputXml.Location = new System.Drawing.Point(130, 112);
this.textOutputXml.Name = "textOutputXml";
this.textOutputXml.Size = new System.Drawing.Size(487, 20);
this.textOutputXml.TabIndex = 5;
//
// buttonChoosetextOutputXml
//
this.buttonChoosetextOutputXml.Location = new System.Drawing.Point(623, 111);
this.buttonChoosetextOutputXml.Name = "buttonChoosetextOutputXml";
this.buttonChoosetextOutputXml.Size = new System.Drawing.Size(28, 23);
this.buttonChoosetextOutputXml.TabIndex = 6;
this.buttonChoosetextOutputXml.Text = "...";
this.buttonChoosetextOutputXml.UseVisualStyleBackColor = true;
this.buttonChoosetextOutputXml.Click += new System.EventHandler(this.buttonChooseTextOutputXml_Click);
//
// buttonViewtextOutputXml
//
this.flowLayoutPanel1.SetFlowBreak(this.buttonViewtextOutputXml, true);
this.buttonViewtextOutputXml.Location = new System.Drawing.Point(657, 111);
this.buttonViewtextOutputXml.Name = "buttonViewtextOutputXml";
this.buttonViewtextOutputXml.Size = new System.Drawing.Size(37, 23);
this.buttonViewtextOutputXml.TabIndex = 7;
this.buttonViewtextOutputXml.Text = "Edit";
this.buttonViewtextOutputXml.UseVisualStyleBackColor = true;
this.buttonViewtextOutputXml.Click += new System.EventHandler(this.buttonViewtextOutputXml_Click);
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(13, 137);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(111, 20);
this.label1.TabIndex = 1;
this.label1.Text = "Step Settings";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textXlgFile
//
this.textXlgFile.Location = new System.Drawing.Point(130, 140);
this.textXlgFile.Name = "textXlgFile";
this.textXlgFile.Size = new System.Drawing.Size(487, 20);
this.textXlgFile.TabIndex = 8;
//
// buttonChooseXlgFile
//
this.buttonChooseXlgFile.Location = new System.Drawing.Point(623, 140);
this.buttonChooseXlgFile.Name = "buttonChooseXlgFile";
this.buttonChooseXlgFile.Size = new System.Drawing.Size(28, 23);
this.buttonChooseXlgFile.TabIndex = 9;
this.buttonChooseXlgFile.Text = "...";
this.buttonChooseXlgFile.UseVisualStyleBackColor = true;
this.buttonChooseXlgFile.Click += new System.EventHandler(this.buttonChooseXlgFile_Click);
//
// buttonEditXlgFile
//
this.flowLayoutPanel1.SetFlowBreak(this.buttonEditXlgFile, true);
this.buttonEditXlgFile.Location = new System.Drawing.Point(657, 140);
this.buttonEditXlgFile.Name = "buttonEditXlgFile";
this.buttonEditXlgFile.Size = new System.Drawing.Size(37, 23);
this.buttonEditXlgFile.TabIndex = 10;
this.buttonEditXlgFile.Text = "Edit";
this.buttonEditXlgFile.UseVisualStyleBackColor = true;
this.buttonEditXlgFile.Click += new System.EventHandler(this.buttonEditXlgFile_Click);
//
// label3
//
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(13, 166);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(111, 20);
this.label3.TabIndex = 1;
this.label3.Text = "Output File";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textOutput
//
this.textOutput.Location = new System.Drawing.Point(130, 169);
this.textOutput.Name = "textOutput";
this.textOutput.Size = new System.Drawing.Size(487, 20);
this.textOutput.TabIndex = 11;
//
// buttonChooseOutput
//
this.buttonChooseOutput.Location = new System.Drawing.Point(623, 169);
this.buttonChooseOutput.Name = "buttonChooseOutput";
this.buttonChooseOutput.Size = new System.Drawing.Size(28, 23);
this.buttonChooseOutput.TabIndex = 12;
this.buttonChooseOutput.Text = "...";
this.buttonChooseOutput.UseVisualStyleBackColor = true;
this.buttonChooseOutput.Click += new System.EventHandler(this.buttonChooseOutput_Click);
//
// buttonViewOutputFolder
//
this.flowLayoutPanel1.SetFlowBreak(this.buttonViewOutputFolder, true);
this.buttonViewOutputFolder.Location = new System.Drawing.Point(657, 169);
this.buttonViewOutputFolder.Name = "buttonViewOutputFolder";
this.buttonViewOutputFolder.Size = new System.Drawing.Size(37, 23);
this.buttonViewOutputFolder.TabIndex = 13;
this.buttonViewOutputFolder.Text = "Edit";
this.buttonViewOutputFolder.UseVisualStyleBackColor = true;
this.buttonViewOutputFolder.Click += new System.EventHandler(this.buttonViewOutputFolder_Click);
//
// label5
//
this.flowLayoutPanel1.SetFlowBreak(this.label5, true);
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.Location = new System.Drawing.Point(13, 195);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(111, 20);
this.label5.TabIndex = 1;
this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label13
//
this.label13.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label13.Location = new System.Drawing.Point(13, 215);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(111, 20);
this.label13.TabIndex = 1;
this.label13.Text = "Provider";
this.label13.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// comboProviderName
//
this.comboProviderName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.flowLayoutPanel1.SetFlowBreak(this.comboProviderName, true);
this.comboProviderName.FormattingEnabled = true;
this.comboProviderName.Items.AddRange(new object[] {
"System.Data.SqlClient",
"Sybase.Data.AseClient",
"MySql.Data.MySqlClient",
"MetX.Standard.Data.Factory.CommandLineProvider",
"MetX.Standard.Data.Factory.PowerShellProvider",
"MetX.Standard.Data.Factory.FileSystemProvider"});
this.comboProviderName.Location = new System.Drawing.Point(130, 218);
this.comboProviderName.Name = "comboProviderName";
this.comboProviderName.Size = new System.Drawing.Size(231, 21);
this.comboProviderName.TabIndex = 14;
//
// label7
//
this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.Location = new System.Drawing.Point(13, 242);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(111, 20);
this.label7.TabIndex = 1;
this.label7.Text = "Connection Name";
this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textConnectionStringName
//
this.flowLayoutPanel1.SetFlowBreak(this.textConnectionStringName, true);
this.textConnectionStringName.Location = new System.Drawing.Point(130, 245);
this.textConnectionStringName.Name = "textConnectionStringName";
this.textConnectionStringName.Size = new System.Drawing.Size(521, 20);
this.textConnectionStringName.TabIndex = 15;
//
// label6
//
this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.Location = new System.Drawing.Point(13, 268);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(111, 20);
this.label6.TabIndex = 1;
this.label6.Text = "Connection String";
this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textConnectionString
//
this.textConnectionString.Location = new System.Drawing.Point(130, 271);
this.textConnectionString.Multiline = true;
this.textConnectionString.Name = "textConnectionString";
this.textConnectionString.Size = new System.Drawing.Size(521, 43);
this.textConnectionString.TabIndex = 16;
//
// buttonEditConnectionString
//
this.buttonEditConnectionString.Location = new System.Drawing.Point(657, 271);
this.buttonEditConnectionString.Name = "buttonEditConnectionString";
this.buttonEditConnectionString.Size = new System.Drawing.Size(37, 23);
this.buttonEditConnectionString.TabIndex = 13;
this.buttonEditConnectionString.Text = "Edit";
this.buttonEditConnectionString.UseVisualStyleBackColor = true;
this.buttonEditConnectionString.Visible = false;
this.buttonEditConnectionString.Click += new System.EventHandler(this.buttonEditConnectionString_Click);
//
// toolStrip1
//
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButton6,
this.toolStripSeparator4,
this.toolStripButton1,
this.toolStripButton2,
this.autoRegenToolbarButton,
this.toolStripSeparator6,
this.toolStripButton4,
this.toolStripButton5,
this.toolStripSeparator8,
this.EditClipScript});
this.toolStrip1.ImageScalingSize = new System.Drawing.Size(24, 24);
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(736, 31);
this.toolStrip1.TabIndex = 0;
//
// toolStripButton6
//
this.toolStripButton6.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton6.Image")));
this.toolStripButton6.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton6.Name = "toolStripButton6";
this.toolStripButton6.Size = new System.Drawing.Size(59, 28);
this.toolStripButton6.Text = "&Save";
this.toolStripButton6.Click += new System.EventHandler(this.buttonSave_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Margin = new System.Windows.Forms.Padding(5, 0, 0, 0);
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(6, 31);
//
// toolStripButton1
//
this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image")));
this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton1.Name = "toolStripButton1";
this.toolStripButton1.Size = new System.Drawing.Size(56, 28);
this.toolStripButton1.Text = "&Gen";
this.toolStripButton1.Click += new System.EventHandler(this.buttonGo_Click);
//
// toolStripButton2
//
this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image")));
this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton2.Name = "toolStripButton2";
this.toolStripButton2.Size = new System.Drawing.Size(68, 28);
this.toolStripButton2.Text = "&Regen";
this.toolStripButton2.Click += new System.EventHandler(this.buttonRegenerate_Click);
//
// autoRegenToolbarButton
//
this.autoRegenToolbarButton.Image = ((System.Drawing.Image)(resources.GetObject("autoRegenToolbarButton.Image")));
this.autoRegenToolbarButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.autoRegenToolbarButton.Name = "autoRegenToolbarButton";
this.autoRegenToolbarButton.Size = new System.Drawing.Size(85, 28);
this.autoRegenToolbarButton.Text = "&Auto Gen";
this.autoRegenToolbarButton.Click += new System.EventHandler(this.buttonAutoGen_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Margin = new System.Windows.Forms.Padding(5, 0, 0, 0);
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(6, 31);
//
// toolStripButton4
//
this.toolStripButton4.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton4.Image")));
this.toolStripButton4.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton4.Name = "toolStripButton4";
this.toolStripButton4.Size = new System.Drawing.Size(83, 28);
this.toolStripButton4.Text = "A&dd Step";
this.toolStripButton4.Click += new System.EventHandler(this.buttonAdd_Click);
//
// toolStripButton5
//
this.toolStripButton5.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton5.Image")));
this.toolStripButton5.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton5.Name = "toolStripButton5";
this.toolStripButton5.Size = new System.Drawing.Size(104, 28);
this.toolStripButton5.Text = "Remove Step";
this.toolStripButton5.Click += new System.EventHandler(this.buttonDelete_Click);
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
this.toolStripSeparator8.Size = new System.Drawing.Size(6, 31);
//
// EditClipScript
//
this.EditClipScript.Image = ((System.Drawing.Image)(resources.GetObject("EditClipScript.Image")));
this.EditClipScript.ImageTransparentColor = System.Drawing.Color.Magenta;
this.EditClipScript.Name = "EditClipScript";
this.EditClipScript.Size = new System.Drawing.Size(101, 28);
this.EditClipScript.Text = "&QuickScripts";
this.EditClipScript.Click += new System.EventHandler(this.EditQuickScript_Click);
//
// GloveMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(907, 377);
this.Controls.Add(this.splitContainer1);
this.Name = "GloveMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "XLG - XML Library Generator - Code Generation from metadata through XML and XSLT";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.GloveMain_FormClosing);
this.Load += new System.EventHandler(this.GloveMain_Load);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.Panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.PerformLayout();
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem NewScriptFile;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem customizeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ListView MetadataSources;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.ToolStripMenuItem generateCheckedToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem generateSelectedToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem regenerateCheckedToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem regenerateSelectedToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem autoRegenOnChangedXSLToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton toolStripButton1;
private System.Windows.Forms.ToolStripButton toolStripButton2;
private System.Windows.Forms.ToolStripButton autoRegenToolbarButton;
private System.Windows.Forms.ToolStripButton toolStripButton4;
private System.Windows.Forms.ToolStripButton toolStripButton5;
private System.Windows.Forms.ToolStripButton toolStripButton6;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textXlgFile;
private System.Windows.Forms.Button buttonChooseXlgFile;
private System.Windows.Forms.Button buttonEditXlgFile;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textAppXlgXsl;
private System.Windows.Forms.Button buttonChooseXlgFileXsl;
private System.Windows.Forms.Button buttonEditXlgXslFile;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.TextBox textOutputXml;
private System.Windows.Forms.Button buttonChoosetextOutputXml;
private System.Windows.Forms.Button buttonViewtextOutputXml;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textOutput;
private System.Windows.Forms.Button buttonChooseOutput;
private System.Windows.Forms.Button buttonViewOutputFolder;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox textConnectionStringName;
private System.Windows.Forms.TextBox textConnectionName;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.ComboBox comboProviderName;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox textConnectionString;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.CheckBox checkRegenerateOnly;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Button buttonEditConnectionString;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripButton EditClipScript;
}
}
| |
// 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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class GroupJoinTests
{
private const int KeyFactor = 8;
private const int ElementFactor = 4;
public static IEnumerable<object[]> GroupJoinUnorderedData(int[] counts)
{
foreach (int leftCount in counts)
{
foreach (int rightCount in counts)
{
yield return new object[] { leftCount, rightCount };
}
}
}
public static IEnumerable<object[]> GroupJoinData(int[] counts)
{
counts = counts.DefaultIfEmpty(Sources.OuterLoopCount / 64).ToArray();
// When dealing with joins, if there aren't multiple matches the ordering of the second operand is immaterial.
foreach (object[] parms in Sources.Ranges(counts, i => counts))
{
yield return parms;
}
}
public static IEnumerable<object[]> GroupJoinMultipleData(int[] counts)
{
counts = counts.DefaultIfEmpty(Sources.OuterLoopCount / 64).ToArray();
foreach (object[] parms in UnorderedSources.BinaryRanges(counts, counts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
}
}
//
// GroupJoin
//
[Theory]
[MemberData(nameof(GroupJoinUnorderedData), new[] { 0, 1, 2, KeyFactor * 2 })]
public static void GroupJoin_Unordered(int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount);
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount);
foreach (var p in leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)))
{
seen.Add(p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
}
else
{
Assert.Empty(p.Value);
}
}
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void GroupJoin_Unordered_Longrunning()
{
GroupJoin_Unordered(Sources.OuterLoopCount / 64, Sources.OuterLoopCount / 64);
}
[Theory]
[MemberData(nameof(GroupJoinData), new[] { 0, 1, 2, KeyFactor * 2 })]
public static void GroupJoin(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
int seen = 0;
foreach (var p in leftQuery.GroupJoin(UnorderedSources.Default(rightCount), x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)))
{
Assert.Equal(seen++, p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
}
else
{
Assert.Empty(p.Value);
}
}
Assert.Equal(leftCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(GroupJoinData), new int[] { /* Sources.OuterLoopCount */ })]
public static void GroupJoin_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount)
{
GroupJoin(left, leftCount, rightCount);
}
[Theory]
[MemberData(nameof(GroupJoinUnorderedData), new[] { 0, 1, 2, KeyFactor * 2 })]
public static void GroupJoin_Unordered_NotPipelined(int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount);
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount);
Assert.All(leftQuery.GroupJoin(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(),
p =>
{
seen.Add(p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
}
else
{
Assert.Empty(p.Value);
}
});
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void GroupJoin_Unordered_NotPipelined_Longrunning()
{
GroupJoin_Unordered_NotPipelined(Sources.OuterLoopCount / 64, Sources.OuterLoopCount / 64);
}
[Theory]
[MemberData(nameof(GroupJoinData), new[] { 0, 1, 2, KeyFactor * 2 })]
public static void GroupJoin_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
int seen = 0;
Assert.All(leftQuery.GroupJoin(UnorderedSources.Default(rightCount), x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(),
p =>
{
Assert.Equal(seen++, p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
Assert.Equal(p.Key * KeyFactor, Assert.Single(p.Value));
}
else
{
Assert.Empty(p.Value);
}
});
Assert.Equal(leftCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(GroupJoinData), new int[] { /* Sources.OuterLoopCount */ })]
public static void GroupJoin_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, int rightCount)
{
GroupJoin_NotPipelined(left, leftCount, rightCount);
}
[Theory]
[MemberData(nameof(GroupJoinUnorderedData), new[] { 0, 1, 2, KeyFactor * 2 })]
public static void GroupJoin_Unordered_Multiple(int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount);
IntegerRangeSet seenOuter = new IntegerRangeSet(0, leftCount);
Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)),
p =>
{
seenOuter.Add(p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
IntegerRangeSet seenInner = new IntegerRangeSet(p.Key * KeyFactor, Math.Min(rightCount - p.Key * KeyFactor, KeyFactor));
Assert.All(p.Value, y => { Assert.Equal(p.Key, y / KeyFactor); seenInner.Add(y); });
seenInner.AssertComplete();
}
else
{
Assert.Empty(p.Value);
}
});
seenOuter.AssertComplete();
}
[Fact]
[OuterLoop]
public static void GroupJoin_Unordered_Multiple_Longrunning()
{
GroupJoin_Unordered_Multiple(Sources.OuterLoopCount / 64, Sources.OuterLoopCount / 64);
}
[Theory]
[ActiveIssue(1155)]
[MemberData(nameof(GroupJoinMultipleData), new[] { 0, 1, 2, KeyFactor * 2 - 1, KeyFactor * 2 })]
public static void GroupJoin_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seenOuter = 0;
Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)),
p =>
{
Assert.Equal(seenOuter++, p.Key);
if (p.Key < (rightCount + (KeyFactor - 1)) / KeyFactor)
{
int seenInner = p.Key * KeyFactor;
Assert.All(p.Value, y =>
{
Assert.Equal(p.Key, y / KeyFactor);
Assert.Equal(seenInner++, y);
});
Assert.Equal(Math.Min((p.Key + 1) * KeyFactor, rightCount), seenInner);
}
else
{
Assert.Empty(p.Value);
}
});
Assert.Equal(leftCount, seenOuter);
}
[Theory]
[ActiveIssue(1155)]
[OuterLoop]
[MemberData(nameof(GroupJoinMultipleData), new int[] { /* Sources.OuterLoopCount */ })]
public static void GroupJoin_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_Multiple(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(GroupJoinUnorderedData), new[] { 0, 1, 2, KeyFactor * 2 })]
public static void GroupJoin_Unordered_CustomComparator(int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(rightCount);
IntegerRangeSet seenOuter = new IntegerRangeSet(0, leftCount);
Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y % ElementFactor, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)),
p =>
{
seenOuter.Add(p.Key);
if (p.Key % KeyFactor < Math.Min(ElementFactor, rightCount))
{
IntegerRangeSet seenInner = new IntegerRangeSet(0, (rightCount + (ElementFactor - 1) - p.Key % ElementFactor) / ElementFactor);
Assert.All(p.Value, y => { Assert.Equal(p.Key % KeyFactor, y % ElementFactor); seenInner.Add(y / ElementFactor); });
seenInner.AssertComplete();
}
else
{
Assert.Empty(p.Value);
}
});
seenOuter.AssertComplete();
}
[Fact]
[OuterLoop]
public static void GroupJoin_Unordered_CustomComparator_Longrunning()
{
GroupJoin_Unordered_CustomComparator(Sources.OuterLoopCount / 64, Sources.OuterLoopCount / 64);
}
[Theory]
[ActiveIssue(1155)]
[MemberData(nameof(GroupJoinMultipleData), new[] { 0, 1, 2, KeyFactor * 2 })]
public static void GroupJoin_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seenOuter = 0;
Assert.All(leftQuery.GroupJoin(rightQuery, x => x, y => y % ElementFactor, (x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)),
p =>
{
Assert.Equal(seenOuter++, p.Key);
if (p.Key % KeyFactor < Math.Min(ElementFactor, rightCount))
{
int seenInner = p.Key % (KeyFactor / 2) - (KeyFactor / 2);
Assert.All(p.Value, y =>
{
Assert.Equal(p.Key % KeyFactor, y % (KeyFactor / 2));
Assert.Equal(seenInner += (KeyFactor / 2), y);
});
Assert.Equal(Math.Max(p.Key % (KeyFactor / 2), rightCount + (p.Key % (KeyFactor / 2) - (KeyFactor / 2))), seenInner);
}
else
{
Assert.Empty(p.Value);
}
});
Assert.Equal(leftCount, seenOuter);
}
[Theory]
[ActiveIssue(1155)]
[OuterLoop]
[MemberData(nameof(GroupJoinMultipleData), new int[] { /* Sources.OuterLoopCount */ })]
public static void GroupJoin_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
GroupJoin_CustomComparator(left, leftCount, right, rightCount);
}
[Fact]
public static void GroupJoin_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).GroupJoin(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i, null));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void GroupJoin_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).GroupJoin(ParallelEnumerable.Range(0, 1).WithCancellation(t), x => x, y => y, (x, e) => e));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).GroupJoin(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1), x => x, y => y, (x, e) => e));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).GroupJoin(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default), x => x, y => y, (x, e) => e));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).GroupJoin(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default), x => x, y => y, (x, e) => e));
}
[Fact]
public static void GroupJoin_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>("outer", () => ((ParallelQuery<int>)null).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>("inner", () => ParallelEnumerable.Range(0, 1).GroupJoin((ParallelQuery<int>)null, i => i, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>("outerKeySelector", () => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>("innerKeySelector", () => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i));
Assert.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, IEnumerable<int>, int>)null));
Assert.Throws<ArgumentNullException>("outer", () => ((ParallelQuery<int>)null).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>("inner", () => ParallelEnumerable.Range(0, 1).GroupJoin((ParallelQuery<int>)null, i => i, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>("outerKeySelector", () => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>("innerKeySelector", () => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Range(0, 1).GroupJoin(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, IEnumerable<int>, int>)null, EqualityComparer<int>.Default));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Internal.Metadata.NativeFormat.Writer;
using Ecma = System.Reflection.Metadata;
using Cts = Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
using TypeAttributes = System.Reflection.TypeAttributes;
namespace ILCompiler.Metadata
{
partial class Transform<TPolicy>
{
internal EntityMap<Cts.TypeDesc, MetadataRecord> _types =
new EntityMap<Cts.TypeDesc, MetadataRecord>(EqualityComparer<Cts.TypeDesc>.Default);
private Action<Cts.MetadataType, TypeDefinition> _initTypeDef;
private Action<Cts.MetadataType, TypeReference> _initTypeRef;
private Action<Cts.ArrayType, TypeSpecification> _initSzArray;
private Action<Cts.ArrayType, TypeSpecification> _initArray;
private Action<Cts.ByRefType, TypeSpecification> _initByRef;
private Action<Cts.PointerType, TypeSpecification> _initPointer;
private Action<Cts.InstantiatedType, TypeSpecification> _initTypeInst;
private Action<Cts.SignatureTypeVariable, TypeSpecification> _initTypeVar;
private Action<Cts.SignatureMethodVariable, TypeSpecification> _initMethodVar;
public override MetadataRecord HandleType(Cts.TypeDesc type)
{
Debug.Assert(!IsBlocked(type));
MetadataRecord rec;
if (_types.TryGet(type, out rec))
{
return rec;
}
if (type.IsSzArray)
{
var arrayType = (Cts.ArrayType)type;
rec = _types.Create(arrayType, _initSzArray ?? (_initSzArray = InitializeSzArray));
}
else if (type.IsArray)
{
var arrayType = (Cts.ArrayType)type;
rec = _types.Create(arrayType, _initArray ?? (_initArray = InitializeArray));
}
else if (type.IsByRef)
{
var byRefType = (Cts.ByRefType)type;
rec = _types.Create(byRefType, _initByRef ?? (_initByRef = InitializeByRef));
}
else if (type.IsPointer)
{
var pointerType = (Cts.PointerType)type;
rec = _types.Create(pointerType, _initPointer ?? (_initPointer = InitializePointer));
}
else if (type is Cts.SignatureTypeVariable)
{
var variable = (Cts.SignatureTypeVariable)type;
rec = _types.Create(variable, _initTypeVar ?? (_initTypeVar = InitializeTypeVariable));
}
else if (type is Cts.SignatureMethodVariable)
{
var variable = (Cts.SignatureMethodVariable)type;
rec = _types.Create(variable, _initMethodVar ?? (_initMethodVar = InitializeMethodVariable));
}
else if (type is Cts.InstantiatedType)
{
var instType = (Cts.InstantiatedType)type;
rec = _types.Create(instType, _initTypeInst ?? (_initTypeInst = InitializeTypeInstance));
}
else
{
var metadataType = (Cts.MetadataType)type;
if (_policy.GeneratesMetadata(metadataType))
{
rec = _types.Create(metadataType, _initTypeDef ?? (_initTypeDef = InitializeTypeDef));
}
else
{
rec = _types.Create(metadataType, _initTypeRef ?? (_initTypeRef = InitializeTypeRef));
}
}
Debug.Assert(rec is TypeDefinition || rec is TypeReference || rec is TypeSpecification);
return rec;
}
private void InitializeSzArray(Cts.ArrayType entity, TypeSpecification record)
{
record.Signature = new SZArraySignature
{
ElementType = HandleType(entity.ElementType),
};
}
private void InitializeArray(Cts.ArrayType entity, TypeSpecification record)
{
record.Signature = new ArraySignature
{
ElementType = HandleType(entity.ElementType),
Rank = entity.Rank,
// TODO: LowerBounds
// TODO: Sizes
};
}
private void InitializeByRef(Cts.ByRefType entity, TypeSpecification record)
{
record.Signature = new ByReferenceSignature
{
Type = HandleType(entity.ParameterType)
};
}
private void InitializePointer(Cts.PointerType entity, TypeSpecification record)
{
record.Signature = new PointerSignature
{
Type = HandleType(entity.ParameterType)
};
}
private void InitializeTypeVariable(Cts.SignatureTypeVariable entity, TypeSpecification record)
{
record.Signature = new TypeVariableSignature
{
Number = entity.Index
};
}
private void InitializeMethodVariable(Cts.SignatureMethodVariable entity, TypeSpecification record)
{
record.Signature = new MethodTypeVariableSignature
{
Number = entity.Index
};
}
private void InitializeTypeInstance(Cts.InstantiatedType entity, TypeSpecification record)
{
var sig = new TypeInstantiationSignature
{
GenericType = HandleType(entity.GetTypeDefinition()),
};
for (int i = 0; i < entity.Instantiation.Length; i++)
{
sig.GenericTypeArguments.Add(HandleType(entity.Instantiation[i]));
}
record.Signature = sig;
}
private TypeReference GetNestedReferenceParent(Cts.MetadataType entity)
{
// This special code deals with the metadata format requirement saying that
// nested type *references* need to have a type *reference* as their containing type.
// This is potentially in conflict with our other rule that says to always resolve
// references to their definition records (we are avoiding emitting references
// to things that have a definition within the same blob to save space).
Cts.MetadataType containingType = entity.ContainingType;
MetadataRecord parentRecord = HandleType(containingType);
TypeReference parentReferenceRecord = parentRecord as TypeReference;
if (parentReferenceRecord != null)
{
// Easy case - parent type doesn't have a definition record.
return parentReferenceRecord;
}
// Parent has a type definition record. We need to make a new record that's a reference.
// We don't bother with interning these because this will be rare and metadata writer
// will do the interning anyway.
Debug.Assert(parentRecord is TypeDefinition);
parentReferenceRecord = new TypeReference
{
TypeName = HandleString(containingType.Name),
};
if (containingType.ContainingType != null)
{
parentReferenceRecord.ParentNamespaceOrType = GetNestedReferenceParent(containingType);
}
else
{
parentReferenceRecord.ParentNamespaceOrType = HandleNamespaceReference(containingType.Module, containingType.Namespace);
}
return parentReferenceRecord;
}
private void InitializeTypeRef(Cts.MetadataType entity, TypeReference record)
{
Debug.Assert(entity.IsTypeDefinition);
if (entity.ContainingType != null)
{
record.ParentNamespaceOrType = GetNestedReferenceParent(entity);
}
else
{
record.ParentNamespaceOrType = HandleNamespaceReference(entity.Module, entity.Namespace);
}
record.TypeName = HandleString(entity.Name);
}
private void InitializeTypeDef(Cts.MetadataType entity, TypeDefinition record)
{
Debug.Assert(entity.IsTypeDefinition);
if (entity.ContainingType != null)
{
var enclosingType = (TypeDefinition)HandleType(entity.ContainingType);
record.EnclosingType = enclosingType;
enclosingType.NestedTypes.Add(record);
var namespaceDefinition =
HandleNamespaceDefinition(entity.ContainingType.Module, entity.ContainingType.Namespace);
record.NamespaceDefinition = namespaceDefinition;
}
else
{
var namespaceDefinition = HandleNamespaceDefinition(entity.Module, entity.Namespace);
record.NamespaceDefinition = namespaceDefinition;
namespaceDefinition.TypeDefinitions.Add(record);
}
record.Name = HandleString(entity.Name);
Cts.ClassLayoutMetadata layoutMetadata = entity.GetClassLayout();
record.Size = checked((uint)layoutMetadata.Size);
record.PackingSize = checked((ushort)layoutMetadata.PackingSize);
record.Flags = GetTypeAttributes(entity);
if (entity.HasBaseType)
{
record.BaseType = HandleType(entity.BaseType);
}
if (entity.ExplicitlyImplementedInterfaces.Length > 0)
{
record.Interfaces.Capacity = entity.ExplicitlyImplementedInterfaces.Length;
record.Interfaces.AddRange(entity.ExplicitlyImplementedInterfaces
.Where(i => !IsBlocked(i))
.Select(i => HandleType(i)));
}
if (entity.HasInstantiation)
{
record.GenericParameters.Capacity = entity.Instantiation.Length;
foreach (var p in entity.Instantiation)
record.GenericParameters.Add(HandleGenericParameter((Cts.GenericParameterDesc)p));
}
foreach (var field in entity.GetFields())
{
if (_policy.GeneratesMetadata(field))
{
record.Fields.Add(HandleFieldDefinition(field));
}
}
foreach (var method in entity.GetMethods())
{
if (_policy.GeneratesMetadata(method))
{
record.Methods.Add(HandleMethodDefinition(method));
}
}
var ecmaEntity = entity as Cts.Ecma.EcmaType;
if (ecmaEntity != null)
{
Ecma.TypeDefinition ecmaRecord = ecmaEntity.MetadataReader.GetTypeDefinition(ecmaEntity.Handle);
foreach (var e in ecmaRecord.GetEvents())
{
Event evt = HandleEvent(ecmaEntity.EcmaModule, e);
if (evt != null)
record.Events.Add(evt);
}
foreach (var property in ecmaRecord.GetProperties())
{
Property prop = HandleProperty(ecmaEntity.EcmaModule, property);
if (prop != null)
record.Properties.Add(prop);
}
// TODO: CustomAttributes
}
// TODO: MethodImpls
}
private TypeAttributes GetTypeAttributes(Cts.MetadataType type)
{
TypeAttributes result;
var ecmaType = type as Cts.Ecma.EcmaType;
if (ecmaType != null)
{
Ecma.TypeDefinition ecmaRecord = ecmaType.MetadataReader.GetTypeDefinition(ecmaType.Handle);
result = ecmaRecord.Attributes;
}
else
{
result = 0;
if (type.IsExplicitLayout)
result |= TypeAttributes.ExplicitLayout;
if (type.IsSequentialLayout)
result |= TypeAttributes.SequentialLayout;
if (type.IsInterface)
result |= TypeAttributes.Interface;
if (type.IsSealed)
result |= TypeAttributes.Sealed;
if (type.IsBeforeFieldInit)
result |= TypeAttributes.BeforeFieldInit;
// Not set: Abstract, Ansi/Unicode/Auto, HasSecurity, Import, visibility, Serializable,
// WindowsRuntime, HasSecurity, SpecialName, RTSpecialName
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Threading.Tasks
{
/// <summary>
/// Provides a set of static (Shared in Visual Basic) methods for working with specific kinds of
/// <see cref="System.Threading.Tasks.Task"/> instances.
/// </summary>
public static class TaskExtensions
{
/// <summary>
/// Creates a proxy <see cref="System.Threading.Tasks.Task">Task</see> that represents the
/// asynchronous operation of a Task{Task}.
/// </summary>
/// <remarks>
/// It is often useful to be able to return a Task from a <see cref="System.Threading.Tasks.Task{TResult}">
/// Task{TResult}</see>, where the inner Task represents work done as part of the outer Task{TResult}. However,
/// doing so results in a Task{Task}, which, if not dealt with carefully, could produce unexpected behavior. Unwrap
/// solves this problem by creating a proxy Task that represents the entire asynchronous operation of such a Task{Task}.
/// </remarks>
/// <param name="task">The Task{Task} to unwrap.</param>
/// <exception cref="T:System.ArgumentNullException">The exception that is thrown if the
/// <paramref name="task"/> argument is null.</exception>
/// <returns>A Task that represents the asynchronous operation of the provided Task{Task}.</returns>
public static Task Unwrap(this Task<Task> task)
{
if (task == null)
throw new ArgumentNullException(nameof(task));
// Fast path for an already successfully completed outer task: just return the inner one.
// As in the subsequent slower path, a null inner task is special-cased to mean cancellation.
if (task.Status == TaskStatus.RanToCompletion && (task.CreationOptions & TaskCreationOptions.AttachedToParent) == 0)
{
return task.Result ?? Task.FromCanceled(new CancellationToken(true));
}
// Create a new Task to serve as a proxy for the actual inner task. Attach it
// to the parent if the original was attached to the parent.
var tcs = new TaskCompletionSource<VoidResult>(task.CreationOptions & TaskCreationOptions.AttachedToParent);
TransferAsynchronously(tcs, task);
return tcs.Task;
}
/// <summary>
/// Creates a proxy <see cref="System.Threading.Tasks.Task{TResult}">Task{TResult}</see> that represents the
/// asynchronous operation of a Task{Task{TResult}}.
/// </summary>
/// <remarks>
/// It is often useful to be able to return a Task{TResult} from a Task{TResult}, where the inner Task{TResult}
/// represents work done as part of the outer Task{TResult}. However, doing so results in a Task{Task{TResult}},
/// which, if not dealt with carefully, could produce unexpected behavior. Unwrap solves this problem by
/// creating a proxy Task{TResult} that represents the entire asynchronous operation of such a Task{Task{TResult}}.
/// </remarks>
/// <param name="task">The Task{Task{TResult}} to unwrap.</param>
/// <exception cref="T:System.ArgumentNullException">The exception that is thrown if the
/// <paramref name="task"/> argument is null.</exception>
/// <returns>A Task{TResult} that represents the asynchronous operation of the provided Task{Task{TResult}}.</returns>
public static Task<TResult> Unwrap<TResult>(this Task<Task<TResult>> task)
{
if (task == null)
throw new ArgumentNullException(nameof(task));
// Fast path for an already successfully completed outer task: just return the inner one.
// As in the subsequent slower path, a null inner task is special-cased to mean cancellation.
if (task.Status == TaskStatus.RanToCompletion && (task.CreationOptions & TaskCreationOptions.AttachedToParent) == 0)
{
return task.Result ?? Task.FromCanceled<TResult>(new CancellationToken(true));
}
// Create a new Task to serve as a proxy for the actual inner task. Attach it
// to the parent if the original was attached to the parent.
var tcs = new TaskCompletionSource<TResult>(task.CreationOptions & TaskCreationOptions.AttachedToParent);
TransferAsynchronously(tcs, task);
return tcs.Task;
}
/// <summary>
/// Transfer the results of the <paramref name="outer"/> task's inner task to the <paramref name="completionSource"/>.
/// </summary>
/// <param name="completionSource">The completion source to which results should be transfered.</param>
/// <param name="outer">
/// The outer task that when completed will yield an inner task whose results we want marshaled to the <paramref name="completionSource"/>.
/// </param>
private static void TransferAsynchronously<TResult, TInner>(TaskCompletionSource<TResult> completionSource, Task<TInner> outer) where TInner : Task
{
Action callback = null;
// Create a continuation delegate. For performance reasons, we reuse the same delegate/closure across multiple
// continuations; by using .ConfigureAwait(false).GetAwaiter().UnsafeOnComplete(action), in most cases
// this delegate can be stored directly into the Task's continuation field, eliminating the need for additional
// allocations. Thus, this whole Unwrap operation generally results in four allocations: one for the TaskCompletionSource,
// one for the returned task, one for the delegate, and one for the closure. Since the delegate is used
// across multiple continuations, we use the callback variable as well to indicate which continuation we're in:
// if the callback is non-null, then we're processing the continuation for the outer task and use the callback
// object as the continuation off of the inner task; if the callback is null, then we're processing the
// inner task.
callback = delegate
{
Debug.Assert(outer.IsCompleted);
if (callback != null)
{
// Process the outer task's completion
// Clear out the callback field to indicate that any future invocations should
// be for processing the inner task, but store away a local copy in case we need
// to use it as the continuation off of the outer task.
Action innerCallback = callback;
callback = null;
bool result = true;
switch (outer.Status)
{
case TaskStatus.Canceled:
case TaskStatus.Faulted:
// The outer task has completed as canceled or faulted; transfer that
// status to the completion source, and we're done.
result = completionSource.TrySetFromTask(outer);
break;
case TaskStatus.RanToCompletion:
Task inner = outer.Result;
if (inner == null)
{
// The outer task completed successfully, but with a null inner task;
// cancel the completionSource, and we're done.
result = completionSource.TrySetCanceled();
}
else if (inner.IsCompleted)
{
// The inner task also completed! Transfer the results, and we're done.
result = completionSource.TrySetFromTask(inner);
}
else
{
// Run this delegate again once the inner task has completed.
inner.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(innerCallback);
}
break;
}
Debug.Assert(result);
}
else
{
// Process the inner task's completion. All we need to do is transfer its results
// to the completion source.
Debug.Assert(outer.Status == TaskStatus.RanToCompletion);
Debug.Assert(outer.Result.IsCompleted);
completionSource.TrySetFromTask(outer.Result);
}
};
// Kick things off by hooking up the callback as the task's continuation
outer.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(callback);
}
/// <summary>Copies that ending state information from <paramref name="task"/> to <paramref name="completionSource"/>.</summary>
private static bool TrySetFromTask<TResult>(this TaskCompletionSource<TResult> completionSource, Task task)
{
Debug.Assert(task.IsCompleted);
// Before transferring the results, check to make sure we're not too deep on the stack. Calling TrySet*
// will cause any synchronous continuations to be invoked, which is fine unless we're so deep that doing
// so overflows. ContinueWith has built-in support for avoiding such stack dives, but that support is not
// (yet) part of await's infrastructure, so until it is we mimic it manually. This matches the behavior
// employed by the Unwrap implementation in mscorlib.
if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
{
// This is very rare. We're too deep to safely invoke
// TrySet* synchronously, so do so asynchronously instead.
Task.Factory.StartNew(s =>
{
var t = (Tuple<TaskCompletionSource<TResult>, Task>)s;
TrySetFromTask(t.Item1, t.Item2);
}, Tuple.Create(completionSource, task), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
return true;
}
// Transfer the results from the supplied Task to the TaskCompletionSource.
bool result = false;
switch(task.Status)
{
case TaskStatus.Canceled:
result = completionSource.TrySetCanceled(ExtractCancellationToken(task));
break;
case TaskStatus.Faulted:
result = completionSource.TrySetException(task.Exception.InnerExceptions);
break;
case TaskStatus.RanToCompletion:
Task<TResult> resultTask = task as Task<TResult>;
result = resultTask != null ?
completionSource.TrySetResult(resultTask.Result) :
completionSource.TrySetResult(default(TResult));
break;
}
return result;
}
/// <summary>Gets the CancellationToken associated with a canceled task.</summary>
private static CancellationToken ExtractCancellationToken(Task task)
{
// With the public Task APIs as of .NET 4.6, the only way to extract a CancellationToken
// that was associated with a Task is by await'ing it, catching the resulting
// OperationCanceledException, and getting the token from the OCE.
Debug.Assert(task.IsCanceled);
try
{
task.GetAwaiter().GetResult();
Debug.Fail("Waiting on the canceled task should always result in an OCE, even if it's manufactured at the time of the wait.");
return new CancellationToken(true);
}
catch (OperationCanceledException oce)
{
// This token may not have cancellation requested; that's ok.
// That can happen if, for example, the Task is canceled with
// TaskCompletionSource<T>.SetCanceled(), without a token.
return oce.CancellationToken;
}
}
/// <summary>Dummy type to use as a void TResult.</summary>
private struct VoidResult { }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace System.Data.SqlClient
{
public sealed partial class SqlConnectionStringBuilder : DbConnectionStringBuilder
{
private enum Keywords
{ // specific ordering for ConnectionString output construction
// NamedConnection,
DataSource,
FailoverPartner,
AttachDBFilename,
InitialCatalog,
IntegratedSecurity,
PersistSecurityInfo,
UserID,
Password,
Enlist,
Pooling,
MinPoolSize,
MaxPoolSize,
MultipleActiveResultSets,
Replication,
ConnectTimeout,
Encrypt,
TrustServerCertificate,
LoadBalanceTimeout,
PacketSize,
TypeSystemVersion,
ApplicationName,
CurrentLanguage,
WorkstationID,
UserInstance,
TransactionBinding,
ApplicationIntent,
MultiSubnetFailover,
ConnectRetryCount,
ConnectRetryInterval,
// keep the count value last
KeywordsCount
}
internal const int KeywordsCount = (int)Keywords.KeywordsCount;
internal const int DeprecatedKeywordsCount = 4;
private static readonly string[] s_validKeywords = CreateValidKeywords();
private static readonly Dictionary<string, Keywords> s_keywords = CreateKeywordsDictionary();
private ApplicationIntent _applicationIntent = DbConnectionStringDefaults.ApplicationIntent;
private string _applicationName = DbConnectionStringDefaults.ApplicationName;
private string _attachDBFilename = DbConnectionStringDefaults.AttachDBFilename;
private string _currentLanguage = DbConnectionStringDefaults.CurrentLanguage;
private string _dataSource = DbConnectionStringDefaults.DataSource;
private string _failoverPartner = DbConnectionStringDefaults.FailoverPartner;
private string _initialCatalog = DbConnectionStringDefaults.InitialCatalog;
// private string _namedConnection = DbConnectionStringDefaults.NamedConnection;
private string _password = DbConnectionStringDefaults.Password;
private string _transactionBinding = DbConnectionStringDefaults.TransactionBinding;
private string _typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion;
private string _userID = DbConnectionStringDefaults.UserID;
private string _workstationID = DbConnectionStringDefaults.WorkstationID;
private int _connectTimeout = DbConnectionStringDefaults.ConnectTimeout;
private int _loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout;
private int _maxPoolSize = DbConnectionStringDefaults.MaxPoolSize;
private int _minPoolSize = DbConnectionStringDefaults.MinPoolSize;
private int _packetSize = DbConnectionStringDefaults.PacketSize;
private int _connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount;
private int _connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval;
private bool _encrypt = DbConnectionStringDefaults.Encrypt;
private bool _trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate;
private bool _enlist = DbConnectionStringDefaults.Enlist;
private bool _integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity;
private bool _multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets;
private bool _multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover;
private bool _persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo;
private bool _pooling = DbConnectionStringDefaults.Pooling;
private bool _replication = DbConnectionStringDefaults.Replication;
private bool _userInstance = DbConnectionStringDefaults.UserInstance;
private static string[] CreateValidKeywords()
{
string[] validKeywords = new string[KeywordsCount];
validKeywords[(int)Keywords.ApplicationIntent] = DbConnectionStringKeywords.ApplicationIntent;
validKeywords[(int)Keywords.ApplicationName] = DbConnectionStringKeywords.ApplicationName;
validKeywords[(int)Keywords.AttachDBFilename] = DbConnectionStringKeywords.AttachDBFilename;
validKeywords[(int)Keywords.ConnectTimeout] = DbConnectionStringKeywords.ConnectTimeout;
validKeywords[(int)Keywords.CurrentLanguage] = DbConnectionStringKeywords.CurrentLanguage;
validKeywords[(int)Keywords.DataSource] = DbConnectionStringKeywords.DataSource;
validKeywords[(int)Keywords.Encrypt] = DbConnectionStringKeywords.Encrypt;
validKeywords[(int)Keywords.Enlist] = DbConnectionStringKeywords.Enlist;
validKeywords[(int)Keywords.FailoverPartner] = DbConnectionStringKeywords.FailoverPartner;
validKeywords[(int)Keywords.InitialCatalog] = DbConnectionStringKeywords.InitialCatalog;
validKeywords[(int)Keywords.IntegratedSecurity] = DbConnectionStringKeywords.IntegratedSecurity;
validKeywords[(int)Keywords.LoadBalanceTimeout] = DbConnectionStringKeywords.LoadBalanceTimeout;
validKeywords[(int)Keywords.MaxPoolSize] = DbConnectionStringKeywords.MaxPoolSize;
validKeywords[(int)Keywords.MinPoolSize] = DbConnectionStringKeywords.MinPoolSize;
validKeywords[(int)Keywords.MultipleActiveResultSets] = DbConnectionStringKeywords.MultipleActiveResultSets;
validKeywords[(int)Keywords.MultiSubnetFailover] = DbConnectionStringKeywords.MultiSubnetFailover;
// validKeywords[(int)Keywords.NamedConnection] = DbConnectionStringKeywords.NamedConnection;
validKeywords[(int)Keywords.PacketSize] = DbConnectionStringKeywords.PacketSize;
validKeywords[(int)Keywords.Password] = DbConnectionStringKeywords.Password;
validKeywords[(int)Keywords.PersistSecurityInfo] = DbConnectionStringKeywords.PersistSecurityInfo;
validKeywords[(int)Keywords.Pooling] = DbConnectionStringKeywords.Pooling;
validKeywords[(int)Keywords.Replication] = DbConnectionStringKeywords.Replication;
validKeywords[(int)Keywords.TransactionBinding] = DbConnectionStringKeywords.TransactionBinding;
validKeywords[(int)Keywords.TrustServerCertificate] = DbConnectionStringKeywords.TrustServerCertificate;
validKeywords[(int)Keywords.TypeSystemVersion] = DbConnectionStringKeywords.TypeSystemVersion;
validKeywords[(int)Keywords.UserID] = DbConnectionStringKeywords.UserID;
validKeywords[(int)Keywords.UserInstance] = DbConnectionStringKeywords.UserInstance;
validKeywords[(int)Keywords.WorkstationID] = DbConnectionStringKeywords.WorkstationID;
validKeywords[(int)Keywords.ConnectRetryCount] = DbConnectionStringKeywords.ConnectRetryCount;
validKeywords[(int)Keywords.ConnectRetryInterval] = DbConnectionStringKeywords.ConnectRetryInterval;
return validKeywords;
}
private static Dictionary<string, Keywords> CreateKeywordsDictionary()
{
Dictionary<string, Keywords> hash = new Dictionary<string, Keywords>(KeywordsCount + SqlConnectionString.SynonymCount, StringComparer.OrdinalIgnoreCase);
hash.Add(DbConnectionStringKeywords.ApplicationIntent, Keywords.ApplicationIntent);
hash.Add(DbConnectionStringKeywords.ApplicationName, Keywords.ApplicationName);
hash.Add(DbConnectionStringKeywords.AttachDBFilename, Keywords.AttachDBFilename);
hash.Add(DbConnectionStringKeywords.ConnectTimeout, Keywords.ConnectTimeout);
hash.Add(DbConnectionStringKeywords.CurrentLanguage, Keywords.CurrentLanguage);
hash.Add(DbConnectionStringKeywords.DataSource, Keywords.DataSource);
hash.Add(DbConnectionStringKeywords.Encrypt, Keywords.Encrypt);
hash.Add(DbConnectionStringKeywords.Enlist, Keywords.Enlist);
hash.Add(DbConnectionStringKeywords.FailoverPartner, Keywords.FailoverPartner);
hash.Add(DbConnectionStringKeywords.InitialCatalog, Keywords.InitialCatalog);
hash.Add(DbConnectionStringKeywords.IntegratedSecurity, Keywords.IntegratedSecurity);
hash.Add(DbConnectionStringKeywords.LoadBalanceTimeout, Keywords.LoadBalanceTimeout);
hash.Add(DbConnectionStringKeywords.MultipleActiveResultSets, Keywords.MultipleActiveResultSets);
hash.Add(DbConnectionStringKeywords.MaxPoolSize, Keywords.MaxPoolSize);
hash.Add(DbConnectionStringKeywords.MinPoolSize, Keywords.MinPoolSize);
hash.Add(DbConnectionStringKeywords.MultiSubnetFailover, Keywords.MultiSubnetFailover);
// hash.Add(DbConnectionStringKeywords.NamedConnection, Keywords.NamedConnection);
hash.Add(DbConnectionStringKeywords.PacketSize, Keywords.PacketSize);
hash.Add(DbConnectionStringKeywords.Password, Keywords.Password);
hash.Add(DbConnectionStringKeywords.PersistSecurityInfo, Keywords.PersistSecurityInfo);
hash.Add(DbConnectionStringKeywords.Pooling, Keywords.Pooling);
hash.Add(DbConnectionStringKeywords.Replication, Keywords.Replication);
hash.Add(DbConnectionStringKeywords.TransactionBinding, Keywords.TransactionBinding);
hash.Add(DbConnectionStringKeywords.TrustServerCertificate, Keywords.TrustServerCertificate);
hash.Add(DbConnectionStringKeywords.TypeSystemVersion, Keywords.TypeSystemVersion);
hash.Add(DbConnectionStringKeywords.UserID, Keywords.UserID);
hash.Add(DbConnectionStringKeywords.UserInstance, Keywords.UserInstance);
hash.Add(DbConnectionStringKeywords.WorkstationID, Keywords.WorkstationID);
hash.Add(DbConnectionStringKeywords.ConnectRetryCount, Keywords.ConnectRetryCount);
hash.Add(DbConnectionStringKeywords.ConnectRetryInterval, Keywords.ConnectRetryInterval);
hash.Add(DbConnectionStringSynonyms.APP, Keywords.ApplicationName);
hash.Add(DbConnectionStringSynonyms.EXTENDEDPROPERTIES, Keywords.AttachDBFilename);
hash.Add(DbConnectionStringSynonyms.INITIALFILENAME, Keywords.AttachDBFilename);
hash.Add(DbConnectionStringSynonyms.CONNECTIONTIMEOUT, Keywords.ConnectTimeout);
hash.Add(DbConnectionStringSynonyms.TIMEOUT, Keywords.ConnectTimeout);
hash.Add(DbConnectionStringSynonyms.LANGUAGE, Keywords.CurrentLanguage);
hash.Add(DbConnectionStringSynonyms.ADDR, Keywords.DataSource);
hash.Add(DbConnectionStringSynonyms.ADDRESS, Keywords.DataSource);
hash.Add(DbConnectionStringSynonyms.NETWORKADDRESS, Keywords.DataSource);
hash.Add(DbConnectionStringSynonyms.SERVER, Keywords.DataSource);
hash.Add(DbConnectionStringSynonyms.DATABASE, Keywords.InitialCatalog);
hash.Add(DbConnectionStringSynonyms.TRUSTEDCONNECTION, Keywords.IntegratedSecurity);
hash.Add(DbConnectionStringSynonyms.ConnectionLifetime, Keywords.LoadBalanceTimeout);
hash.Add(DbConnectionStringSynonyms.Pwd, Keywords.Password);
hash.Add(DbConnectionStringSynonyms.PERSISTSECURITYINFO, Keywords.PersistSecurityInfo);
hash.Add(DbConnectionStringSynonyms.UID, Keywords.UserID);
hash.Add(DbConnectionStringSynonyms.User, Keywords.UserID);
hash.Add(DbConnectionStringSynonyms.WSID, Keywords.WorkstationID);
Debug.Assert((KeywordsCount + SqlConnectionString.SynonymCount) == hash.Count, "initial expected size is incorrect");
return hash;
}
public SqlConnectionStringBuilder() : this((string)null)
{
}
public SqlConnectionStringBuilder(string connectionString) : base()
{
if (!string.IsNullOrEmpty(connectionString))
{
ConnectionString = connectionString;
}
}
public override object this[string keyword]
{
get
{
Keywords index = GetIndex(keyword);
return GetAt(index);
}
set
{
if (null != value)
{
Keywords index = GetIndex(keyword);
switch (index)
{
case Keywords.ApplicationIntent: this.ApplicationIntent = ConvertToApplicationIntent(keyword, value); break;
case Keywords.ApplicationName: ApplicationName = ConvertToString(value); break;
case Keywords.AttachDBFilename: AttachDBFilename = ConvertToString(value); break;
case Keywords.CurrentLanguage: CurrentLanguage = ConvertToString(value); break;
case Keywords.DataSource: DataSource = ConvertToString(value); break;
case Keywords.FailoverPartner: FailoverPartner = ConvertToString(value); break;
case Keywords.InitialCatalog: InitialCatalog = ConvertToString(value); break;
// case Keywords.NamedConnection: NamedConnection = ConvertToString(value); break;
case Keywords.Password: Password = ConvertToString(value); break;
case Keywords.UserID: UserID = ConvertToString(value); break;
case Keywords.TransactionBinding: TransactionBinding = ConvertToString(value); break;
case Keywords.TypeSystemVersion: TypeSystemVersion = ConvertToString(value); break;
case Keywords.WorkstationID: WorkstationID = ConvertToString(value); break;
case Keywords.ConnectTimeout: ConnectTimeout = ConvertToInt32(value); break;
case Keywords.LoadBalanceTimeout: LoadBalanceTimeout = ConvertToInt32(value); break;
case Keywords.MaxPoolSize: MaxPoolSize = ConvertToInt32(value); break;
case Keywords.MinPoolSize: MinPoolSize = ConvertToInt32(value); break;
case Keywords.PacketSize: PacketSize = ConvertToInt32(value); break;
case Keywords.IntegratedSecurity: IntegratedSecurity = ConvertToIntegratedSecurity(value); break;
case Keywords.Encrypt: Encrypt = ConvertToBoolean(value); break;
case Keywords.TrustServerCertificate: TrustServerCertificate = ConvertToBoolean(value); break;
case Keywords.Enlist: Enlist = ConvertToBoolean(value); break;
case Keywords.MultipleActiveResultSets: MultipleActiveResultSets = ConvertToBoolean(value); break;
case Keywords.MultiSubnetFailover: MultiSubnetFailover = ConvertToBoolean(value); break;
case Keywords.PersistSecurityInfo: PersistSecurityInfo = ConvertToBoolean(value); break;
case Keywords.Pooling: Pooling = ConvertToBoolean(value); break;
case Keywords.Replication: Replication = ConvertToBoolean(value); break;
case Keywords.UserInstance: UserInstance = ConvertToBoolean(value); break;
case Keywords.ConnectRetryCount: ConnectRetryCount = ConvertToInt32(value); break;
case Keywords.ConnectRetryInterval: ConnectRetryInterval = ConvertToInt32(value); break;
default:
Debug.Assert(false, "unexpected keyword");
throw UnsupportedKeyword(keyword);
}
}
else
{
Remove(keyword);
}
}
}
public ApplicationIntent ApplicationIntent
{
get { return _applicationIntent; }
set
{
if (!DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value))
{
throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)value);
}
SetApplicationIntentValue(value);
_applicationIntent = value;
}
}
public string ApplicationName
{
get { return _applicationName; }
set
{
SetValue(DbConnectionStringKeywords.ApplicationName, value);
_applicationName = value;
}
}
public string AttachDBFilename
{
get { return _attachDBFilename; }
set
{
SetValue(DbConnectionStringKeywords.AttachDBFilename, value);
_attachDBFilename = value;
}
}
public int ConnectTimeout
{
get { return _connectTimeout; }
set
{
if (value < 0)
{
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectTimeout);
}
SetValue(DbConnectionStringKeywords.ConnectTimeout, value);
_connectTimeout = value;
}
}
public string CurrentLanguage
{
get { return _currentLanguage; }
set
{
SetValue(DbConnectionStringKeywords.CurrentLanguage, value);
_currentLanguage = value;
}
}
public string DataSource
{
get { return _dataSource; }
set
{
SetValue(DbConnectionStringKeywords.DataSource, value);
_dataSource = value;
}
}
public bool Encrypt
{
get { return _encrypt; }
set
{
SetValue(DbConnectionStringKeywords.Encrypt, value);
_encrypt = value;
}
}
public bool TrustServerCertificate
{
get { return _trustServerCertificate; }
set
{
SetValue(DbConnectionStringKeywords.TrustServerCertificate, value);
_trustServerCertificate = value;
}
}
public bool Enlist
{
get { return _enlist; }
set
{
SetValue(DbConnectionStringKeywords.Enlist, value);
_enlist = value;
}
}
public string FailoverPartner
{
get { return _failoverPartner; }
set
{
SetValue(DbConnectionStringKeywords.FailoverPartner, value);
_failoverPartner = value;
}
}
[TypeConverter(typeof(SqlInitialCatalogConverter))]
public string InitialCatalog
{
get { return _initialCatalog; }
set
{
SetValue(DbConnectionStringKeywords.InitialCatalog, value);
_initialCatalog = value;
}
}
public bool IntegratedSecurity
{
get { return _integratedSecurity; }
set
{
SetValue(DbConnectionStringKeywords.IntegratedSecurity, value);
_integratedSecurity = value;
}
}
public int LoadBalanceTimeout
{
get { return _loadBalanceTimeout; }
set
{
if (value < 0)
{
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.LoadBalanceTimeout);
}
SetValue(DbConnectionStringKeywords.LoadBalanceTimeout, value);
_loadBalanceTimeout = value;
}
}
public int MaxPoolSize
{
get { return _maxPoolSize; }
set
{
if (value < 1)
{
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.MaxPoolSize);
}
SetValue(DbConnectionStringKeywords.MaxPoolSize, value);
_maxPoolSize = value;
}
}
public int ConnectRetryCount
{
get { return _connectRetryCount; }
set
{
if ((value < 0) || (value > 255))
{
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectRetryCount);
}
SetValue(DbConnectionStringKeywords.ConnectRetryCount, value);
_connectRetryCount = value;
}
}
public int ConnectRetryInterval
{
get { return _connectRetryInterval; }
set
{
if ((value < 1) || (value > 60))
{
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectRetryInterval);
}
SetValue(DbConnectionStringKeywords.ConnectRetryInterval, value);
_connectRetryInterval = value;
}
}
public int MinPoolSize
{
get { return _minPoolSize; }
set
{
if (value < 0)
{
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.MinPoolSize);
}
SetValue(DbConnectionStringKeywords.MinPoolSize, value);
_minPoolSize = value;
}
}
public bool MultipleActiveResultSets
{
get { return _multipleActiveResultSets; }
set
{
SetValue(DbConnectionStringKeywords.MultipleActiveResultSets, value);
_multipleActiveResultSets = value;
}
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Reviewed and Approved by UE")]
public bool MultiSubnetFailover
{
get { return _multiSubnetFailover; }
set
{
SetValue(DbConnectionStringKeywords.MultiSubnetFailover, value);
_multiSubnetFailover = value;
}
}
/*
[DisplayName(DbConnectionStringKeywords.NamedConnection)]
[ResCategoryAttribute(Res.DataCategory_NamedConnectionString)]
[ResDescriptionAttribute(Res.DbConnectionString_NamedConnection)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[TypeConverter(typeof(NamedConnectionStringConverter))]
public string NamedConnection {
get { return _namedConnection; }
set {
SetValue(DbConnectionStringKeywords.NamedConnection, value);
_namedConnection = value;
}
}
*/
public int PacketSize
{
get { return _packetSize; }
set
{
if ((value < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < value))
{
throw SQL.InvalidPacketSizeValue();
}
SetValue(DbConnectionStringKeywords.PacketSize, value);
_packetSize = value;
}
}
public string Password
{
get { return _password; }
set
{
SetValue(DbConnectionStringKeywords.Password, value);
_password = value;
}
}
public bool PersistSecurityInfo
{
get { return _persistSecurityInfo; }
set
{
SetValue(DbConnectionStringKeywords.PersistSecurityInfo, value);
_persistSecurityInfo = value;
}
}
public bool Pooling
{
get { return _pooling; }
set
{
SetValue(DbConnectionStringKeywords.Pooling, value);
_pooling = value;
}
}
public bool Replication
{
get { return _replication; }
set
{
SetValue(DbConnectionStringKeywords.Replication, value);
_replication = value;
}
}
public string TransactionBinding
{
get { return _transactionBinding; }
set
{
SetValue(DbConnectionStringKeywords.TransactionBinding, value);
_transactionBinding = value;
}
}
public string TypeSystemVersion
{
get { return _typeSystemVersion; }
set
{
SetValue(DbConnectionStringKeywords.TypeSystemVersion, value);
_typeSystemVersion = value;
}
}
public string UserID
{
get { return _userID; }
set
{
SetValue(DbConnectionStringKeywords.UserID, value);
_userID = value;
}
}
public bool UserInstance
{
get { return _userInstance; }
set
{
SetValue(DbConnectionStringKeywords.UserInstance, value);
_userInstance = value;
}
}
public string WorkstationID
{
get { return _workstationID; }
set
{
SetValue(DbConnectionStringKeywords.WorkstationID, value);
_workstationID = value;
}
}
public override ICollection Keys
{
get
{
return new System.Collections.ObjectModel.ReadOnlyCollection<string>(s_validKeywords);
}
}
public override ICollection Values
{
get
{
// written this way so if the ordering of Keywords & _validKeywords changes
// this is one less place to maintain
object[] values = new object[s_validKeywords.Length];
for (int i = 0; i < values.Length; ++i)
{
values[i] = GetAt((Keywords)i);
}
return new System.Collections.ObjectModel.ReadOnlyCollection<object>(values);
}
}
public override void Clear()
{
base.Clear();
for (int i = 0; i < s_validKeywords.Length; ++i)
{
Reset((Keywords)i);
}
}
public override bool ContainsKey(string keyword)
{
ADP.CheckArgumentNull(keyword, nameof(keyword));
return s_keywords.ContainsKey(keyword);
}
private static bool ConvertToBoolean(object value)
{
return DbConnectionStringBuilderUtil.ConvertToBoolean(value);
}
private static int ConvertToInt32(object value)
{
return DbConnectionStringBuilderUtil.ConvertToInt32(value);
}
private static bool ConvertToIntegratedSecurity(object value)
{
return DbConnectionStringBuilderUtil.ConvertToIntegratedSecurity(value);
}
private static string ConvertToString(object value)
{
return DbConnectionStringBuilderUtil.ConvertToString(value);
}
private static ApplicationIntent ConvertToApplicationIntent(string keyword, object value)
{
return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(keyword, value);
}
private object GetAt(Keywords index)
{
switch (index)
{
case Keywords.ApplicationIntent: return this.ApplicationIntent;
case Keywords.ApplicationName: return ApplicationName;
case Keywords.AttachDBFilename: return AttachDBFilename;
case Keywords.ConnectTimeout: return ConnectTimeout;
case Keywords.CurrentLanguage: return CurrentLanguage;
case Keywords.DataSource: return DataSource;
case Keywords.Encrypt: return Encrypt;
case Keywords.Enlist: return Enlist;
case Keywords.FailoverPartner: return FailoverPartner;
case Keywords.InitialCatalog: return InitialCatalog;
case Keywords.IntegratedSecurity: return IntegratedSecurity;
case Keywords.LoadBalanceTimeout: return LoadBalanceTimeout;
case Keywords.MultipleActiveResultSets: return MultipleActiveResultSets;
case Keywords.MaxPoolSize: return MaxPoolSize;
case Keywords.MinPoolSize: return MinPoolSize;
case Keywords.MultiSubnetFailover: return MultiSubnetFailover;
// case Keywords.NamedConnection: return NamedConnection;
case Keywords.PacketSize: return PacketSize;
case Keywords.Password: return Password;
case Keywords.PersistSecurityInfo: return PersistSecurityInfo;
case Keywords.Pooling: return Pooling;
case Keywords.Replication: return Replication;
case Keywords.TransactionBinding: return TransactionBinding;
case Keywords.TrustServerCertificate: return TrustServerCertificate;
case Keywords.TypeSystemVersion: return TypeSystemVersion;
case Keywords.UserID: return UserID;
case Keywords.UserInstance: return UserInstance;
case Keywords.WorkstationID: return WorkstationID;
case Keywords.ConnectRetryCount: return ConnectRetryCount;
case Keywords.ConnectRetryInterval: return ConnectRetryInterval;
default:
Debug.Assert(false, "unexpected keyword");
throw UnsupportedKeyword(s_validKeywords[(int)index]);
}
}
private Keywords GetIndex(string keyword)
{
ADP.CheckArgumentNull(keyword, nameof(keyword));
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
return index;
}
throw UnsupportedKeyword(keyword);
}
public override bool Remove(string keyword)
{
ADP.CheckArgumentNull(keyword, nameof(keyword));
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
if (base.Remove(s_validKeywords[(int)index]))
{
Reset(index);
return true;
}
}
return false;
}
private void Reset(Keywords index)
{
switch (index)
{
case Keywords.ApplicationIntent:
_applicationIntent = DbConnectionStringDefaults.ApplicationIntent;
break;
case Keywords.ApplicationName:
_applicationName = DbConnectionStringDefaults.ApplicationName;
break;
case Keywords.AttachDBFilename:
_attachDBFilename = DbConnectionStringDefaults.AttachDBFilename;
break;
case Keywords.ConnectTimeout:
_connectTimeout = DbConnectionStringDefaults.ConnectTimeout;
break;
case Keywords.CurrentLanguage:
_currentLanguage = DbConnectionStringDefaults.CurrentLanguage;
break;
case Keywords.DataSource:
_dataSource = DbConnectionStringDefaults.DataSource;
break;
case Keywords.Encrypt:
_encrypt = DbConnectionStringDefaults.Encrypt;
break;
case Keywords.Enlist:
_enlist = DbConnectionStringDefaults.Enlist;
break;
case Keywords.FailoverPartner:
_failoverPartner = DbConnectionStringDefaults.FailoverPartner;
break;
case Keywords.InitialCatalog:
_initialCatalog = DbConnectionStringDefaults.InitialCatalog;
break;
case Keywords.IntegratedSecurity:
_integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity;
break;
case Keywords.LoadBalanceTimeout:
_loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout;
break;
case Keywords.MultipleActiveResultSets:
_multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets;
break;
case Keywords.MaxPoolSize:
_maxPoolSize = DbConnectionStringDefaults.MaxPoolSize;
break;
case Keywords.MinPoolSize:
_minPoolSize = DbConnectionStringDefaults.MinPoolSize;
break;
case Keywords.MultiSubnetFailover:
_multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover;
break;
// case Keywords.NamedConnection:
// _namedConnection = DbConnectionStringDefaults.NamedConnection;
// break;
case Keywords.PacketSize:
_packetSize = DbConnectionStringDefaults.PacketSize;
break;
case Keywords.Password:
_password = DbConnectionStringDefaults.Password;
break;
case Keywords.PersistSecurityInfo:
_persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo;
break;
case Keywords.Pooling:
_pooling = DbConnectionStringDefaults.Pooling;
break;
case Keywords.ConnectRetryCount:
_connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount;
break;
case Keywords.ConnectRetryInterval:
_connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval;
break;
case Keywords.Replication:
_replication = DbConnectionStringDefaults.Replication;
break;
case Keywords.TransactionBinding:
_transactionBinding = DbConnectionStringDefaults.TransactionBinding;
break;
case Keywords.TrustServerCertificate:
_trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate;
break;
case Keywords.TypeSystemVersion:
_typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion;
break;
case Keywords.UserID:
_userID = DbConnectionStringDefaults.UserID;
break;
case Keywords.UserInstance:
_userInstance = DbConnectionStringDefaults.UserInstance;
break;
case Keywords.WorkstationID:
_workstationID = DbConnectionStringDefaults.WorkstationID;
break;
default:
Debug.Assert(false, "unexpected keyword");
throw UnsupportedKeyword(s_validKeywords[(int)index]);
}
}
private void SetValue(string keyword, bool value)
{
base[keyword] = value.ToString();
}
private void SetValue(string keyword, int value)
{
base[keyword] = value.ToString((System.IFormatProvider)null);
}
private void SetValue(string keyword, string value)
{
ADP.CheckArgumentNull(value, keyword);
base[keyword] = value;
}
private void SetApplicationIntentValue(ApplicationIntent value)
{
Debug.Assert(DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value), "invalid value");
base[DbConnectionStringKeywords.ApplicationIntent] = DbConnectionStringBuilderUtil.ApplicationIntentToString(value);
}
public override bool ShouldSerialize(string keyword)
{
ADP.CheckArgumentNull(keyword, nameof(keyword));
Keywords index;
return s_keywords.TryGetValue(keyword, out index) && base.ShouldSerialize(s_validKeywords[(int)index]);
}
public override bool TryGetValue(string keyword, out object value)
{
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
value = GetAt(index);
return true;
}
value = null;
return false;
}
private static readonly string[] s_notSupportedKeywords = new string[] {
DbConnectionStringKeywords.AsynchronousProcessing,
DbConnectionStringKeywords.ConnectionReset,
DbConnectionStringKeywords.ContextConnection,
DbConnectionStringKeywords.TransactionBinding,
DbConnectionStringSynonyms.Async
};
private static readonly string[] s_notSupportedNetworkLibraryKeywords = new string[] {
DbConnectionStringKeywords.NetworkLibrary,
DbConnectionStringSynonyms.NET,
DbConnectionStringSynonyms.NETWORK
};
private Exception UnsupportedKeyword(string keyword)
{
if (s_notSupportedKeywords.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
return SQL.UnsupportedKeyword(keyword);
}
else if (s_notSupportedNetworkLibraryKeywords.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
return SQL.NetworkLibraryKeywordNotSupported();
}
else
{
return ADP.KeywordNotSupported(keyword);
}
}
private sealed class SqlInitialCatalogConverter : StringConverter
{
// converter classes should have public ctor
public SqlInitialCatalogConverter()
{
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return GetStandardValuesSupportedInternal(context);
}
private bool GetStandardValuesSupportedInternal(ITypeDescriptorContext context)
{
// Only say standard values are supported if the connection string has enough
// information set to instantiate a connection and retrieve a list of databases
bool flag = false;
if (null != context)
{
SqlConnectionStringBuilder constr = (context.Instance as SqlConnectionStringBuilder);
if (null != constr)
{
if ((0 < constr.DataSource.Length) && (constr.IntegratedSecurity || (0 < constr.UserID.Length)))
{
flag = true;
}
}
}
return flag;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
// Although theoretically this could be true, some people may want to just type in a name
return false;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
// There can only be standard values if the connection string is in a state that might
// be able to instantiate a connection
if (GetStandardValuesSupportedInternal(context))
{
// Create an array list to store the database names
List<string> values = new List<string>();
try
{
SqlConnectionStringBuilder constr = (SqlConnectionStringBuilder)context.Instance;
// Create a connection
using (SqlConnection connection = new SqlConnection())
{
// Create a basic connection string from current property values
connection.ConnectionString = constr.ConnectionString;
// Try to open the connection
connection.Open();
DataTable databaseTable = connection.GetSchema("DATABASES");
foreach (DataRow row in databaseTable.Rows)
{
string dbName = (string)row["database_name"];
values.Add(dbName);
}
}
}
catch (SqlException e)
{
ADP.TraceExceptionWithoutRethrow(e);
// silently fail
}
// Return values as a StandardValuesCollection
return new StandardValuesCollection(values);
}
return null;
}
}
}
}
| |
using System;
using NSubstitute;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using SineSignal.Ottoman.Specs.Framework;
using SineSignal.Ottoman.Serialization;
namespace SineSignal.Ottoman.Specs.Serialization.JsonReaderSpecs
{
public class ReadingArraySpecs
{
public class When_reading_a_json_string_that_contains_an_array_with_an_empty_string : ConcernFor<JsonReader>
{
private string input;
protected override void Given()
{
input = "[ \"\" ]";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
public class And_when_calling_read_twice : When_reading_a_json_string_that_contains_an_array_with_an_empty_string
{
protected override void When()
{
Sut.Read();
Sut.Read();
Sut.Close();
}
[Test]
public void Should_set_current_token_value_to_an_empty_string()
{
Assert.That(Sut.CurrentTokenValue, Is.EqualTo(String.Empty));
}
}
}
public class When_reading_a_json_string_that_contains_an_array_with_two_booleans : ConcernFor<JsonReader>
{
private string input;
protected override void Given()
{
input = "[ true, false ]";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
public class And_when_calling_read_once : When_reading_a_json_string_that_contains_an_array_with_two_booleans
{
protected override void When()
{
Sut.Read();
}
[Test]
public void Should_set_current_token_to_array_start()
{
Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.ArrayStart));
}
}
public class And_when_calling_read_twice : When_reading_a_json_string_that_contains_an_array_with_two_booleans
{
protected override void When()
{
Sut.Read();
Sut.Read();
}
[Test]
public void Should_set_current_token_to_json_boolean()
{
Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.Boolean));
}
[Test]
public void Should_set_current_token_value_to_true()
{
Assert.That(Sut.CurrentTokenValue, Is.True);
}
}
public class And_when_calling_read_three_times : When_reading_a_json_string_that_contains_an_array_with_two_booleans
{
protected override void When()
{
for (int index = 1; index <= 3; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_to_json_boolean()
{
Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.Boolean));
}
[Test]
public void Should_set_current_token_value_to_false()
{
Assert.That(Sut.CurrentTokenValue, Is.False);
}
}
public class And_when_calling_read_four_times : When_reading_a_json_string_that_contains_an_array_with_two_booleans
{
protected override void When()
{
for (int index = 1; index <= 4; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_to_array_end()
{
Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.ArrayEnd));
}
}
public class And_when_calling_read_five_times : When_reading_a_json_string_that_contains_an_array_with_two_booleans
{
protected override void When()
{
for (int index = 1; index <= 5; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_end_of_json_to_true()
{
Assert.That(Sut.EndOfJson, Is.True);
}
}
}
public class When_reading_a_json_string_that_contains_an_array_containing_four_strings : ConcernFor<JsonReader>
{
private string input;
private string stringValue3;
private string stringValue4;
protected override void Given()
{
input = "[ \"One\", \"Two\", \"abc 123 \\n\\f\\b\\t\\r \\\" \\\\ \\u263a \\u25CF\", \"\\\"Hello\\\" \\'world\\'\" ]";
stringValue3 = "abc 123 \n\f\b\t\r \" \\ \u263a \u25cf";
stringValue4 = "\"Hello\" 'world'";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
public class And_when_calling_read_once : When_reading_a_json_string_that_contains_an_array_containing_four_strings
{
protected override void When()
{
Sut.Read();
}
[Test]
public void Should_set_current_token_to_array_start()
{
Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.ArrayStart));
}
}
public class And_when_calling_read_twice : When_reading_a_json_string_that_contains_an_array_containing_four_strings
{
protected override void When()
{
Sut.Read();
Sut.Read();
}
[Test]
public void Should_set_current_token_to_json_string()
{
Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.String));
}
[Test]
public void Should_set_current_token_value_to_One()
{
Assert.That(Sut.CurrentTokenValue, Is.EqualTo("One"));
}
}
public class And_when_calling_read_three_times : When_reading_a_json_string_that_contains_an_array_containing_four_strings
{
protected override void When()
{
for (int index = 1; index <= 3; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_to_json_string()
{
Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.String));
}
[Test]
public void Should_set_current_token_value_to_Two()
{
Assert.That(Sut.CurrentTokenValue, Is.EqualTo("Two"));
}
}
public class And_when_calling_read_four_times : When_reading_a_json_string_that_contains_an_array_containing_four_strings
{
protected override void When()
{
for (int index = 1; index <= 4; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_to_json_string()
{
Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.String));
}
[Test]
public void Should_set_current_token_value_to_stringValue3()
{
Assert.That(Sut.CurrentTokenValue, Is.EqualTo(stringValue3));
}
}
public class And_when_calling_read_five_times : When_reading_a_json_string_that_contains_an_array_containing_four_strings
{
protected override void When()
{
for (int index = 1; index <= 5; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_to_json_string()
{
Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.String));
}
[Test]
public void Should_set_current_token_value_to_stringValue4()
{
Assert.That(Sut.CurrentTokenValue, Is.EqualTo(stringValue4));
}
}
public class And_when_calling_read_six_times : When_reading_a_json_string_that_contains_an_array_containing_four_strings
{
protected override void When()
{
for (int index = 1; index <= 6; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_to_array_end()
{
Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.ArrayEnd));
}
}
public class And_when_calling_read_seven_times : When_reading_a_json_string_that_contains_an_array_containing_four_strings
{
protected override void When()
{
for (int index = 1; index <= 7; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_end_of_json_to_true()
{
Assert.That(Sut.EndOfJson, Is.True);
}
}
}
public class When_reading_a_json_string_that_contains_an_array_of_ints : ConcernFor<JsonReader>
{
private string input;
protected override void Given()
{
input = @"[ -10, -5, -0, 0, 5, 10 ]";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
public class And_when_calling_read_twice : When_reading_a_json_string_that_contains_an_array_of_ints
{
protected override void When()
{
Sut.Read();
Sut.Read();
}
[Test]
public void Should_set_current_token_value_to_negative_10()
{
Assert.That((int)Sut.CurrentTokenValue, Is.EqualTo(-10));
}
}
public class And_when_calling_read_three_times : When_reading_a_json_string_that_contains_an_array_of_ints
{
protected override void When()
{
for (int index = 1; index <= 3; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_negative_5()
{
Assert.That((int)Sut.CurrentTokenValue, Is.EqualTo(-5));
}
}
public class And_when_calling_read_four_times : When_reading_a_json_string_that_contains_an_array_of_ints
{
protected override void When()
{
for (int index = 1; index <= 4; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_0()
{
Assert.That((int)Sut.CurrentTokenValue, Is.EqualTo(0));
}
}
public class And_when_calling_read_five_times : When_reading_a_json_string_that_contains_an_array_of_ints
{
protected override void When()
{
for (int index = 1; index <= 5; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_0()
{
Assert.That((int)Sut.CurrentTokenValue, Is.EqualTo(0));
}
}
public class And_when_calling_read_six_times : When_reading_a_json_string_that_contains_an_array_of_ints
{
protected override void When()
{
for (int index = 1; index <= 6; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_5()
{
Assert.That((int)Sut.CurrentTokenValue, Is.EqualTo(5));
}
}
public class And_when_calling_read_seven_times : When_reading_a_json_string_that_contains_an_array_of_ints
{
protected override void When()
{
for (int index = 1; index <= 7; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_10()
{
Assert.That((int)Sut.CurrentTokenValue, Is.EqualTo(10));
}
}
}
public class When_reading_a_json_string_that_contains_an_array_of_doubles : ConcernFor<JsonReader>
{
private string input;
protected override void Given()
{
input = @"[ -125.000009, 10.0, -10.0, 0.0, -0.0, 3.1415926536, 5e-4, 233e+5, 0.6e2, 2E-5 ]";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
public class And_when_calling_read_twice : When_reading_a_json_string_that_contains_an_array_of_doubles
{
protected override void When()
{
Sut.Read();
Sut.Read();
}
[Test]
public void Should_set_current_token_value_to_negative_125_dot_000009()
{
Assert.That((double)Sut.CurrentTokenValue, Is.EqualTo(-125.000009));
}
}
public class And_when_calling_read_three_times : When_reading_a_json_string_that_contains_an_array_of_doubles
{
protected override void When()
{
for (int index = 1; index <= 3; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_10_dot_0()
{
Assert.That((double)Sut.CurrentTokenValue, Is.EqualTo(10.0));
}
}
public class And_when_calling_read_four_times : When_reading_a_json_string_that_contains_an_array_of_doubles
{
protected override void When()
{
for (int index = 1; index <= 4; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_negative_10_dot_0()
{
Assert.That((double)Sut.CurrentTokenValue, Is.EqualTo(-10.0));
}
}
public class And_when_calling_read_five_times : When_reading_a_json_string_that_contains_an_array_of_doubles
{
protected override void When()
{
for (int index = 1; index <= 5; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_0_dot_0()
{
Assert.That((double)Sut.CurrentTokenValue, Is.EqualTo(0.0));
}
}
public class And_when_calling_read_six_times : When_reading_a_json_string_that_contains_an_array_of_doubles
{
protected override void When()
{
for (int index = 1; index <= 6; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_0_dot_0()
{
Assert.That((double)Sut.CurrentTokenValue, Is.EqualTo(0.0));
}
}
public class And_when_calling_read_seven_times : When_reading_a_json_string_that_contains_an_array_of_doubles
{
protected override void When()
{
for (int index = 1; index <= 7; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_3_dot_1415926536()
{
Assert.That((double)Sut.CurrentTokenValue, Is.EqualTo(3.1415926536));
}
}
public class And_when_calling_read_eight_times : When_reading_a_json_string_that_contains_an_array_of_doubles
{
protected override void When()
{
for (int index = 1; index <= 8; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_0_dot_0005()
{
Assert.That((double)Sut.CurrentTokenValue, Is.EqualTo(0.0005));
}
}
public class And_when_calling_read_nine_times : When_reading_a_json_string_that_contains_an_array_of_doubles
{
protected override void When()
{
for (int index = 1; index <= 9; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_23300000_dot_0()
{
Assert.That((double)Sut.CurrentTokenValue, Is.EqualTo(23300000.0));
}
}
public class And_when_calling_read_ten_times : When_reading_a_json_string_that_contains_an_array_of_doubles
{
protected override void When()
{
for (int index = 1; index <= 10; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_60_dot_0()
{
Assert.That((double)Sut.CurrentTokenValue, Is.EqualTo(60.0));
}
}
public class And_when_calling_read_eleven_times : When_reading_a_json_string_that_contains_an_array_of_doubles
{
protected override void When()
{
for (int index = 1; index <= 11; index++)
{
Sut.Read();
}
}
[Test]
public void Should_set_current_token_value_to_0_dot_00002()
{
Assert.That((double)Sut.CurrentTokenValue, Is.EqualTo(0.00002));
}
}
}
public class When_reading_a_json_string_that_contains_an_error_in_the_escape_sequence : ConcernFor<JsonReader>
{
private string input;
private JsonException expectedException;
protected override void Given()
{
input = "[ \"Hello World \\ufffg \" ]";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
protected override void When()
{
try
{
while (Sut.Read());
}
catch (JsonException e)
{
expectedException = e;
}
}
[Test]
public void Should_throw_a_json_exception()
{
Assert.That(expectedException, Is.TypeOf(typeof(JsonException)));
}
[Test]
public void Should_set_message_to_Invalid_character_g_in_input_string()
{
Assert.That(expectedException.Message, Is.EqualTo("Invalid character 'g' in input string"));
}
}
public class When_reading_a_json_string_that_contains_an_invalid_real_number : ConcernFor<JsonReader>
{
private string input;
private JsonException expectedException;
protected override void Given()
{
input = "[ 0.e5 ]";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
protected override void When()
{
try
{
while (Sut.Read());
}
catch (JsonException e)
{
expectedException = e;
}
}
[Test]
public void Should_throw_a_json_exception()
{
Assert.That(expectedException, Is.TypeOf(typeof(JsonException)));
}
[Test]
public void Should_set_message_to_Invalid_character_e_in_input_string()
{
Assert.That(expectedException.Message, Is.EqualTo("Invalid character 'e' in input string"));
}
}
public class When_reading_a_json_string_that_contains_an_invalid_boolean_value : ConcernFor<JsonReader>
{
private string input;
private JsonException expectedException;
protected override void Given()
{
input = "[ TRUE ]";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
protected override void When()
{
try
{
while (Sut.Read());
}
catch (JsonException e)
{
expectedException = e;
}
}
[Test]
public void Should_throw_a_json_exception()
{
Assert.That(expectedException, Is.TypeOf(typeof(JsonException)));
}
[Test]
public void Should_set_message_to_Invalid_character_T_in_input_string()
{
Assert.That(expectedException.Message, Is.EqualTo("Invalid character 'T' in input string"));
}
}
public class When_reading_a_json_string_that_contains_an_array_with_the_wrong_closing_token : ConcernFor<JsonReader>
{
private string input;
private JsonException expectedException;
protected override void Given()
{
input = "[ 1, 2, 3 }";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
protected override void When()
{
try
{
while (Sut.Read());
}
catch (JsonException e)
{
expectedException = e;
}
}
[Test]
public void Should_throw_a_json_exception()
{
Assert.That(expectedException, Is.TypeOf(typeof(JsonException)));
}
[Test]
public void Should_set_message_to_Invalid_token_125_in_input_string()
{
Assert.That(expectedException.Message, Is.EqualTo("Invalid token '125' in input string"));
}
}
public class When_reading_a_json_string_that_contains_an_array_with_no_closing_token : ConcernFor<JsonReader>
{
private string input;
private JsonException expectedException;
protected override void Given()
{
input = "[ \"name1\" ";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
protected override void When()
{
try
{
while (Sut.Read());
}
catch (JsonException e)
{
expectedException = e;
}
}
[Test]
public void Should_throw_a_json_exception()
{
Assert.That(expectedException, Is.TypeOf(typeof(JsonException)));
}
[Test]
public void Should_set_message_to_Input_does_not_evaluate_to_proper_JSON_text()
{
Assert.That(expectedException.Message, Is.EqualTo("Input doesn't evaluate to proper JSON text"));
}
}
public class When_reading_a_json_string_that_contains_no_array_or_object_tokens : ConcernFor<JsonReader>
{
private string input;
private JsonException expectedException;
protected override void Given()
{
input = " true ";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
protected override void When()
{
try
{
while (Sut.Read());
}
catch (JsonException e)
{
expectedException = e;
}
}
[Test]
public void Should_throw_a_json_exception()
{
Assert.That(expectedException, Is.TypeOf(typeof(JsonException)));
}
[Test]
public void Should_set_message_to_Invalid_token_True_in_input_string()
{
Assert.That(expectedException.Message, Is.EqualTo("Invalid token 'True' in input string"));
}
}
public class When_reading_a_json_string_with_nested_arrays : ConcernFor<JsonReader>
{
private string input;
private int arrayCount;
protected override void Given()
{
input = "[ [ [ [ [ 1, 2, 3 ] ] ] ] ]";
arrayCount = 0;
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
protected override void When()
{
while (Sut.Read())
{
if (Sut.CurrentToken == JsonToken.ArrayStart)
{
arrayCount++;
}
}
}
[Test]
public void Should_count_five_arrays()
{
Assert.That(arrayCount, Is.EqualTo(5));
}
}
public class When_reading_a_json_string_that_contains_an_array_with_comments : ConcernFor<JsonReader>
{
private string input;
private JsonException expectedException;
protected override void Given()
{
input = @"
[
// This is a comment
1,
2,
3
]";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
public class And_when_comments_are_not_allowed : When_reading_a_json_string_that_contains_an_array_with_comments
{
protected override void When()
{
try
{
while (Sut.Read());
}
catch (JsonException e)
{
expectedException = e;
}
}
[Test]
public void Should_throw_a_json_exception()
{
Assert.That(expectedException, Is.TypeOf(typeof(JsonException)));
}
[Test]
public void Should_set_message_to_Invalid_character_forward_slash_in_input_string()
{
Assert.That(expectedException.Message, Is.EqualTo("Invalid character '/' in input string"));
}
}
}
public class When_reading_a_json_string_that_contains_an_array_with_a_string_in_single_quotes : ConcernFor<JsonReader>
{
private string input;
private JsonException expectedException;
protected override void Given()
{
input = "[ 'Single quotes' ]";
}
public override JsonReader CreateSystemUnderTest()
{
return new JsonReader(input);
}
public class And_when_single_quotes_are_not_allowed : When_reading_a_json_string_that_contains_an_array_with_a_string_in_single_quotes
{
protected override void When()
{
try
{
while (Sut.Read());
}
catch (JsonException e)
{
expectedException = e;
}
}
[Test]
public void Should_throw_a_json_exception()
{
Assert.That(expectedException, Is.TypeOf(typeof(JsonException)));
}
[Test]
public void Should_set_message_to_Invalid_character_single_quote_in_input_string()
{
Assert.That(expectedException.Message, Is.EqualTo("Invalid character ''' in input string"));
}
}
}
}
}
| |
using Moq;
using NFluent;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WireMock.Handlers;
using WireMock.Server;
using WireMock.Settings;
using Xunit;
namespace WireMock.Net.Tests
{
public class WireMockServerAdminFilesTests
{
private readonly HttpClient _client = new HttpClient();
[Fact]
public async Task WireMockServer_Admin_Files_Post_Ascii()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("__admin/mappings");
filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>()));
var server = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var multipartFormDataContent = new MultipartFormDataContent();
multipartFormDataContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
multipartFormDataContent.Add(new StreamContent(new MemoryStream(Encoding.ASCII.GetBytes("Here's a string."))));
// Act
var httpResponseMessage = await _client.PostAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt", multipartFormDataContent).ConfigureAwait(false);
// Assert
Check.That(httpResponseMessage.StatusCode).Equals(HttpStatusCode.OK);
Check.That(server.LogEntries.Count().Equals(1));
// Verify
filesystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Once);
filesystemHandlerMock.Verify(fs => fs.FolderExists(It.IsAny<string>()), Times.Once);
filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is<string>(p => p == "filename.txt"), It.IsAny<byte[]>()), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task WireMockServer_Admin_Files_Post_MappingFolderDoesNotExistsButWillBeCreated()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("x");
filesystemHandlerMock.Setup(fs => fs.CreateFolder(It.IsAny<string>()));
filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(false);
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>()));
var server = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var multipartFormDataContent = new MultipartFormDataContent();
multipartFormDataContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
multipartFormDataContent.Add(new StreamContent(new MemoryStream(Encoding.ASCII.GetBytes("Here's a string."))));
// Act
var httpResponseMessage = await _client.PostAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt", multipartFormDataContent).ConfigureAwait(false);
// Assert
Check.That(httpResponseMessage.StatusCode).Equals(HttpStatusCode.OK);
// Verify
filesystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Once);
filesystemHandlerMock.Verify(fs => fs.FolderExists(It.IsAny<string>()), Times.Once);
filesystemHandlerMock.Verify(fs => fs.CreateFolder(It.Is<string>(p => p == "x")), Times.Once);
filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is<string>(p => p == "filename.txt"), It.IsAny<byte[]>()), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task WireMockServer_Admin_Files_GetAscii()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(Encoding.ASCII.GetBytes("Here's a string."));
var server = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var multipartFormDataContent = new MultipartFormDataContent();
multipartFormDataContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
multipartFormDataContent.Add(new StreamContent(new MemoryStream()));
// Act
var httpResponseMessageGet = await _client.GetAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt").ConfigureAwait(false);
// Assert
Check.That(httpResponseMessageGet.StatusCode).Equals(HttpStatusCode.OK);
Check.That(httpResponseMessageGet.Content.ReadAsStringAsync().Result).Equals("Here's a string.");
Check.That(server.LogEntries.Count().Equals(2));
// Verify
filesystemHandlerMock.Verify(fs => fs.ReadFile(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task WireMockServer_Admin_Files_GetUTF16()
{
// Arrange
byte[] symbol = Encoding.UTF32.GetBytes(char.ConvertFromUtf32(0x1D161));
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(symbol);
var server = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var multipartFormDataContent = new MultipartFormDataContent();
multipartFormDataContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
multipartFormDataContent.Add(new StreamContent(new MemoryStream()));
// Act
var httpResponseMessageGet = await _client.GetAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.bin").ConfigureAwait(false);
// Assert
Check.That(httpResponseMessageGet.StatusCode).Equals(HttpStatusCode.OK);
Check.That(httpResponseMessageGet.Content.ReadAsByteArrayAsync().Result).Equals(symbol);
Check.That(server.LogEntries.Count().Equals(2));
// Verify
filesystemHandlerMock.Verify(fs => fs.ReadFile(It.Is<string>(p => p == "filename.bin")), Times.Once);
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.bin")), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task WireMockServer_Admin_Files_Head()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
var server = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
// Act
var requestUri = "http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, requestUri);
var httpResponseMessage = await _client.SendAsync(httpRequestMessage).ConfigureAwait(false);
// Assert
Check.That(httpResponseMessage.StatusCode).Equals(HttpStatusCode.NoContent);
Check.That(server.LogEntries.Count().Equals(1));
// Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.IsAny<string>()), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task WireMockServer_Admin_Files_Head_FileDoesNotExistsReturns404()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false);
var server = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
// Act
var requestUri = "http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, requestUri);
var httpResponseMessage = await _client.SendAsync(httpRequestMessage).ConfigureAwait(false);
// Assert
Check.That(httpResponseMessage.StatusCode).Equals(HttpStatusCode.NotFound);
Check.That(server.LogEntries.Count().Equals(1));
// Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.IsAny<string>()), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// RecipientInfo.cs
//
namespace System.Security.Cryptography.Pkcs
{
using System.Collections;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Globalization;
public enum RecipientInfoType {
Unknown = 0,
KeyTransport = 1, // Must be the same as CAPI.CMSG_KEY_TRANS_RECIPIENT (1)
KeyAgreement = 2, // Must be the same as CAPI.CMSG_KEY_AGREE_RECIPIENT (2)
}
internal enum RecipientSubType {
Unknown = 0,
Pkcs7KeyTransport = 1,
CmsKeyTransport = 2,
CertIdKeyAgreement = 3,
PublicKeyAgreement = 4,
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public abstract class RecipientInfo {
private RecipientInfoType m_recipentInfoType;
private RecipientSubType m_recipientSubType;
[SecurityCritical]
private SafeLocalAllocHandle m_pCmsgRecipientInfo;
private Object m_cmsgRecipientInfo;
private uint m_index;
internal RecipientInfo () {}
[SecurityCritical]
internal RecipientInfo (RecipientInfoType recipientInfoType, RecipientSubType recipientSubType, SafeLocalAllocHandle pCmsgRecipientInfo, Object cmsgRecipientInfo, uint index) {
if (recipientInfoType < RecipientInfoType.Unknown || recipientInfoType > RecipientInfoType.KeyAgreement)
recipientInfoType = RecipientInfoType.Unknown;
if (recipientSubType < RecipientSubType.Unknown || recipientSubType > RecipientSubType.PublicKeyAgreement)
recipientSubType = RecipientSubType.Unknown;
m_recipentInfoType = recipientInfoType;
m_recipientSubType = recipientSubType;
m_pCmsgRecipientInfo = pCmsgRecipientInfo;
m_cmsgRecipientInfo = cmsgRecipientInfo;
m_index = index;
}
public RecipientInfoType Type {
get {
return m_recipentInfoType;
}
}
public abstract int Version { get; }
public abstract SubjectIdentifier RecipientIdentifier { get; }
public abstract AlgorithmIdentifier KeyEncryptionAlgorithm { get; }
public abstract byte[] EncryptedKey { get; }
//
// Internal methods.
//
internal RecipientSubType SubType {
get {
return m_recipientSubType;
}
}
internal SafeLocalAllocHandle pCmsgRecipientInfo {
[SecurityCritical]
get {
return m_pCmsgRecipientInfo;
}
}
internal Object CmsgRecipientInfo {
get {
return m_cmsgRecipientInfo;
}
}
internal uint Index {
get {
return m_index;
}
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class KeyTransRecipientInfo : RecipientInfo {
private int m_version;
private SubjectIdentifier m_recipientIdentifier;
private AlgorithmIdentifier m_encryptionAlgorithm;
private byte[] m_encryptedKey;
[SecurityCritical]
internal unsafe KeyTransRecipientInfo (SafeLocalAllocHandle pRecipientInfo, CAPI.CERT_INFO certInfo, uint index) : base(RecipientInfoType.KeyTransport, RecipientSubType.Pkcs7KeyTransport, pRecipientInfo, certInfo, index) {
// If serial number is 0, then it is the special SKI encoding.
int version = 2;
byte * pb = (byte *) certInfo.SerialNumber.pbData;
for (int i = 0; i < certInfo.SerialNumber.cbData; i++) {
if (*pb++ != (byte) 0) {
version = 0;
break;
}
}
Reset(version);
}
[SecurityCritical]
internal KeyTransRecipientInfo (SafeLocalAllocHandle pRecipientInfo, CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO keyTrans, uint index) : base(RecipientInfoType.KeyTransport, RecipientSubType.CmsKeyTransport, pRecipientInfo, keyTrans, index) {
Reset((int) keyTrans.dwVersion);
}
public override int Version {
get {
return m_version;
}
}
public override SubjectIdentifier RecipientIdentifier {
[SecuritySafeCritical]
get {
if (m_recipientIdentifier == null) {
if (this.SubType == RecipientSubType.CmsKeyTransport) {
CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO keyTrans = (CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO) CmsgRecipientInfo;
m_recipientIdentifier = new SubjectIdentifier(keyTrans.RecipientId);
}
else {
CAPI.CERT_INFO certInfo = (CAPI.CERT_INFO) CmsgRecipientInfo;
m_recipientIdentifier = new SubjectIdentifier(certInfo);
}
}
return m_recipientIdentifier;
}
}
public override AlgorithmIdentifier KeyEncryptionAlgorithm {
[SecuritySafeCritical]
get {
if (m_encryptionAlgorithm == null) {
if (this.SubType == RecipientSubType.CmsKeyTransport) {
CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO keyTrans = (CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO) CmsgRecipientInfo;
m_encryptionAlgorithm = new AlgorithmIdentifier(keyTrans.KeyEncryptionAlgorithm);
}
else {
CAPI.CERT_INFO certInfo = (CAPI.CERT_INFO) CmsgRecipientInfo;
m_encryptionAlgorithm = new AlgorithmIdentifier(certInfo.SignatureAlgorithm);
}
}
return m_encryptionAlgorithm;
}
}
public override byte[] EncryptedKey {
[SecuritySafeCritical]
get {
if (m_encryptedKey.Length == 0) {
// CAPI does not provide a way to retrieve encrypted key for PKCS 7 message.
if (this.SubType == RecipientSubType.CmsKeyTransport) {
CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO keyTrans = (CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO) CmsgRecipientInfo;
if (keyTrans.EncryptedKey.cbData > 0) {
m_encryptedKey = new byte[keyTrans.EncryptedKey.cbData];
Marshal.Copy(keyTrans.EncryptedKey.pbData, m_encryptedKey, 0, m_encryptedKey.Length);
}
}
}
return m_encryptedKey;
}
}
//
// Private methods.
//
private void Reset (int version) {
m_version = version;
m_recipientIdentifier = null;
m_encryptionAlgorithm = null;
m_encryptedKey = new byte[0];
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class KeyAgreeRecipientInfo : RecipientInfo {
private CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO m_encryptedKeyInfo;
private uint m_originatorChoice;
private int m_version;
private SubjectIdentifierOrKey m_originatorIdentifier;
private byte[] m_userKeyMaterial;
private AlgorithmIdentifier m_encryptionAlgorithm;
private SubjectIdentifier m_recipientIdentifier;
private byte[] m_encryptedKey;
private DateTime m_date;
private CryptographicAttributeObject m_otherKeyAttribute;
private uint m_subIndex;
private KeyAgreeRecipientInfo () {}
[SecurityCritical]
internal KeyAgreeRecipientInfo (SafeLocalAllocHandle pRecipientInfo, CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO certIdRecipient, uint index, uint subIndex) : base(RecipientInfoType.KeyAgreement, RecipientSubType.CertIdKeyAgreement, pRecipientInfo, certIdRecipient, index) {
checked {
IntPtr pEncryptedKeyInfo = Marshal.ReadIntPtr(new IntPtr((long) certIdRecipient.rgpRecipientEncryptedKeys + (long) (subIndex * Marshal.SizeOf(typeof(IntPtr)))));
CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO encryptedKeyInfo = (CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO) Marshal.PtrToStructure(pEncryptedKeyInfo, typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO));
Reset(CAPI.CMSG_KEY_AGREE_ORIGINATOR_CERT, certIdRecipient.dwVersion, encryptedKeyInfo, subIndex);
}
}
[SecurityCritical]
internal KeyAgreeRecipientInfo (SafeLocalAllocHandle pRecipientInfo, CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO publicKeyRecipient, uint index, uint subIndex) : base(RecipientInfoType.KeyAgreement, RecipientSubType.PublicKeyAgreement, pRecipientInfo, publicKeyRecipient, index) {
checked {
IntPtr pEncryptedKeyInfo = Marshal.ReadIntPtr(new IntPtr((long) publicKeyRecipient.rgpRecipientEncryptedKeys + (long) (subIndex * Marshal.SizeOf(typeof(IntPtr)))));
CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO encryptedKeyInfo = (CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO) Marshal.PtrToStructure(pEncryptedKeyInfo, typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO));
Reset(CAPI.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY, publicKeyRecipient.dwVersion, encryptedKeyInfo, subIndex);
}
}
public override int Version {
get {
return m_version;
}
}
public SubjectIdentifierOrKey OriginatorIdentifierOrKey {
[SecuritySafeCritical]
get {
if (m_originatorIdentifier == null) {
if (m_originatorChoice == CAPI.CMSG_KEY_AGREE_ORIGINATOR_CERT) {
CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO recipientInfo = (CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO) CmsgRecipientInfo;
m_originatorIdentifier = new SubjectIdentifierOrKey(recipientInfo.OriginatorCertId);
}
else {
CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO recipientInfo = (CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO) CmsgRecipientInfo;
m_originatorIdentifier = new SubjectIdentifierOrKey(recipientInfo.OriginatorPublicKeyInfo);
}
}
return m_originatorIdentifier;
}
}
public override SubjectIdentifier RecipientIdentifier {
[SecuritySafeCritical]
get {
if (m_recipientIdentifier == null)
m_recipientIdentifier = new SubjectIdentifier(m_encryptedKeyInfo.RecipientId);
return m_recipientIdentifier;
}
}
public DateTime Date {
get {
if (m_date == DateTime.MinValue) {
if (this.RecipientIdentifier.Type != SubjectIdentifierType.SubjectKeyIdentifier)
throw new InvalidOperationException(SecurityResources.GetResourceString("Cryptography_Cms_Key_Agree_Date_Not_Available"));
long date = (((long)(uint) m_encryptedKeyInfo.Date.dwHighDateTime) << 32) | ((long)(uint) m_encryptedKeyInfo.Date.dwLowDateTime);
m_date = DateTime.FromFileTimeUtc(date);
}
return m_date;
}
}
public CryptographicAttributeObject OtherKeyAttribute {
[SecuritySafeCritical]
get {
if (m_otherKeyAttribute == null) {
if (this.RecipientIdentifier.Type != SubjectIdentifierType.SubjectKeyIdentifier)
throw new InvalidOperationException(SecurityResources.GetResourceString("Cryptography_Cms_Key_Agree_Other_Key_Attribute_Not_Available"));
if (m_encryptedKeyInfo.pOtherAttr != IntPtr.Zero) {
CAPI.CRYPT_ATTRIBUTE_TYPE_VALUE otherKeyAttribute = (CAPI.CRYPT_ATTRIBUTE_TYPE_VALUE) Marshal.PtrToStructure(m_encryptedKeyInfo.pOtherAttr, typeof(CAPI.CRYPT_ATTRIBUTE_TYPE_VALUE));
m_otherKeyAttribute = new CryptographicAttributeObject(otherKeyAttribute);
}
}
return m_otherKeyAttribute;
}
}
public override AlgorithmIdentifier KeyEncryptionAlgorithm {
[SecuritySafeCritical]
get {
if (m_encryptionAlgorithm == null) {
if (m_originatorChoice == CAPI.CMSG_KEY_AGREE_ORIGINATOR_CERT) {
CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO recipientInfo = (CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO) CmsgRecipientInfo;
m_encryptionAlgorithm = new AlgorithmIdentifier(recipientInfo.KeyEncryptionAlgorithm);
}
else {
CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO recipientInfo = (CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO) CmsgRecipientInfo;
m_encryptionAlgorithm = new AlgorithmIdentifier(recipientInfo.KeyEncryptionAlgorithm);
}
}
return m_encryptionAlgorithm;
}
}
public override byte[] EncryptedKey {
[SecuritySafeCritical]
get {
if (m_encryptedKey.Length == 0) {
if (m_encryptedKeyInfo.EncryptedKey.cbData > 0) {
m_encryptedKey = new byte[m_encryptedKeyInfo.EncryptedKey.cbData];
Marshal.Copy(m_encryptedKeyInfo.EncryptedKey.pbData, m_encryptedKey, 0, m_encryptedKey.Length);
}
}
return m_encryptedKey;
}
}
//
// Internal methods.
//
internal CAPI.CERT_ID RecipientId {
get {
return m_encryptedKeyInfo.RecipientId;
}
}
internal uint SubIndex {
get {
return m_subIndex;
}
}
//
// Private methods.
//
private void Reset (uint originatorChoice, uint version, CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO encryptedKeyInfo, uint subIndex) {
m_encryptedKeyInfo = encryptedKeyInfo;
m_originatorChoice = originatorChoice;
m_version = (int) version;
m_originatorIdentifier = null;
m_userKeyMaterial = new byte[0];
m_encryptionAlgorithm = null;
m_recipientIdentifier = null;
m_encryptedKey = new byte[0];
m_date = DateTime.MinValue;
m_otherKeyAttribute = null;
m_subIndex = subIndex;
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class RecipientInfoCollection : ICollection {
[SecurityCritical]
private SafeCryptMsgHandle m_safeCryptMsgHandle;
private ArrayList m_recipientInfos;
[SecuritySafeCritical]
internal RecipientInfoCollection () {
m_safeCryptMsgHandle = SafeCryptMsgHandle.InvalidHandle;
m_recipientInfos = new ArrayList();
}
[SecuritySafeCritical]
internal RecipientInfoCollection (RecipientInfo recipientInfo) {
m_safeCryptMsgHandle = SafeCryptMsgHandle.InvalidHandle;
m_recipientInfos = new ArrayList(1);
m_recipientInfos.Add(recipientInfo);
}
[SecurityCritical]
internal unsafe RecipientInfoCollection (SafeCryptMsgHandle safeCryptMsgHandle) {
bool cmsSupported = PkcsUtils.CmsSupported();
uint dwRecipients = 0;
uint cbCount = (uint) Marshal.SizeOf(typeof(uint));
// Use CMS if supported.
if (cmsSupported) {
// CMS.
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
CAPI.CMSG_CMS_RECIPIENT_COUNT_PARAM,
0,
new IntPtr(&dwRecipients),
new IntPtr(&cbCount)))
throw new CryptographicException(Marshal.GetLastWin32Error());
}
else {
// PKCS7.
if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
CAPI.CMSG_RECIPIENT_COUNT_PARAM,
0,
new IntPtr(&dwRecipients),
new IntPtr(&cbCount)))
throw new CryptographicException(Marshal.GetLastWin32Error());
}
m_recipientInfos = new ArrayList();
for (uint index = 0; index < dwRecipients; index++) {
if (cmsSupported) {
uint cbCmsRecipientInfo;
SafeLocalAllocHandle pbCmsRecipientInfo;
PkcsUtils.GetParam(safeCryptMsgHandle, CAPI.CMSG_CMS_RECIPIENT_INFO_PARAM, index, out pbCmsRecipientInfo, out cbCmsRecipientInfo);
CAPI.CMSG_CMS_RECIPIENT_INFO cmsRecipientInfo = (CAPI.CMSG_CMS_RECIPIENT_INFO) Marshal.PtrToStructure(pbCmsRecipientInfo.DangerousGetHandle(), typeof(CAPI.CMSG_CMS_RECIPIENT_INFO));
switch (cmsRecipientInfo.dwRecipientChoice) {
case CAPI.CMSG_KEY_TRANS_RECIPIENT:
CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO keyTrans = (CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO) Marshal.PtrToStructure(cmsRecipientInfo.pRecipientInfo, typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO));
m_recipientInfos.Add(new KeyTransRecipientInfo(pbCmsRecipientInfo, keyTrans, index));
break;
case CAPI.CMSG_KEY_AGREE_RECIPIENT:
CAPI.CMSG_KEY_AGREE_RECIPIENT_INFO keyAgree = (CAPI.CMSG_KEY_AGREE_RECIPIENT_INFO) Marshal.PtrToStructure(cmsRecipientInfo.pRecipientInfo, typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_INFO));
switch (keyAgree.dwOriginatorChoice) {
case CAPI.CMSG_KEY_AGREE_ORIGINATOR_CERT:
CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO certIdRecipient = (CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO) Marshal.PtrToStructure(cmsRecipientInfo.pRecipientInfo, typeof(CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO));
for (uint cRecipient = 0; cRecipient < certIdRecipient.cRecipientEncryptedKeys; cRecipient++) {
m_recipientInfos.Add(new KeyAgreeRecipientInfo(pbCmsRecipientInfo, certIdRecipient, index, cRecipient));
}
break;
case CAPI.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY:
CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO publicKeyRecipient = (CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO) Marshal.PtrToStructure(cmsRecipientInfo.pRecipientInfo, typeof(CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO));
for (uint cRecipient = 0; cRecipient < publicKeyRecipient.cRecipientEncryptedKeys; cRecipient++) {
m_recipientInfos.Add(new KeyAgreeRecipientInfo(pbCmsRecipientInfo, publicKeyRecipient, index, cRecipient));
}
break;
default:
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Invalid_Originator_Identifier_Choice"), keyAgree.dwOriginatorChoice.ToString(CultureInfo.CurrentCulture));
}
break;
default:
throw new CryptographicException(CAPI.E_NOTIMPL);
}
}
else {
uint cbCertInfo;
SafeLocalAllocHandle pbCertInfo;
PkcsUtils.GetParam(safeCryptMsgHandle, CAPI.CMSG_RECIPIENT_INFO_PARAM, index, out pbCertInfo, out cbCertInfo);
CAPI.CERT_INFO certInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pbCertInfo.DangerousGetHandle(), typeof(CAPI.CERT_INFO));
m_recipientInfos.Add(new KeyTransRecipientInfo(pbCertInfo, certInfo, index));
}
}
m_safeCryptMsgHandle = safeCryptMsgHandle;
}
public RecipientInfo this[int index] {
get {
if (index < 0 || index >= m_recipientInfos.Count)
throw new ArgumentOutOfRangeException("index", SecurityResources.GetResourceString("ArgumentOutOfRange_Index"));
return (RecipientInfo) m_recipientInfos[index];
}
}
public int Count {
get {
return m_recipientInfos.Count;
}
}
public RecipientInfoEnumerator GetEnumerator() {
return new RecipientInfoEnumerator(this);
}
/// <internalonly/>
IEnumerator IEnumerable.GetEnumerator() {
return new RecipientInfoEnumerator(this);
}
public void CopyTo(Array array, int index) {
if (array == null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException(SecurityResources.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0 || index >= array.Length)
throw new ArgumentOutOfRangeException("index", SecurityResources.GetResourceString("ArgumentOutOfRange_Index"));
if (index + this.Count > array.Length)
throw new ArgumentException(SecurityResources.GetResourceString("Argument_InvalidOffLen"));
for (int i=0; i < this.Count; i++) {
array.SetValue(this[i], index);
index++;
}
}
public void CopyTo(RecipientInfo[] array, int index) {
((ICollection)this).CopyTo(array, index);
}
public bool IsSynchronized {
get {
return false;
}
}
public Object SyncRoot {
get {
return this;
}
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class RecipientInfoEnumerator : IEnumerator {
private RecipientInfoCollection m_recipientInfos;
private int m_current;
private RecipientInfoEnumerator() {}
internal RecipientInfoEnumerator(RecipientInfoCollection RecipientInfos) {
m_recipientInfos = RecipientInfos;
m_current = -1;
}
public RecipientInfo Current {
get {
return m_recipientInfos[m_current];
}
}
/// <internalonly/>
Object IEnumerator.Current {
get {
return (Object) m_recipientInfos[m_current];
}
}
public bool MoveNext() {
if (m_current == ((int) m_recipientInfos.Count - 1)) {
return false;
}
m_current++;
return true;
}
public void Reset() {
m_current = -1;
}
}
}
| |
// 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.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_VarPatternDeclaration()
{
string source = @"
using System;
class X
{
void M()
{
int? x = 12;
switch (x)
{
/*<bind>*/case var y:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case var y:) (CaseKind.Pattern) (OperationKind.CaseClause) (Syntax: 'case var y:')
Pattern:
IDeclarationPattern (Declared Symbol: System.Int32? y) (OperationKind.DeclarationPattern) (Syntax: 'var y')
Guard Expression:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_PrimitiveTypePatternDeclaration()
{
string source = @"
using System;
class X
{
void M()
{
int? x = 12;
switch (x)
{
/*<bind>*/case int y:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case int y:) (CaseKind.Pattern) (OperationKind.CaseClause) (Syntax: 'case int y:')
Pattern:
IDeclarationPattern (Declared Symbol: System.Int32 y) (OperationKind.DeclarationPattern) (Syntax: 'int y')
Guard Expression:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_ReferenceTypePatternDeclaration()
{
string source = @"
using System;
class X
{
void M(object x)
{
switch (x)
{
/*<bind>*/case X y:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case X y:) (CaseKind.Pattern) (OperationKind.CaseClause) (Syntax: 'case X y:')
Pattern:
IDeclarationPattern (Declared Symbol: X y) (OperationKind.DeclarationPattern) (Syntax: 'X y')
Guard Expression:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_TypeParameterTypePatternDeclaration()
{
string source = @"
using System;
class X
{
void M<T>(object x) where T : class
{
switch (x)
{
/*<bind>*/case T y:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case T y:) (CaseKind.Pattern) (OperationKind.CaseClause) (Syntax: 'case T y:')
Pattern:
IDeclarationPattern (Declared Symbol: T y) (OperationKind.DeclarationPattern) (Syntax: 'T y')
Guard Expression:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_DynamicTypePatternDeclaration()
{
string source = @"
using System;
class X
{
void M<T>(object x) where T : class
{
switch (x)
{
/*<bind>*/case dynamic y:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case dynamic y:) (CaseKind.Pattern) (OperationKind.CaseClause, IsInvalid) (Syntax: 'case dynamic y:')
Pattern:
IDeclarationPattern (Declared Symbol: dynamic y) (OperationKind.DeclarationPattern, IsInvalid) (Syntax: 'dynamic y')
Guard Expression:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8208: It is not legal to use the type 'dynamic' in a pattern.
// /*<bind>*/case dynamic y:/*</bind>*/
Diagnostic(ErrorCode.ERR_PatternDynamicType, "dynamic").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_MixedDeclarationPatternAndConstantPatternClauses()
{
string source = @"
using System;
class X
{
void M(object x)
{
switch (x)
{
case null:
break;
/*<bind>*/case X y:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case X y:) (CaseKind.Pattern) (OperationKind.CaseClause) (Syntax: 'case X y:')
Pattern:
IDeclarationPattern (Declared Symbol: X y) (OperationKind.DeclarationPattern) (Syntax: 'X y')
Guard Expression:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_MixedDeclarationPatternAndConstantPatternClausesInSameSwitchSection()
{
string source = @"
using System;
class X
{
void M(object x)
{
switch (x)
{
case null:
/*<bind>*/case X y:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case X y:) (CaseKind.Pattern) (OperationKind.CaseClause) (Syntax: 'case X y:')
Pattern:
IDeclarationPattern (Declared Symbol: X y) (OperationKind.DeclarationPattern) (Syntax: 'X y')
Guard Expression:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_MixedDeclarationPatternAndConstantPatternWithDefaultLabel()
{
string source = @"
using System;
class X
{
void M(object x)
{
switch (x)
{
case null:
/*<bind>*/case X y:/*</bind>*/
default:
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case X y:) (CaseKind.Pattern) (OperationKind.CaseClause) (Syntax: 'case X y:')
Pattern:
IDeclarationPattern (Declared Symbol: X y) (OperationKind.DeclarationPattern) (Syntax: 'X y')
Guard Expression:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_GuardExpressionInPattern()
{
string source = @"
using System;
class X
{
void M(object x)
{
switch (x)
{
/*<bind>*/case X y when x != null:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case X y when x != null:) (CaseKind.Pattern) (OperationKind.CaseClause) (Syntax: 'case X y when x != null:')
Pattern:
IDeclarationPattern (Declared Symbol: X y) (OperationKind.DeclarationPattern) (Syntax: 'X y')
Guard Expression:
IBinaryOperatorExpression (BinaryOperatorKind.NotEquals) (OperationKind.BinaryOperatorExpression, Type: System.Boolean) (Syntax: 'x != null')
Left:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Object) (Syntax: 'x')
Right:
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralExpression (OperationKind.LiteralExpression, Type: null, Constant: null) (Syntax: 'null')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_PatternInGuardExpressionInPattern()
{
string source = @"
using System;
class X
{
void M(object x)
{
switch (x)
{
/*<bind>*/case X y when x is X z :/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case X y when x is X z :) (CaseKind.Pattern) (OperationKind.CaseClause) (Syntax: 'case X y when x is X z :')
Pattern:
IDeclarationPattern (Declared Symbol: X y) (OperationKind.DeclarationPattern) (Syntax: 'X y')
Guard Expression:
IIsPatternExpression (OperationKind.IsPatternExpression, Type: System.Boolean) (Syntax: 'x is X z')
Expression:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Object) (Syntax: 'x')
Pattern:
IDeclarationPattern (Declared Symbol: X z) (OperationKind.DeclarationPattern) (Syntax: 'X z')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_SyntaxErrorInGuardExpressionInPattern()
{
string source = @"
using System;
class X
{
void M(object x)
{
switch (x)
{
/*<bind>*/case X y when :/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case X y when :) (CaseKind.Pattern) (OperationKind.CaseClause, IsInvalid) (Syntax: 'case X y when :')
Pattern:
IDeclarationPattern (Declared Symbol: X y) (OperationKind.DeclarationPattern) (Syntax: 'X y')
Guard Expression:
IInvalidExpression (OperationKind.InvalidExpression, Type: null, IsInvalid) (Syntax: '')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term ':'
// /*<bind>*/case X y when :/*</bind>*/
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(9, 37)
};
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_SemanticErrorInGuardExpressionInPattern()
{
string source = @"
using System;
class X
{
void M(object x)
{
switch (x)
{
/*<bind>*/case X y when x:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case X y when x:) (CaseKind.Pattern) (OperationKind.CaseClause, IsInvalid) (Syntax: 'case X y when x:')
Pattern:
IDeclarationPattern (Declared Symbol: X y) (OperationKind.DeclarationPattern) (Syntax: 'X y')
Guard Expression:
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Object, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0266: Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?)
// /*<bind>*/case X y when x:/*</bind>*/
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "bool").WithLocation(9, 37)
};
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_ConstantPattern()
{
string source = @"
using System;
class X
{
void M(bool x)
{
switch (x)
{
case /*<bind>*/x is true/*</bind>*/:
break;
}
}
}
";
string expectedOperationTree = @"
IIsPatternExpression (OperationKind.IsPatternExpression, Type: System.Boolean, IsInvalid) (Syntax: 'x is true')
Expression:
IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.Boolean, IsInvalid) (Syntax: 'x')
Pattern:
IConstantPattern (OperationKind.ConstantPattern, IsInvalid) (Syntax: 'true')
Value:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Boolean, Constant: True, IsInvalid) (Syntax: 'true')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0150: A constant value is expected
// case /*<bind>*/x is true/*</bind>*/:
Diagnostic(ErrorCode.ERR_ConstantExpected, "x is true").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_DefaultLabel()
{
string source = @"
using System;
class X
{
void M(object x)
{
switch (x)
{
case X y:
/*<bind>*/default:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IDefaultCaseClause (CaseKind.Default) (OperationKind.CaseClause) (Syntax: 'default:')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<DefaultSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_InvalidTypeSwitch()
{
string source = @"
using System;
class X
{
void M(object x)
{
switch (x.GetType())
{
/*<bind>*/case typeof(X):/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case typeof(X):) (CaseKind.Pattern) (OperationKind.CaseClause, IsInvalid) (Syntax: 'case typeof(X):')
Pattern:
IConstantPattern (OperationKind.ConstantPattern, IsInvalid) (Syntax: 'case typeof(X):')
Value:
ITypeOfExpression (OperationKind.TypeOfExpression, Type: System.Type, IsInvalid) (Syntax: 'typeof(X)')
TypeOperand: X
Guard Expression:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0150: A constant value is expected
// /*<bind>*/case typeof(X):/*</bind>*/
Diagnostic(ErrorCode.ERR_ConstantExpected, "typeof(X)").WithLocation(9, 28),
// CS0162: Unreachable code detected
// break;
Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(10, 17)
};
VerifyOperationTreeAndDiagnosticsForTest<CaseSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_UndefinedTypeInPatternDeclaration()
{
string source = @"
using System;
class X
{
void M(object x)
{
switch (x)
{
/*<bind>*/case UndefinedType y:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case UndefinedType y:) (CaseKind.Pattern) (OperationKind.CaseClause, IsInvalid) (Syntax: 'case UndefinedType y:')
Pattern:
IDeclarationPattern (Declared Symbol: UndefinedType y) (OperationKind.DeclarationPattern, IsInvalid) (Syntax: 'UndefinedType y')
Guard Expression:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/case UndefinedType y:/*</bind>*/
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndefinedType").WithArguments("UndefinedType").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_InvalidTypeInPatternDeclaration()
{
string source = @"
using System;
class X
{
void M(int? x)
{
switch (x)
{
/*<bind>*/case X y:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case X y:) (CaseKind.Pattern) (OperationKind.CaseClause, IsInvalid) (Syntax: 'case X y:')
Pattern:
IDeclarationPattern (Declared Symbol: X y) (OperationKind.DeclarationPattern, IsInvalid) (Syntax: 'X y')
Guard Expression:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(9,28): error CS8121: An expression of type 'int?' cannot be handled by a pattern of type 'X'.
// /*<bind>*/case X y:/*</bind>*/
Diagnostic(ErrorCode.ERR_PatternWrongType, "X").WithArguments("int?", "X").WithLocation(9, 28),
// file.cs(10,17): warning CS0162: Unreachable code detected
// break;
Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(10, 17)
};
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_DuplicateLocalInPatternDeclaration()
{
string source = @"
using System;
class X
{
void M(int? x)
{
int? y = 0;
switch (x)
{
/*<bind>*/case int y:/*</bind>*/
break;
}
}
}
";
string expectedOperationTree = @"
IPatternCaseClause (Label Symbol: case int y:) (CaseKind.Pattern) (OperationKind.CaseClause, IsInvalid) (Syntax: 'case int y:')
Pattern:
IDeclarationPattern (Declared Symbol: System.Int32 y) (OperationKind.DeclarationPattern, IsInvalid) (Syntax: 'int y')
Guard Expression:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// /*<bind>*/case int y:/*</bind>*/
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(10, 32),
// CS0219: The variable 'y' is assigned but its value is never used
// int? y = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(7, 14)
};
VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_InvalidConstDeclarationInPatternDeclaration()
{
string source = @"
using System;
class X
{
void M(int? x)
{
switch (x)
{
/*<bind>*/case /*</bind>*/const int y:
break;
}
}
}
";
string expectedOperationTree = @"
ISingleValueCaseClause (CaseKind.SingleValue) (OperationKind.CaseClause, IsInvalid) (Syntax: 'case /*</bind>*/')
Value:
IInvalidExpression (OperationKind.InvalidExpression, Type: null, IsInvalid) (Syntax: '')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term 'const'
// /*<bind>*/case /*</bind>*/const int y:
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "const").WithArguments("const").WithLocation(9, 39),
// CS1003: Syntax error, ':' expected
// /*<bind>*/case /*</bind>*/const int y:
Diagnostic(ErrorCode.ERR_SyntaxError, "const").WithArguments(":", "const").WithLocation(9, 39),
// CS0145: A const field requires a value to be provided
// /*<bind>*/case /*</bind>*/const int y:
Diagnostic(ErrorCode.ERR_ConstValueRequired, "y").WithLocation(9, 49),
// CS1002: ; expected
// /*<bind>*/case /*</bind>*/const int y:
Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(9, 50),
// CS1513: } expected
// /*<bind>*/case /*</bind>*/const int y:
Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(9, 50),
// CS0168: The variable 'y' is declared but never used
// /*<bind>*/case /*</bind>*/const int y:
Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(9, 49)
};
VerifyOperationTreeAndDiagnosticsForTest<CaseSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")]
public void TestPatternCaseClause_RedundantPatternDeclarationClauses()
{
string source = @"
using System;
class X
{
void M(object p)
{
/*<bind>*/switch (p)
{
case int x:
break;
case int y:
break;
case X z:
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchStatement (3 cases) (OperationKind.SwitchStatement, IsInvalid) (Syntax: 'switch (p) ... }')
Switch expression:
IParameterReferenceExpression: p (OperationKind.ParameterReferenceExpression, Type: System.Object) (Syntax: 'p')
Sections:
ISwitchCase (1 case clauses, 1 statements) (OperationKind.SwitchCase) (Syntax: 'case int x: ... break;')
Clauses:
IPatternCaseClause (Label Symbol: case int x:) (CaseKind.Pattern) (OperationKind.CaseClause) (Syntax: 'case int x:')
Pattern:
IDeclarationPattern (Declared Symbol: System.Int32 x) (OperationKind.DeclarationPattern) (Syntax: 'int x')
Guard Expression:
null
Body:
IBranchStatement (BranchKind.Break) (OperationKind.BranchStatement) (Syntax: 'break;')
ISwitchCase (1 case clauses, 1 statements) (OperationKind.SwitchCase, IsInvalid) (Syntax: 'case int y: ... break;')
Clauses:
IPatternCaseClause (Label Symbol: case int y:) (CaseKind.Pattern) (OperationKind.CaseClause, IsInvalid) (Syntax: 'case int y:')
Pattern:
IDeclarationPattern (Declared Symbol: System.Int32 y) (OperationKind.DeclarationPattern, IsInvalid) (Syntax: 'int y')
Guard Expression:
null
Body:
IBranchStatement (BranchKind.Break) (OperationKind.BranchStatement) (Syntax: 'break;')
ISwitchCase (1 case clauses, 1 statements) (OperationKind.SwitchCase) (Syntax: 'case X z: ... break;')
Clauses:
IPatternCaseClause (Label Symbol: case X z:) (CaseKind.Pattern) (OperationKind.CaseClause) (Syntax: 'case X z:')
Pattern:
IDeclarationPattern (Declared Symbol: X z) (OperationKind.DeclarationPattern) (Syntax: 'X z')
Guard Expression:
null
Body:
IBranchStatement (BranchKind.Break) (OperationKind.BranchStatement) (Syntax: 'break;')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8120: The switch case has already been handled by a previous case.
// case int y:
Diagnostic(ErrorCode.ERR_PatternIsSubsumed, "int y").WithLocation(11, 18),
// CS0162: Unreachable code detected
// break;
Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(12, 17)
};
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using AutoRest.Core.ClientModel;
using AutoRest.Core.Logging;
using AutoRest.Core.Utilities;
using AutoRest.Swagger.Model;
using AutoRest.Swagger.Properties;
using ParameterLocation = AutoRest.Swagger.Model.ParameterLocation;
namespace AutoRest.Swagger
{
/// <summary>
/// The builder for building swagger operations into client model methods.
/// </summary>
public class OperationBuilder
{
private IList<string> _effectiveProduces;
private IList<string> _effectiveConsumes;
private SwaggerModeler _swaggerModeler;
private Operation _operation;
private const string APP_JSON_MIME = "application/json";
public OperationBuilder(Operation operation, SwaggerModeler swaggerModeler)
{
if (operation == null)
{
throw new ArgumentNullException("operation");
}
if (swaggerModeler == null)
{
throw new ArgumentNullException("swaggerModeler");
}
this._operation = operation;
this._swaggerModeler = swaggerModeler;
this._effectiveProduces = operation.Produces.Any() ? operation.Produces : swaggerModeler.ServiceDefinition.Produces;
this._effectiveConsumes = operation.Consumes.Any() ? operation.Consumes : swaggerModeler.ServiceDefinition.Consumes;
}
public Method BuildMethod(HttpMethod httpMethod, string url, string methodName, string methodGroup)
{
EnsureUniqueMethodName(methodName, methodGroup);
var method = new Method
{
HttpMethod = httpMethod,
Url = url,
Name = methodName,
SerializedName = _operation.OperationId
};
method.RequestContentType = _effectiveConsumes.FirstOrDefault() ?? APP_JSON_MIME;
string produce = _effectiveConsumes.FirstOrDefault(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(produce))
{
method.RequestContentType = produce;
}
if (method.RequestContentType.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase) &&
method.RequestContentType.IndexOf("charset=", StringComparison.OrdinalIgnoreCase) == -1)
{
// Enable UTF-8 charset
method.RequestContentType += "; charset=utf-8";
}
method.Description = _operation.Description;
method.Summary = _operation.Summary;
method.ExternalDocsUrl = _operation.ExternalDocs?.Url;
method.Deprecated = _operation.Deprecated;
// Service parameters
if (_operation.Parameters != null)
{
BuildMethodParameters(method);
}
// Build header object
var responseHeaders = new Dictionary<string, Header>();
foreach (var response in _operation.Responses.Values)
{
if (response.Headers != null)
{
response.Headers.ForEach(h => responseHeaders[h.Key] = h.Value);
}
}
var headerTypeName = string.Format(CultureInfo.InvariantCulture,
"{0}-{1}-Headers", methodGroup, methodName).Trim('-');
var headerType = new CompositeType
{
Name = headerTypeName,
SerializedName = headerTypeName,
Documentation = string.Format(CultureInfo.InvariantCulture, "Defines headers for {0} operation.", methodName)
};
responseHeaders.ForEach(h =>
{
var property = new Property
{
Name = h.Key,
SerializedName = h.Key,
Type = h.Value.GetBuilder(this._swaggerModeler).BuildServiceType(h.Key),
Documentation = h.Value.Description
};
headerType.Properties.Add(property);
});
if (!headerType.Properties.Any())
{
headerType = null;
}
// Response format
List<Stack<IType>> typesList = BuildResponses(method, headerType);
method.ReturnType = BuildMethodReturnType(typesList, headerType);
if (method.Responses.Count == 0)
{
method.ReturnType = method.DefaultResponse;
}
if (method.ReturnType.Headers != null)
{
_swaggerModeler.ServiceClient.HeaderTypes.Add(method.ReturnType.Headers as CompositeType);
}
// Copy extensions
_operation.Extensions.ForEach(extention => method.Extensions.Add(extention.Key, extention.Value));
return method;
}
private static IEnumerable<SwaggerParameter> DeduplicateParameters(IEnumerable<SwaggerParameter> parameters)
{
return parameters
.Select(s =>
{
// if parameter with the same name exists in Body and Path/Query then we need to give it a unique name
if (s.In == ParameterLocation.Body)
{
string newName = s.Name;
while (parameters.Any(t => t.In != ParameterLocation.Body &&
string.Equals(t.Name, newName,
StringComparison.OrdinalIgnoreCase)))
{
newName += "Body";
}
s.Name = newName;
}
// if parameter with same name exists in Query and Path, make Query one required
if (s.In == ParameterLocation.Query &&
parameters.Any(t => t.In == ParameterLocation.Path &&
string.Equals(t.Name, s.Name, StringComparison.OrdinalIgnoreCase)))
{
s.IsRequired = true;
}
return s;
});
}
private static void BuildMethodReturnTypeStack(IType type, List<Stack<IType>> types)
{
var typeStack = new Stack<IType>();
typeStack.Push(type);
types.Add(typeStack);
}
private void BuildMethodParameters(Method method)
{
foreach (var swaggerParameter in DeduplicateParameters(_operation.Parameters))
{
var parameter = ((ParameterBuilder)swaggerParameter.GetBuilder(_swaggerModeler)).Build();
method.Parameters.Add(parameter);
StringBuilder parameterName = new StringBuilder(parameter.Name);
parameterName = CollectionFormatBuilder.OnBuildMethodParameter(method, swaggerParameter,
parameterName);
if (swaggerParameter.In == ParameterLocation.Header)
{
method.RequestHeaders[swaggerParameter.Name] =
string.Format(CultureInfo.InvariantCulture, "{{{0}}}", parameterName);
}
}
}
private List<Stack<IType>> BuildResponses(Method method, CompositeType headerType)
{
string methodName = method.Name;
var typesList = new List<Stack<IType>>();
foreach (var response in _operation.Responses)
{
if (string.Equals(response.Key, "default", StringComparison.OrdinalIgnoreCase))
{
TryBuildDefaultResponse(methodName, response.Value, method, headerType);
}
else
{
if (
!(TryBuildResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method,
typesList, headerType) ||
TryBuildStreamResponse(response.Key.ToHttpStatusCode(), response.Value, method, typesList, headerType) ||
TryBuildEmptyResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method,
typesList, headerType)))
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture,
Resources.UnsupportedMimeTypeForResponseBody,
methodName,
response.Key));
}
}
}
return typesList;
}
private Response BuildMethodReturnType(List<Stack<IType>> types, IType headerType)
{
IType baseType = new PrimaryType(KnownPrimaryType.Object);
// Return null if no response is specified
if (types.Count == 0)
{
return new Response(null, headerType);
}
// Return first if only one return type
if (types.Count == 1)
{
return new Response(types.First().Pop(), headerType);
}
// BuildParameter up type inheritance tree
types.ForEach(typeStack =>
{
IType type = typeStack.Peek();
while (!Equals(type, baseType))
{
if (type is CompositeType && _swaggerModeler.ExtendedTypes.ContainsKey(type.Name))
{
type = _swaggerModeler.GeneratedTypes[_swaggerModeler.ExtendedTypes[type.Name]];
}
else
{
type = baseType;
}
typeStack.Push(type);
}
});
// Eliminate commonly shared base classes
while (!types.First().IsNullOrEmpty())
{
IType currentType = types.First().Peek();
foreach (var typeStack in types)
{
IType t = typeStack.Pop();
if (!Equals(t, currentType))
{
return new Response(baseType, headerType);
}
}
baseType = currentType;
}
return new Response(baseType, headerType);
}
private bool TryBuildStreamResponse(HttpStatusCode responseStatusCode, OperationResponse response,
Method method, List<Stack<IType>> types, IType headerType)
{
bool handled = false;
if (SwaggerOperationProducesNotEmpty())
{
if (response.Schema != null)
{
IType serviceType = response.Schema.GetBuilder(_swaggerModeler)
.BuildServiceType(response.Schema.Reference.StripDefinitionPath());
Debug.Assert(serviceType != null);
BuildMethodReturnTypeStack(serviceType, types);
var compositeType = serviceType as CompositeType;
if (compositeType != null)
{
VerifyFirstPropertyIsByteArray(compositeType);
}
method.Responses[responseStatusCode] = new Response(serviceType, headerType);
handled = true;
}
}
return handled;
}
private void VerifyFirstPropertyIsByteArray(CompositeType serviceType)
{
var referenceKey = serviceType.Name;
var responseType = _swaggerModeler.GeneratedTypes[referenceKey];
var property = responseType.Properties.FirstOrDefault(p => p.Type is PrimaryType && ((PrimaryType)p.Type).Type == KnownPrimaryType.ByteArray);
if (property == null)
{
throw new KeyNotFoundException(
"Please specify a field with type of System.Byte[] to deserialize the file contents to");
}
}
private bool TryBuildResponse(string methodName, HttpStatusCode responseStatusCode,
OperationResponse response, Method method, List<Stack<IType>> types, IType headerType)
{
bool handled = false;
IType serviceType;
if (SwaggerOperationProducesJson())
{
if (TryBuildResponseBody(methodName, response,
s => GenerateResponseObjectName(s, responseStatusCode), out serviceType))
{
method.Responses[responseStatusCode] = new Response(serviceType, headerType);
BuildMethodReturnTypeStack(serviceType, types);
handled = true;
}
}
return handled;
}
private bool TryBuildEmptyResponse(string methodName, HttpStatusCode responseStatusCode,
OperationResponse response, Method method, List<Stack<IType>> types, IType headerType)
{
bool handled = false;
if (response.Schema == null)
{
method.Responses[responseStatusCode] = new Response(null, headerType);
handled = true;
}
else
{
if (_operation.Produces.IsNullOrEmpty())
{
method.Responses[responseStatusCode] = new Response(new PrimaryType(KnownPrimaryType.Object), headerType);
BuildMethodReturnTypeStack(new PrimaryType(KnownPrimaryType.Object), types);
handled = true;
}
var unwrapedSchemaProperties =
_swaggerModeler.Resolver.Unwrap(response.Schema).Properties;
if (unwrapedSchemaProperties != null && unwrapedSchemaProperties.Any())
{
Logger.LogWarning(Resources.NoProduceOperationWithBody,
methodName);
}
}
return handled;
}
private void TryBuildDefaultResponse(string methodName, OperationResponse response, Method method, IType headerType)
{
IType errorModel = null;
if (SwaggerOperationProducesJson())
{
if (TryBuildResponseBody(methodName, response, s => GenerateErrorModelName(s), out errorModel))
{
method.DefaultResponse = new Response(errorModel, headerType);
}
}
}
private bool TryBuildResponseBody(string methodName, OperationResponse response,
Func<string, string> typeNamer, out IType responseType)
{
bool handled = false;
responseType = null;
if (SwaggerOperationProducesJson())
{
if (response.Schema != null)
{
string referenceKey;
if (response.Schema.Reference != null)
{
referenceKey = response.Schema.Reference.StripDefinitionPath();
response.Schema.Reference = referenceKey;
}
else
{
referenceKey = typeNamer(methodName);
}
responseType = response.Schema.GetBuilder(_swaggerModeler).BuildServiceType(referenceKey);
handled = true;
}
}
return handled;
}
private bool SwaggerOperationProducesJson()
{
return _effectiveProduces != null &&
_effectiveProduces.Any(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase));
}
private bool SwaggerOperationProducesNotEmpty()
{
return _effectiveProduces != null
&& _effectiveProduces.Any();
}
private void EnsureUniqueMethodName(string methodName, string methodGroup)
{
string serviceOperationPrefix = "";
if (methodGroup != null)
{
serviceOperationPrefix = methodGroup + "_";
}
if (_swaggerModeler.ServiceClient.Methods.Any(m => m.Group == methodGroup && m.Name == methodName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
Resources.DuplicateOperationIdException,
serviceOperationPrefix + methodName));
}
}
private static string GenerateResponseObjectName(string methodName, HttpStatusCode responseStatusCode)
{
return string.Format(CultureInfo.InvariantCulture,
"{0}{1}Response", methodName, responseStatusCode);
}
private static string GenerateErrorModelName(string methodName)
{
return string.Format(CultureInfo.InvariantCulture,
"{0}ErrorModel", methodName);
}
}
}
| |
//
// ControlOverlay.cs
//
// Author:
// Stephane Delcroix <stephane@delcroix.org>
// Larry Ewing <lewing@src.gnome.org>
//
// Copyright (C) 2007-2009 Novell, Inc.
// Copyright (C) 2008-2009 Stephane Delcroix
// Copyright (C) 2007 Larry Ewing
//
// 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 Cairo;
using System;
using Gtk;
using FSpot.Widgets;
using FSpot.Utils;
using FSpot.Core;
using FSpot.Gui;
namespace FSpot {
public class ControlOverlay : Window {
Widget host;
Window host_toplevel;
bool composited;
VisibilityType visibility;
int round = 12;
DelayedOperation hide;
DelayedOperation fade;
DelayedOperation dismiss;
bool auto_hide = true;
double x_align = 0.5;
double y_align = 1.0;
public enum VisibilityType
{
None,
Partial,
Full
}
public double XAlign {
get { return x_align; }
set {
x_align = value;
Relocate ();
}
}
public double YAlign {
get { return y_align; }
set {
y_align = value;
Relocate ();
}
}
public bool AutoHide {
get { return auto_hide; }
set { auto_hide = value; }
}
public VisibilityType Visibility {
get { return visibility; }
set {
if (dismiss.IsPending && value != VisibilityType.None)
return;
switch (value) {
case VisibilityType.None:
FadeToTarget (0.0);
break;
case VisibilityType.Partial:
FadeToTarget (0.4);
break;
case VisibilityType.Full:
FadeToTarget (0.8);
break;
}
visibility = value;
}
}
public ControlOverlay (Gtk.Widget host) : base (WindowType.Popup)
{
this.host = host;
Decorated = false;
DestroyWithParent = true;
Name = "FullscreenContainer";
AllowGrow = true;
//AllowShrink = true;
KeepAbove = true;
host_toplevel = (Gtk.Window) host.Toplevel;
TransientFor = host_toplevel;
host_toplevel.ConfigureEvent += HandleHostConfigure;
host_toplevel.SizeAllocated += HandleHostSizeAllocated;
AddEvents ((int) (Gdk.EventMask.PointerMotionMask));
hide = new DelayedOperation (2000, HideControls);
fade = new DelayedOperation (40, FadeToTarget);
dismiss = new DelayedOperation (2000, delegate { /* do nothing */ return false; });
}
protected override void OnDestroyed ()
{
hide.Stop ();
fade.Stop ();
base.OnDestroyed ();
}
public bool HideControls ()
{
int x, y;
Gdk.ModifierType type;
if (!auto_hide)
return false;
if (IsRealized) {
GdkWindow.GetPointer (out x, out y, out type);
if (Allocation.Contains (x, y)) {
hide.Start ();
return true;
}
}
hide.Stop ();
Visibility = VisibilityType.None;
return false;
}
protected virtual void ShapeSurface (Context cr, Cairo.Color color)
{
cr.Operator = Operator.Source;
Cairo.Pattern p = new Cairo.SolidPattern (new Cairo.Color (0, 0, 0, 0));
cr.Source = p;
p.Destroy ();
cr.Paint ();
cr.Operator = Operator.Over;
Cairo.Pattern r = new SolidPattern (color);
cr.Source = r;
r.Destroy ();
cr.MoveTo (round, 0);
if (x_align == 1.0)
cr.LineTo (Allocation.Width, 0);
else
cr.Arc (Allocation.Width - round, round, round, - Math.PI * 0.5, 0);
if (x_align == 1.0 || y_align == 1.0)
cr.LineTo (Allocation.Width, Allocation.Height);
else
cr.Arc (Allocation.Width - round, Allocation.Height - round, round, 0, Math.PI * 0.5);
if (y_align == 1.0)
cr.LineTo (0, Allocation.Height);
else
cr.Arc (round, Allocation.Height - round, round, Math.PI * 0.5, Math.PI);
cr.Arc (round, round, round, Math.PI, Math.PI * 1.5);
cr.ClosePath ();
cr.Fill ();
}
double target;
double opacity = 0;
bool FadeToTarget ()
{
//Log.Debug ("op {0}\ttarget{1}", opacity, target);
Visible = (opacity > 0.05);
if (Math.Abs (target - opacity) < .05)
return false;
if (target > opacity)
opacity += .04;
else
opacity -= .04;
if (Visible)
CompositeUtils.SetWinOpacity (this, opacity);
else
Hide ();
return true;
}
bool FadeToTarget (double target)
{
//Log.Debug ("FadeToTarget {0}", target);
Realize ();
this.target = target;
fade.Start ();
if (target > 0.0)
hide.Restart ();
return false;
}
private void ShapeWindow ()
{
if (composited)
return;
Gdk.Pixmap bitmap = new Gdk.Pixmap (GdkWindow,
Allocation.Width,
Allocation.Height, 1);
Context cr = Gdk.CairoHelper.Create (bitmap);
ShapeCombineMask (bitmap, 0, 0);
ShapeSurface (cr, new Color (1, 1, 1));
ShapeCombineMask (bitmap, 0, 0);
((IDisposable)cr).Dispose ();
bitmap.Dispose ();
}
protected override bool OnExposeEvent (Gdk.EventExpose args)
{
Gdk.Color c = Style.Background (State);
Context cr = Gdk.CairoHelper.Create (GdkWindow);
ShapeSurface (cr, new Cairo.Color (c.Red / (double) ushort.MaxValue,
c.Blue / (double) ushort.MaxValue,
c.Green / (double) ushort.MaxValue,
0.8));
((IDisposable)cr).Dispose ();
return base.OnExposeEvent (args);
}
protected override bool OnMotionNotifyEvent (Gdk.EventMotion args)
{
this.Visibility = VisibilityType.Full;
base.OnMotionNotifyEvent (args);
return false;
}
protected override void OnSizeAllocated (Gdk.Rectangle rec)
{
base.OnSizeAllocated (rec);
Relocate ();
ShapeWindow ();
QueueDraw ();
}
private void HandleHostSizeAllocated (object o, SizeAllocatedArgs args)
{
Relocate ();
}
private void HandleHostConfigure (object o, ConfigureEventArgs args)
{
Relocate ();
}
private void Relocate ()
{
int x, y;
if (!IsRealized || !host_toplevel.IsRealized)
return;
host.GdkWindow.GetOrigin (out x, out y);
int xOrigin = x;
int yOrigin = y;
x += (int) (host.Allocation.Width * x_align);
y += (int) (host.Allocation.Height * y_align);
x -= (int) (Allocation.Width * 0.5);
y -= (int) (Allocation.Height * 0.5);
x = Math.Max (0, Math.Min (x, xOrigin + host.Allocation.Width - Allocation.Width));
y = Math.Max (0, Math.Min (y, yOrigin + host.Allocation.Height - Allocation.Height));
Move (x, y);
}
protected override void OnRealized ()
{
composited = CompositeUtils.IsComposited (Screen) && CompositeUtils.SetRgbaColormap (this);
AppPaintable = composited;
base.OnRealized ();
ShapeWindow ();
Relocate ();
}
public void Dismiss ()
{
Visibility = VisibilityType.None;
dismiss.Start ();
}
protected override void OnMapped ()
{
base.OnMapped ();
Relocate ();
}
}
}
| |
#region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// 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;
namespace NodaTime.Fields
{
/// <summary>
/// An immutable collection of date/time and duration fields.
/// </summary>
[Serializable]
internal sealed class FieldSet
{
private readonly DurationField ticks;
private readonly DurationField milliseconds;
private readonly DurationField seconds;
private readonly DurationField minutes;
private readonly DurationField hours;
private readonly DurationField halfDays;
private readonly DurationField days;
private readonly DurationField weeks;
private readonly DurationField weekYears;
private readonly DurationField months;
private readonly DurationField years;
private readonly DurationField centuries;
private readonly DurationField eras;
private readonly DateTimeField tickOfSecond;
private readonly DateTimeField tickOfMillisecond;
private readonly DateTimeField tickOfDay;
private readonly DateTimeField millisecondOfSecond;
private readonly DateTimeField millisecondOfDay;
private readonly DateTimeField secondOfMinute;
private readonly DateTimeField secondOfDay;
private readonly DateTimeField minuteOfHour;
private readonly DateTimeField minuteOfDay;
private readonly DateTimeField hourOfDay;
private readonly DateTimeField clockHourOfDay;
private readonly DateTimeField hourOfHalfDay;
private readonly DateTimeField clockHourOfHalfDay;
private readonly DateTimeField halfDayOfDay;
private readonly DateTimeField dayOfWeek;
private readonly DateTimeField dayOfMonth;
private readonly DateTimeField dayOfYear;
private readonly DateTimeField weekOfWeekYear;
private readonly DateTimeField weekYear;
private readonly DateTimeField weekYearOfCentury;
private readonly DateTimeField monthOfYear;
private readonly DateTimeField year;
private readonly DateTimeField yearOfCentury;
private readonly DateTimeField yearOfEra;
private readonly DateTimeField centruryOfEra;
private readonly DateTimeField era;
internal DurationField Ticks { get { return ticks; } }
internal DurationField Milliseconds { get { return milliseconds; } }
internal DurationField Seconds { get { return seconds; } }
internal DurationField Minutes { get { return minutes; } }
internal DurationField Hours { get { return hours; } }
internal DurationField HalfDays { get { return halfDays; } }
internal DurationField Days { get { return days; } }
internal DurationField Weeks { get { return weeks; } }
internal DurationField WeekYears { get { return weekYears; } }
internal DurationField Months { get { return months; } }
internal DurationField Years { get { return years; } }
internal DurationField Centuries { get { return centuries; } }
internal DurationField Eras { get { return eras; } }
internal DateTimeField TickOfSecond { get { return tickOfSecond; } }
internal DateTimeField TickOfMillisecond { get { return tickOfMillisecond; } }
internal DateTimeField TickOfDay { get { return tickOfDay; } }
internal DateTimeField MillisecondOfSecond { get { return millisecondOfSecond; } }
internal DateTimeField MillisecondOfDay { get { return millisecondOfDay; } }
internal DateTimeField SecondOfMinute { get { return secondOfMinute; } }
internal DateTimeField SecondOfDay { get { return secondOfDay; } }
internal DateTimeField MinuteOfHour { get { return minuteOfHour; } }
internal DateTimeField MinuteOfDay { get { return minuteOfDay; } }
internal DateTimeField HourOfDay { get { return hourOfDay; } }
internal DateTimeField ClockHourOfDay { get { return clockHourOfDay; } }
internal DateTimeField HourOfHalfDay { get { return hourOfHalfDay; } }
internal DateTimeField ClockHourOfHalfDay { get { return clockHourOfHalfDay; } }
internal DateTimeField HalfDayOfDay { get { return halfDayOfDay; } }
internal DateTimeField DayOfWeek { get { return dayOfWeek; } }
internal DateTimeField DayOfMonth { get { return dayOfMonth; } }
internal DateTimeField DayOfYear { get { return dayOfYear; } }
internal DateTimeField WeekOfWeekYear { get { return weekOfWeekYear; } }
internal DateTimeField WeekYear { get { return weekYear; } }
internal DateTimeField WeekYearOfCentury { get { return weekYearOfCentury; } }
internal DateTimeField MonthOfYear { get { return monthOfYear; } }
internal DateTimeField Year { get { return year; } }
internal DateTimeField YearOfCentury { get { return yearOfCentury; } }
internal DateTimeField YearOfEra { get { return yearOfEra; } }
internal DateTimeField CenturyOfEra { get { return centruryOfEra; } }
internal DateTimeField Era { get { return era; } }
private FieldSet(Builder builder)
{
ticks = builder.Ticks ?? UnsupportedDurationField.Ticks;
milliseconds = builder.Milliseconds ?? UnsupportedDurationField.Milliseconds;
seconds = builder.Seconds ?? UnsupportedDurationField.Seconds;
minutes = builder.Minutes ?? UnsupportedDurationField.Minutes;
hours = builder.Hours ?? UnsupportedDurationField.Hours;
halfDays = builder.HalfDays ?? UnsupportedDurationField.HalfDays;
days = builder.Days ?? UnsupportedDurationField.Days;
weeks = builder.Weeks ?? UnsupportedDurationField.Weeks;
weekYears = builder.WeekYears ?? UnsupportedDurationField.WeekYears;
months = builder.Months ?? UnsupportedDurationField.Months;
years = builder.Years ?? UnsupportedDurationField.Years;
centuries = builder.Centuries ?? UnsupportedDurationField.Centuries;
eras = builder.Eras ?? UnsupportedDurationField.Eras;
tickOfSecond = builder.TickOfSecond ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.TickOfSecond, ticks);
tickOfMillisecond = builder.TickOfMillisecond ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.TickOfMillisecond, ticks);
tickOfDay = builder.TickOfDay ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.TickOfDay, ticks);
millisecondOfSecond = builder.MillisecondOfSecond ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.MillisecondOfSecond, milliseconds);
millisecondOfDay = builder.MillisecondOfDay ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.MillisecondOfDay, milliseconds);
secondOfMinute = builder.SecondOfMinute ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.SecondOfMinute, seconds);
secondOfDay = builder.SecondOfDay ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.SecondOfDay, seconds);
minuteOfHour = builder.MinuteOfHour ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.MinuteOfHour, minutes);
minuteOfDay = builder.MinuteOfDay ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.MinuteOfDay, minutes);
hourOfDay = builder.HourOfDay ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.HourOfDay, hours);
clockHourOfDay = builder.ClockHourOfDay ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.ClockHourOfDay, hours);
hourOfHalfDay = builder.HourOfHalfDay ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.HourOfHalfDay, hours);
clockHourOfHalfDay = builder.ClockHourOfHalfDay ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.ClockHourOfHalfDay, hours);
halfDayOfDay = builder.HalfDayOfDay ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.HalfDayOfDay, halfDays);
dayOfWeek = builder.DayOfWeek ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.DayOfWeek, days);
dayOfMonth = builder.DayOfMonth ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.DayOfMonth, days);
dayOfYear = builder.DayOfYear ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.DayOfYear, days);
weekOfWeekYear = builder.WeekOfWeekYear ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.WeekOfWeekYear, weeks);
weekYear = builder.WeekYear ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.WeekYear, years);
weekYearOfCentury = builder.WeekYearOfCentury ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.WeekYearOfCentury, weekYears);
monthOfYear = builder.MonthOfYear ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.MonthOfYear, months);
year = builder.Year ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.Year, years);
yearOfCentury = builder.YearOfCentury ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.YearOfCentury, years);
yearOfEra = builder.YearOfEra ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.YearOfEra, years);
centruryOfEra = builder.CenturyOfEra ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.CenturyOfEra, centuries);
era = builder.Era ?? UnsupportedDateTimeField.GetInstance(DateTimeFieldType.Era, eras);
}
/// <summary>
/// Convenience method to create a new field set with
/// the current field set as a "base" overridden with
/// supported fields from the given set.
/// </summary>
internal FieldSet WithSupportedFieldsFrom(FieldSet fields)
{
return new Builder(this).WithSupportedFieldsFrom(fields).Build();
}
// TODO: Consider making FieldSet privately mutable and mutate it directly in the builder.
// Pros: Less copying
// Cons: Builders aren't reusable, and FieldSet isn't as obviously thread-safe.
internal class Builder
{
internal DurationField Ticks { get; set; }
internal DurationField Milliseconds { get; set; }
internal DurationField Seconds { get; set; }
internal DurationField Minutes { get; set; }
internal DurationField Hours { get; set; }
internal DurationField HalfDays { get; set; }
internal DurationField Days { get; set; }
internal DurationField Weeks { get; set; }
internal DurationField WeekYears { get; set; }
internal DurationField Months { get; set; }
internal DurationField Years { get; set; }
internal DurationField Centuries { get; set; }
internal DurationField Eras { get; set; }
internal DateTimeField TickOfSecond { get; set; }
internal DateTimeField TickOfMillisecond { get; set; }
internal DateTimeField TickOfDay { get; set; }
internal DateTimeField MillisecondOfSecond { get; set; }
internal DateTimeField MillisecondOfDay { get; set; }
internal DateTimeField SecondOfMinute { get; set; }
internal DateTimeField SecondOfDay { get; set; }
internal DateTimeField MinuteOfHour { get; set; }
internal DateTimeField MinuteOfDay { get; set; }
internal DateTimeField HourOfDay { get; set; }
internal DateTimeField ClockHourOfDay { get; set; }
internal DateTimeField HourOfHalfDay { get; set; }
internal DateTimeField ClockHourOfHalfDay { get; set; }
internal DateTimeField HalfDayOfDay { get; set; }
internal DateTimeField DayOfWeek { get; set; }
internal DateTimeField DayOfMonth { get; set; }
internal DateTimeField DayOfYear { get; set; }
internal DateTimeField WeekOfWeekYear { get; set; }
internal DateTimeField WeekYear { get; set; }
internal DateTimeField WeekYearOfCentury { get; set; }
internal DateTimeField MonthOfYear { get; set; }
internal DateTimeField Year { get; set; }
internal DateTimeField YearOfCentury { get; set; }
internal DateTimeField YearOfEra { get; set; }
internal DateTimeField CenturyOfEra { get; set; }
internal DateTimeField Era { get; set; }
internal Builder()
{
}
internal Builder(FieldSet baseSet)
{
if (baseSet == null)
{
throw new ArgumentNullException("baseSet");
}
Ticks = baseSet.Ticks;
Milliseconds = baseSet.Milliseconds;
Seconds = baseSet.Seconds;
Minutes = baseSet.Minutes;
Hours = baseSet.Hours;
HalfDays = baseSet.HalfDays;
Days = baseSet.Days;
Weeks = baseSet.Weeks;
WeekYears = baseSet.WeekYears;
Months = baseSet.Months;
Years = baseSet.Years;
Centuries = baseSet.Centuries;
Eras = baseSet.Eras;
TickOfSecond = baseSet.TickOfSecond;
TickOfMillisecond = baseSet.TickOfMillisecond;
TickOfDay = baseSet.TickOfDay;
MillisecondOfSecond = baseSet.MillisecondOfSecond;
MillisecondOfDay = baseSet.MillisecondOfDay;
SecondOfMinute = baseSet.SecondOfMinute;
SecondOfDay = baseSet.SecondOfDay;
MinuteOfHour = baseSet.MinuteOfHour;
MinuteOfDay = baseSet.MinuteOfDay;
HourOfDay = baseSet.HourOfDay;
ClockHourOfDay = baseSet.ClockHourOfDay;
HourOfHalfDay = baseSet.HourOfHalfDay;
ClockHourOfHalfDay = baseSet.ClockHourOfHalfDay;
HalfDayOfDay = baseSet.HalfDayOfDay;
DayOfWeek = baseSet.DayOfWeek;
DayOfMonth = baseSet.DayOfMonth;
DayOfYear = baseSet.DayOfYear;
WeekOfWeekYear = baseSet.WeekOfWeekYear;
WeekYear = baseSet.WeekYear;
WeekYearOfCentury = baseSet.WeekYearOfCentury;
MonthOfYear = baseSet.MonthOfYear;
Year = baseSet.Year;
YearOfCentury = baseSet.YearOfCentury;
YearOfEra = baseSet.YearOfEra;
CenturyOfEra = baseSet.CenturyOfEra;
Era = baseSet.Era;
}
/// <summary>
/// Copies just the supported fields from the specified set into this builder,
/// and returns this builder again (for fluent building).
/// </summary>
/// <param name="other">The set of fields to copy.</param>
internal Builder WithSupportedFieldsFrom(FieldSet other)
{
if (other == null)
{
throw new ArgumentNullException("other");
}
Ticks = other.Ticks.IsSupported ? other.Ticks : Ticks;
Milliseconds = other.Milliseconds.IsSupported ? other.Milliseconds : Milliseconds;
Seconds = other.Seconds.IsSupported ? other.Seconds : Seconds;
Minutes = other.Minutes.IsSupported ? other.Minutes : Minutes;
Hours = other.Hours.IsSupported ? other.Hours : Hours;
HalfDays = other.HalfDays.IsSupported ? other.HalfDays : HalfDays;
Days = other.Days.IsSupported ? other.Days : Days;
Weeks = other.Weeks.IsSupported ? other.Weeks : Weeks;
WeekYears = other.WeekYears.IsSupported ? other.WeekYears : WeekYears;
Months = other.Months.IsSupported ? other.Months : Months;
Years = other.Years.IsSupported ? other.Years : Years;
Centuries = other.Centuries.IsSupported ? other.Centuries : Centuries;
Eras = other.Eras.IsSupported ? other.Eras : Eras;
TickOfSecond = other.TickOfSecond.IsSupported ? other.TickOfSecond : TickOfSecond;
TickOfMillisecond = other.TickOfMillisecond.IsSupported ? other.TickOfMillisecond : TickOfMillisecond;
TickOfDay = other.TickOfDay.IsSupported ? other.TickOfDay : TickOfDay;
MillisecondOfSecond = other.MillisecondOfSecond.IsSupported ? other.MillisecondOfSecond : MillisecondOfSecond;
MillisecondOfDay = other.MillisecondOfDay.IsSupported ? other.MillisecondOfDay : MillisecondOfDay;
SecondOfMinute = other.SecondOfMinute.IsSupported ? other.SecondOfMinute : SecondOfMinute;
SecondOfDay = other.SecondOfDay.IsSupported ? other.SecondOfDay : SecondOfDay;
MinuteOfHour = other.MinuteOfHour.IsSupported ? other.MinuteOfHour : MinuteOfHour;
MinuteOfDay = other.MinuteOfDay.IsSupported ? other.MinuteOfDay : MinuteOfDay;
HourOfDay = other.HourOfDay.IsSupported ? other.HourOfDay : HourOfDay;
ClockHourOfDay = other.ClockHourOfDay.IsSupported ? other.ClockHourOfDay : ClockHourOfDay;
HourOfHalfDay = other.HourOfHalfDay.IsSupported ? other.HourOfHalfDay : HourOfHalfDay;
ClockHourOfHalfDay = other.ClockHourOfHalfDay.IsSupported ? other.ClockHourOfHalfDay : ClockHourOfHalfDay;
HalfDayOfDay = other.HalfDayOfDay.IsSupported ? other.HalfDayOfDay : HalfDayOfDay;
DayOfWeek = other.DayOfWeek.IsSupported ? other.DayOfWeek : DayOfWeek;
DayOfMonth = other.DayOfMonth.IsSupported ? other.DayOfMonth : DayOfMonth;
DayOfYear = other.DayOfYear.IsSupported ? other.DayOfYear : DayOfYear;
WeekOfWeekYear = other.WeekOfWeekYear.IsSupported ? other.WeekOfWeekYear : WeekOfWeekYear;
WeekYear = other.WeekYear.IsSupported ? other.WeekYear : WeekYear;
WeekYearOfCentury = other.WeekYearOfCentury.IsSupported ? other.WeekYearOfCentury : WeekYearOfCentury;
MonthOfYear = other.MonthOfYear.IsSupported ? other.MonthOfYear : MonthOfYear;
Year = other.Year.IsSupported ? other.Year : Year;
YearOfCentury = other.YearOfCentury.IsSupported ? other.YearOfCentury : YearOfCentury;
YearOfEra = other.YearOfEra.IsSupported ? other.YearOfEra : YearOfEra;
CenturyOfEra = other.CenturyOfEra.IsSupported ? other.CenturyOfEra : CenturyOfEra;
Era = other.Era.IsSupported ? other.Era : Era;
return this;
}
internal FieldSet Build()
{
return new FieldSet(this);
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the SysMunicipio class.
/// </summary>
[Serializable]
public partial class SysMunicipioCollection : ActiveList<SysMunicipio, SysMunicipioCollection>
{
public SysMunicipioCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SysMunicipioCollection</returns>
public SysMunicipioCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
SysMunicipio o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Sys_Municipio table.
/// </summary>
[Serializable]
public partial class SysMunicipio : ActiveRecord<SysMunicipio>, IActiveRecord
{
#region .ctors and Default Settings
public SysMunicipio()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public SysMunicipio(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public SysMunicipio(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public SysMunicipio(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Sys_Municipio", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdMunicipio = new TableSchema.TableColumn(schema);
colvarIdMunicipio.ColumnName = "idMunicipio";
colvarIdMunicipio.DataType = DbType.Int32;
colvarIdMunicipio.MaxLength = 0;
colvarIdMunicipio.AutoIncrement = true;
colvarIdMunicipio.IsNullable = false;
colvarIdMunicipio.IsPrimaryKey = true;
colvarIdMunicipio.IsForeignKey = false;
colvarIdMunicipio.IsReadOnly = false;
colvarIdMunicipio.DefaultSetting = @"";
colvarIdMunicipio.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdMunicipio);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 200;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"('')";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Sys_Municipio",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdMunicipio")]
[Bindable(true)]
public int IdMunicipio
{
get { return GetColumnValue<int>(Columns.IdMunicipio); }
set { SetColumnValue(Columns.IdMunicipio, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.RemFormularioCollection colRemFormularioRecords;
public DalSic.RemFormularioCollection RemFormularioRecords
{
get
{
if(colRemFormularioRecords == null)
{
colRemFormularioRecords = new DalSic.RemFormularioCollection().Where(RemFormulario.Columns.IdMunicipio, IdMunicipio).Load();
colRemFormularioRecords.ListChanged += new ListChangedEventHandler(colRemFormularioRecords_ListChanged);
}
return colRemFormularioRecords;
}
set
{
colRemFormularioRecords = value;
colRemFormularioRecords.ListChanged += new ListChangedEventHandler(colRemFormularioRecords_ListChanged);
}
}
void colRemFormularioRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colRemFormularioRecords[e.NewIndex].IdMunicipio = IdMunicipio;
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre)
{
SysMunicipio item = new SysMunicipio();
item.Nombre = varNombre;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdMunicipio,string varNombre)
{
SysMunicipio item = new SysMunicipio();
item.IdMunicipio = varIdMunicipio;
item.Nombre = varNombre;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdMunicipioColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdMunicipio = @"idMunicipio";
public static string Nombre = @"nombre";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colRemFormularioRecords != null)
{
foreach (DalSic.RemFormulario item in colRemFormularioRecords)
{
if (item.IdMunicipio != IdMunicipio)
{
item.IdMunicipio = IdMunicipio;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colRemFormularioRecords != null)
{
colRemFormularioRecords.SaveAll();
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SignInt32()
{
var test = new SimpleBinaryOpTest__SignInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SignInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int32> _fld1;
public Vector256<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__SignInt32 testClass)
{
var result = Avx2.Sign(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__SignInt32 testClass)
{
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx2.Sign(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__SignInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public SimpleBinaryOpTest__SignInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Sign(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Sign(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Sign(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Sign), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Sign), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Sign), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Sign(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int32>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Sign(
Avx.LoadVector256((Int32*)(pClsVar1)),
Avx.LoadVector256((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx2.Sign(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.Sign(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.Sign(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__SignInt32();
var result = Avx2.Sign(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__SignInt32();
fixed (Vector256<Int32>* pFld1 = &test._fld1)
fixed (Vector256<Int32>* pFld2 = &test._fld2)
{
var result = Avx2.Sign(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Sign(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx2.Sign(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Sign(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Sign(
Avx.LoadVector256((Int32*)(&test._fld1)),
Avx.LoadVector256((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int32> op1, Vector256<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (right[0] < 0 ? (int)(-left[0]) : (right[0] > 0 ? left[0] : 0)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (right[i] < 0 ? (int)(-left[i]) : (right[i] > 0 ? left[i] : 0)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Sign)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: TextEditorCopyPaste.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: A Component of TextEditor supporting Cut/Copy/Paste commands
//
//---------------------------------------------------------------------------
namespace System.Windows.Documents
{
using MS.Internal;
using System.Globalization;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.ComponentModel;
using System.Text;
using System.Xml;
using System.IO;
using System.Collections; // ArrayList
using System.Runtime.InteropServices;
using System.Windows.Threading;
using System.Windows.Input;
using System.Windows.Controls; // ScrollChangedEventArgs
using System.Windows.Controls.Primitives; // CharacterCasing, TextBoxBase
using System.Windows.Media;
using System.Windows.Markup;
using MS.Utility;
using MS.Win32;
using MS.Internal.Documents;
using MS.Internal.Commands; // CommandHelpers
/// <summary>
/// Text editing service for controls.
/// </summary>
internal static class TextEditorCopyPaste
{
//------------------------------------------------------
//
// Class Internal Methods
//
//------------------------------------------------------
#region Class Internal Methods
// Registers all text editing command handlers for a given control type
/// <SecurityNote>
/// Critical - elevates to associate a protected command (paste) with keyboard
/// TreatAsSafe - Shift+Insert is the correct key binding, and therefore is
/// expected by the user.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal static void _RegisterClassHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)
{
CommandHelpers.RegisterCommandHandler(controlType, ApplicationCommands.Copy, new ExecutedRoutedEventHandler(OnCopy), new CanExecuteRoutedEventHandler(OnQueryStatusCopy), KeyGesture.CreateFromResourceStrings(SR.Get(SRID.KeyCopy), SR.Get(SRID.KeyCopyDisplayString)), KeyGesture.CreateFromResourceStrings(SR.Get(SRID.KeyCtrlInsert), SR.Get(SRID.KeyCtrlInsertDisplayString)));
if (acceptsRichContent)
{
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.CopyFormat, new ExecutedRoutedEventHandler(OnCopyFormat), new CanExecuteRoutedEventHandler(OnQueryStatusCopyFormat), SRID.KeyCopyFormat, SRID.KeyCopyFormatDisplayString);
}
if (!readOnly)
{
CommandHelpers.RegisterCommandHandler(controlType, ApplicationCommands.Cut, new ExecutedRoutedEventHandler(OnCut), new CanExecuteRoutedEventHandler(OnQueryStatusCut), KeyGesture.CreateFromResourceStrings(SR.Get(SRID.KeyCut), SR.Get(SRID.KeyCutDisplayString)), KeyGesture.CreateFromResourceStrings(SR.Get(SRID.KeyShiftDelete), SR.Get(SRID.KeyShiftDeleteDisplayString)));
// temp vars to reduce code under elevation
ExecutedRoutedEventHandler ExecutedRoutedEventHandler = new ExecutedRoutedEventHandler(OnPaste);
CanExecuteRoutedEventHandler CanExecuteRoutedEventHandler = new CanExecuteRoutedEventHandler(OnQueryStatusPaste);
InputGesture inputGesture = KeyGesture.CreateFromResourceStrings(SR.Get(SRID.KeyShiftInsert), SR.Get(SRID.KeyShiftInsertDisplayString));
new UIPermission(UIPermissionClipboard.AllClipboard).Assert(); //BlessedAssert
try
{
CommandHelpers.RegisterCommandHandler(controlType, ApplicationCommands.Paste, ExecutedRoutedEventHandler, CanExecuteRoutedEventHandler, inputGesture);
}
finally
{
CodeAccessPermission.RevertAssert();
}
if (acceptsRichContent)
{
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.PasteFormat, new ExecutedRoutedEventHandler(OnPasteFormat), new CanExecuteRoutedEventHandler(OnQueryStatusPasteFormat), SRID.KeyPasteFormat, SRID.KeyPasteFormatDisplayString);
}
}
}
/// <summary>
/// Creates DataObject for Copy and Drag operations
/// </summary>
/// <SecurityNote>
/// Critical: This code calls into SetData under an assert which has the ability to set xaml content on clipboard.
/// </SecurityNote>
[SecurityCritical]
internal static DataObject _CreateDataObject(TextEditor This, bool isDragDrop)
{
DataObject dataObject;
// Create the data object for drag and drop.
//
(new UIPermission(UIPermissionClipboard.AllClipboard)).Assert();//BlessedAssert
try
{
dataObject = new DataObject();
}
finally
{
UIPermission.RevertAssert();
}
// Get plain text and copy it into the data object.
string textString = This.Selection.Text;
if (textString != String.Empty)
{
// Copy plain text into data object.
// ConfirmDataFormatSetting rasies a public event - could throw recoverable exception.
if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Text))
{
CriticalSetDataWrapper(dataObject,DataFormats.Text, textString);
}
// Copy unicode text into data object.
// ConfirmDataFormatSetting rasies a public event - could throw recoverable exception.
if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.UnicodeText))
{
CriticalSetDataWrapper(dataObject,DataFormats.UnicodeText, textString);
}
}
// Get the rtf and xaml text and then copy it into the data object after confirm data format.
// We do this only if our content is rich
if (This.AcceptsRichContent)
{
// This ensures that in the confines of partial trust RTF is not enabled.
// We use unmanaged code permission over clipboard permission since
// the latter is available in intranet zone and this is something that will
// fail in intranet too.
if (SecurityHelper.CheckUnmanagedCodePermission())
{
// In FullTrust we allow all rich formats on the clipboard
Stream wpfContainerMemory = null;
// null wpfContainerMemory on entry means that container is optional
// and will be not created when there is no images in the range.
// Create in-memory wpf package, and serialize the content of selection into it
string xamlTextWithImages = WpfPayload.SaveRange(This.Selection, ref wpfContainerMemory, /*useFlowDocumentAsRoot:*/false);
if (xamlTextWithImages.Length > 0)
{
// ConfirmDataFormatSetting raises a public event - could throw recoverable exception.
if (wpfContainerMemory != null && ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.XamlPackage))
{
dataObject.SetData(DataFormats.XamlPackage, wpfContainerMemory);
}
// ConfirmDataFormatSetting raises a public event - could throw recoverable exception.
if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Rtf))
{
// Convert xaml to rtf text to set rtf data into data object.
string rtfText = ConvertXamlToRtf(xamlTextWithImages, wpfContainerMemory);
if (rtfText != String.Empty)
{
dataObject.SetData(DataFormats.Rtf, rtfText, true);
}
}
}
// Add a CF_BITMAP if we have only one image selected.
Image image = This.Selection.GetUIElementSelected() as Image;
if (image != null && image.Source is System.Windows.Media.Imaging.BitmapSource)
{
dataObject.SetImage((System.Windows.Media.Imaging.BitmapSource)image.Source);
}
}
// Xaml format is availabe both in Full Trust and in Partial Trust
// Need to re-serialize xaml to avoid image references within a container:
StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
TextRangeSerialization.WriteXaml(xmlWriter, This.Selection, /*useFlowDocumentAsRoot:*/false, /*wpfPayload:*/null);
string xamlText = stringWriter.ToString();
//
if (xamlText.Length > 0)
{
// ConfirmDataFormatSetting rasies a public event - could throw recoverable exception.
if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Xaml))
{
// Place Xaml data onto the dataobject using safe setter
CriticalSetDataWrapper(dataObject, DataFormats.Xaml, xamlText);
// The dataobject itself must hold an information about permission set
// of the source appdomain. Set it there:
// Package permission set for the current appdomain
PermissionSet psCurrentAppDomain = SecurityHelper.ExtractAppDomainPermissionSetMinusSiteOfOrigin();
string permissionSetCurrentAppDomain = psCurrentAppDomain.ToString();
CriticalSetDataWrapper(dataObject, DataFormats.ApplicationTrust, permissionSetCurrentAppDomain);
}
}
}
// Notify application about our data object preparation completion
DataObjectCopyingEventArgs dataObjectCopyingEventArgs = new DataObjectCopyingEventArgs(dataObject, /*isDragDrop:*/isDragDrop);
This.UiScope.RaiseEvent(dataObjectCopyingEventArgs);
if (dataObjectCopyingEventArgs.CommandCancelled)
{
dataObject = null;
}
return dataObject;
}
/// <summary>
/// Paste contents of data object into text selection
/// </summary>
/// <param name="This"></param>
/// <param name="dataObject">
/// data object containing data to paste
/// </param>
/// <param name="isDragDrop">
/// </param>
/// <returns>
/// true if successful, false otherwise
/// </returns>
/// <SecurityNote>
/// To disable paste in partial trust case,
/// this function checks if the current call stack has the all clipboard permission.
/// Critical: This code calls into AppDomain methods and enables xaml cut and paste
/// TreatAsSafe: It has a demand for All Clipboard permissions
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
internal static bool _DoPaste(TextEditor This, IDataObject dataObject, bool isDragDrop)
{
// Don't try anything if the caller doesn't have the rights to read from the clipboard...
//
if (!SecurityHelper.CallerHasAllClipboardPermission()) return false;
Invariant.Assert(dataObject != null);
// Choose what format we are going to paste
string formatToApply;
bool pasted;
pasted = false;
// Get the default paste content applying format
formatToApply = GetPasteApplyFormat(This, dataObject);
DataObjectPastingEventArgs dataObjectPastingEventArgs;
try
{
// Let the application to participate in Paste process
dataObjectPastingEventArgs = new DataObjectPastingEventArgs(dataObject, isDragDrop, formatToApply);
}
catch (ArgumentException)
{
// Clipboard can be changed by set new or empty data during creating
// DataObjectPastingEvent that check the representing of the
// formatToApply. Do nothing if we encounter AgrumentException.
return pasted;
}
// Public event call - could raise recoverable exception.
This.UiScope.RaiseEvent(dataObjectPastingEventArgs);
if (!dataObjectPastingEventArgs.CommandCancelled)
{
// When custom handler decides to suggest its own data,
// it must create a new instance of DataObject and put it
// into DataObjectPastingEventArgs.DataObject property.
// Exisiting DataObject is on global Clipboard and can not be changed.
// Here we need to get this potentially changed instance
// of DataObject
IDataObject dataObjectToApply = dataObjectPastingEventArgs.DataObject;
formatToApply = dataObjectPastingEventArgs.FormatToApply;
// Paste the content data(Text, Unicode, Xaml and Rtf) to the current text selection
pasted = PasteContentData(This, dataObject, dataObjectToApply, formatToApply);
}
return pasted;
}
// Get the default paste content applying format
internal static string GetPasteApplyFormat(TextEditor This, IDataObject dataObject)
{
string formatToApply;
// Currently we won't allow DataFormats.Xaml on the partial trust.
// GetDataPresent(DataFormats.Xaml)have a chance to register Xaml format
// by calling the unmanaged code which is RegisterClipboardFormat.
bool hasUnmanagedCodePermission = SecurityHelper.CheckUnmanagedCodePermission();
if (This.AcceptsRichContent && hasUnmanagedCodePermission && dataObject.GetDataPresent(DataFormats.XamlPackage))
{
formatToApply = DataFormats.XamlPackage;
}
else if (This.AcceptsRichContent && dataObject.GetDataPresent(DataFormats.Xaml))
{
formatToApply = DataFormats.Xaml;
}
else if (This.AcceptsRichContent && hasUnmanagedCodePermission && dataObject.GetDataPresent(DataFormats.Rtf))
{
formatToApply = DataFormats.Rtf;
}
else if (dataObject.GetDataPresent(DataFormats.UnicodeText))
{
formatToApply = DataFormats.UnicodeText;
}
else if (dataObject.GetDataPresent(DataFormats.Text))
{
formatToApply = DataFormats.Text;
}
else if (This.AcceptsRichContent && hasUnmanagedCodePermission && dataObject is DataObject && ((DataObject)dataObject).ContainsImage())
{
formatToApply = DataFormats.Bitmap;
}
else
{
// Even if we do not see any recognizable formats,
// we continue the process because application custom
// paste needs it and may do something useful.
formatToApply = String.Empty;
}
return formatToApply;
}
/// <summary>
/// Cut worker.
/// </summary>
/// <SecurityNote>
/// Critical - Sets data on the clipboard and accepts a parameter which indicates
/// whether or not this action was user-initiated.
/// </SecurityNote>
[SecurityCritical]
internal static void Cut(TextEditor This, bool userInitiated)
{
if (userInitiated)
{
// Fail silently if the app explicitly denies clipboard access.
try
{
new UIPermission(UIPermissionClipboard.OwnClipboard).Demand();
}
catch (SecurityException)
{
return;
}
}
else if (!SecurityHelper.CallerHasAllClipboardPermission())
{
// Fail silently if we don't have clipboard permission.
return;
}
TextEditorTyping._FlushPendingInputItems(This);
TextEditorTyping._BreakTypingSequence(This);
if (This.Selection != null && !This.Selection.IsEmpty)
{
// Copy content onto the clipboard
// Note: _CreateDataObject raises a public event which might throw a recoverable exception.
DataObject dataObject = TextEditorCopyPaste._CreateDataObject(This, /*isDragDrop:*/false);
if (dataObject != null)
{
try
{
// The copy command was not terminated by application
// One of reason should be the opening fail of Clipboard by the destroyed hwnd.
Clipboard.CriticalSetDataObject(dataObject, true);
}
catch (ExternalException)
{
// Clipboard is failed to set the data object.
return;
}
// Delete selected content
using (This.Selection.DeclareChangeBlock())
{
// Forget previously suggested horizontal position
TextEditorSelection._ClearSuggestedX(This);
This.Selection.Text = String.Empty;
// Clear springload formatting
if (This.Selection is TextSelection)
{
((TextSelection)This.Selection).ClearSpringloadFormatting();
}
}
}
}
}
/// <summary>
/// Copy worker.
/// </summary>
/// <SecurityNote>
/// Critical - Sets data on the clipboard and accepts a parameter which indicates
/// whether or not this action was user-initiated.
/// </SecurityNote>
[SecurityCritical]
internal static void Copy(TextEditor This, bool userInitiated)
{
if (userInitiated)
{
// Fail silently if the app explicitly denies clipboard access.
try
{
new UIPermission(UIPermissionClipboard.OwnClipboard).Demand();
}
catch (SecurityException)
{
return;
}
}
else if (!SecurityHelper.CallerHasAllClipboardPermission())
{
// Fail silently if we don't have clipboard permission.
return;
}
TextEditorTyping._FlushPendingInputItems(This);
TextEditorTyping._BreakTypingSequence(This);
if (This.Selection != null && !This.Selection.IsEmpty)
{
// Note: _CreateDataObject raises a public event which might throw a recoverable exception.
DataObject dataObject = TextEditorCopyPaste._CreateDataObject(This, /*isDragDrop:*/false);
if (dataObject != null)
{
try
{
// The copy command was not terminated by application
// One of reason should be the opening fail of Clipboard by the destroyed hwnd.
Clipboard.CriticalSetDataObject(dataObject, true);
}
catch (ExternalException)
{
// Clipboard is failed to set the data object.
return;
}
}
}
// Do not clear springload formatting
}
/// <summary>
/// Paste worker.
/// </summary>
/// <SecurityNote>
/// Critical:To disable paste in partial trust case,
/// TreatAsSafe: this function checks if the current call stack has the all clipboard permission.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal static void Paste(TextEditor This)
{
// Don't try anything if the caller doesn't have the rights to read from the clipboard...
if (!SecurityHelper.CallerHasAllClipboardPermission())
{
return;
}
if (This.Selection.IsTableCellRange)
{
//
return;
}
TextEditorTyping._FlushPendingInputItems(This);
TextEditorTyping._BreakTypingSequence(This);
// Get DataObject from the Clipboard
IDataObject dataObject;
try
{
dataObject = Clipboard.GetDataObject();
}
catch (ExternalException)
{
// Clipboard is failed to get the data object.
// One of reason should be the opening fail of Clipboard by the destroyed hwnd.
dataObject = null;
//
}
bool forceLayoutUpdate = This.Selection.CoversEntireContent;
if (dataObject != null)
{
using (This.Selection.DeclareChangeBlock())
{
// Forget previously suggested horizontal position
TextEditorSelection._ClearSuggestedX(This);
// _DoPaste raises a public event -- could raise recoverable exception.
if (TextEditorCopyPaste._DoPaste(This, dataObject, /*isDragDrop:*/false))
{
// Collapse selection to the end
// Use backward direction to stay oriented towards pasted content
This.Selection.SetCaretToPosition(This.Selection.End, LogicalDirection.Backward, /*allowStopAtLineEnd:*/false, /*allowStopNearSpace:*/true);
// Clear springload formatting
if (This.Selection is TextSelection)
{
((TextSelection)This.Selection).ClearSpringloadFormatting();
}
}
} // PUBLIC EVENT RAISED HERE AS CHANGEBLOCK CLOSES!
}
// If we replaced the entire document content, background layout will
// kick in. Force it to complete now.
if (forceLayoutUpdate)
{
This.Selection.ValidateLayout();
}
}
// Converts xaml content to rtf content.
internal static string ConvertXamlToRtf(string xamlContent, Stream wpfContainerMemory)
{
// Create XamlRtfConverter to process the converting from Xaml to Rtf
XamlRtfConverter xamlRtfConverter = new XamlRtfConverter();
if (wpfContainerMemory != null)
{
xamlRtfConverter.WpfPayload = WpfPayload.OpenWpfPayload(wpfContainerMemory);
}
// Process Xaml-Rtf converting
string rtfContent = xamlRtfConverter.ConvertXamlToRtf(xamlContent);
return rtfContent;
}
// Converts an rtf content to xaml content.
internal static MemoryStream ConvertRtfToXaml(string rtfContent)
{
MemoryStream memoryStream = new MemoryStream();
WpfPayload wpfPayload = WpfPayload.CreateWpfPayload(memoryStream);
using (wpfPayload.Package)
{
using (Stream xamlStream = wpfPayload.CreateXamlStream())
{
// Create XamlRtfConverter to process the converting from Rtf to Xaml
XamlRtfConverter xamlRtfConverter = new XamlRtfConverter();
xamlRtfConverter.WpfPayload = wpfPayload;
string xamlContent = xamlRtfConverter.ConvertRtfToXaml(rtfContent);
if (xamlContent != string.Empty)
{
StreamWriter streamWriter = new StreamWriter(xamlStream);
using (streamWriter)
{
streamWriter.Write(xamlContent);
}
}
else
{
memoryStream = null;
}
} // This closes xamlStream
} // This closes the package
return memoryStream;
}
#endregion Class Internal Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Cut command QueryStatus handler
/// </summary>
private static void OnQueryStatusCut(object target, CanExecuteRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled || This.IsReadOnly)
{
return;
}
// Ignore the cut event if the editor is on PasswordBox control.
if (This.UiScope is PasswordBox)
{
args.CanExecute = false;
args.Handled = true;
return;
}
args.CanExecute = !This.Selection.IsEmpty;
args.Handled = true;
}
/// <summary>
/// Cut command event handler.
/// </summary>
/// <SecurityNote>
/// Critical - Calls TextEditorCopyPaste.Cut, using the UserInitiated
/// bit in the event args, to set data on the clipboard.
/// TreatAsSafe - The bit is protected by the UserIniatedRoutedEvent permission and
/// the content being set is based on the active selection.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled || This.IsReadOnly)
{
return;
}
// Ignore the cut event if the editor is on PasswordBox control.
if (This.UiScope is PasswordBox)
{
return;
}
Cut(This, args.UserInitiated);
}
/// <summary>
/// Copy command QueryStatus handler
/// </summary>
private static void OnQueryStatusCopy(object target, CanExecuteRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled)
{
return;
}
// Ignore the copy event if the editor is on PasswordBox control.
if (This.UiScope is PasswordBox)
{
args.CanExecute = false;
args.Handled = true;
return;
}
args.CanExecute = !This.Selection.IsEmpty;
args.Handled = true;
}
/// <summary>
/// Copy command event handler.
/// This method is used both in Copy, Cut and DragDrop commands.
/// </summary>
/// <SecurityNote>
/// Critical - Calls TextEditorCopyPaste.Copy, using the UserInitiated
/// bit in the event args, to set data on the clipboard.
/// TreatAsSafe - The bit is protected by the UserIniatedRoutedEvent permission and
/// the content being set is based on the active selection.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled)
{
return;
}
// Ignore the copy event if the editor is on PasswordBox control.
if (This.UiScope is PasswordBox)
{
return;
}
Copy(This, args.UserInitiated);
}
/// <summary>
/// Paste command QueryStatus handler
/// </summary>
private static void OnQueryStatusPaste(object target, CanExecuteRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled || This.IsReadOnly)
{
return;
}
args.Handled = true;
try
{
if (SecurityHelper.CallerHasAllClipboardPermission())
{
// Define what format our paste mechanism recognizes on the clipbord appropriate for this selection
string formatToApply = GetPasteApplyFormat(This, Clipboard.GetDataObject());
args.CanExecute = formatToApply.Length > 0;
}
else
{
// Simplified version of clipboard sniffing for partial trust
args.CanExecute = Clipboard.IsClipboardPopulated();
}
}
catch (ExternalException)
{
// Clipboard is failed to get the data object.
// One of reason should be the opening fail of Clipboard while other
// process opens the clipboard or missing close of Clipboard.
args.CanExecute = false;
}
}
/// <summary>
/// Paste command event handler.
/// </summary>
private static void OnPaste(object target, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled || This.IsReadOnly)
{
return;
}
Paste(This);
}
/// <summary>
/// StartInputCorrection command QueryStatus handler
/// </summary>
private static void OnQueryStatusCopyFormat(object target, CanExecuteRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled)
{
return;
}
//
args.CanExecute = false;
args.Handled = true;
}
private static void OnCopyFormat(object sender, ExecutedRoutedEventArgs args)
{
//
}
/// <summary>
/// StartInputCorrection command QueryStatus handler
/// </summary>
private static void OnQueryStatusPasteFormat(object target, CanExecuteRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled || This.IsReadOnly)
{
return;
}
//
args.CanExecute = false;
args.Handled = true;
}
private static void OnPasteFormat(object sender, ExecutedRoutedEventArgs args)
{
//
}
/// <SecurityNote>
/// Critical: This code calls into CriticalSetData which circumvents all checks for setting data
/// </SecurityNote>
/// <summary>
/// This code is used to call into an internal overload to set data which circumvents the demand for
/// all clipboard permission. Although this is not the cleanest we prefer to cast it to DataObject
/// and call the critical overload to reduce the scope of the code that gets called here.
/// This saves us one high level assert.
/// </summary>
/// <param name="dataObjectValue"></param>
/// <param name="format"></param>
/// <param name="content"></param>
[SecurityCritical]
private static void CriticalSetDataWrapper(IDataObject dataObjectValue, string format, string content)
{
if (dataObjectValue is DataObject)
{
((DataObject)dataObjectValue).CriticalSetData(format, content, format == DataFormats.ApplicationTrust ? /*autoConvert:*/false : true);
}
}
/// <summary>
/// Paste the content data(Text, Unicode, Xaml and Rtf) to the current text selection
/// </summary>
/// <param name="This"></param>
/// <param name="dataObject">
/// data object containing data to paste
/// </param>
/// <param name="dataObjectToApply">
/// </param>
/// <param name="formatToApply">
/// </param>
/// <returns>
/// true if successful, false otherwise
/// </returns>
/// <SecurityNote>
/// This function paste the content data and also can set new apply format with
/// checking the unmanaged code permission if the content data is failed to paste.
/// Critical: This function falls back to DataFormats.Rtf in case Xaml paste fails. It calls Critical WpfPayload.SaveImage.
/// TreatAsSafe: In partial trust we revert to DataFormats.UnicodeText or DataFormats.Text
/// format and hence the risk is mitigated of having Rtf paste enabled
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private static bool PasteContentData(TextEditor This, IDataObject dataObject, IDataObject dataObjectToApply, string formatToApply)
{
// CF_BITMAP - pasting a single image.
if (formatToApply == DataFormats.Bitmap && dataObjectToApply is DataObject)
{
// This demand is present to explicitly disable RTF independant of any
// asserts in the confines of partial trust
// We check unmanaged code instead of all clipboard because in paste
// there is a high level assert for all clipboard in commandmanager.cs
if (This.AcceptsRichContent && This.Selection is TextSelection &&
SecurityHelper.CheckUnmanagedCodePermission())
{
System.Windows.Media.Imaging.BitmapSource bitmapSource = GetPasteData(dataObjectToApply, DataFormats.Bitmap) as System.Windows.Media.Imaging.BitmapSource;
if (bitmapSource != null)
{
// Pack the image into a WPF container
MemoryStream packagedImage = WpfPayload.SaveImage(bitmapSource, WpfPayload.ImageBmpContentType);
// Place it onto a data object
dataObjectToApply = new DataObject();
formatToApply = DataFormats.XamlPackage;
dataObjectToApply.SetData(DataFormats.XamlPackage, packagedImage);
}
}
}
if (formatToApply == DataFormats.XamlPackage)
{
// This demand is present to explicitly disable RTF independant of any
// asserts in the confines of partial trust
// We check unmanaged code instead of all clipboard because in paste
// there is a high level assert for all clipboard in commandmanager.cs
if (This.AcceptsRichContent && This.Selection is TextSelection &&
SecurityHelper.CheckUnmanagedCodePermission())
{
object pastedData = GetPasteData(dataObjectToApply, DataFormats.XamlPackage);
MemoryStream pastedMemoryStream = pastedData as MemoryStream;
if (pastedMemoryStream != null)
{
object element = WpfPayload.LoadElement(pastedMemoryStream);
if ((element is Section || element is Span) && PasteTextElement(This, (TextElement)element))
{
return true;
}
else if (element is FrameworkElement)
{
((TextSelection)This.Selection).InsertEmbeddedUIElement((FrameworkElement)element);
return true;
}
}
}
// Fall to Xaml:
dataObjectToApply = dataObject; // go back to source data object
if (dataObjectToApply.GetDataPresent(DataFormats.Xaml))
{
formatToApply = DataFormats.Xaml;
}
else if (SecurityHelper.CheckUnmanagedCodePermission() && dataObjectToApply.GetDataPresent(DataFormats.Rtf))
{
formatToApply = DataFormats.Rtf;
}
else if (dataObjectToApply.GetDataPresent(DataFormats.UnicodeText))
{
formatToApply = DataFormats.UnicodeText;
}
else if (dataObjectToApply.GetDataPresent(DataFormats.Text))
{
formatToApply = DataFormats.Text;
}
}
if (formatToApply == DataFormats.Xaml)
{
if (This.AcceptsRichContent && This.Selection is TextSelection)
{
object pastedData = GetPasteData(dataObjectToApply, DataFormats.Xaml);
if (pastedData != null && PasteXaml(This, pastedData.ToString()))
{
return true;
}
}
// Fall to Rtf:
dataObjectToApply = dataObject; // go back to source data object
if (SecurityHelper.CheckUnmanagedCodePermission() && dataObjectToApply.GetDataPresent(DataFormats.Rtf))
{
formatToApply = DataFormats.Rtf;
}
else if (dataObjectToApply.GetDataPresent(DataFormats.UnicodeText))
{
formatToApply = DataFormats.UnicodeText;
}
else if (dataObjectToApply.GetDataPresent(DataFormats.Text))
{
formatToApply = DataFormats.Text;
}
}
if (formatToApply == DataFormats.Rtf)
{
// This demand is present to explicitly disable RTF independant of any
// asserts in the confines of partial trust
// We check unmanaged code instead of all clipboard because in paste
// there is a high level assert for all clipboard in commandmanager.cs
if (This.AcceptsRichContent && SecurityHelper.CheckUnmanagedCodePermission())
{
object pastedData = GetPasteData(dataObjectToApply, DataFormats.Rtf);
// Convert rtf to xaml text to paste rtf data into the target.
if (pastedData != null)
{
MemoryStream memoryStream = ConvertRtfToXaml(pastedData.ToString());
if (memoryStream != null)
{
TextElement textElement = WpfPayload.LoadElement(memoryStream) as TextElement;
if ((textElement is Section || textElement is Span) && PasteTextElement(This, textElement))
{
return true;
}
}
}
}
// Fall to plain text:
dataObjectToApply = dataObject; // go back to source data object
if (dataObjectToApply.GetDataPresent(DataFormats.UnicodeText))
{
formatToApply = DataFormats.UnicodeText;
}
else if (dataObjectToApply.GetDataPresent(DataFormats.Text))
{
formatToApply = DataFormats.Text;
}
}
if (formatToApply == DataFormats.UnicodeText)
{
object pastedData = GetPasteData(dataObjectToApply, DataFormats.UnicodeText);
if (pastedData == null)
{
if (dataObjectToApply.GetDataPresent(DataFormats.Text))
{
formatToApply = DataFormats.Text; // fall to plain text
dataObjectToApply = dataObject; // go back to source data object
}
}
else
{
// Dont attempt to recover if pasting Unicode text fails because our only fallback is mbcs text,
// which will either evaluate identically (at best) or
// produce a string with unexpected text (worse!) from WideCharToMultiByte conversion.
return PastePlainText(This, pastedData.ToString());
}
}
if (formatToApply == DataFormats.Text)
{
object pastedData = GetPasteData(dataObjectToApply, DataFormats.Text);
if (pastedData != null && PastePlainText(This, pastedData.ToString()))
{
return true;
}
}
return false;
}
/// <summary>
/// Get the paste data from the specified DataObject and data format.
/// </summary>
/// <SecurityNote>
/// Critical: This function calls the critical methods which access the unmanaged code
/// to get the pasted data from DataObject
/// </SecurityNote>
[SecurityCritical]
private static object GetPasteData(IDataObject dataObject, string dataFormat)
{
object pastedData;
try
{
// We don't need to verify data present here. First, GetPasteApplyFormat()
// is already verified the data present, so reduce the perf. Second, we can't
// guarantee the presenting data for the some specified data after raising
// DataObjectPastingEventArgs which case is that set FormatToApply first then
// set the DataObject that doesn't have FormatToApply data format.
//Invariant.Assert(dataObject.GetDataPresent(dataFormat));
pastedData = dataObject.GetData(dataFormat, true);
}
// DataObject data can have the invalid value that throw the Exception.
// In case of OutOfMemoryException, ExternalException(and Win32Exception),
// we return null quietly and do nothing for paste.
// For example(Bug#1391689) , IE set the invalid Rich Text Format data that bring
// CLR OutOfMemoryException.
catch (OutOfMemoryException)
{
pastedData = null;
}
catch (ExternalException)
{
pastedData = null;
}
return pastedData;
}
// Paste flow content into the current text selection
// Returns false if pasting was not successful - assuming that the caller will choose another format for pasting
private static bool PasteTextElement(TextEditor This, TextElement sectionOrSpan)
{
bool success = false;
This.Selection.BeginChange();
try
{
((TextRange)This.Selection).SetXmlVirtual(sectionOrSpan);
// Merge new Lists with surrounding Lists.
TextRangeEditLists.MergeListsAroundNormalizedPosition((TextPointer)This.Selection.Start);
TextRangeEditLists.MergeListsAroundNormalizedPosition((TextPointer)This.Selection.End);
// Merge flow direction of the new content if it matches its surroundings.
TextRangeEdit.MergeFlowDirection((TextPointer)This.Selection.Start);
TextRangeEdit.MergeFlowDirection((TextPointer)This.Selection.End);
success = true;
}
finally
{
This.Selection.EndChange();
}
return success;
}
// Paste xaml content into the current text selection
// Returns false if pasting was not successful - assuming that the caller will choose another format for pasting
private static bool PasteXaml(TextEditor This, string pasteXaml)
{
bool success;
if (pasteXaml.Length == 0)
{
success = false;
}
else
{
try
{
// Parse the fragment into a separate subtree
object xamlObject = XamlReader.Load(new XmlTextReader(new System.IO.StringReader(pasteXaml)));
TextElement flowContent = xamlObject as TextElement;
success = flowContent == null ? false : PasteTextElement(This, flowContent);
}
catch (XamlParseException e)
{
// Clipboard data can have the invalid xaml content that will throw
// the XamlParseException.
// In case of XamlParseException, we shouldn't paste anything and quiet.
// Xaml invalid character range is from 0x00 to 0x20. (e.g. �x03)
//
Invariant.Assert(e != null); //to make compiler happy about not using a variable e. This variable is useful in debugging process though - to see a reason of a parsing failure
success = false;
}
}
return success;
}
// Helper for plain text filtering when pasted into rich or plain destination
private static bool PastePlainText(TextEditor This, string pastedText)
{
pastedText = This._FilterText(pastedText, This.Selection);
if (pastedText.Length > 0)
{
if (This.AcceptsRichContent && This.Selection.Start is TextPointer)
{
// Clear selection content
This.Selection.Text = String.Empty;
// Ensure that text is insertable at current selection
TextPointer start = TextRangeEditTables.EnsureInsertionPosition((TextPointer)This.Selection.Start);
// Store boundaries of inserted text
start = start.GetPositionAtOffset(0, LogicalDirection.Backward);
TextPointer end = start.GetPositionAtOffset(0, LogicalDirection.Forward);
// For rich text we need to remove control characters and
// replace linebreaks by paragraphs
int currentLineStart = 0;
for (int i = 0; i < pastedText.Length; i++)
{
if (pastedText[i] == '\r' || pastedText[i] == '\n')
{
end.InsertTextInRun(pastedText.Substring(currentLineStart, i - currentLineStart));
if (!This.AcceptsReturn)
{
return true; // All lined except for the first one are ignored when TextBox does not accept Return key
}
if (end.HasNonMergeableInlineAncestor)
{
// We cannot split a Hyperlink or other non-mergeable Inline element,
// so insert a space character instead (similar to embedded object).
// Note that this means, Paste operation would loose
// paragraph break information in this case.
end.InsertTextInRun(" ");
}
else
{
end = end.InsertParagraphBreak();
}
if (pastedText[i] == '\r' && i + 1 < pastedText.Length && pastedText[i + 1] == '\n')
{
i++;
}
currentLineStart = i + 1;
}
}
end.InsertTextInRun(pastedText.Substring(currentLineStart, pastedText.Length - currentLineStart));
// Select all pasted content
This.Selection.Select(start, end);
}
else
{
// For plain text we insert the content as is (including control characters)
This.Selection.Text = pastedText;
}
return true;
}
return false;
}
// Event firing helper for DataObjectSettingData event
private static bool ConfirmDataFormatSetting(FrameworkElement uiScope, IDataObject dataObject, string format)
{
DataObjectSettingDataEventArgs dataObjectSettingDataEventArgs;
dataObjectSettingDataEventArgs = new DataObjectSettingDataEventArgs(dataObject, format);
uiScope.RaiseEvent(dataObjectSettingDataEventArgs);
return !dataObjectSettingDataEventArgs.CommandCancelled;
}
#endregion Private methods
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="Win32Api.cs" company="Tethys">
// Copyright (C) 1998-2021 T. Graf
// </copyright>
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 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.
// ---------------------------------------------------------------------------
// ReSharper disable once CheckNamespace
namespace Tethys.Win32
{
using System;
using System.CodeDom.Compiler;
using System.Runtime.InteropServices;
using System.Text;
#pragma warning disable 1591
/// <summary>
/// The class Win32 Api encapsulates native Win32 constants and functions.
/// </summary>
[GeneratedCode("Ignore this class in FxCop", "0.0")]
public static class Win32Api
{
// Win32Api()
#region MISC CONSTANTS
/// <summary>
/// Scroll bar constant.
/// </summary>
public const int SB_VERT = 1;
/// <summary>
/// Win32 API message to set scroll bar position.
/// </summary>
public const int EM_SETSCROLLPOS = 0x0400 + 222;
#endregion // MISC CONSTANTS
#region MESSAGEBOX FLAGS
// ----- MessageBox Flags -----
public const int MB_OK = 0x00000000;
public const int MB_OKCANCEL = 0x00000001;
public const int MB_ABORTRETRYIGNORE = 0x00000002;
public const int MB_YESNOCANCEL = 0x00000003;
public const int MB_YESNO = 0x00000004;
public const int MB_RETRYCANCEL = 0x00000005;
public const int MB_ICONHAND = 0x00000010;
public const int MB_ICONQUESTION = 0x00000020;
public const int MB_ICONEXCLAMATION = 0x00000030;
public const int MB_ICONASTERISK = 0x00000040;
public const int MB_APPLMODAL = 0x00000000;
public const int MB_SYSTEMMODAL = 0x00001000;
public const int MB_TASKMODAL = 0x00002000;
public const int MB_SETFOREGROUND = 0x00010000;
public const int MB_TOPMOST = 0x00040000;
public const int MB_HELP = 0x00004000;
public const int MB_DEFBUTTON1 = 0x00000000;
public const int MB_DEFBUTTON2 = 0x00000100;
public const int MB_DEFBUTTON3 = 0x00000200;
public const int MB_DEFBUTTON4 = 0x00000300;
// Dialog Box Command IDs
public const int IDOK = 1;
public const int IDCANCEL = 2;
public const int IDABORT = 3;
public const int IDRETRY = 4;
public const int IDIGNORE = 5;
public const int IDYES = 6;
public const int IDNO = 7;
public const int IDCLOSE = 8;
public const int IDHELP = 9;
#endregion // MESSAGEBOX FLAGS
#region WINDOWS MESSAGES
// ----- Windows Messages -----
public const int WM_CHAR = 0x0102;
public const int WM_SYSKEYDOWN = 0x0104;
public const int WM_LBUTTONDOWN = 0x0201;
public const int WM_RBUTTONDOWN = 0x0204;
public const int WM_MBUTTONDOWN = 0x0207;
public const int WM_NCLBUTTONDOWN = 0x00A1;
public const int WM_NCRBUTTONDOWN = 0x00A4;
public const int WM_NCMBUTTONDOWN = 0x00A7;
#endregion // WINDOWS MESSAGES
#region WINDOW STYLES
public const int WS_OVERLAPPED = 0x00000000;
public const uint WS_POPUP = 0x80000000;
public const int WS_CHILD = 0x40000000;
public const int WS_MINIMIZE = 0x20000000;
public const int WS_VISIBLE = 0x10000000;
public const int WS_DISABLED = 0x08000000;
public const int WS_CLIPSIBLINGS = 0x04000000;
public const int WS_CLIPCHILDREN = 0x02000000;
public const int WS_MAXIMIZE = 0x01000000;
public const int WS_CAPTION = 0x00C00000;
public const int WS_BORDER = 0x00800000;
public const int WS_DLGFRAME = 0x00400000;
public const int WS_VSCROLL = 0x00200000;
public const int WS_HSCROLL = 0x00100000;
public const int WS_SYSMENU = 0x00080000;
public const int WS_THICKFRAME = 0x00040000;
public const int WS_GROUP = 0x00020000;
public const int WS_TABSTOP = 0x00010000;
public const int WS_MINIMIZEBOX = 0x00020000;
public const int WS_MAXIMIZEBOX = 0x00010000;
#endregion // WINDOW STYLES
#region SHFILEOPERATION CONSTANTS
// SHFileOperation operations
public const int FO_MOVE = 0x0001;
public const int FO_COPY = 0x0002;
public const int FO_DELETE = 0x0003;
public const int FO_RENAME = 0x0004;
// SHFileOperation flags
/// <summary>
/// The pTo member specifies multiple destination files (one for each source file) rather than one directory where all source files are to be deposited.
/// </summary>
public const int FOF_MULTIDESTFILES = 0x0001;
/// <summary>
/// Not used.
/// </summary>
public const int FOF_CONFIRMMOUSE = 0x0002;
/// <summary>
/// Do not display a progress dialog box.
/// </summary>
public const int FOF_SILENT = 0x0004;
/// <summary>
/// Give the file being operated on a new name in a move, copy, or rename operation if a file with the target name already exists.
/// </summary>
public const int FOF_RENAMEONCOLLISION = 0x0008;
/// <summary>
/// Respond with "Yes to All" for any dialog box that is displayed.
/// </summary>
public const int FOF_NOCONFIRMATION = 0x0010;
/// <summary>
/// If FOF_RENAMEONCOLLISION is specified and any files were renamed, assign a name mapping object containing their old and new names to the hNameMappings member.
/// </summary>
public const int FOF_WANTMAPPINGHANDLE = 0x0020;
/// <summary>
/// Preserve undo information, if possible. Operations can be undone only from the same process that performed the original operation. If pFrom does not contain fully qualified path and file names, this flag is ignored.
/// </summary>
public const int FOF_ALLOWUNDO = 0x0040;
/// <summary>
/// Perform the operation on files only if a wildcard file name (*.*) is specified.
/// </summary>
public const int FOF_FILESONLY = 0x0080;
/// <summary>
/// Display a progress dialog box but do not show the file names.
/// </summary>
public const int FOF_SIMPLEPROGRESS = 0x0100;
/// <summary>
/// Do not confirm the creation of a new directory if the operation requires one to be created.
/// </summary>
public const int FOF_NOCONFIRMMKDIR = 0x0200;
/// <summary>
/// Do not display a user interface if an error occurs.
/// </summary>
public const int FOF_NOERRORUI = 0x0400;
/// <summary>
/// Version 4.71. Do not copy the security attributes of the file.
/// </summary>
public const int FOF_NOCOPYSECURITYATTRIBS = 0x0800;
#endregion SHFILEOPERATION CONSTANTS
//// ------------------------------------------------------------------
#region WIN32 API FUNCTIONS
#region CONSTANTS
public const string TOOLBARCLASSNAME = "ToolbarWindow32";
public const string REBARCLASSNAME = "ReBarWindow32";
public const string PROGRESSBARCLASSNAME = "msctls_progress32";
#endregion // CONSTANTS
#region CALLBACKS
/// <summary>
/// Hook callback delegate.
/// </summary>
/// <param name="nCode"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
/// <summary>
/// Time callback delegate.
/// </summary>
/// <param name="hWnd"></param>
/// <param name="uMsg"></param>
/// <param name="nIDEvent"></param>
/// <param name="dwTime"></param>
public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);
#endregion // CALLBACKS
#region KERNEL32.DLL FUNCTIONS
[DllImport("kernel32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int GetCurrentThreadId();
#endregion // KERNEL32.DLL FUNCTIONS
#region GDI32.DLL FUNCTIONS
[DllImport("gdi32.dll")]
static public extern bool StretchBlt(IntPtr hDCDest, int XOriginDest, int YOriginDest, int WidthDest, int HeightDest,
IntPtr hDCSrc, int XOriginScr, int YOriginSrc, int WidthScr, int HeightScr, uint Rop);
[DllImport("gdi32.dll")]
static public extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32.dll")]
static public extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int Width, int Heigth);
[DllImport("gdi32.dll")]
static public extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[DllImport("gdi32.dll")]
static public extern bool BitBlt(IntPtr hDCDest, int XOriginDest, int YOriginDest, int WidthDest, int HeightDest,
IntPtr hDCSrc, int XOriginScr, int YOriginSrc, uint Rop);
[DllImport("gdi32.dll")]
static public extern IntPtr DeleteDC(IntPtr hDC);
[DllImport("gdi32.dll")]
static public extern bool PatBlt(IntPtr hDC, int XLeft, int YLeft, int Width, int Height, uint Rop);
[DllImport("gdi32.dll")]
static public extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
static public extern uint GetPixel(IntPtr hDC, int XPos, int YPos);
[DllImport("gdi32.dll")]
static public extern int SetMapMode(IntPtr hDC, int fnMapMode);
[DllImport("gdi32.dll")]
static public extern int GetObjectType(IntPtr handle);
[DllImport("gdi32")]
public static extern IntPtr CreateDIBSection(IntPtr hdc, ref BITMAPINFO_FLAT bmi,
int iUsage, ref int ppvBits, IntPtr hSection, int dwOffset);
[DllImport("gdi32")]
public static extern int GetDIBits(IntPtr hDC, IntPtr hbm, int StartScan, int ScanLines, int lpBits, BITMAPINFOHEADER bmi, int usage);
[DllImport("gdi32")]
public static extern int GetDIBits(IntPtr hdc, IntPtr hbm, int StartScan, int ScanLines, int lpBits, ref BITMAPINFO_FLAT bmi, int usage);
[DllImport("gdi32")]
public static extern IntPtr GetPaletteEntries(IntPtr hpal, int iStartIndex, int nEntries, byte[] lppe);
[DllImport("gdi32")]
public static extern IntPtr GetSystemPaletteEntries(IntPtr hdc, int iStartIndex, int nEntries, byte[] lppe);
[DllImport("gdi32")]
public static extern uint SetDCBrushColor(IntPtr hdc, uint crColor);
[DllImport("gdi32")]
public static extern IntPtr CreateSolidBrush(uint crColor);
[DllImport("gdi32")]
public static extern int SetBkMode(IntPtr hDC, BackgroundMode mode);
#endregion // GDI32.DLL FUNCTIONS
#region USER32.DLL FUNCTIONS
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static public extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static public extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static public extern IntPtr GetDesktopWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static public extern bool ShowWindow(IntPtr hWnd, short State);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static public extern bool UpdateWindow(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static public extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static public extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int Width, int Height, uint flags);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static public extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static public extern bool CloseClipboard();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static public extern bool EmptyClipboard();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static public extern IntPtr SetClipboardData(uint Format, IntPtr hData);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static public extern bool GetMenuItemRect(IntPtr hWnd, IntPtr hMenu, uint Item, ref RECT rc);
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr GetParent(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam);
//[DllImport("user32.dll", CharSet=CharSet.Auto)]
//public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref RECT lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, ref RECT lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, ref POINT lParam);
/// <summary>
/// Win32 API SendMessage function.
/// </summary>
/// <param name="hWnd"></param>
/// <param name="msg"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
[DllImport("user32", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, POINT lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref TBBUTTON lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref TBBUTTONINFO lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref REBARBANDINFO lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref TVITEM lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref LVITEM lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref HDITEM lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref HD_HITTESTINFO hti);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr PostMessage(IntPtr hWnd, int msg, int wParam, int lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SetWindowsHookEx(int hookid, HookProc pfnhook, IntPtr hinst, int threadid);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool UnhookWindowsHookEx(IntPtr hhook);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr CallNextHookEx(IntPtr hhook, int code, IntPtr wparam, IntPtr lparam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public extern static int DrawText(IntPtr hdc, string lpString, int nCount, ref RECT lpRect, int uFormat);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public extern static IntPtr SetParent(IntPtr hChild, IntPtr hParent);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public extern static IntPtr GetDlgItem(IntPtr hDlg, int nControlID);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public extern static int GetClientRect(IntPtr hWnd, ref RECT rc);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public extern static int InvalidateRect(IntPtr hWnd, IntPtr rect, int bErase);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool WaitMessage();
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool PeekMessage(ref MSG msg, int hWnd, uint wFilterMin, uint wFilterMax, uint wFlag);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool GetMessage(ref MSG msg, int hWnd, uint wFilterMin, uint wFilterMax);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool TranslateMessage(ref MSG msg);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool DispatchMessage(ref MSG msg);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr LoadCursor(IntPtr hInstance, uint cursor);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SetCursor(IntPtr hCursor);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetFocus();
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool ReleaseCapture();
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr BeginPaint(IntPtr hWnd, ref PAINTSTRUCT ps);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool EndPaint(IntPtr hWnd, ref PAINTSTRUCT ps);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref POINT pptDst, ref SIZE psize, IntPtr hdcSrc, ref POINT pprSrc, Int32 crKey, ref BLENDFUNCTION pblend, Int32 dwFlags);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT pt);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool TrackMouseEvent(ref TRACKMOUSEEVENTS tme);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool redraw);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern ushort GetKeyState(int virtKey);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool MoveWindow(IntPtr hWnd, int x, int y, int width, int height, bool repaint);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetClassName(IntPtr hWnd, out STRINGBUFFER ClassName, int nMaxCount);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr hRegion, uint flags);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
/// <summary>
/// The MessageBeep function plays a waveform sound. The waveform
/// sound for each sound type is identified by an entry in the
/// registry.
/// </summary>
/// <param name="type">
/// Sound type, as identified by an entry in the registry.
/// This parameter can be one of the following values.<br/>
/// <table>
/// <tr>
/// <td>Value</td><td>Sound</td>
/// </tr>
/// <tr>
/// <td>-1</td>
/// <td>Simple beep. If the sound card is not available, the sound is generated using the speaker.</td>
/// </tr>
/// <tr>
/// <td>MB_ICONASTERISK</td>
/// <td>SystemAsterisk</td>
/// </tr>
/// <tr>
/// <td>MB_ICONEXCLAMATION</td>
/// <td>SystemExclamation</td>
/// </tr>
/// <tr>
/// <td>MB_ICONHAND</td>
/// <td>SystemHand</td>
/// </tr>
/// <tr>
/// <td>MB_ICONQUESTION</td>
/// <td>SystemQuestion</td>
/// </tr>
/// <tr>
/// <td>MB_OK</td>
/// <td>SystemDefault</td>
/// </tr>
/// </table>
/// </param>
[DllImport("user32.dll")]
public static extern int MessageBeep(int type);
/// <summary>
/// The MessageBox function creates, displays, and operates a message box.
/// The message box contains an application-defined message and title,
/// plus any combination of predefined icons and push buttons.
/// <br/>
/// See SKD Documentation for more information.
/// </summary>
/// <param name="hWndParent">handle to owner window</param>
/// <param name="text">text in message box</param>
/// <param name="caption">message box title</param>
/// <param name="type">message box style</param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern int MessageBox(IntPtr hWndParent,
string text, string caption, int type);
/// <summary>
/// The CreateWindowEx function creates an overlapped, pop-up, or child
/// window with an extended window style; otherwise, this function is
/// identical to the CreateWindow function. For more information about
/// creating a window and for full descriptions of the other parameters
/// see the SDk documentation.
/// </summary>
/// <param name="dwExStyle">extended window style</param>
/// <param name="lpClassName">registered class name</param>
/// <param name="lpWindowName">window name</param>
/// <param name="dwStyle">window style</param>
/// <param name="x">horizontal position of window</param>
/// <param name="y">vertical position of window</param>
/// <param name="nWidth">window width</param>
/// <param name="nHeight">window height</param>
/// <param name="hWndParent">handle to parent or owner window</param>
/// <param name="hMenu">menu handle or child identifier</param>
/// <param name="hInstance">handle to application instance</param>
/// <param name="lpParam">window-creation data</param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern IntPtr CreateWindowEx(uint dwExStyle,
string lpClassName, string lpWindowName, uint dwStyle,
int x, int y, int nWidth, int nHeight, IntPtr hWndParent,
IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
/// <summary>
/// Gets the sroll range of the given window.
/// </summary>
/// <param name="hWnd"></param>
/// <param name="nBar"></param>
/// <param name="lpMinPos"></param>
/// <param name="lpMaxPos"></param>
/// <returns></returns>
[DllImport("user32", CharSet = CharSet.Auto)]
public static extern bool GetScrollRange(IntPtr hWnd, int nBar,
out int lpMinPos, out int lpMaxPos);
[DllImport("User32.dll")]
public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent,
uint uElapse, TimerProc lpTimerFunc);
[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern void CreateCaret(IntPtr hwnd, System.Drawing.Bitmap bmp,
int nWidth, int nHeight);
[DllImport("user32.dll")]
public static extern int CreateCaret(IntPtr hwnd, IntPtr hbm,
int cx, int cy);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern void CreateCaret(IntPtr hwnd, int dummy,
int nWidth, int nHeight);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool DestroyCaret();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool ShowCaret(IntPtr hwnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool HideCaret(IntPtr hwnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool SetCaretPos(int x, int y);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool GetCaretPos(ref int pos);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool SetCaretBlinkTime(int nMSeconds);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int GetCaretBlinkTime();
#endregion // USER32.DLL FUNCTIONS
#region COMMON CONTROLS FUNCTIONS
[DllImport("comctl32.dll")]
public static extern bool InitCommonControlsEx(INITCOMMONCONTROLSEX icc);
[DllImport("comctl32.dll", EntryPoint = "DllGetVersion")]
public extern static int GetCommonControlDLLVersion(ref DLLVERSIONINFO dvi);
#endregion // COMMON CONTROLS FUNCTIONS
#region SHELL32.DLL FUNCTIONS
/// <summary>
/// Copies, moves, renames, or deletes a file system object.
/// </summary>
/// <param name="lpFileOperationData">
/// [in] Pointer to an SHFILEOPSTRUCT structure that contains information
/// this function needs to carry out the specified operation. This
/// parameter must contain a valid value that is not NULL. You are
/// responsibile for validating the value. If you do not validate it,
/// you will experience unexpected results.
/// </param>
/// <returns>
/// Returns zero if successful, or nonzero otherwise.
/// </returns>
[DllImport("shell32.Dll", CharSet = CharSet.Auto)]
public static extern Int32 SHFileOperation(ref SHFILEOPSTRUCT lpFileOperationData);
[DllImport("shell32.dll", EntryPoint = "ExtractIconA",
CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr ExtractIcon
(int hInst, string lpszExeFileName, int nIconIndex);
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern int ExtractIconEx(string stExeFileName,
int nIconIndex, ref IntPtr phiconLarge, ref IntPtr phiconSmall, int nIcons);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public extern static bool DestroyIcon(IntPtr handle);
[DllImport("shfolder.dll", CharSet = CharSet.Auto)]
internal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder,
IntPtr hToken, int dwFlags, StringBuilder lpszPath);
#endregion // SHELL32.DLL FUNCTIONS
#endregion // WIN32 API FUNCTIONS
#pragma warning restore 1591
} // Win32Api
} // Tethys
// ==========================
// Tethys: end of win32api.cs
// ==========================
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
using Microsoft.Research.ClousotRegression;
[assembly: RegressionOutcome("Detected call to method 'System.Object.Equals(System.Object)' without [Pure] in contracts of method 'OldTests.GenericWithOld`1.Set(type parameter.T)'.")]
namespace OldTests
{
class FibonacciHeapCell
{
FibonacciHeapCell mParent;
internal FibonacciHeapLinkedList Children { get; set; }
internal FibonacciHeapCell Parent
{
get
{
Contract.Ensures(Contract.Result<FibonacciHeapCell>() == null || Contract.Result<FibonacciHeapCell>().Children != null); //Commented out because nowhere picks up this contract
return mParent;
}
set
{
mParent = value;
}
}
internal FibonacciHeapCell Next { get; set; }
internal FibonacciHeapCell Previous { get; set; }
internal int Count { get; set; }
}
class FibonacciHeapLinkedList
{
internal void AddLast(FibonacciHeapCell Node)
{
Contract.Requires(Node.Previous == null);
Contract.Requires(Node.Count <= 0); // Add this to test old in numerical domains
}
internal void Remove(FibonacciHeapCell Node)
{
Contract.Requires<ArgumentNullException>(Node != null);
Contract.Ensures(Node.Next == null);
Contract.Ensures(Node.Previous == null);
Contract.Ensures(Node.Count <= 0);
Node.Next = null;
Node.Previous = null;
}
}
class Roy
{
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 41, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 52, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 59, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 82, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 89, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 8, MethodILOffset = 52)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 67, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 10, MethodILOffset = 82)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 28, MethodILOffset = 82)]
private static void BadTest(FibonacciHeapCell Node, FibonacciHeapLinkedList children, FibonacciHeapLinkedList others)
{
Contract.Requires<ArgumentNullException>(Node != null);
Contract.Requires<ArgumentNullException>(children != null);
Contract.Requires<ArgumentNullException>(others != null);
var parentNode = Node.Parent;
while (parentNode != null)
{
children.Remove(parentNode);
Contract.Assert(parentNode.Previous == null);
UpdateNodesDegree(parentNode);
others.AddLast(parentNode);
parentNode = parentNode.Parent;
}
}
private static void UpdateNodesDegree(FibonacciHeapCell parentNode)
{
Contract.Ensures(parentNode.Previous == Contract.OldValue(parentNode.Previous));
Contract.Ensures(parentNode.Next == Contract.OldValue(parentNode.Next));
Contract.Ensures(parentNode.Count == Contract.OldValue(parentNode.Count));
}
}
public class NestedOldTest
{
public struct A
{
public B b;
}
public struct B
{
public C c;
}
public struct C
{
public int x;
}
[Pure]
static int GetX(A a)
{
Contract.Ensures(Contract.Result<int>() == Contract.OldValue(a.b.c.x));
int x = a.b.c.x;
return x;
}
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 24, MethodILOffset = 45)]
static int Test(ref A a)
{
Contract.Ensures(Contract.Result<int>() == Contract.OldValue(GetX(a)));
return GetX(a);
}
}
public class CallOnStructWithinOldTest {
public struct T
{
public int Y { get; set; }
}
public struct S
{
public int X { get; set; }
private T t;
public T T
{
get { return this.t; }
set { this.t = value; }
}
}
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 48, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 56, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 64, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 27, MethodILOffset = 73)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"ensures unproven: s.X > 0", PrimaryILOffset = 11, MethodILOffset = 73)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 39, MethodILOffset = 73)]
static int Test(S s)
{
Contract.Ensures(s.X > 0); // wrong and useless, but should work and not crash
Contract.Ensures(s.T.Y == Contract.Result<int>());
s.X = 5;
return s.T.Y;
}
}
class AccountExample
{
public int Balance { get; private set; }
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 40, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 47, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 12, MethodILOffset = 53)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 32, MethodILOffset = 53)]
public void Deposit(int amount)
{
Contract.Requires(amount > 0);
Contract.Ensures(Balance == Contract.OldValue(Balance) + amount);
Balance = Balance + amount;
}
}
class GenericWithOld<T>
{
public T Field;
// TODO: support Equals in contracts
public void Set(T value)
{
Contract.Ensures(this.Field.Equals(value));
Field = value;
}
}
class TestGenericInstanceWithOld
{
// TODO, once we support equals, this should work
public static void Test1()
{
var v = new GenericWithOld<string>();
var x = "foo";
v.Set(x);
Contract.Assert(v.Field == x);
}
struct S
{
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 43, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 50, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 15, MethodILOffset = 55)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 35, MethodILOffset = 55)]
public S(int a, int b)
{
Contract.Ensures(Contract.ValueAtReturn(out this.x) == a);
Contract.Ensures(Contract.ValueAtReturn(out this.y) == b);
this.x = a;
this.y = b;
}
public int x;
public int y;
}
// TODO, once we support Equals, this should pass
public static void Test2()
{
var v = new GenericWithOld<S>();
var s = new S(5,6);
Contract.Assert(s.x == 5);
v.Set(s);
Contract.Assert(v.Field.y == 6);
}
}
}
namespace OldScopeInference
{
struct S
{
public int X;
}
class OldWithoutEnd
{
/// <summary>
/// Tests an issue with oldscope inference in ensures with ldarga. In this example, there is no actual memory
/// access happening in the old state. Still, we need to end the old scope. We now do so at any instructions
/// other than nop and ldflda.
/// </summary>
/// <param name="s"></param>
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 16, MethodILOffset = 22)]
unsafe public static void Test(S s)
{
Contract.Ensures(&s.X != null);
}
[Pure]
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 23, MethodILOffset = 42)]
public static bool Predicate1(int data, ref S s)
{
Contract.Ensures(Contract.Result<bool>() || data != s.X);
return data == s.X;
}
[Pure]
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 42, MethodILOffset = 61)]
public static bool Predicate2(ref S s, int data)
{
Contract.Ensures(Contract.Result<bool>() && data == s.X || !Contract.Result<bool>() && data != s.X);
return data == s.X;
}
/// <summary>
/// This is a weird case, where we want to refer to the pre state of s, in the post condition.
/// However, s is only dereferenced in WeirdMethod, and we cannot wrap old around that.
/// What happens is that WeirdMethod gets evaluated in the new state because, and thus we effectively
/// read the post state of s. Thus the ensures fails, even though it should succeed.
/// </summary>
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 38, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 29, MethodILOffset = 48)]
unsafe public static int WeirdPost1(S s)
{
Contract.Requires(s.X == 0);
Contract.Ensures(Predicate1(Contract.Result<int>(), ref s)); // should be valid
s.X = 5;
return 0;
}
/// <summary>
/// Like WeirdPost1, showing that indeed we evaluate s.X in the post state.
/// The parameter order of Predicate2 should not matter
/// </summary>
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 22, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"ensures unproven: Predicate2(ref s, Contract.Result<int>())", PrimaryILOffset = 13, MethodILOffset = 32)]
unsafe public static int WeirdPost2(S s)
{
Contract.Ensures(Predicate2(ref s, Contract.Result<int>())); // should not be valid!
s.X = 0;
return 0;
}
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 18, MethodILOffset = 0)]
public static void Caller1(S s)
{
int result = WeirdPost2(s);
Contract.Assert(result == s.X); // can't prove it due to our handling of struct copies and the weird by-ref predicate
}
}
}
| |
//#define DATETIME_AS_TIMESTAMPS
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace LunarLabs.Parser
{
public enum NodeKind
{
Unknown,
Object,
Array,
String,
Numeric,
Boolean,
Null
}
public class DataNode: IEnumerable<DataNode>
{
protected List<DataNode> _children = new List<DataNode>();
public IEnumerable<DataNode> Children { get { return _children; } }
public DataNode Parent { get; private set; }
public int ChildCount { get { return _children.Count; } }
public bool HasChildren { get { return _children.Count > 0; } }
public string Name { get; set; }
public string Value { get; set; }
public NodeKind Kind { get; private set; }
private DataNode(NodeKind kind, string name = null, string value = null)
{
this.Kind = kind;
this.Parent = null;
this.Name = name;
this.Value = value;
}
public IEnumerator<DataNode> GetEnumerator()
{
return _children.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _children.GetEnumerator();
}
public DataNode this[string name]
{
get { return GetNode(name); }
}
public DataNode this[int index]
{
get { return GetNodeByIndex(index); }
}
public static DataNode CreateObject(string name = null)
{
return new DataNode(NodeKind.Object, name);
}
public static DataNode CreateArray(string name = null)
{
return new DataNode(NodeKind.Array, name);
}
public static DataNode CreateValue(object value)
{
NodeKind kind;
var val = ConvertValue(value, out kind);
return new DataNode(kind, null, val);
}
public override string ToString()
{
if (this.ChildCount == 0 && !string.IsNullOrEmpty(this.Value))
{
return this.Value;
}
if (!string.IsNullOrEmpty(Name))
{
return $"{Name}";
}
if (this.Parent == null)
{
return "[Root]";
}
return "[Null]";
}
public DataNode AddNode(DataNode node)
{
if (node == null)
{
return null;
}
this._children.Add(node);
node.Parent = this;
return node;
}
private static readonly long epochTicks = new DateTime(1970, 1, 1).Ticks;
public DataNode AddValue(object value)
{
return AddField(null, value);
}
public DataNode AddField(string name, object value)
{
if (this.Kind != NodeKind.Array && this.Kind != NodeKind.Object)
{
throw new Exception("The kind of this node is not 'object'!");
}
if (value is DataNode)
{
throw new Exception("Cannot add a node as a field!");
}
NodeKind kind;
string val = ConvertValue(value, out kind);
var child = new DataNode(kind, name, val);
this.AddNode(child);
return child;
}
#if DATETIME_AS_TIMESTAMPS
internal static DateTime FromTimestamp(long unixTimeStamp)
{
// Unix timestamp is seconds past epoch
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
return dtDateTime;
}
internal static long ToTimestamp(DateTime value)
{
long epoch = (value.Ticks - 621355968000000000) / 10000000;
return epoch;
}
#endif
private static string ConvertValue(object value, out NodeKind kind)
{
if (value == null)
{
kind = NodeKind.Null;
return "";
}
string val;
#if DATETIME_AS_TIMESTAMPS
// convert dates to unix timestamps
if (value.GetType() == typeof(DateTime))
{
val = ToTimestamp(((DateTime)value)).ToString();
kind = NodeKind.Numeric;
}
else
#endif
if (value is int)
{
val = ((int)value).ToString(CultureInfo.InvariantCulture);
kind = NodeKind.Numeric;
}
else
if (value is uint)
{
val = ((uint)value).ToString(CultureInfo.InvariantCulture);
kind = NodeKind.Numeric;
}
else
if (value is long)
{
val = ((long)value).ToString(CultureInfo.InvariantCulture);
kind = NodeKind.Numeric;
}
else
if (value is ulong)
{
val = ((ulong)value).ToString(CultureInfo.InvariantCulture);
kind = NodeKind.Numeric;
}
else
if (value is byte)
{
val = ((byte)value).ToString(CultureInfo.InvariantCulture);
kind = NodeKind.Numeric;
}
else
if (value is sbyte)
{
val = ((sbyte)value).ToString(CultureInfo.InvariantCulture);
kind = NodeKind.Numeric;
}
else
if (value is short)
{
val = ((short)value).ToString(CultureInfo.InvariantCulture);
kind = NodeKind.Numeric;
}
else
if (value is ushort)
{
val = ((ushort)value).ToString(CultureInfo.InvariantCulture);
kind = NodeKind.Numeric;
}
else
if (value is float)
{
val = ((float)value).ToString(CultureInfo.InvariantCulture);
kind = NodeKind.Numeric;
}
else
if (value is double)
{
val = ((double)value).ToString(CultureInfo.InvariantCulture);
kind = NodeKind.Numeric;
}
else
if (value is decimal)
{
val = ((decimal)value).ToString(CultureInfo.InvariantCulture);
kind = NodeKind.Numeric;
}
else
if (value is bool)
{
val = ((bool)value)?"true":"false";
kind = NodeKind.Boolean;
}
else
{
val = value.ToString();
kind = NodeKind.String;
}
return val;
}
public bool HasNode(string name, int index = 0)
{
return GetNode(name, index) != null;
}
// internal auxiliary
private DataNode FindNode(string name, int ndepth, int maxdepth)
{
if (String.Compare(this.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
{
return this;
}
if (ndepth >= maxdepth)
{
return null;
}
foreach (DataNode child in _children)
{
DataNode n = child.FindNode(name, ndepth + 1, maxdepth);
if (n != null)
{
return n;
}
}
return null;
}
public DataNode FindNode(string name, int maxdepth = 0)
{
return FindNode(name, 0, maxdepth > 0 ? maxdepth : int.MaxValue);
}
public DataNode GetNode(string name, int index = 0)
{
int n = 0;
foreach (DataNode child in _children)
{
if (String.Compare(child.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
{
if (n >= index)
{
return child;
}
else
{
n++;
}
}
}
return null;
}
public DataNode GetNodeByIndex(int index)
{
if (index < 0 || index >= _children.Count)
{
return null;
}
return _children[index];
}
#region LONG
public long AsLong(long defaultValue = 0)
{
long result = defaultValue;
if (long.TryParse(this.Value, out result))
return result;
return defaultValue;
}
public long GetLong(string name, long defaultValue = 0)
{
DataNode node = this.GetNode(name);
if (node != null)
{
return node.AsLong(defaultValue);
}
return defaultValue;
}
public long GetLong(int index, long defaultValue = 0)
{
DataNode node = this.GetNodeByIndex(index);
if (node != null)
{
return node.AsLong(defaultValue);
}
return defaultValue;
}
#endregion
#region INT32
public int AsInt32(int defaultValue = 0)
{
int result = defaultValue;
if (int.TryParse(this.Value, out result))
return result;
return defaultValue;
}
public int GetInt32(string name, int defaultValue = 0)
{
DataNode node = this.GetNode(name);
if (node != null)
{
return node.AsInt32(defaultValue);
}
return defaultValue;
}
public int GetInt32(int index, int defaultValue = 0)
{
DataNode node = this.GetNodeByIndex(index);
if (node != null)
{
return node.AsInt32(defaultValue);
}
return defaultValue;
}
#endregion
#region UINT32
public uint AsUInt32(uint defaultValue = 0)
{
uint result = defaultValue;
if (uint.TryParse(this.Value, out result))
return result;
return defaultValue;
}
public uint GetUInt32(string name, uint defaultValue = 0)
{
DataNode node = this.GetNode(name);
if (node != null)
{
return node.AsUInt32(defaultValue);
}
return defaultValue;
}
#endregion
#region BYTE
public byte AsByte(byte defaultValue = 0)
{
byte result = defaultValue;
if (byte.TryParse(this.Value, out result))
return result;
return defaultValue;
}
public byte GetByte(string name, byte defaultValue = 0)
{
DataNode node = this.GetNode(name);
if (node != null)
{
return node.AsByte(defaultValue);
}
return defaultValue;
}
public byte GetByte(int index, byte defaultValue = 0)
{
DataNode node = this.GetNodeByIndex(index);
if (node != null)
{
return node.AsByte(defaultValue);
}
return defaultValue;
}
#endregion
#region SBYTE
public sbyte AsSByte(sbyte defaultValue = 0)
{
sbyte result = defaultValue;
if (sbyte.TryParse(this.Value, out result))
return result;
return defaultValue;
}
public sbyte GetSByte(string name, sbyte defaultValue = 0)
{
DataNode node = this.GetNode(name);
if (node != null)
{
return node.AsSByte(defaultValue);
}
return defaultValue;
}
public sbyte GetSByte(int index, sbyte defaultValue = 0)
{
DataNode node = this.GetNodeByIndex(index);
if (node != null)
{
return node.AsSByte(defaultValue);
}
return defaultValue;
}
#endregion
#region ENUM
public T AsEnum<T>(T defaultValue = default(T)) where T : IConvertible
{
try
{
return (T)Enum.Parse(typeof(T), this.Value, /* ignorecase */ true);
}
catch (Exception)
{
int result = 0;
if (int.TryParse(this.Value, out result))
{
return (T)(object)result;
}
}
return defaultValue;
}
public T GetEnum<T>(string name, T defaultValue = default(T)) where T : IConvertible
{
DataNode node = this.GetNode(name);
if (node != null)
{
return node.AsEnum<T>(defaultValue);
}
return defaultValue;
}
public T GetEnum<T>(int index, T defaultValue = default(T)) where T : IConvertible
{
DataNode node = this.GetNodeByIndex(index);
if (node != null)
{
return node.AsEnum<T>(defaultValue);
}
return defaultValue;
}
#endregion
#region BOOL
public bool AsBool(bool defaultValue = false)
{
if (this.Value.Equals("1") || string.Equals(this.Value, "true", StringComparison.CurrentCultureIgnoreCase))
{
return true;
}
if (this.Value.Equals("0") || string.Equals(this.Value, "false", StringComparison.CurrentCultureIgnoreCase))
{
return false;
}
return defaultValue;
}
public bool GetBool(string name, bool defaultValue = false)
{
DataNode node = this.GetNode(name);
if (node != null)
{
return node.AsBool(defaultValue);
}
return defaultValue;
}
public bool GetBool(int index, bool defaultValue = false)
{
DataNode node = this.GetNodeByIndex(index);
if (node != null)
{
return node.AsBool(defaultValue);
}
return defaultValue;
}
#endregion
#region FLOAT
public float AsFloat(float defaultValue = 0)
{
float result = defaultValue;
if (float.TryParse(this.Value, NumberStyles.Number, CultureInfo.InvariantCulture.NumberFormat, out result))
{
return result;
}
return defaultValue;
}
public float GetFloat(string name, float defaultValue = 0)
{
DataNode node = this.GetNode(name);
if (node != null)
{
return node.AsFloat(defaultValue);
}
return defaultValue;
}
public float GetFloat(int index, float defaultValue = 0)
{
DataNode node = this.GetNodeByIndex(index);
if (node != null)
{
return node.AsFloat(defaultValue);
}
return defaultValue;
}
#endregion
#region DOUBLE
public double AsDouble(double defaultValue = 0)
{
double result = defaultValue;
if (double.TryParse(this.Value, NumberStyles.Number, CultureInfo.InvariantCulture.NumberFormat, out result))
{
return result;
}
return defaultValue;
}
public double GetDouble(string name, double defaultValue = 0)
{
DataNode node = this.GetNode(name);
if (node != null)
{
return node.AsDouble(defaultValue);
}
return defaultValue;
}
public double GetDouble(int index, double defaultValue = 0)
{
DataNode node = this.GetNodeByIndex(index);
if (node != null)
{
return node.AsDouble(defaultValue);
}
return defaultValue;
}
#endregion
#region DECIMAL
public Decimal AsDecimal(decimal defaultValue = 0)
{
decimal result = defaultValue;
if (decimal.TryParse(this.Value, NumberStyles.Number | NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture.NumberFormat, out result))
{
return result;
}
return defaultValue;
}
public Decimal GetDecimal(string name, decimal defaultValue = 0)
{
DataNode node = this.GetNode(name);
if (node != null)
{
return node.AsDecimal(defaultValue);
}
return defaultValue;
}
public Decimal GetDecimal(int index, decimal defaultValue = 0)
{
DataNode node = this.GetNodeByIndex(index);
if (node != null)
{
return node.AsDecimal(defaultValue);
}
return defaultValue;
}
#endregion
#region STRING
public string AsString(string defaultValue = "")
{
if (this.Value != null)
return this.Value;
return defaultValue;
}
public string GetString(string name, string defaultValue = "")
{
DataNode node = this.GetNode(name);
if (node != null)
{
return node.Value;
}
return defaultValue;
}
public string GetString(int index, string defaultValue = "")
{
DataNode node = this.GetNodeByIndex(index);
if (node != null)
{
return node.Value;
}
return defaultValue;
}
#endregion
#region DATETIME
public DateTime AsDateTime(DateTime defaultValue = default(DateTime))
{
#if DATETIME_AS_TIMESTAMPS
long ticks;
if (long.TryParse(this.Value, out ticks))
{
return FromTimestamp(ticks);
}
#endif
DateTime result;
if (DateTime.TryParse(this.Value, out result))
{
return result;
}
return defaultValue;
}
public DateTime GetDateTime(string name, DateTime defaultValue = default(DateTime))
{
DataNode node = this.GetNode(name);
if (node != null)
{
return node.AsDateTime(defaultValue);
}
return defaultValue;
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using TermDocs = Lucene.Net.Index.TermDocs;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
using IDFExplanation = Lucene.Net.Search.Explanation.IDFExplanation;
namespace Lucene.Net.Search
{
/// <summary>A Query that matches documents containing a term.
/// This may be combined with other terms with a {@link BooleanQuery}.
/// </summary>
[Serializable]
public class TermQuery:Query
{
private Term term;
[Serializable]
private class TermWeight:Weight
{
private void InitBlock(TermQuery enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private TermQuery enclosingInstance;
public TermQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private Similarity similarity;
private float value_Renamed;
private float idf;
private float queryNorm;
private float queryWeight;
private IDFExplanation idfExp;
public TermWeight(TermQuery enclosingInstance, Searcher searcher)
{
InitBlock(enclosingInstance);
this.similarity = Enclosing_Instance.GetSimilarity(searcher);
idfExp = similarity.IdfExplain(Enclosing_Instance.term, searcher);
idf = idfExp.GetIdf();
}
public override System.String ToString()
{
return "weight(" + Enclosing_Instance + ")";
}
public override Query GetQuery()
{
return Enclosing_Instance;
}
public override float GetValue()
{
return value_Renamed;
}
public override float SumOfSquaredWeights()
{
queryWeight = idf * Enclosing_Instance.GetBoost(); // compute query weight
return queryWeight * queryWeight; // square it
}
public override void Normalize(float queryNorm)
{
this.queryNorm = queryNorm;
queryWeight *= queryNorm; // normalize query weight
value_Renamed = queryWeight * idf; // idf for document
}
public override Scorer Scorer(IndexReader reader, bool scoreDocsInOrder, bool topScorer)
{
TermDocs termDocs = reader.TermDocs(Enclosing_Instance.term);
if (termDocs == null)
return null;
return new TermScorer(this, termDocs, similarity, reader.Norms(Enclosing_Instance.term.Field()));
}
public override Explanation Explain(IndexReader reader, int doc)
{
ComplexExplanation result = new ComplexExplanation();
result.SetDescription("weight(" + GetQuery() + " in " + doc + "), product of:");
Explanation expl = new Explanation(idf, idfExp.Explain());
// explain query weight
Explanation queryExpl = new Explanation();
queryExpl.SetDescription("queryWeight(" + GetQuery() + "), product of:");
Explanation boostExpl = new Explanation(Enclosing_Instance.GetBoost(), "boost");
if (Enclosing_Instance.GetBoost() != 1.0f)
queryExpl.AddDetail(boostExpl);
queryExpl.AddDetail(expl);
Explanation queryNormExpl = new Explanation(queryNorm, "queryNorm");
queryExpl.AddDetail(queryNormExpl);
queryExpl.SetValue(boostExpl.GetValue() * expl.GetValue() * queryNormExpl.GetValue());
result.AddDetail(queryExpl);
// explain field weight
System.String field = Enclosing_Instance.term.Field();
ComplexExplanation fieldExpl = new ComplexExplanation();
fieldExpl.SetDescription("fieldWeight(" + Enclosing_Instance.term + " in " + doc + "), product of:");
Explanation tfExpl = Scorer(reader, true, false).Explain(doc);
fieldExpl.AddDetail(tfExpl);
fieldExpl.AddDetail(expl);
Explanation fieldNormExpl = new Explanation();
byte[] fieldNorms = reader.Norms(field);
float fieldNorm = fieldNorms != null?Similarity.DecodeNorm(fieldNorms[doc]):1.0f;
fieldNormExpl.SetValue(fieldNorm);
fieldNormExpl.SetDescription("fieldNorm(field=" + field + ", doc=" + doc + ")");
fieldExpl.AddDetail(fieldNormExpl);
fieldExpl.SetMatch(tfExpl.IsMatch());
fieldExpl.SetValue(tfExpl.GetValue() * expl.GetValue() * fieldNormExpl.GetValue());
result.AddDetail(fieldExpl);
System.Boolean? tempAux = fieldExpl.GetMatch();
result.SetMatch(tempAux);
// combine them
result.SetValue(queryExpl.GetValue() * fieldExpl.GetValue());
if (queryExpl.GetValue() == 1.0f)
return fieldExpl;
return result;
}
}
/// <summary>Constructs a query for the term <code>t</code>. </summary>
public TermQuery(Term t)
{
term = t;
}
/// <summary>Returns the term of this query. </summary>
public virtual Term GetTerm()
{
return term;
}
public override Weight CreateWeight(Searcher searcher)
{
return new TermWeight(this, searcher);
}
public override void ExtractTerms(System.Collections.Hashtable terms)
{
SupportClass.CollectionsHelper.AddIfNotContains(terms, GetTerm());
}
/// <summary>Prints a user-readable version of this query. </summary>
public override System.String ToString(System.String field)
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
if (!term.Field().Equals(field))
{
buffer.Append(term.Field());
buffer.Append(":");
}
buffer.Append(term.Text());
buffer.Append(ToStringUtils.Boost(GetBoost()));
return buffer.ToString();
}
/// <summary>Returns true iff <code>o</code> is equal to this. </summary>
public override bool Equals(System.Object o)
{
if (!(o is TermQuery))
return false;
TermQuery other = (TermQuery) o;
return (this.GetBoost() == other.GetBoost()) && this.term.Equals(other.term);
}
/// <summary>Returns a hash code value for this object.</summary>
public override int GetHashCode()
{
return BitConverter.ToInt32(BitConverter.GetBytes(GetBoost()), 0) ^ term.GetHashCode();
}
}
}
| |
namespace Nancy.Routing.Trie.Nodes
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A base class representing a node in the route trie
/// </summary>
public abstract class TrieNode
{
private readonly ITrieNodeFactory nodeFactory;
/// <summary>
/// Gets or sets the parent node
/// </summary>
public TrieNode Parent { get; protected set; }
/// <summary>
/// Gets or sets the segment from the route definition that this node represents
/// </summary>
public string RouteDefinitionSegment { get; protected set; }
/// <summary>
/// Gets or sets the children of this node
/// </summary>
public IDictionary<string, TrieNode> Children { get; protected set; }
/// <summary>
/// Gets or sets the node data stored at this node, which will be converted
/// into the <see cref="MatchResult"/> if a match is found
/// </summary>
public IList<NodeData> NodeData { get; protected set; }
/// <summary>
/// Additional parameters to set that can be determined at trie build time
/// </summary>
public IDictionary<string, object> AdditionalParameters { get; protected set; }
/// <summary>
/// Score for this node
/// </summary>
public abstract int Score { get; }
/// <summary>
/// Initializes a new instance of the <see cref="TrieNode"/> class
/// </summary>
/// <param name="parent">Parent node</param>
/// <param name="segment">Segment of the route definition</param>
/// <param name="nodeFactory">Factory for creating new nodes</param>
protected TrieNode(TrieNode parent, string segment, ITrieNodeFactory nodeFactory)
{
this.nodeFactory = nodeFactory;
this.Parent = parent;
this.RouteDefinitionSegment = segment;
this.Children = new Dictionary<string, TrieNode>();
this.AdditionalParameters = new Dictionary<string, object>();
this.NodeData = new List<NodeData>();
}
/// <summary>
/// Add a new route to the trie
/// </summary>
/// <param name="segments">The segments of the route definition</param>
/// <param name="moduleType">The module key the route comes from</param>
/// <param name="routeIndex">The route index in the module</param>
/// <param name="routeDescription">The route description</param>
public void Add(string[] segments, Type moduleType, int routeIndex, RouteDescription routeDescription)
{
this.Add(segments, -1, 0, 0, moduleType, routeIndex, routeDescription);
}
/// <summary>
/// Add a new route to the trie
/// </summary>
/// <param name="segments">The segments of the route definition</param>
/// <param name="currentIndex">Current index in the segments array</param>
/// <param name="currentScore">Current score for this route</param>
/// <param name="nodeCount">Number of nodes added for this route</param>
/// <param name="moduleType">The module key the route comes from</param>
/// <param name="routeIndex">The route index in the module</param>
/// <param name="routeDescription">The route description</param>
public virtual void Add(string[] segments, int currentIndex, int currentScore, int nodeCount, Type moduleType, int routeIndex, RouteDescription routeDescription)
{
if (this.NoMoreSegments(segments, currentIndex))
{
this.NodeData.Add(this.BuildNodeData(nodeCount, currentScore + this.Score, moduleType, routeIndex, routeDescription));
return;
}
nodeCount++;
currentIndex++;
TrieNode child;
if (!this.Children.TryGetValue(segments[currentIndex], out child))
{
child = this.nodeFactory.GetNodeForSegment(this, segments[currentIndex]);
this.Children.Add(segments[currentIndex], child);
}
child.Add(segments, currentIndex, currentScore + this.Score, nodeCount, moduleType, routeIndex, routeDescription);
}
/// <summary>
/// Gets all matches for a given requested route
/// </summary>
/// <param name="segments">Requested route segments</param>
/// <param name="context">Current Nancy context</param>
/// <returns>A collection of <see cref="MatchResult"/> objects</returns>
public virtual IEnumerable<MatchResult> GetMatches(string[] segments, NancyContext context)
{
return this.GetMatches(segments, 0, new Dictionary<string, object>(this.AdditionalParameters), context);
}
/// <summary>
/// Gets all matches for a given requested route
/// </summary>
/// <param name="segments">Requested route segments</param>
/// <param name="currentIndex">Current index in the route segments</param>
/// <param name="capturedParameters">Currently captured parameters</param>
/// <param name="context">Current Nancy context</param>
/// <returns>A collection of <see cref="MatchResult"/> objects</returns>
public virtual IEnumerable<MatchResult> GetMatches(string[] segments, int currentIndex, IDictionary<string, object> capturedParameters, NancyContext context)
{
var segmentMatch = this.Match(segments[currentIndex]);
if (segmentMatch == SegmentMatch.NoMatch)
{
return MatchResult.NoMatches;
}
if (this.NoMoreSegments(segments, currentIndex))
{
return this.BuildResults(capturedParameters, segmentMatch.CapturedParameters) ?? MatchResult.NoMatches;
}
currentIndex++;
return this.GetMatchingChildren(segments, currentIndex, capturedParameters, segmentMatch.CapturedParameters, context);
}
/// <summary>
/// Gets a string representation of all routes
/// </summary>
/// <returns>Collection of strings, each representing a route</returns>
public virtual IEnumerable<string> GetRoutes()
{
var routeList = new List<string>(this.Children.Values.SelectMany(c => c.GetRoutes())
.Select(s => (this.RouteDefinitionSegment ?? string.Empty) + "/" + s));
if (this.NodeData.Any())
{
var node = this.NodeData.First();
var resultData = string.Format("{0} (Segments: {1} Score: {2})", this.RouteDefinitionSegment ?? "/", node.RouteLength, node.Score);
routeList.Add(resultData);
}
return routeList;
}
/// <summary>
/// Build the node data that will be used to create the <see cref="MatchResult"/>
/// We calculate/store as much as possible at build time to reduce match time.
/// </summary>
/// <param name="nodeCount">Number of nodes in the route</param>
/// <param name="score">Score for the route</param>
/// <param name="moduleType">The module key the route comes from</param>
/// <param name="routeIndex">The route index in the module</param>
/// <param name="routeDescription">The route description</param>
/// <returns>A NodeData instance</returns>
protected virtual NodeData BuildNodeData(int nodeCount, int score, Type moduleType, int routeIndex, RouteDescription routeDescription)
{
return new NodeData
{
Method = routeDescription.Method,
RouteIndex = routeIndex,
RouteLength = nodeCount,
Score = score,
Condition = routeDescription.Condition,
ModuleType = moduleType,
};
}
/// <summary>
/// Returns whether we are at the end of the segments
/// </summary>
/// <param name="segments">Route segments</param>
/// <param name="currentIndex">Current index</param>
/// <returns>True if no more segments left, false otherwise</returns>
protected bool NoMoreSegments(string[] segments, int currentIndex)
{
return currentIndex >= segments.Length - 1;
}
/// <summary>
/// Build the results collection from the captured parameters if
/// this node is the end result
/// </summary>
/// <param name="capturedParameters">Currently captured parameters</param>
/// <param name="localCaptures">Parameters captured by the local matching</param>
/// <returns>Array of <see cref="MatchResult"/> objects corresponding to each set of <see cref="NodeData"/> stored at this node</returns>
protected IEnumerable<MatchResult> BuildResults(IDictionary<string, object> capturedParameters, IDictionary<string, object> localCaptures)
{
if (!this.NodeData.Any())
{
return MatchResult.NoMatches;
}
var parameters = new Dictionary<string, object>(capturedParameters);
if (this.AdditionalParameters.Any())
{
foreach (var additionalParameter in this.AdditionalParameters)
{
if (!parameters.ContainsKey(additionalParameter.Key))
{
parameters[additionalParameter.Key] = additionalParameter.Value;
}
}
}
if (localCaptures.Any())
{
foreach (var localCapture in localCaptures)
{
parameters[localCapture.Key] = localCapture.Value;
}
}
return this.NodeData.Select(n => n.ToResult(parameters));
}
/// <summary>
/// Gets all the matches from this node's children
/// </summary>
/// <param name="segments">Requested route segments</param>
/// <param name="currentIndex">Current index</param>
/// <param name="capturedParameters">Currently captured parameters</param>
/// <param name="localCaptures">Parameters captured by the local matching</param>
/// <param name="context">Current Nancy context</param>
/// <returns>Collection of <see cref="MatchResult"/> objects</returns>
protected IEnumerable<MatchResult> GetMatchingChildren(string[] segments, int currentIndex, IDictionary<string, object> capturedParameters, IDictionary<string, object> localCaptures, NancyContext context)
{
var parameters = capturedParameters;
if (localCaptures.Any() || this.AdditionalParameters.Any())
{
parameters = new Dictionary<string, object>(parameters);
foreach (var localParameter in localCaptures)
{
parameters[localParameter.Key] = localParameter.Value;
}
foreach (var additionalParameter in this.AdditionalParameters)
{
parameters[additionalParameter.Key] = additionalParameter.Value;
}
}
foreach (var childNode in this.Children.Values)
{
foreach (var match in childNode.GetMatches(segments, currentIndex, parameters, context))
{
yield return match;
}
}
}
/// <summary>
/// Matches the segment for a requested route
/// </summary>
/// <param name="segment">Segment string</param>
/// <returns>A <see cref="SegmentMatch"/> instance representing the result of the match</returns>
public abstract SegmentMatch Match(string segment);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Xml
{
using System;
internal interface IXmlTextWriterInitializer
{
void SetOutput(Stream stream, Encoding encoding, bool ownsStream);
}
internal class XmlUTF8TextWriter : XmlBaseWriter, IXmlTextWriterInitializer
{
private XmlUTF8NodeWriter _writer;
public void SetOutput(Stream stream, Encoding encoding, bool ownsStream)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (encoding.WebName != Encoding.UTF8.WebName)
{
stream = new EncodingStreamWrapper(stream, encoding, true);
}
if (_writer == null)
{
_writer = new XmlUTF8NodeWriter();
}
_writer.SetOutput(stream, ownsStream, encoding);
SetOutput(_writer);
}
}
internal class XmlUTF8NodeWriter : XmlStreamNodeWriter
{
private byte[] _entityChars;
private bool[] _isEscapedAttributeChar;
private bool[] _isEscapedElementChar;
private bool _inAttribute;
private const int bufferLength = 512;
private const int maxEntityLength = 32;
private Encoding _encoding;
private char[] _chars;
private static readonly byte[] s_startDecl =
{
(byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l', (byte)' ',
(byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"', (byte)' ',
(byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=', (byte)'"',
};
private static readonly byte[] s_endDecl =
{
(byte)'"', (byte)'?', (byte)'>'
};
private static readonly byte[] s_utf8Decl =
{
(byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l', (byte)' ',
(byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"', (byte)' ',
(byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=', (byte)'"', (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8', (byte)'"',
(byte)'?', (byte)'>'
};
private static readonly byte[] s_digits =
{
(byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
(byte) '8', (byte) '9', (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F'
};
private static readonly bool[] s_defaultIsEscapedAttributeChar = new bool[]
{
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
false, false, true, false, false, false, true, false, false, false, false, false, false, false, false, false, // '"', '&'
false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false // '<', '>'
};
private static readonly bool[] s_defaultIsEscapedElementChar = new bool[]
{
true, true, true, true, true, true, true, true, true, false, false, true, true, true, true, true, // All but 0x09, 0x0A
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, // '&'
false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false // '<', '>'
};
public XmlUTF8NodeWriter()
: this(s_defaultIsEscapedAttributeChar, s_defaultIsEscapedElementChar)
{
}
public XmlUTF8NodeWriter(bool[] isEscapedAttributeChar, bool[] isEscapedElementChar)
{
_isEscapedAttributeChar = isEscapedAttributeChar;
_isEscapedElementChar = isEscapedElementChar;
_inAttribute = false;
}
new public void SetOutput(Stream stream, bool ownsStream, Encoding encoding)
{
Encoding utf8Encoding = null;
if (encoding != null && encoding == Encoding.UTF8)
{
utf8Encoding = encoding;
encoding = null;
}
base.SetOutput(stream, ownsStream, utf8Encoding);
_encoding = encoding;
_inAttribute = false;
}
public Encoding Encoding
{
get
{
return _encoding;
}
}
private byte[] GetCharEntityBuffer()
{
if (_entityChars == null)
{
_entityChars = new byte[maxEntityLength];
}
return _entityChars;
}
private char[] GetCharBuffer(int charCount)
{
if (charCount >= 256)
return new char[charCount];
if (_chars == null || _chars.Length < charCount)
_chars = new char[charCount];
return _chars;
}
public override void WriteDeclaration()
{
if (_encoding == null)
{
WriteUTF8Chars(s_utf8Decl, 0, s_utf8Decl.Length);
}
else
{
WriteUTF8Chars(s_startDecl, 0, s_startDecl.Length);
if (_encoding.WebName == Encoding.BigEndianUnicode.WebName)
WriteUTF8Chars("utf-16BE");
else
WriteUTF8Chars(_encoding.WebName);
WriteUTF8Chars(s_endDecl, 0, s_endDecl.Length);
}
}
public override void WriteCData(string text)
{
byte[] buffer;
int offset;
buffer = GetBuffer(9, out offset);
buffer[offset + 0] = (byte)'<';
buffer[offset + 1] = (byte)'!';
buffer[offset + 2] = (byte)'[';
buffer[offset + 3] = (byte)'C';
buffer[offset + 4] = (byte)'D';
buffer[offset + 5] = (byte)'A';
buffer[offset + 6] = (byte)'T';
buffer[offset + 7] = (byte)'A';
buffer[offset + 8] = (byte)'[';
Advance(9);
WriteUTF8Chars(text);
buffer = GetBuffer(3, out offset);
buffer[offset + 0] = (byte)']';
buffer[offset + 1] = (byte)']';
buffer[offset + 2] = (byte)'>';
Advance(3);
}
private void WriteStartComment()
{
int offset;
byte[] buffer = GetBuffer(4, out offset);
buffer[offset + 0] = (byte)'<';
buffer[offset + 1] = (byte)'!';
buffer[offset + 2] = (byte)'-';
buffer[offset + 3] = (byte)'-';
Advance(4);
}
private void WriteEndComment()
{
int offset;
byte[] buffer = GetBuffer(3, out offset);
buffer[offset + 0] = (byte)'-';
buffer[offset + 1] = (byte)'-';
buffer[offset + 2] = (byte)'>';
Advance(3);
}
public override void WriteComment(string text)
{
WriteStartComment();
WriteUTF8Chars(text);
WriteEndComment();
}
public override void WriteStartElement(string prefix, string localName)
{
WriteByte('<');
if (prefix.Length != 0)
{
WritePrefix(prefix);
WriteByte(':');
}
WriteLocalName(localName);
}
public override async Task WriteStartElementAsync(string prefix, string localName)
{
await WriteByteAsync('<').ConfigureAwait(false);
if (prefix.Length != 0)
{
// This method calls into unsafe method which cannot run asyncly.
WritePrefix(prefix);
await WriteByteAsync(':').ConfigureAwait(false);
}
// This method calls into unsafe method which cannot run asyncly.
WriteLocalName(localName);
}
public override void WriteStartElement(string prefix, XmlDictionaryString localName)
{
WriteStartElement(prefix, localName.Value);
}
public override void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength)
{
WriteByte('<');
if (prefixLength != 0)
{
WritePrefix(prefixBuffer, prefixOffset, prefixLength);
WriteByte(':');
}
WriteLocalName(localNameBuffer, localNameOffset, localNameLength);
}
public override void WriteEndStartElement(bool isEmpty)
{
if (!isEmpty)
{
WriteByte('>');
}
else
{
WriteBytes('/', '>');
}
}
public override async Task WriteEndStartElementAsync(bool isEmpty)
{
if (!isEmpty)
{
await WriteByteAsync('>').ConfigureAwait(false);
}
else
{
await WriteBytesAsync('/', '>').ConfigureAwait(false);
}
}
public override void WriteEndElement(string prefix, string localName)
{
WriteBytes('<', '/');
if (prefix.Length != 0)
{
WritePrefix(prefix);
WriteByte(':');
}
WriteLocalName(localName);
WriteByte('>');
}
public override async Task WriteEndElementAsync(string prefix, string localName)
{
await WriteBytesAsync('<', '/').ConfigureAwait(false);
if (prefix.Length != 0)
{
WritePrefix(prefix);
await WriteByteAsync(':').ConfigureAwait(false);
}
WriteLocalName(localName);
await WriteByteAsync('>').ConfigureAwait(false);
}
public override void WriteEndElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength)
{
WriteBytes('<', '/');
if (prefixLength != 0)
{
WritePrefix(prefixBuffer, prefixOffset, prefixLength);
WriteByte(':');
}
WriteLocalName(localNameBuffer, localNameOffset, localNameLength);
WriteByte('>');
}
private void WriteStartXmlnsAttribute()
{
int offset;
byte[] buffer = GetBuffer(6, out offset);
buffer[offset + 0] = (byte)' ';
buffer[offset + 1] = (byte)'x';
buffer[offset + 2] = (byte)'m';
buffer[offset + 3] = (byte)'l';
buffer[offset + 4] = (byte)'n';
buffer[offset + 5] = (byte)'s';
Advance(6);
_inAttribute = true;
}
public override void WriteXmlnsAttribute(string prefix, string ns)
{
WriteStartXmlnsAttribute();
if (prefix.Length != 0)
{
WriteByte(':');
WritePrefix(prefix);
}
WriteBytes('=', '"');
WriteEscapedText(ns);
WriteEndAttribute();
}
public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
{
WriteXmlnsAttribute(prefix, ns.Value);
}
public override void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength)
{
WriteStartXmlnsAttribute();
if (prefixLength != 0)
{
WriteByte(':');
WritePrefix(prefixBuffer, prefixOffset, prefixLength);
}
WriteBytes('=', '"');
WriteEscapedText(nsBuffer, nsOffset, nsLength);
WriteEndAttribute();
}
public override void WriteStartAttribute(string prefix, string localName)
{
WriteByte(' ');
if (prefix.Length != 0)
{
WritePrefix(prefix);
WriteByte(':');
}
WriteLocalName(localName);
WriteBytes('=', '"');
_inAttribute = true;
}
public override void WriteStartAttribute(string prefix, XmlDictionaryString localName)
{
WriteStartAttribute(prefix, localName.Value);
}
public override void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength)
{
WriteByte(' ');
if (prefixLength != 0)
{
WritePrefix(prefixBuffer, prefixOffset, prefixLength);
WriteByte(':');
}
WriteLocalName(localNameBuffer, localNameOffset, localNameLength);
WriteBytes('=', '"');
_inAttribute = true;
}
public override void WriteEndAttribute()
{
WriteByte('"');
_inAttribute = false;
}
public override async Task WriteEndAttributeAsync()
{
await WriteByteAsync('"').ConfigureAwait(false);
_inAttribute = false;
}
private void WritePrefix(string prefix)
{
if (prefix.Length == 1)
{
WriteUTF8Char(prefix[0]);
}
else
{
WriteUTF8Chars(prefix);
}
}
private void WritePrefix(byte[] prefixBuffer, int prefixOffset, int prefixLength)
{
if (prefixLength == 1)
{
WriteUTF8Char((char)prefixBuffer[prefixOffset]);
}
else
{
WriteUTF8Chars(prefixBuffer, prefixOffset, prefixLength);
}
}
private void WriteLocalName(string localName)
{
WriteUTF8Chars(localName);
}
private void WriteLocalName(byte[] localNameBuffer, int localNameOffset, int localNameLength)
{
WriteUTF8Chars(localNameBuffer, localNameOffset, localNameLength);
}
public override void WriteEscapedText(XmlDictionaryString s)
{
WriteEscapedText(s.Value);
}
[SecuritySafeCritical]
unsafe public override void WriteEscapedText(string s)
{
int count = s.Length;
if (count > 0)
{
fixed (char* chars = s)
{
UnsafeWriteEscapedText(chars, count);
}
}
}
[SecuritySafeCritical]
unsafe public override void WriteEscapedText(char[] s, int offset, int count)
{
if (count > 0)
{
fixed (char* chars = &s[offset])
{
UnsafeWriteEscapedText(chars, count);
}
}
}
[SecurityCritical]
private unsafe void UnsafeWriteEscapedText(char* chars, int count)
{
bool[] isEscapedChar = (_inAttribute ? _isEscapedAttributeChar : _isEscapedElementChar);
int isEscapedCharLength = isEscapedChar.Length;
int i = 0;
for (int j = 0; j < count; j++)
{
char ch = chars[j];
if (ch < isEscapedCharLength && isEscapedChar[ch] || ch >= 0xFFFE)
{
UnsafeWriteUTF8Chars(chars + i, j - i);
WriteCharEntity(ch);
i = j + 1;
}
}
UnsafeWriteUTF8Chars(chars + i, count - i);
}
public override void WriteEscapedText(byte[] chars, int offset, int count)
{
bool[] isEscapedChar = (_inAttribute ? _isEscapedAttributeChar : _isEscapedElementChar);
int isEscapedCharLength = isEscapedChar.Length;
int i = 0;
for (int j = 0; j < count; j++)
{
byte ch = chars[offset + j];
if (ch < isEscapedCharLength && isEscapedChar[ch])
{
WriteUTF8Chars(chars, offset + i, j - i);
WriteCharEntity(ch);
i = j + 1;
}
else if (ch == 239 && offset + j + 2 < count)
{
// 0xFFFE and 0xFFFF must be written as char entities
// UTF8(239, 191, 190) = (char) 0xFFFE
// UTF8(239, 191, 191) = (char) 0xFFFF
byte ch2 = chars[offset + j + 1];
byte ch3 = chars[offset + j + 2];
if (ch2 == 191 && (ch3 == 190 || ch3 == 191))
{
WriteUTF8Chars(chars, offset + i, j - i);
WriteCharEntity(ch3 == 190 ? (char)0xFFFE : (char)0xFFFF);
i = j + 3;
}
}
}
WriteUTF8Chars(chars, offset + i, count - i);
}
public void WriteText(int ch)
{
WriteUTF8Char(ch);
}
public override void WriteText(byte[] chars, int offset, int count)
{
WriteUTF8Chars(chars, offset, count);
}
[SecuritySafeCritical]
unsafe public override void WriteText(char[] chars, int offset, int count)
{
if (count > 0)
{
fixed (char* pch = &chars[offset])
{
UnsafeWriteUTF8Chars(pch, count);
}
}
}
public override void WriteText(string value)
{
WriteUTF8Chars(value);
}
public override void WriteText(XmlDictionaryString value)
{
WriteUTF8Chars(value.Value);
}
public void WriteLessThanCharEntity()
{
int offset;
byte[] buffer = GetBuffer(4, out offset);
buffer[offset + 0] = (byte)'&';
buffer[offset + 1] = (byte)'l';
buffer[offset + 2] = (byte)'t';
buffer[offset + 3] = (byte)';';
Advance(4);
}
public void WriteGreaterThanCharEntity()
{
int offset;
byte[] buffer = GetBuffer(4, out offset);
buffer[offset + 0] = (byte)'&';
buffer[offset + 1] = (byte)'g';
buffer[offset + 2] = (byte)'t';
buffer[offset + 3] = (byte)';';
Advance(4);
}
public void WriteAmpersandCharEntity()
{
int offset;
byte[] buffer = GetBuffer(5, out offset);
buffer[offset + 0] = (byte)'&';
buffer[offset + 1] = (byte)'a';
buffer[offset + 2] = (byte)'m';
buffer[offset + 3] = (byte)'p';
buffer[offset + 4] = (byte)';';
Advance(5);
}
public void WriteApostropheCharEntity()
{
int offset;
byte[] buffer = GetBuffer(6, out offset);
buffer[offset + 0] = (byte)'&';
buffer[offset + 1] = (byte)'a';
buffer[offset + 2] = (byte)'p';
buffer[offset + 3] = (byte)'o';
buffer[offset + 4] = (byte)'s';
buffer[offset + 5] = (byte)';';
Advance(6);
}
public void WriteQuoteCharEntity()
{
int offset;
byte[] buffer = GetBuffer(6, out offset);
buffer[offset + 0] = (byte)'&';
buffer[offset + 1] = (byte)'q';
buffer[offset + 2] = (byte)'u';
buffer[offset + 3] = (byte)'o';
buffer[offset + 4] = (byte)'t';
buffer[offset + 5] = (byte)';';
Advance(6);
}
private void WriteHexCharEntity(int ch)
{
byte[] chars = GetCharEntityBuffer();
int offset = maxEntityLength;
chars[--offset] = (byte)';';
offset -= ToBase16(chars, offset, (uint)ch);
chars[--offset] = (byte)'x';
chars[--offset] = (byte)'#';
chars[--offset] = (byte)'&';
WriteUTF8Chars(chars, offset, maxEntityLength - offset);
}
public override void WriteCharEntity(int ch)
{
switch (ch)
{
case '<':
WriteLessThanCharEntity();
break;
case '>':
WriteGreaterThanCharEntity();
break;
case '&':
WriteAmpersandCharEntity();
break;
case '\'':
WriteApostropheCharEntity();
break;
case '"':
WriteQuoteCharEntity();
break;
default:
WriteHexCharEntity(ch);
break;
}
}
private int ToBase16(byte[] chars, int offset, uint value)
{
int count = 0;
do
{
count++;
chars[--offset] = s_digits[(int)(value & 0x0F)];
value /= 16;
}
while (value != 0);
return count;
}
public override void WriteBoolText(bool value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxBoolChars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteDecimalText(decimal value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxDecimalChars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteDoubleText(double value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxDoubleChars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteFloatText(float value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxFloatChars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteDateTimeText(DateTime value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxDateTimeChars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteUniqueIdText(UniqueId value)
{
if (value.IsGuid)
{
int charCount = value.CharArrayLength;
char[] chars = GetCharBuffer(charCount);
value.ToCharArray(chars, 0);
WriteText(chars, 0, charCount);
}
else
{
WriteEscapedText(value.ToString());
}
}
public override void WriteInt32Text(int value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxInt32Chars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteInt64Text(long value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxInt64Chars, out offset);
Advance(XmlConverter.ToChars(value, buffer, offset));
}
public override void WriteUInt64Text(ulong value)
{
int offset;
byte[] buffer = GetBuffer(XmlConverter.MaxUInt64Chars, out offset);
Advance(XmlConverter.ToChars((double)value, buffer, offset));
}
public override void WriteGuidText(Guid value)
{
WriteText(value.ToString());
}
public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count)
{
if (trailByteCount > 0)
{
InternalWriteBase64Text(trailBytes, 0, trailByteCount);
}
InternalWriteBase64Text(buffer, offset, count);
}
public override async Task WriteBase64TextAsync(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count)
{
if (trailByteCount > 0)
{
await InternalWriteBase64TextAsync(trailBytes, 0, trailByteCount).ConfigureAwait(false);
}
await InternalWriteBase64TextAsync(buffer, offset, count).ConfigureAwait(false);
}
private void InternalWriteBase64Text(byte[] buffer, int offset, int count)
{
Base64Encoding encoding = XmlConverter.Base64Encoding;
while (count >= 3)
{
int byteCount = Math.Min(bufferLength / 4 * 3, count - count % 3);
int charCount = byteCount / 3 * 4;
int charOffset;
byte[] chars = GetBuffer(charCount, out charOffset);
Advance(encoding.GetChars(buffer, offset, byteCount, chars, charOffset));
offset += byteCount;
count -= byteCount;
}
if (count > 0)
{
int charOffset;
byte[] chars = GetBuffer(4, out charOffset);
Advance(encoding.GetChars(buffer, offset, count, chars, charOffset));
}
}
private async Task InternalWriteBase64TextAsync(byte[] buffer, int offset, int count)
{
Base64Encoding encoding = XmlConverter.Base64Encoding;
while (count >= 3)
{
int byteCount = Math.Min(bufferLength / 4 * 3, count - count % 3);
int charCount = byteCount / 3 * 4;
int charOffset;
BytesWithOffset bufferResult = await GetBufferAsync(charCount).ConfigureAwait(false);
byte[] chars = bufferResult.Bytes;
charOffset = bufferResult.Offset;
Advance(encoding.GetChars(buffer, offset, byteCount, chars, charOffset));
offset += byteCount;
count -= byteCount;
}
if (count > 0)
{
int charOffset;
BytesWithOffset bufferResult = await GetBufferAsync(4).ConfigureAwait(false);
byte[] chars = bufferResult.Bytes;
charOffset = bufferResult.Offset;
Advance(encoding.GetChars(buffer, offset, count, chars, charOffset));
}
}
public override void WriteTimeSpanText(TimeSpan value)
{
WriteText(XmlConvert.ToString(value));
}
public override void WriteStartListText()
{
}
public override void WriteListSeparator()
{
WriteByte(' ');
}
public override void WriteEndListText()
{
}
public override void WriteQualifiedName(string prefix, XmlDictionaryString localName)
{
if (prefix.Length != 0)
{
WritePrefix(prefix);
WriteByte(':');
}
WriteText(localName);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERCLevel;
namespace ParentLoad.DataAccess.Sql.ERCLevel
{
/// <summary>
/// DAL SQL Server implementation of <see cref="IB01_ContinentCollDal"/>
/// </summary>
public partial class B01_ContinentCollDal : IB01_ContinentCollDal
{
private List<B03_Continent_ChildDto> _b03_Continent_Child = new List<B03_Continent_ChildDto>();
private List<B03_Continent_ReChildDto> _b03_Continent_ReChild = new List<B03_Continent_ReChildDto>();
private List<B04_SubContinentDto> _b03_SubContinentColl = new List<B04_SubContinentDto>();
private List<B05_SubContinent_ChildDto> _b05_SubContinent_Child = new List<B05_SubContinent_ChildDto>();
private List<B05_SubContinent_ReChildDto> _b05_SubContinent_ReChild = new List<B05_SubContinent_ReChildDto>();
private List<B06_CountryDto> _b05_CountryColl = new List<B06_CountryDto>();
private List<B07_Country_ChildDto> _b07_Country_Child = new List<B07_Country_ChildDto>();
private List<B07_Country_ReChildDto> _b07_Country_ReChild = new List<B07_Country_ReChildDto>();
private List<B08_RegionDto> _b07_RegionColl = new List<B08_RegionDto>();
private List<B09_Region_ChildDto> _b09_Region_Child = new List<B09_Region_ChildDto>();
private List<B09_Region_ReChildDto> _b09_Region_ReChild = new List<B09_Region_ReChildDto>();
private List<B10_CityDto> _b09_CityColl = new List<B10_CityDto>();
private List<B11_City_ChildDto> _b11_City_Child = new List<B11_City_ChildDto>();
private List<B11_City_ReChildDto> _b11_City_ReChild = new List<B11_City_ReChildDto>();
private List<B12_CityRoadDto> _b11_CityRoadColl = new List<B12_CityRoadDto>();
/// <summary>
/// Gets the B03 Continent Single Object.
/// </summary>
/// <value>A list of <see cref="B03_Continent_ChildDto"/>.</value>
public List<B03_Continent_ChildDto> B03_Continent_Child
{
get { return _b03_Continent_Child; }
}
/// <summary>
/// Gets the B03 Continent ASingle Object.
/// </summary>
/// <value>A list of <see cref="B03_Continent_ReChildDto"/>.</value>
public List<B03_Continent_ReChildDto> B03_Continent_ReChild
{
get { return _b03_Continent_ReChild; }
}
/// <summary>
/// Gets the B03 SubContinent Objects.
/// </summary>
/// <value>A list of <see cref="B04_SubContinentDto"/>.</value>
public List<B04_SubContinentDto> B03_SubContinentColl
{
get { return _b03_SubContinentColl; }
}
/// <summary>
/// Gets the B05 SubContinent Single Object.
/// </summary>
/// <value>A list of <see cref="B05_SubContinent_ChildDto"/>.</value>
public List<B05_SubContinent_ChildDto> B05_SubContinent_Child
{
get { return _b05_SubContinent_Child; }
}
/// <summary>
/// Gets the B05 SubContinent ASingle Object.
/// </summary>
/// <value>A list of <see cref="B05_SubContinent_ReChildDto"/>.</value>
public List<B05_SubContinent_ReChildDto> B05_SubContinent_ReChild
{
get { return _b05_SubContinent_ReChild; }
}
/// <summary>
/// Gets the B05 Country Objects.
/// </summary>
/// <value>A list of <see cref="B06_CountryDto"/>.</value>
public List<B06_CountryDto> B05_CountryColl
{
get { return _b05_CountryColl; }
}
/// <summary>
/// Gets the B07 Country Single Object.
/// </summary>
/// <value>A list of <see cref="B07_Country_ChildDto"/>.</value>
public List<B07_Country_ChildDto> B07_Country_Child
{
get { return _b07_Country_Child; }
}
/// <summary>
/// Gets the B07 Country ASingle Object.
/// </summary>
/// <value>A list of <see cref="B07_Country_ReChildDto"/>.</value>
public List<B07_Country_ReChildDto> B07_Country_ReChild
{
get { return _b07_Country_ReChild; }
}
/// <summary>
/// Gets the B07 Region Objects.
/// </summary>
/// <value>A list of <see cref="B08_RegionDto"/>.</value>
public List<B08_RegionDto> B07_RegionColl
{
get { return _b07_RegionColl; }
}
/// <summary>
/// Gets the B09 Region Single Object.
/// </summary>
/// <value>A list of <see cref="B09_Region_ChildDto"/>.</value>
public List<B09_Region_ChildDto> B09_Region_Child
{
get { return _b09_Region_Child; }
}
/// <summary>
/// Gets the B09 Region ASingle Object.
/// </summary>
/// <value>A list of <see cref="B09_Region_ReChildDto"/>.</value>
public List<B09_Region_ReChildDto> B09_Region_ReChild
{
get { return _b09_Region_ReChild; }
}
/// <summary>
/// Gets the B09 City Objects.
/// </summary>
/// <value>A list of <see cref="B10_CityDto"/>.</value>
public List<B10_CityDto> B09_CityColl
{
get { return _b09_CityColl; }
}
/// <summary>
/// Gets the B11 City Single Object.
/// </summary>
/// <value>A list of <see cref="B11_City_ChildDto"/>.</value>
public List<B11_City_ChildDto> B11_City_Child
{
get { return _b11_City_Child; }
}
/// <summary>
/// Gets the B11 City ASingle Object.
/// </summary>
/// <value>A list of <see cref="B11_City_ReChildDto"/>.</value>
public List<B11_City_ReChildDto> B11_City_ReChild
{
get { return _b11_City_ReChild; }
}
/// <summary>
/// Gets the B11 CityRoad Objects.
/// </summary>
/// <value>A list of <see cref="B12_CityRoadDto"/>.</value>
public List<B12_CityRoadDto> B11_CityRoadColl
{
get { return _b11_CityRoadColl; }
}
/// <summary>
/// Loads a B01_ContinentColl collection from the database.
/// </summary>
/// <returns>A list of <see cref="B02_ContinentDto"/>.</returns>
public List<B02_ContinentDto> Fetch()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetB01_ContinentColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
var dr = cmd.ExecuteReader();
return LoadCollection(dr);
}
}
}
private List<B02_ContinentDto> LoadCollection(IDataReader data)
{
var b01_ContinentColl = new List<B02_ContinentDto>();
using (var dr = new SafeDataReader(data))
{
while (dr.Read())
{
b01_ContinentColl.Add(Fetch(dr));
}
if (b01_ContinentColl.Count > 0)
FetchChildren(dr);
}
return b01_ContinentColl;
}
private B02_ContinentDto Fetch(SafeDataReader dr)
{
var b02_Continent = new B02_ContinentDto();
// Value properties
b02_Continent.Continent_ID = dr.GetInt32("Continent_ID");
b02_Continent.Continent_Name = dr.GetString("Continent_Name");
return b02_Continent;
}
private void FetchChildren(SafeDataReader dr)
{
dr.NextResult();
while (dr.Read())
{
_b03_Continent_Child.Add(FetchB03_Continent_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_b03_Continent_ReChild.Add(FetchB03_Continent_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_b03_SubContinentColl.Add(FetchB04_SubContinent(dr));
}
dr.NextResult();
while (dr.Read())
{
_b05_SubContinent_Child.Add(FetchB05_SubContinent_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_b05_SubContinent_ReChild.Add(FetchB05_SubContinent_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_b05_CountryColl.Add(FetchB06_Country(dr));
}
dr.NextResult();
while (dr.Read())
{
_b07_Country_Child.Add(FetchB07_Country_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_b07_Country_ReChild.Add(FetchB07_Country_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_b07_RegionColl.Add(FetchB08_Region(dr));
}
dr.NextResult();
while (dr.Read())
{
_b09_Region_Child.Add(FetchB09_Region_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_b09_Region_ReChild.Add(FetchB09_Region_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_b09_CityColl.Add(FetchB10_City(dr));
}
dr.NextResult();
while (dr.Read())
{
_b11_City_Child.Add(FetchB11_City_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_b11_City_ReChild.Add(FetchB11_City_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_b11_CityRoadColl.Add(FetchB12_CityRoad(dr));
}
}
private B03_Continent_ChildDto FetchB03_Continent_Child(SafeDataReader dr)
{
var b03_Continent_Child = new B03_Continent_ChildDto();
// Value properties
b03_Continent_Child.Continent_Child_Name = dr.GetString("Continent_Child_Name");
// parent properties
b03_Continent_Child.Parent_Continent_ID = dr.GetInt32("Continent_ID1");
return b03_Continent_Child;
}
private B03_Continent_ReChildDto FetchB03_Continent_ReChild(SafeDataReader dr)
{
var b03_Continent_ReChild = new B03_Continent_ReChildDto();
// Value properties
b03_Continent_ReChild.Continent_Child_Name = dr.GetString("Continent_Child_Name");
// parent properties
b03_Continent_ReChild.Parent_Continent_ID = dr.GetInt32("Continent_ID2");
return b03_Continent_ReChild;
}
private B04_SubContinentDto FetchB04_SubContinent(SafeDataReader dr)
{
var b04_SubContinent = new B04_SubContinentDto();
// Value properties
b04_SubContinent.SubContinent_ID = dr.GetInt32("SubContinent_ID");
b04_SubContinent.SubContinent_Name = dr.GetString("SubContinent_Name");
// parent properties
b04_SubContinent.Parent_Continent_ID = dr.GetInt32("Parent_Continent_ID");
return b04_SubContinent;
}
private B05_SubContinent_ChildDto FetchB05_SubContinent_Child(SafeDataReader dr)
{
var b05_SubContinent_Child = new B05_SubContinent_ChildDto();
// Value properties
b05_SubContinent_Child.SubContinent_Child_Name = dr.GetString("SubContinent_Child_Name");
// parent properties
b05_SubContinent_Child.Parent_SubContinent_ID = dr.GetInt32("SubContinent_ID1");
return b05_SubContinent_Child;
}
private B05_SubContinent_ReChildDto FetchB05_SubContinent_ReChild(SafeDataReader dr)
{
var b05_SubContinent_ReChild = new B05_SubContinent_ReChildDto();
// Value properties
b05_SubContinent_ReChild.SubContinent_Child_Name = dr.GetString("SubContinent_Child_Name");
// parent properties
b05_SubContinent_ReChild.Parent_SubContinent_ID = dr.GetInt32("SubContinent_ID2");
return b05_SubContinent_ReChild;
}
private B06_CountryDto FetchB06_Country(SafeDataReader dr)
{
var b06_Country = new B06_CountryDto();
// Value properties
b06_Country.Country_ID = dr.GetInt32("Country_ID");
b06_Country.Country_Name = dr.GetString("Country_Name");
// parent properties
b06_Country.Parent_SubContinent_ID = dr.GetInt32("Parent_SubContinent_ID");
return b06_Country;
}
private B07_Country_ChildDto FetchB07_Country_Child(SafeDataReader dr)
{
var b07_Country_Child = new B07_Country_ChildDto();
// Value properties
b07_Country_Child.Country_Child_Name = dr.GetString("Country_Child_Name");
// parent properties
b07_Country_Child.Parent_Country_ID = dr.GetInt32("Country_ID1");
return b07_Country_Child;
}
private B07_Country_ReChildDto FetchB07_Country_ReChild(SafeDataReader dr)
{
var b07_Country_ReChild = new B07_Country_ReChildDto();
// Value properties
b07_Country_ReChild.Country_Child_Name = dr.GetString("Country_Child_Name");
// parent properties
b07_Country_ReChild.Parent_Country_ID = dr.GetInt32("Country_ID2");
return b07_Country_ReChild;
}
private B08_RegionDto FetchB08_Region(SafeDataReader dr)
{
var b08_Region = new B08_RegionDto();
// Value properties
b08_Region.Region_ID = dr.GetInt32("Region_ID");
b08_Region.Region_Name = dr.GetString("Region_Name");
// parent properties
b08_Region.Parent_Country_ID = dr.GetInt32("Parent_Country_ID");
return b08_Region;
}
private B09_Region_ChildDto FetchB09_Region_Child(SafeDataReader dr)
{
var b09_Region_Child = new B09_Region_ChildDto();
// Value properties
b09_Region_Child.Region_Child_Name = dr.GetString("Region_Child_Name");
// parent properties
b09_Region_Child.Parent_Region_ID = dr.GetInt32("Region_ID1");
return b09_Region_Child;
}
private B09_Region_ReChildDto FetchB09_Region_ReChild(SafeDataReader dr)
{
var b09_Region_ReChild = new B09_Region_ReChildDto();
// Value properties
b09_Region_ReChild.Region_Child_Name = dr.GetString("Region_Child_Name");
// parent properties
b09_Region_ReChild.Parent_Region_ID = dr.GetInt32("Region_ID2");
return b09_Region_ReChild;
}
private B10_CityDto FetchB10_City(SafeDataReader dr)
{
var b10_City = new B10_CityDto();
// Value properties
b10_City.City_ID = dr.GetInt32("City_ID");
b10_City.City_Name = dr.GetString("City_Name");
// parent properties
b10_City.Parent_Region_ID = dr.GetInt32("Parent_Region_ID");
return b10_City;
}
private B11_City_ChildDto FetchB11_City_Child(SafeDataReader dr)
{
var b11_City_Child = new B11_City_ChildDto();
// Value properties
b11_City_Child.City_Child_Name = dr.GetString("City_Child_Name");
// parent properties
b11_City_Child.Parent_City_ID = dr.GetInt32("City_ID1");
return b11_City_Child;
}
private B11_City_ReChildDto FetchB11_City_ReChild(SafeDataReader dr)
{
var b11_City_ReChild = new B11_City_ReChildDto();
// Value properties
b11_City_ReChild.City_Child_Name = dr.GetString("City_Child_Name");
// parent properties
b11_City_ReChild.Parent_City_ID = dr.GetInt32("City_ID2");
return b11_City_ReChild;
}
private B12_CityRoadDto FetchB12_CityRoad(SafeDataReader dr)
{
var b12_CityRoad = new B12_CityRoadDto();
// Value properties
b12_CityRoad.CityRoad_ID = dr.GetInt32("CityRoad_ID");
b12_CityRoad.CityRoad_Name = dr.GetString("CityRoad_Name");
// parent properties
b12_CityRoad.Parent_City_ID = dr.GetInt32("Parent_City_ID");
return b12_CityRoad;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// //
// MIT X11 license, Copyright (c) 2005-2006 by: //
// //
// Authors: //
// Michael Dominic K. <michaldominik@gmail.com> //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included //
// in all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS //
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN //
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, //
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR //
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE //
// USE OR OTHER DEALINGS IN THE SOFTWARE. //
// //
////////////////////////////////////////////////////////////////////////////////
/* An overriden ComboBox that is used to select a zoom level.
*/
namespace Diva.Editor.Gui {
using System;
using Gtk;
using Mono.Unix;
using Util;
public sealed class ZoomToComboBox : ComboBox {
// Private enums ///////////////////////////////////////////////
enum ZoomLevel { OneSecond, FewSeconds, OneMinute, FewMinutes,
OneHour }
// Translatable ////////////////////////////////////////////////
readonly static string toOneSecondSS =
Catalog.GetString ("Zoom to one second");
readonly static string toFewSecondsSS =
Catalog.GetString ("Zoom to few seconds");
readonly static string toOneMinuteSS =
Catalog.GetString ("Zoom to one minute");
readonly static string toFewMinutesSS =
Catalog.GetString ("Zoom to few minutes");
readonly static string toOneHourSS =
Catalog.GetString ("Zoom to one hour");
// Fields /////////////////////////////////////////////////////
Model.Root modelRoot = null;
ZoomLevel currentLevel; // To avoid some extra proc when nothing changes
bool trickSwitch = false; // To avoid recursive events
// Members /////////////////////////////////////////////////////
Gtk.ListStore listStore = new Gtk.ListStore (typeof (string),
typeof (ZoomLevel));
// Public methods ///////////////////////////////////////////
/* CONSTRUCTOR */
public ZoomToComboBox (Model.Root root) : base ()
{
modelRoot = root;
listStore.AppendValues (String.Format ("<small>{0}</small>", toOneSecondSS),
ZoomLevel.OneSecond);
listStore.AppendValues (String.Format ("<small>{0}</small>", toFewSecondsSS),
ZoomLevel.FewSeconds);
listStore.AppendValues (String.Format ("<small>{0}</small>", toOneMinuteSS),
ZoomLevel.OneMinute);
listStore.AppendValues (String.Format ("<small>{0}</small>", toFewMinutesSS),
ZoomLevel.FewMinutes);
//listStore.AppendValues (String.Format ("<small>{0}</small>", toOneHourSS),
// ZoomLevel.OneHour);
this.Model = listStore;
// Renderers
Gtk.CellRendererText textRenderer = new Gtk.CellRendererText ();
PackStart (textRenderer, true);
AddAttribute (textRenderer, "markup", 0);
// Initial
SelectByLevel (TimeSpanToLevel (modelRoot.Timeline.DisplayedTimeSpan));
// Model bind
modelRoot.Timeline.DisplayedTimeSpanChange += OnDisplayTimeSpanChange;
}
// Private methods //////////////////////////////////////////
ZoomLevel TimeSpanToLevel (Gdv.TimeSpan timeSpan)
{
//if (timeSpan.Duration.Seconds >= 3600.0)
// return ZoomLevel.OneHour;
if (timeSpan.Duration.Seconds >= 180.0)
return ZoomLevel.FewMinutes;
else if (timeSpan.Duration.Seconds >= 60.0)
return ZoomLevel.OneMinute;
else if (timeSpan.Duration.Seconds >= 3.0)
return ZoomLevel.FewSeconds;
else
return ZoomLevel.OneSecond;
}
Gdv.TimeSpan LevelToTimeSpan (ZoomLevel level)
{
Gdv.Time halfDuration = Gdv.Time.Empty;
Gdv.Time zoomCenter = (modelRoot.Timeline.DisplayedTimeSpan.Start +
modelRoot.Timeline.DisplayedTimeSpan.End) / 2;
switch (level) {
case ZoomLevel.OneSecond:
halfDuration = Gdv.Time.FromSeconds (1.0);
break;
case ZoomLevel.FewSeconds:
halfDuration = Gdv.Time.FromSeconds (5.0);
break;
case ZoomLevel.OneMinute:
halfDuration = Gdv.Time.FromSeconds (60.0);
break;
case ZoomLevel.FewMinutes:
halfDuration = Gdv.Time.FromSeconds (180.0);
break;
//case ZoomLevel.OneHour:
//halfDuration = Gdv.Time.FromSeconds (3600.0);
//break;
}
Gdv.Time leftCut = (zoomCenter >= halfDuration) ? halfDuration : zoomCenter;
Gdv.TimeSpan newTimeSpan = new Gdv.TimeSpan (zoomCenter - leftCut,
zoomCenter + halfDuration +
(halfDuration - leftCut));
return newTimeSpan;
}
void SelectByLevel (ZoomLevel level)
{
TreeIter methodIter = GtkFu.TreeModelIterByInt (listStore, (int) level, 1);
trickSwitch = true;
SetActiveIter (methodIter);
trickSwitch = false;
currentLevel = level;
}
void OnDisplayTimeSpanChange (object o, Model.TimeSpanArgs args)
{
ZoomLevel newLevel = TimeSpanToLevel (args.TimeSpan);
if (newLevel != currentLevel)
SelectByLevel (newLevel);
}
/* Selection was changed */
protected override void OnChanged ()
{
if (trickSwitch)
return;
TreeIter iter;
GetActiveIter (out iter);
ZoomLevel newLevel = (ZoomLevel) listStore.GetValue (iter, 1);
Gdv.Time currentTicker = modelRoot.Pipeline.CurrentTicker;
Gdv.TimeSpan zoomSpan = LevelToTimeSpan (newLevel);
Gdv.Time leftCut = zoomSpan.Duration / 2;
if (leftCut > currentTicker)
leftCut = currentTicker;
Gdv.Time start = currentTicker - leftCut;
Gdv.Time end = currentTicker + (zoomSpan.Duration - leftCut);
modelRoot.Timeline.DisplayedTimeSpan = new Gdv.TimeSpan (start, end);
}
}
}
| |
/********************************************************************
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.
*********************************************************************/
namespace Multiverse.Tools.ModelViewer {
partial class BoneDisplay {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.boneTreeView = new System.Windows.Forms.TreeView();
this.bonePositionLabel = new System.Windows.Forms.Label();
this.bonePosition = new System.Windows.Forms.Label();
this.boneNameLabel = new System.Windows.Forms.Label();
this.boneRotationLabel = new System.Windows.Forms.Label();
this.boneRotation = new System.Windows.Forms.Label();
this.relPositionLabel = new System.Windows.Forms.Label();
this.relRotationLabel = new System.Windows.Forms.Label();
this.relPosition = new System.Windows.Forms.Label();
this.relRotation = new System.Windows.Forms.Label();
this.boneRotation2 = new System.Windows.Forms.Label();
this.relRotation2 = new System.Windows.Forms.Label();
this.bindPositionLabel = new System.Windows.Forms.Label();
this.bindPosition = new System.Windows.Forms.Label();
this.bindRotationLabel = new System.Windows.Forms.Label();
this.bindRotation = new System.Windows.Forms.Label();
this.bindRotation2 = new System.Windows.Forms.Label();
this.animationTime = new System.Windows.Forms.Label();
this.keyFrame1Rotation2 = new System.Windows.Forms.Label();
this.keyFrame1Rotation = new System.Windows.Forms.Label();
this.keyFrame1RotationLabel = new System.Windows.Forms.Label();
this.keyFrame1Position = new System.Windows.Forms.Label();
this.keyFrame1PositionLabel = new System.Windows.Forms.Label();
this.keyFrame2Rotation2 = new System.Windows.Forms.Label();
this.keyFrame2Rotation = new System.Windows.Forms.Label();
this.keyFrame2RotationLabel = new System.Windows.Forms.Label();
this.keyFrame2Position = new System.Windows.Forms.Label();
this.keyFrame2PositionLabel = new System.Windows.Forms.Label();
this.animationName = new System.Windows.Forms.Label();
this.keyFrame1TimeLabel = new System.Windows.Forms.Label();
this.keyFrame2TimeLabel = new System.Windows.Forms.Label();
this.keyFrame2Time = new System.Windows.Forms.Label();
this.keyFrame1Time = new System.Windows.Forms.Label();
this.prevKeyframeLabel = new System.Windows.Forms.Label();
this.nextKeyframeLabel = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// boneTreeView
//
this.boneTreeView.Location = new System.Drawing.Point(7, 12);
this.boneTreeView.Name = "boneTreeView";
this.boneTreeView.Size = new System.Drawing.Size(349, 438);
this.boneTreeView.TabIndex = 0;
this.boneTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.boneTreeView_AfterSelect);
//
// bonePositionLabel
//
this.bonePositionLabel.AutoSize = true;
this.bonePositionLabel.Location = new System.Drawing.Point(362, 58);
this.bonePositionLabel.Name = "bonePositionLabel";
this.bonePositionLabel.Size = new System.Drawing.Size(44, 13);
this.bonePositionLabel.TabIndex = 1;
this.bonePositionLabel.Text = "Position";
//
// bonePosition
//
this.bonePosition.AutoSize = true;
this.bonePosition.Location = new System.Drawing.Point(471, 58);
this.bonePosition.Name = "bonePosition";
this.bonePosition.Size = new System.Drawing.Size(43, 13);
this.bonePosition.TabIndex = 2;
this.bonePosition.Text = "position";
//
// boneNameLabel
//
this.boneNameLabel.AutoSize = true;
this.boneNameLabel.Location = new System.Drawing.Point(362, 35);
this.boneNameLabel.Name = "boneNameLabel";
this.boneNameLabel.Size = new System.Drawing.Size(63, 13);
this.boneNameLabel.TabIndex = 3;
this.boneNameLabel.Text = "Bone Name";
//
// boneRotationLabel
//
this.boneRotationLabel.AutoSize = true;
this.boneRotationLabel.Location = new System.Drawing.Point(362, 71);
this.boneRotationLabel.Name = "boneRotationLabel";
this.boneRotationLabel.Size = new System.Drawing.Size(47, 13);
this.boneRotationLabel.TabIndex = 4;
this.boneRotationLabel.Text = "Rotation";
//
// boneRotation
//
this.boneRotation.AutoSize = true;
this.boneRotation.Location = new System.Drawing.Point(471, 71);
this.boneRotation.Name = "boneRotation";
this.boneRotation.Size = new System.Drawing.Size(42, 13);
this.boneRotation.TabIndex = 5;
this.boneRotation.Text = "rotation";
//
// relPositionLabel
//
this.relPositionLabel.AutoSize = true;
this.relPositionLabel.Location = new System.Drawing.Point(362, 116);
this.relPositionLabel.Name = "relPositionLabel";
this.relPositionLabel.Size = new System.Drawing.Size(86, 13);
this.relPositionLabel.TabIndex = 6;
this.relPositionLabel.Text = "Relative Position";
//
// relRotationLabel
//
this.relRotationLabel.AutoSize = true;
this.relRotationLabel.Location = new System.Drawing.Point(362, 129);
this.relRotationLabel.Name = "relRotationLabel";
this.relRotationLabel.Size = new System.Drawing.Size(89, 13);
this.relRotationLabel.TabIndex = 7;
this.relRotationLabel.Text = "Relative Rotation";
//
// relPosition
//
this.relPosition.AutoSize = true;
this.relPosition.Location = new System.Drawing.Point(471, 116);
this.relPosition.Name = "relPosition";
this.relPosition.Size = new System.Drawing.Size(43, 13);
this.relPosition.TabIndex = 8;
this.relPosition.Text = "position";
//
// relRotation
//
this.relRotation.AutoSize = true;
this.relRotation.Location = new System.Drawing.Point(471, 129);
this.relRotation.Name = "relRotation";
this.relRotation.Size = new System.Drawing.Size(42, 13);
this.relRotation.TabIndex = 9;
this.relRotation.Text = "rotation";
//
// boneRotation2
//
this.boneRotation2.AutoSize = true;
this.boneRotation2.Location = new System.Drawing.Point(471, 84);
this.boneRotation2.Name = "boneRotation2";
this.boneRotation2.Size = new System.Drawing.Size(63, 13);
this.boneRotation2.TabIndex = 10;
this.boneRotation2.Text = "rotationXYZ";
//
// relRotation2
//
this.relRotation2.AutoSize = true;
this.relRotation2.Location = new System.Drawing.Point(471, 142);
this.relRotation2.Name = "relRotation2";
this.relRotation2.Size = new System.Drawing.Size(63, 13);
this.relRotation2.TabIndex = 11;
this.relRotation2.Text = "rotationXYZ";
//
// bindPositionLabel
//
this.bindPositionLabel.AutoSize = true;
this.bindPositionLabel.Location = new System.Drawing.Point(362, 172);
this.bindPositionLabel.Name = "bindPositionLabel";
this.bindPositionLabel.Size = new System.Drawing.Size(68, 13);
this.bindPositionLabel.TabIndex = 12;
this.bindPositionLabel.Text = "Bind Position";
//
// bindPosition
//
this.bindPosition.AutoSize = true;
this.bindPosition.Location = new System.Drawing.Point(471, 172);
this.bindPosition.Name = "bindPosition";
this.bindPosition.Size = new System.Drawing.Size(43, 13);
this.bindPosition.TabIndex = 13;
this.bindPosition.Text = "position";
//
// bindRotationLabel
//
this.bindRotationLabel.AutoSize = true;
this.bindRotationLabel.Location = new System.Drawing.Point(362, 185);
this.bindRotationLabel.Name = "bindRotationLabel";
this.bindRotationLabel.Size = new System.Drawing.Size(71, 13);
this.bindRotationLabel.TabIndex = 14;
this.bindRotationLabel.Text = "Bind Rotation";
//
// bindRotation
//
this.bindRotation.AutoSize = true;
this.bindRotation.Location = new System.Drawing.Point(471, 185);
this.bindRotation.Name = "bindRotation";
this.bindRotation.Size = new System.Drawing.Size(42, 13);
this.bindRotation.TabIndex = 15;
this.bindRotation.Text = "rotation";
//
// bindRotation2
//
this.bindRotation2.AutoSize = true;
this.bindRotation2.Location = new System.Drawing.Point(471, 198);
this.bindRotation2.Name = "bindRotation2";
this.bindRotation2.Size = new System.Drawing.Size(63, 13);
this.bindRotation2.TabIndex = 16;
this.bindRotation2.Text = "rotationXYZ";
//
// animationTime
//
this.animationTime.AutoSize = true;
this.animationTime.Location = new System.Drawing.Point(471, 12);
this.animationTime.Name = "animationTime";
this.animationTime.Size = new System.Drawing.Size(55, 13);
this.animationTime.TabIndex = 31;
this.animationTime.Text = "Time: time";
//
// keyFrame1Rotation2
//
this.keyFrame1Rotation2.AutoSize = true;
this.keyFrame1Rotation2.Location = new System.Drawing.Point(471, 287);
this.keyFrame1Rotation2.Name = "keyFrame1Rotation2";
this.keyFrame1Rotation2.Size = new System.Drawing.Size(63, 13);
this.keyFrame1Rotation2.TabIndex = 36;
this.keyFrame1Rotation2.Text = "rotationXYZ";
//
// keyFrame1Rotation
//
this.keyFrame1Rotation.AutoSize = true;
this.keyFrame1Rotation.Location = new System.Drawing.Point(471, 271);
this.keyFrame1Rotation.Name = "keyFrame1Rotation";
this.keyFrame1Rotation.Size = new System.Drawing.Size(42, 13);
this.keyFrame1Rotation.TabIndex = 35;
this.keyFrame1Rotation.Text = "rotation";
//
// keyFrame1RotationLabel
//
this.keyFrame1RotationLabel.AutoSize = true;
this.keyFrame1RotationLabel.Location = new System.Drawing.Point(362, 271);
this.keyFrame1RotationLabel.Name = "keyFrame1RotationLabel";
this.keyFrame1RotationLabel.Size = new System.Drawing.Size(47, 13);
this.keyFrame1RotationLabel.TabIndex = 34;
this.keyFrame1RotationLabel.Text = "Rotation";
//
// keyFrame1Position
//
this.keyFrame1Position.AutoSize = true;
this.keyFrame1Position.Location = new System.Drawing.Point(471, 255);
this.keyFrame1Position.Name = "keyFrame1Position";
this.keyFrame1Position.Size = new System.Drawing.Size(43, 13);
this.keyFrame1Position.TabIndex = 33;
this.keyFrame1Position.Text = "position";
//
// keyFrame1PositionLabel
//
this.keyFrame1PositionLabel.AutoSize = true;
this.keyFrame1PositionLabel.Location = new System.Drawing.Point(362, 255);
this.keyFrame1PositionLabel.Name = "keyFrame1PositionLabel";
this.keyFrame1PositionLabel.Size = new System.Drawing.Size(44, 13);
this.keyFrame1PositionLabel.TabIndex = 32;
this.keyFrame1PositionLabel.Text = "Position";
//
// keyFrame2Rotation2
//
this.keyFrame2Rotation2.AutoSize = true;
this.keyFrame2Rotation2.Location = new System.Drawing.Point(471, 371);
this.keyFrame2Rotation2.Name = "keyFrame2Rotation2";
this.keyFrame2Rotation2.Size = new System.Drawing.Size(63, 13);
this.keyFrame2Rotation2.TabIndex = 41;
this.keyFrame2Rotation2.Text = "rotationXYZ";
//
// keyFrame2Rotation
//
this.keyFrame2Rotation.AutoSize = true;
this.keyFrame2Rotation.Location = new System.Drawing.Point(471, 355);
this.keyFrame2Rotation.Name = "keyFrame2Rotation";
this.keyFrame2Rotation.Size = new System.Drawing.Size(42, 13);
this.keyFrame2Rotation.TabIndex = 40;
this.keyFrame2Rotation.Text = "rotation";
//
// keyFrame2RotationLabel
//
this.keyFrame2RotationLabel.AutoSize = true;
this.keyFrame2RotationLabel.Location = new System.Drawing.Point(362, 355);
this.keyFrame2RotationLabel.Name = "keyFrame2RotationLabel";
this.keyFrame2RotationLabel.Size = new System.Drawing.Size(47, 13);
this.keyFrame2RotationLabel.TabIndex = 39;
this.keyFrame2RotationLabel.Text = "Rotation";
//
// keyFrame2Position
//
this.keyFrame2Position.AutoSize = true;
this.keyFrame2Position.Location = new System.Drawing.Point(471, 339);
this.keyFrame2Position.Name = "keyFrame2Position";
this.keyFrame2Position.Size = new System.Drawing.Size(43, 13);
this.keyFrame2Position.TabIndex = 38;
this.keyFrame2Position.Text = "position";
//
// keyFrame2PositionLabel
//
this.keyFrame2PositionLabel.AutoSize = true;
this.keyFrame2PositionLabel.Location = new System.Drawing.Point(362, 339);
this.keyFrame2PositionLabel.Name = "keyFrame2PositionLabel";
this.keyFrame2PositionLabel.Size = new System.Drawing.Size(44, 13);
this.keyFrame2PositionLabel.TabIndex = 37;
this.keyFrame2PositionLabel.Text = "Position";
//
// animationName
//
this.animationName.AutoSize = true;
this.animationName.Location = new System.Drawing.Point(362, 12);
this.animationName.Name = "animationName";
this.animationName.Size = new System.Drawing.Size(85, 13);
this.animationName.TabIndex = 42;
this.animationName.Text = "Animation: name";
//
// keyFrame1TimeLabel
//
this.keyFrame1TimeLabel.AutoSize = true;
this.keyFrame1TimeLabel.Location = new System.Drawing.Point(362, 239);
this.keyFrame1TimeLabel.Name = "keyFrame1TimeLabel";
this.keyFrame1TimeLabel.Size = new System.Drawing.Size(30, 13);
this.keyFrame1TimeLabel.TabIndex = 43;
this.keyFrame1TimeLabel.Text = "Time";
//
// keyFrame2TimeLabel
//
this.keyFrame2TimeLabel.AutoSize = true;
this.keyFrame2TimeLabel.Location = new System.Drawing.Point(362, 323);
this.keyFrame2TimeLabel.Name = "keyFrame2TimeLabel";
this.keyFrame2TimeLabel.Size = new System.Drawing.Size(30, 13);
this.keyFrame2TimeLabel.TabIndex = 44;
this.keyFrame2TimeLabel.Text = "Time";
//
// keyFrame2Time
//
this.keyFrame2Time.AutoSize = true;
this.keyFrame2Time.Location = new System.Drawing.Point(471, 323);
this.keyFrame2Time.Name = "keyFrame2Time";
this.keyFrame2Time.Size = new System.Drawing.Size(26, 13);
this.keyFrame2Time.TabIndex = 45;
this.keyFrame2Time.Text = "time";
//
// keyFrame1Time
//
this.keyFrame1Time.AutoSize = true;
this.keyFrame1Time.Location = new System.Drawing.Point(471, 239);
this.keyFrame1Time.Name = "keyFrame1Time";
this.keyFrame1Time.Size = new System.Drawing.Size(26, 13);
this.keyFrame1Time.TabIndex = 46;
this.keyFrame1Time.Text = "time";
//
// prevKeyframeLabel
//
this.prevKeyframeLabel.AutoSize = true;
this.prevKeyframeLabel.Location = new System.Drawing.Point(362, 223);
this.prevKeyframeLabel.Name = "prevKeyframeLabel";
this.prevKeyframeLabel.Size = new System.Drawing.Size(95, 13);
this.prevKeyframeLabel.TabIndex = 47;
this.prevKeyframeLabel.Text = "Previous Keyframe";
//
// nextKeyframeLabel
//
this.nextKeyframeLabel.AutoSize = true;
this.nextKeyframeLabel.Location = new System.Drawing.Point(362, 307);
this.nextKeyframeLabel.Name = "nextKeyframeLabel";
this.nextKeyframeLabel.Size = new System.Drawing.Size(76, 13);
this.nextKeyframeLabel.TabIndex = 48;
this.nextKeyframeLabel.Text = "Next Keyframe";
//
// BoneDisplay
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(798, 462);
this.Controls.Add(this.nextKeyframeLabel);
this.Controls.Add(this.prevKeyframeLabel);
this.Controls.Add(this.keyFrame1Time);
this.Controls.Add(this.keyFrame2Time);
this.Controls.Add(this.keyFrame2TimeLabel);
this.Controls.Add(this.keyFrame1TimeLabel);
this.Controls.Add(this.keyFrame2Rotation2);
this.Controls.Add(this.keyFrame2Rotation);
this.Controls.Add(this.keyFrame2RotationLabel);
this.Controls.Add(this.keyFrame2Position);
this.Controls.Add(this.keyFrame2PositionLabel);
this.Controls.Add(this.keyFrame1Rotation2);
this.Controls.Add(this.keyFrame1Rotation);
this.Controls.Add(this.keyFrame1RotationLabel);
this.Controls.Add(this.keyFrame1Position);
this.Controls.Add(this.keyFrame1PositionLabel);
this.Controls.Add(this.animationName);
this.Controls.Add(this.animationTime);
this.Controls.Add(this.bindRotation2);
this.Controls.Add(this.bindRotation);
this.Controls.Add(this.bindRotationLabel);
this.Controls.Add(this.bindPosition);
this.Controls.Add(this.bindPositionLabel);
this.Controls.Add(this.relRotation2);
this.Controls.Add(this.boneRotation2);
this.Controls.Add(this.relRotation);
this.Controls.Add(this.relPosition);
this.Controls.Add(this.relRotationLabel);
this.Controls.Add(this.relPositionLabel);
this.Controls.Add(this.boneRotation);
this.Controls.Add(this.boneRotationLabel);
this.Controls.Add(this.boneNameLabel);
this.Controls.Add(this.bonePosition);
this.Controls.Add(this.bonePositionLabel);
this.Controls.Add(this.boneTreeView);
this.Name = "BoneDisplay";
this.ShowInTaskbar = false;
this.Text = "Bone Display";
this.Load += new System.EventHandler(this.BoneDisplay_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TreeView boneTreeView;
private System.Windows.Forms.Label bonePositionLabel;
private System.Windows.Forms.Label bonePosition;
private System.Windows.Forms.Label boneNameLabel;
private System.Windows.Forms.Label boneRotationLabel;
private System.Windows.Forms.Label boneRotation;
private System.Windows.Forms.Label relPositionLabel;
private System.Windows.Forms.Label relRotationLabel;
private System.Windows.Forms.Label relPosition;
private System.Windows.Forms.Label relRotation;
private System.Windows.Forms.Label boneRotation2;
private System.Windows.Forms.Label relRotation2;
private System.Windows.Forms.Label bindPositionLabel;
private System.Windows.Forms.Label bindPosition;
private System.Windows.Forms.Label bindRotationLabel;
private System.Windows.Forms.Label bindRotation;
private System.Windows.Forms.Label bindRotation2;
private System.Windows.Forms.Label animationTime;
private System.Windows.Forms.Label keyFrame1Rotation2;
private System.Windows.Forms.Label keyFrame1Rotation;
private System.Windows.Forms.Label keyFrame1RotationLabel;
private System.Windows.Forms.Label keyFrame1Position;
private System.Windows.Forms.Label keyFrame1PositionLabel;
private System.Windows.Forms.Label keyFrame2Rotation2;
private System.Windows.Forms.Label keyFrame2Rotation;
private System.Windows.Forms.Label keyFrame2RotationLabel;
private System.Windows.Forms.Label keyFrame2Position;
private System.Windows.Forms.Label keyFrame2PositionLabel;
private System.Windows.Forms.Label animationName;
private System.Windows.Forms.Label keyFrame1TimeLabel;
private System.Windows.Forms.Label keyFrame2TimeLabel;
private System.Windows.Forms.Label keyFrame2Time;
private System.Windows.Forms.Label keyFrame1Time;
private System.Windows.Forms.Label prevKeyframeLabel;
private System.Windows.Forms.Label nextKeyframeLabel;
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Configuration;
using System.Reflection;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;
#if MONO_IOS
using System.Linq;
using MonoTouch.Foundation;
#endif
namespace log4net.Util
{
/// <summary>
/// Utility class for system specific information.
/// </summary>
/// <remarks>
/// <para>
/// Utility class of static methods for system specific information.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Alexey Solofnenko</author>
public sealed class SystemInfo
{
#region Private Constants
private const string DEFAULT_NULL_TEXT = "(null)";
private const string DEFAULT_NOT_AVAILABLE_TEXT = "NOT AVAILABLE";
#endregion
#region Private Instance Constructors
/// <summary>
/// Private constructor to prevent instances.
/// </summary>
/// <remarks>
/// <para>
/// Only static methods are exposed from this type.
/// </para>
/// </remarks>
private SystemInfo()
{
}
#endregion Private Instance Constructors
#region Public Static Constructor
/// <summary>
/// Initialize default values for private static fields.
/// </summary>
/// <remarks>
/// <para>
/// Only static methods are exposed from this type.
/// </para>
/// </remarks>
static SystemInfo()
{
string nullText = DEFAULT_NULL_TEXT;
string notAvailableText = DEFAULT_NOT_AVAILABLE_TEXT;
#if !NETCF
// Look for log4net.NullText in AppSettings
string nullTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NullText");
if (nullTextAppSettingsKey != null && nullTextAppSettingsKey.Length > 0)
{
LogLog.Debug(declaringType, "Initializing NullText value to [" + nullTextAppSettingsKey + "].");
nullText = nullTextAppSettingsKey;
}
// Look for log4net.NotAvailableText in AppSettings
string notAvailableTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NotAvailableText");
if (notAvailableTextAppSettingsKey != null && notAvailableTextAppSettingsKey.Length > 0)
{
LogLog.Debug(declaringType, "Initializing NotAvailableText value to [" + notAvailableTextAppSettingsKey + "].");
notAvailableText = notAvailableTextAppSettingsKey;
}
#endif
s_notAvailableText = notAvailableText;
s_nullText = nullText;
}
#endregion
#region Public Static Properties
/// <summary>
/// Gets the system dependent line terminator.
/// </summary>
/// <value>
/// The system dependent line terminator.
/// </value>
/// <remarks>
/// <para>
/// Gets the system dependent line terminator.
/// </para>
/// </remarks>
public static string NewLine
{
get
{
#if NETCF
return "\r\n";
#else
return System.Environment.NewLine;
#endif
}
}
/// <summary>
/// Gets the base directory for this <see cref="AppDomain"/>.
/// </summary>
/// <value>The base directory path for the current <see cref="AppDomain"/>.</value>
/// <remarks>
/// <para>
/// Gets the base directory for this <see cref="AppDomain"/>.
/// </para>
/// <para>
/// The value returned may be either a local file path or a URI.
/// </para>
/// </remarks>
public static string ApplicationBaseDirectory
{
get
{
#if NETCF
return System.IO.Path.GetDirectoryName(SystemInfo.EntryAssemblyLocation) + System.IO.Path.DirectorySeparatorChar;
#else
return AppDomain.CurrentDomain.BaseDirectory;
#endif
}
}
#if MONO_IOS
public static string ApplicationCachesDirectory
{
get
{
return NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User).FirstOrDefault() ?? "";
}
}
#endif
/// <summary>
/// Gets the path to the configuration file for the current <see cref="AppDomain"/>.
/// </summary>
/// <value>The path to the configuration file for the current <see cref="AppDomain"/>.</value>
/// <remarks>
/// <para>
/// The .NET Compact Framework 1.0 does not have a concept of a configuration
/// file. For this runtime, we use the entry assembly location as the root for
/// the configuration file name.
/// </para>
/// <para>
/// The value returned may be either a local file path or a URI.
/// </para>
/// </remarks>
public static string ConfigurationFileLocation
{
get
{
#if NETCF
return SystemInfo.EntryAssemblyLocation+".config";
#else
return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
#endif
}
}
/// <summary>
/// Gets the path to the file that first executed in the current <see cref="AppDomain"/>.
/// </summary>
/// <value>The path to the entry assembly.</value>
/// <remarks>
/// <para>
/// Gets the path to the file that first executed in the current <see cref="AppDomain"/>.
/// </para>
/// </remarks>
public static string EntryAssemblyLocation
{
get
{
#if NETCF
return SystemInfo.NativeEntryAssemblyLocation;
#else
return System.Reflection.Assembly.GetEntryAssembly().Location;
#endif
}
}
/// <summary>
/// Gets the ID of the current thread.
/// </summary>
/// <value>The ID of the current thread.</value>
/// <remarks>
/// <para>
/// On the .NET framework, the <c>AppDomain.GetCurrentThreadId</c> method
/// is used to obtain the thread ID for the current thread. This is the
/// operating system ID for the thread.
/// </para>
/// <para>
/// On the .NET Compact Framework 1.0 it is not possible to get the
/// operating system thread ID for the current thread. The native method
/// <c>GetCurrentThreadId</c> is implemented inline in a header file
/// and cannot be called.
/// </para>
/// <para>
/// On the .NET Framework 2.0 the <c>Thread.ManagedThreadId</c> is used as this
/// gives a stable id unrelated to the operating system thread ID which may
/// change if the runtime is using fibers.
/// </para>
/// </remarks>
public static int CurrentThreadId
{
get
{
#if NETCF_1_0
return System.Threading.Thread.CurrentThread.GetHashCode();
#elif NET_2_0 || NETCF_2_0 || MONO_2_0
return System.Threading.Thread.CurrentThread.ManagedThreadId;
#else
return AppDomain.GetCurrentThreadId();
#endif
}
}
/// <summary>
/// Get the host name or machine name for the current machine
/// </summary>
/// <value>
/// The hostname or machine name
/// </value>
/// <remarks>
/// <para>
/// Get the host name or machine name for the current machine
/// </para>
/// <para>
/// The host name (<see cref="System.Net.Dns.GetHostName"/>) or
/// the machine name (<c>Environment.MachineName</c>) for
/// the current machine, or if neither of these are available
/// then <c>NOT AVAILABLE</c> is returned.
/// </para>
/// </remarks>
public static string HostName
{
get
{
if (s_hostName == null)
{
// Get the DNS host name of the current machine
try
{
// Lookup the host name
s_hostName = System.Net.Dns.GetHostName();
}
catch (System.Net.Sockets.SocketException)
{
LogLog.Debug(declaringType, "Socket exception occurred while getting the dns hostname. Error Ignored.");
}
catch (System.Security.SecurityException)
{
// We may get a security exception looking up the hostname
// You must have Unrestricted DnsPermission to access resource
LogLog.Debug(declaringType, "Security exception occurred while getting the dns hostname. Error Ignored.");
}
catch (Exception ex)
{
LogLog.Debug(declaringType, "Some other exception occurred while getting the dns hostname. Error Ignored.", ex);
}
// Get the NETBIOS machine name of the current machine
if (s_hostName == null || s_hostName.Length == 0)
{
try
{
#if (!SSCLI && !NETCF)
s_hostName = Environment.MachineName;
#endif
}
catch(InvalidOperationException)
{
}
catch(System.Security.SecurityException)
{
// We may get a security exception looking up the machine name
// You must have Unrestricted EnvironmentPermission to access resource
}
}
// Couldn't find a value
if (s_hostName == null || s_hostName.Length == 0)
{
s_hostName = s_notAvailableText;
LogLog.Debug(declaringType, "Could not determine the hostname. Error Ignored. Empty host name will be used");
}
}
return s_hostName;
}
}
/// <summary>
/// Get this application's friendly name
/// </summary>
/// <value>
/// The friendly name of this application as a string
/// </value>
/// <remarks>
/// <para>
/// If available the name of the application is retrieved from
/// the <c>AppDomain</c> using <c>AppDomain.CurrentDomain.FriendlyName</c>.
/// </para>
/// <para>
/// Otherwise the file name of the entry assembly is used.
/// </para>
/// </remarks>
public static string ApplicationFriendlyName
{
get
{
if (s_appFriendlyName == null)
{
try
{
#if !NETCF
s_appFriendlyName = AppDomain.CurrentDomain.FriendlyName;
#endif
}
catch(System.Security.SecurityException)
{
// This security exception will occur if the caller does not have
// some undefined set of SecurityPermission flags.
LogLog.Debug(declaringType, "Security exception while trying to get current domain friendly name. Error Ignored.");
}
if (s_appFriendlyName == null || s_appFriendlyName.Length == 0)
{
try
{
string assemblyLocation = SystemInfo.EntryAssemblyLocation;
s_appFriendlyName = System.IO.Path.GetFileName(assemblyLocation);
}
catch(System.Security.SecurityException)
{
// Caller needs path discovery permission
}
}
if (s_appFriendlyName == null || s_appFriendlyName.Length == 0)
{
s_appFriendlyName = s_notAvailableText;
}
}
return s_appFriendlyName;
}
}
/// <summary>
/// Get the start time for the current process.
/// </summary>
/// <remarks>
/// <para>
/// This is the time at which the log4net library was loaded into the
/// AppDomain. Due to reports of a hang in the call to <c>System.Diagnostics.Process.StartTime</c>
/// this is not the start time for the current process.
/// </para>
/// <para>
/// The log4net library should be loaded by an application early during its
/// startup, therefore this start time should be a good approximation for
/// the actual start time.
/// </para>
/// <para>
/// Note that AppDomains may be loaded and unloaded within the
/// same process without the process terminating, however this start time
/// will be set per AppDomain.
/// </para>
/// </remarks>
public static DateTime ProcessStartTime
{
get { return s_processStartTime; }
}
/// <summary>
/// Text to output when a <c>null</c> is encountered.
/// </summary>
/// <remarks>
/// <para>
/// Use this value to indicate a <c>null</c> has been encountered while
/// outputting a string representation of an item.
/// </para>
/// <para>
/// The default value is <c>(null)</c>. This value can be overridden by specifying
/// a value for the <c>log4net.NullText</c> appSetting in the application's
/// .config file.
/// </para>
/// </remarks>
public static string NullText
{
get { return s_nullText; }
set { s_nullText = value; }
}
/// <summary>
/// Text to output when an unsupported feature is requested.
/// </summary>
/// <remarks>
/// <para>
/// Use this value when an unsupported feature is requested.
/// </para>
/// <para>
/// The default value is <c>NOT AVAILABLE</c>. This value can be overridden by specifying
/// a value for the <c>log4net.NotAvailableText</c> appSetting in the application's
/// .config file.
/// </para>
/// </remarks>
public static string NotAvailableText
{
get { return s_notAvailableText; }
set { s_notAvailableText = value; }
}
#endregion Public Static Properties
#region Public Static Methods
/// <summary>
/// Gets the assembly location path for the specified assembly.
/// </summary>
/// <param name="myAssembly">The assembly to get the location for.</param>
/// <returns>The location of the assembly.</returns>
/// <remarks>
/// <para>
/// This method does not guarantee to return the correct path
/// to the assembly. If only tries to give an indication as to
/// where the assembly was loaded from.
/// </para>
/// </remarks>
public static string AssemblyLocationInfo(Assembly myAssembly)
{
#if NETCF
return "Not supported on Microsoft .NET Compact Framework";
#else
if (myAssembly.GlobalAssemblyCache)
{
return "Global Assembly Cache";
}
else
{
try
{
#if NET_4_0 || MONO_IOS
if (myAssembly.IsDynamic)
{
return "Dynamic Assembly";
}
#else
if (myAssembly is System.Reflection.Emit.AssemblyBuilder)
{
return "Dynamic Assembly";
}
else if(myAssembly.GetType().FullName == "System.Reflection.Emit.InternalAssemblyBuilder")
{
return "Dynamic Assembly";
}
#endif
else
{
// This call requires FileIOPermission for access to the path
// if we don't have permission then we just ignore it and
// carry on.
return myAssembly.Location;
}
}
catch (NotSupportedException)
{
// The location information may be unavailable for dynamic assemblies and a NotSupportedException
// is thrown in those cases. See: http://msdn.microsoft.com/de-de/library/system.reflection.assembly.location.aspx
return "Dynamic Assembly";
}
catch (TargetInvocationException ex)
{
return "Location Detect Failed (" + ex.Message + ")";
}
catch (ArgumentException ex)
{
return "Location Detect Failed (" + ex.Message + ")";
}
catch (System.Security.SecurityException)
{
return "Location Permission Denied";
}
}
#endif
}
/// <summary>
/// Gets the fully qualified name of the <see cref="Type" />, including
/// the name of the assembly from which the <see cref="Type" /> was
/// loaded.
/// </summary>
/// <param name="type">The <see cref="Type" /> to get the fully qualified name for.</param>
/// <returns>The fully qualified name for the <see cref="Type" />.</returns>
/// <remarks>
/// <para>
/// This is equivalent to the <c>Type.AssemblyQualifiedName</c> property,
/// but this method works on the .NET Compact Framework 1.0 as well as
/// the full .NET runtime.
/// </para>
/// </remarks>
public static string AssemblyQualifiedName(Type type)
{
return type.FullName + ", " + type.Assembly.FullName;
}
/// <summary>
/// Gets the short name of the <see cref="Assembly" />.
/// </summary>
/// <param name="myAssembly">The <see cref="Assembly" /> to get the name for.</param>
/// <returns>The short name of the <see cref="Assembly" />.</returns>
/// <remarks>
/// <para>
/// The short name of the assembly is the <see cref="Assembly.FullName" />
/// without the version, culture, or public key. i.e. it is just the
/// assembly's file name without the extension.
/// </para>
/// <para>
/// Use this rather than <c>Assembly.GetName().Name</c> because that
/// is not available on the Compact Framework.
/// </para>
/// <para>
/// Because of a FileIOPermission security demand we cannot do
/// the obvious Assembly.GetName().Name. We are allowed to get
/// the <see cref="Assembly.FullName" /> of the assembly so we
/// start from there and strip out just the assembly name.
/// </para>
/// </remarks>
public static string AssemblyShortName(Assembly myAssembly)
{
string name = myAssembly.FullName;
int offset = name.IndexOf(',');
if (offset > 0)
{
name = name.Substring(0, offset);
}
return name.Trim();
// TODO: Do we need to unescape the assembly name string?
// Doc says '\' is an escape char but has this already been
// done by the string loader?
}
/// <summary>
/// Gets the file name portion of the <see cref="Assembly" />, including the extension.
/// </summary>
/// <param name="myAssembly">The <see cref="Assembly" /> to get the file name for.</param>
/// <returns>The file name of the assembly.</returns>
/// <remarks>
/// <para>
/// Gets the file name portion of the <see cref="Assembly" />, including the extension.
/// </para>
/// </remarks>
public static string AssemblyFileName(Assembly myAssembly)
{
#if NETCF
// This is not very good because it assumes that only
// the entry assembly can be an EXE. In fact multiple
// EXEs can be loaded in to a process.
string assemblyShortName = SystemInfo.AssemblyShortName(myAssembly);
string entryAssemblyShortName = System.IO.Path.GetFileNameWithoutExtension(SystemInfo.EntryAssemblyLocation);
if (string.Compare(assemblyShortName, entryAssemblyShortName, true) == 0)
{
// assembly is entry assembly
return assemblyShortName + ".exe";
}
else
{
// assembly is not entry assembly
return assemblyShortName + ".dll";
}
#else
return System.IO.Path.GetFileName(myAssembly.Location);
#endif
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeType">A sibling type to use to load the type.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified, it will be loaded from the assembly
/// containing the specified relative type. If the type is not found in the assembly
/// then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase);
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the
/// assembly that is directly calling this method. If the type is not found
/// in the assembly then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase);
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeAssembly">An assembly to load the type from.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the specified
/// assembly. If the type is not found in the assembly then all the loaded assemblies
/// will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase)
{
// Check if the type name specifies the assembly name
if(typeName.IndexOf(',') == -1)
{
//LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
#if NETCF
return relativeAssembly.GetType(typeName, throwOnError);
#else
// Attempt to lookup the type from the relativeAssembly
Type type = relativeAssembly.GetType(typeName, false, ignoreCase);
if (type != null)
{
// Found type in relative assembly
//LogLog.Debug(declaringType, "SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
return type;
}
Assembly[] loadedAssemblies = null;
try
{
loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
}
catch(System.Security.SecurityException)
{
// Insufficient permissions to get the list of loaded assemblies
}
if (loadedAssemblies != null)
{
// Search the loaded assemblies for the type
foreach (Assembly assembly in loadedAssemblies)
{
type = assembly.GetType(typeName, false, ignoreCase);
if (type != null)
{
// Found type in loaded assembly
LogLog.Debug(declaringType, "Loaded type ["+typeName+"] from assembly ["+assembly.FullName+"] by searching loaded assemblies.");
return type;
}
}
}
// Didn't find the type
if (throwOnError)
{
throw new TypeLoadException("Could not load type ["+typeName+"]. Tried assembly ["+relativeAssembly.FullName+"] and all loaded assemblies");
}
return null;
#endif
}
else
{
// Includes explicit assembly name
//LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from global Type");
#if NETCF
// In NETCF 2 and 3 arg versions seem to behave differently
// https://issues.apache.org/jira/browse/LOG4NET-113
return Type.GetType(typeName, throwOnError);
#else
return Type.GetType(typeName, throwOnError, ignoreCase);
#endif
}
}
/// <summary>
/// Generate a new guid
/// </summary>
/// <returns>A new Guid</returns>
/// <remarks>
/// <para>
/// Generate a new guid
/// </para>
/// </remarks>
public static Guid NewGuid()
{
#if NETCF_1_0
return PocketGuid.NewGuid();
#else
return Guid.NewGuid();
#endif
}
/// <summary>
/// Create an <see cref="ArgumentOutOfRangeException"/>
/// </summary>
/// <param name="parameterName">The name of the parameter that caused the exception</param>
/// <param name="actualValue">The value of the argument that causes this exception</param>
/// <param name="message">The message that describes the error</param>
/// <returns>the ArgumentOutOfRangeException object</returns>
/// <remarks>
/// <para>
/// Create a new instance of the <see cref="ArgumentOutOfRangeException"/> class
/// with a specified error message, the parameter name, and the value
/// of the argument.
/// </para>
/// <para>
/// The Compact Framework does not support the 3 parameter constructor for the
/// <see cref="ArgumentOutOfRangeException"/> type. This method provides an
/// implementation that works for all platforms.
/// </para>
/// </remarks>
public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message)
{
#if NETCF_1_0
return new ArgumentOutOfRangeException(message + " [param=" + parameterName + "] [value=" + actualValue + "]");
#elif NETCF_2_0
return new ArgumentOutOfRangeException(parameterName, message + " [value=" + actualValue + "]");
#else
return new ArgumentOutOfRangeException(parameterName, actualValue, message);
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int32"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out int val)
{
#if NETCF
val = 0;
try
{
val = int.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt32(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int64"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out long val)
{
#if NETCF
val = 0;
try
{
val = long.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt64(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int16"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out short val)
{
#if NETCF
val = 0;
try
{
val = short.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt16(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Lookup an application setting
/// </summary>
/// <param name="key">the application settings key to lookup</param>
/// <returns>the value for the key, or <c>null</c></returns>
/// <remarks>
/// <para>
/// Configuration APIs are not supported under the Compact Framework
/// </para>
/// </remarks>
public static string GetAppSetting(string key)
{
try
{
#if NETCF || MONO_IOS
// Configuration APIs are not suported under the Compact Framework
#elif NET_2_0
return ConfigurationManager.AppSettings[key];
#else
return ConfigurationSettings.AppSettings[key];
#endif
}
catch(Exception ex)
{
// If an exception is thrown here then it looks like the config file does not parse correctly.
LogLog.Error(declaringType, "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex);
}
return null;
}
/// <summary>
/// Convert a path into a fully qualified local file path.
/// </summary>
/// <param name="path">The path to convert.</param>
/// <returns>The fully qualified path.</returns>
/// <remarks>
/// <para>
/// Converts the path specified to a fully
/// qualified path. If the path is relative it is
/// taken as relative from the application base
/// directory.
/// </para>
/// <para>
/// The path specified must be a local file path, a URI is not supported.
/// </para>
/// </remarks>
public static string ConvertToFullPath(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
string baseDirectory = "";
try
{
string applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
if (applicationBaseDirectory != null)
{
// applicationBaseDirectory may be a URI not a local file path
Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory);
if (applicationBaseDirectoryUri.IsFile)
{
baseDirectory = applicationBaseDirectoryUri.LocalPath;
}
}
}
catch
{
// Ignore URI exceptions & SecurityExceptions from SystemInfo.ApplicationBaseDirectory
}
if (baseDirectory != null && baseDirectory.Length > 0)
{
// Note that Path.Combine will return the second path if it is rooted
return Path.GetFullPath(Path.Combine(baseDirectory, path));
}
return Path.GetFullPath(path);
}
/// <summary>
/// Creates a new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity.
/// </summary>
/// <returns>A new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity</returns>
/// <remarks>
/// <para>
/// The new Hashtable instance uses the default load factor, the CaseInsensitiveHashCodeProvider, and the CaseInsensitiveComparer.
/// </para>
/// </remarks>
public static Hashtable CreateCaseInsensitiveHashtable()
{
#if NETCF_1_0
return new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default);
#elif NETCF_2_0 || NET_2_0 || MONO_2_0 || MONO_IOS
return new Hashtable(StringComparer.OrdinalIgnoreCase);
#else
return System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable();
#endif
}
#endregion Public Static Methods
#region Private Static Methods
#if NETCF
private static string NativeEntryAssemblyLocation
{
get
{
StringBuilder moduleName = null;
IntPtr moduleHandle = GetModuleHandle(IntPtr.Zero);
if (moduleHandle != IntPtr.Zero)
{
moduleName = new StringBuilder(255);
if (GetModuleFileName(moduleHandle, moduleName, moduleName.Capacity) == 0)
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
}
else
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
return moduleName.ToString();
}
}
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern IntPtr GetModuleHandle(IntPtr ModuleName);
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern Int32 GetModuleFileName(
IntPtr hModule,
StringBuilder ModuleName,
Int32 cch);
#endif
#endregion Private Static Methods
#region Public Static Fields
/// <summary>
/// Gets an empty array of types.
/// </summary>
/// <remarks>
/// <para>
/// The <c>Type.EmptyTypes</c> field is not available on
/// the .NET Compact Framework 1.0.
/// </para>
/// </remarks>
public static readonly Type[] EmptyTypes = new Type[0];
#endregion Public Static Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the SystemInfo class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(SystemInfo);
/// <summary>
/// Cache the host name for the current machine
/// </summary>
private static string s_hostName;
/// <summary>
/// Cache the application friendly name
/// </summary>
private static string s_appFriendlyName;
/// <summary>
/// Text to output when a <c>null</c> is encountered.
/// </summary>
private static string s_nullText;
/// <summary>
/// Text to output when an unsupported feature is requested.
/// </summary>
private static string s_notAvailableText;
/// <summary>
/// Start time for the current process.
/// </summary>
private static DateTime s_processStartTime = DateTime.Now;
#endregion
#region Compact Framework Helper Classes
#if NETCF_1_0
/// <summary>
/// Generate GUIDs on the .NET Compact Framework.
/// </summary>
public class PocketGuid
{
// guid variant types
private enum GuidVariant
{
ReservedNCS = 0x00,
Standard = 0x02,
ReservedMicrosoft = 0x06,
ReservedFuture = 0x07
}
// guid version types
private enum GuidVersion
{
TimeBased = 0x01,
Reserved = 0x02,
NameBased = 0x03,
Random = 0x04
}
// constants that are used in the class
private class Const
{
// number of bytes in guid
public const int ByteArraySize = 16;
// multiplex variant info
public const int VariantByte = 8;
public const int VariantByteMask = 0x3f;
public const int VariantByteShift = 6;
// multiplex version info
public const int VersionByte = 7;
public const int VersionByteMask = 0x0f;
public const int VersionByteShift = 4;
}
// imports for the crypto api functions
private class WinApi
{
public const uint PROV_RSA_FULL = 1;
public const uint CRYPT_VERIFYCONTEXT = 0xf0000000;
[DllImport("CoreDll.dll")]
public static extern bool CryptAcquireContext(
ref IntPtr phProv, string pszContainer, string pszProvider,
uint dwProvType, uint dwFlags);
[DllImport("CoreDll.dll")]
public static extern bool CryptReleaseContext(
IntPtr hProv, uint dwFlags);
[DllImport("CoreDll.dll")]
public static extern bool CryptGenRandom(
IntPtr hProv, int dwLen, byte[] pbBuffer);
}
// all static methods
private PocketGuid()
{
}
/// <summary>
/// Return a new System.Guid object.
/// </summary>
public static Guid NewGuid()
{
IntPtr hCryptProv = IntPtr.Zero;
Guid guid = Guid.Empty;
try
{
// holds random bits for guid
byte[] bits = new byte[Const.ByteArraySize];
// get crypto provider handle
if (!WinApi.CryptAcquireContext(ref hCryptProv, null, null,
WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT))
{
throw new SystemException(
"Failed to acquire cryptography handle.");
}
// generate a 128 bit (16 byte) cryptographically random number
if (!WinApi.CryptGenRandom(hCryptProv, bits.Length, bits))
{
throw new SystemException(
"Failed to generate cryptography random bytes.");
}
// set the variant
bits[Const.VariantByte] &= Const.VariantByteMask;
bits[Const.VariantByte] |=
((int)GuidVariant.Standard << Const.VariantByteShift);
// set the version
bits[Const.VersionByte] &= Const.VersionByteMask;
bits[Const.VersionByte] |=
((int)GuidVersion.Random << Const.VersionByteShift);
// create the new System.Guid object
guid = new Guid(bits);
}
finally
{
// release the crypto provider handle
if (hCryptProv != IntPtr.Zero)
WinApi.CryptReleaseContext(hCryptProv, 0);
}
return guid;
}
}
#endif
#endregion Compact Framework Helper Classes
}
}
| |
using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Touch;
using Skewworks.NETMF.Controls;
// ReSharper disable StringIndexOfIsCultureSpecific.1
namespace Skewworks.NETMF
{
/// <summary>
/// Class for managing all EWR settings
/// </summary>
public class SettingsManager
{
#region Variables
private static ManualResetEvent _activeBlock; // Used to display Modal Forms
private static bool _bLoaded;
#endregion
#region Properties
/// <summary>
/// Gets the current LCD settings
/// </summary>
public static LCDSettings LCD
{
get
{
if (!_bLoaded)
{
LoadLCDSettings();
_bLoaded = true;
}
return _lcd;
}
}
#endregion
#region Public Methods
/// <summary>
/// Starts the touch calibration
/// </summary>
/// <param name="cc">Configuration to use when calibrating the screen</param>
/// <remarks>
/// This will show the touch calibration window.
/// </remarks>
public static void CalibrateTouch(CalibrationConfiguration cc)
{
IContainer prv = Core.ActiveContainer;
var cw = new CalibrationWindow(cc);
Core.ActiveContainer = cw;
_activeBlock = new ManualResetEvent(false);
_activeBlock.Reset();
while (!_activeBlock.WaitOne(1000, false))
{ }
_activeBlock = null;
Core.ActiveContainer = prv;
}
#endregion
#region LCD Settings
// dummy type to identify the EWR
private class LcdEwr
{ }
private static ExtendedWeakReference _lcdEwrSettings;
private static LCDSettings _lcd;
/// <summary>
/// LCD settings for the touch screen
/// </summary>
[Serializable]
public class LCDSettings
{
/// <summary>
/// Creates new LCD settings
/// </summary>
/// <param name="calibrate">Calibration mode</param>
/// <param name="calibrationPoints">Number of points used for calibration</param>
/// <param name="calibrationSx">SX values of calibration</param>
/// <param name="calibrationSy">SY values of calibration</param>
/// <param name="calibrationCx">CX values of calibration</param>
/// <param name="calibrationCy">CY values of calibration</param>
public LCDSettings(ScreenCalibration calibrate, int calibrationPoints, short[] calibrationSx, short[] calibrationSy, short[] calibrationCx, short[] calibrationCy)
{
calibrateLCD = calibrate;
calibrationpoints = calibrationPoints;
calibrationSX = calibrationSx;
calibrationSY = calibrationSy;
calibrationCX = calibrationCx;
calibrationCY = calibrationCy;
}
// ReSharper disable InconsistentNaming
// Fields must be realizable.
/// <summary>
/// Calibration mode
/// </summary>
public ScreenCalibration calibrateLCD;
/// <summary>
/// Number of points used for calibration
/// </summary>
public int calibrationpoints;
/// <summary>
/// SX values of calibration
/// </summary>
public short[] calibrationSX;
/// <summary>
/// SY values of calibration
/// </summary>
public short[] calibrationSY;
/// <summary>
/// CX values of calibration
/// </summary>
public short[] calibrationCX;
/// <summary>
/// CY values of calibration
/// </summary>
public short[] calibrationCY;
// ReSharper restore InconsistentNaming
}
private static void LoadLCDSettings()
{
// Grab the data
_lcdEwrSettings = ExtendedWeakReference.RecoverOrCreate(typeof(LcdEwr), 0, ExtendedWeakReference.c_SurvivePowerdown);
_lcdEwrSettings.Priority = (Int32)ExtendedWeakReference.PriorityLevel.Critical;
_lcd = (LCDSettings)_lcdEwrSettings.Target;
}
/// <summary>
/// Restores touch calibration from EWR
/// </summary>
public static void RestoreLCDCalibration()
{
// Set calibration
Touch.ActiveTouchPanel.SetCalibration(_lcd.calibrationpoints, _lcd.calibrationSX, _lcd.calibrationSY, _lcd.calibrationCX, _lcd.calibrationCY);
}
/// <summary>
/// Restores touch calibration from supplied points
/// </summary>
/// <param name="points">Number of points used for calibration</param>
/// <param name="sx">SX values of calibration</param>
/// <param name="sy">SY values of calibration</param>
/// <param name="cx">CX values of calibration</param>
/// <param name="cy">CY values of calibration</param>
public static void RestoreLCDCalibration(int points, short[] sx, short[] sy, short[] cx, short[] cy)
{
// Set calibration
Touch.ActiveTouchPanel.SetCalibration(points, sx, sy, cx, cy);
}
/// <summary>
/// Save touch calibration to EWR
/// </summary>
/// <param name="calibrationPoints">Number of points used for calibration</param>
/// <param name="calibrationSx">SX values of calibration</param>
/// <param name="calibrationSy">SY values of calibration</param>
/// <param name="calibrationCx">CX values of calibration</param>
/// <param name="calibrationCy">CY values of calibration</param>
/// <returns>Returns true if the calibration was successfully saved.</returns>
public static bool SaveLCDCalibration(int calibrationPoints, short[] calibrationSx, short[] calibrationSy, short[] calibrationCx, short[] calibrationCy)
{
// Save calibration
if (_lcd == null)
{
_lcd = new LCDSettings(ScreenCalibration.Restore, calibrationPoints, calibrationSx, calibrationSy, calibrationCx, calibrationCy);
}
else
{
_lcd.calibrateLCD = ScreenCalibration.Restore;
_lcd.calibrationpoints = calibrationPoints;
_lcd.calibrationSX = calibrationSx;
_lcd.calibrationSY = calibrationSy;
_lcd.calibrationCX = calibrationCx;
_lcd.calibrationCY = calibrationCy;
}
_lcdEwrSettings.Target = _lcd;
return true;
}
#endregion
#region Calibration Control
private sealed class CalibrationWindow : Container
{
#region Variables
readonly point[] _calpoints;
int _currentCalpoint;
readonly short[] _sx;
readonly short[] _sy;
readonly short[] _cx;
readonly short[] _cy;
readonly int _x;
readonly int _y;
readonly int _calibrationpointCount;
bool _step1;
readonly CalibrationConfiguration _cc;
#endregion
#region Constructor
public CalibrationWindow(CalibrationConfiguration cc)
{
int i;
_sy = null;
_cc = cc;
_step1 = true;
X = 0;
Y = 0;
Width = Core.Screen.Width;
Height = Core.Screen.Height;
// Ask the touch system how many points are needed to
// calibrate.
Touch.ActiveTouchPanel.GetCalibrationPointCount(ref _calibrationpointCount);
// Create the calibration point array.
_calpoints = new point[_calibrationpointCount];
_sx = new short[_calibrationpointCount];
_sy = new short[_calibrationpointCount];
_cx = new short[_calibrationpointCount];
_cy = new short[_calibrationpointCount];
// Get the points for calibration.
for (i = 0; i < _calibrationpointCount; i++)
{
Touch.ActiveTouchPanel.GetCalibrationPoint(i, ref _x, ref _y);
_calpoints[i].X = _x;
_calpoints[i].Y = _y;
_sx[i] = (short)_x;
_sy[i] = (short)_y;
}
// Start the calibration process.
_currentCalpoint = 0;
Touch.ActiveTouchPanel.StartCalibration();
}
#endregion
#region Properties
private bool Done { get; set; }
#endregion
#region Touch Overrides
// ReSharper disable once RedundantAssignment
protected override void TouchUpMessage(object sender, point point, ref bool handled)
{
handled = true;
try
{
if (_step1)
{
_step1 = false;
Render(true);
return;
}
if (Done)
{
return;
}
++_currentCalpoint;
_cx[_currentCalpoint - 1] = (short) point.X;
_cy[_currentCalpoint - 1] = (short) point.Y;
if (_currentCalpoint == _calpoints.Length)
{
Touch.ActiveTouchPanel.SetCalibration(_calpoints.Length, _sx, _sy, _cx, _cy);
if (ConfirmCalibration())
{
// The last point has been reached , so set the
// calibration.
Touch.ActiveTouchPanel.SetCalibration(_calpoints.Length, _sx, _sy, _cx, _cy);
SaveLCDCalibration(_calpoints.Length, _sx, _sy, _cx, _cy);
Done = true;
_activeBlock.Set();
return;
}
Touch.ActiveTouchPanel.StartCalibration();
_currentCalpoint = 0;
}
Render(true);
}
finally
{
base.TouchUpMessage(sender, point, ref handled);
}
}
#endregion
#region Private Methods
private bool ConfirmCalibration()
{
var bChecked = new bool[3];
var rects = new rect[3];
long lStop = 0;
int y = Core.Screen.Height / 2 - (_cc.ConfirmationBoxSize + _cc.Font.Height);
int x = Core.Screen.Width / 2 - (_cc.ConfirmationBoxSize * 3 + _cc.ConfirmationBoxSpacing * 2) / 2;
const long l100Ms = TimeSpan.TicksPerMillisecond * 100;
string confLeft;
string confRight;
int i = _cc.ConfirmationText.IndexOf("[SECONDS]");
if (i == 0)
{
confLeft = _cc.ConfirmationText;
confRight = string.Empty;
}
else
{
confLeft = _cc.ConfirmationText.Substring(0, i);
confRight = _cc.ConfirmationText.Substring(i + 9);
}
rects[0] = new rect(x, y, _cc.ConfirmationBoxSize, _cc.ConfirmationBoxSize);
rects[1] = new rect(x + _cc.ConfirmationBoxSize + _cc.ConfirmationBoxSpacing, y, _cc.ConfirmationBoxSize, _cc.ConfirmationBoxSize);
rects[2] = new rect(rects[1].X + _cc.ConfirmationBoxSize + _cc.ConfirmationBoxSpacing, y, _cc.ConfirmationBoxSize, _cc.ConfirmationBoxSize);
while (true)
{
string s;
if (lStop == 0)
{
Core.Screen.SetClippingRectangle(0, 0, Core.Screen.Width, Core.Screen.Height);
Core.Screen.DrawRectangle(0, 0, 0, 0, Width, Height, 0, 0, _cc.BackgroundGradientTop, 0, 0, _cc.BackgroundGradientBottom, 0, Height, 256);
// Draw Check boxes
DrawCheckbox(rects[0].X, rects[0].Y, false);
DrawCheckbox(rects[1].X, rects[1].Y, false);
DrawCheckbox(rects[2].X, rects[2].Y, false);
// Draw Text
if (confRight == string.Empty)
s = confLeft;
else
s = confLeft + _cc.ConfirmationTimeout + confRight;
Core.Screen.DrawTextInRect(s, 0, y + 21, Core.Screen.Width, _cc.Font.Height * 2, Bitmap.DT_AlignmentCenter, _cc.ForeColor, _cc.Font);
Core.Screen.Flush();
lStop = DateTime.Now.Ticks + (TimeSpan.TicksPerSecond * _cc.ConfirmationTimeout);
}
else if (lStop < DateTime.Now.Ticks)
return false;
// Get Touch Down
point p = Core.ManualTouchPoint(DateTime.Now.Ticks + l100Ms).location;
for (i = 0; i < 3; i++)
{
if (rects[i].Contains(p))
{
bChecked[i] = true;
break;
}
}
float remain = (float)(lStop - DateTime.Now.Ticks) / TimeSpan.TicksPerSecond;
// Refresh Screen
Core.Screen.DrawRectangle(0, 0, 0, 0, Width, Height, 0, 0, _cc.BackgroundGradientTop, 0, 0, _cc.BackgroundGradientBottom, 0, Height, 256);
DrawCheckbox(rects[0].X, rects[0].Y, bChecked[0]);
DrawCheckbox(rects[1].X, rects[1].Y, bChecked[1]);
DrawCheckbox(rects[2].X, rects[2].Y, bChecked[2]);
if (confRight == string.Empty)
{
s = confLeft;
}
else
{
s = confLeft + System.Math.Round(remain) + confRight;
}
Core.Screen.DrawTextInRect(s, 0, y + 21, Core.Screen.Width, _cc.Font.Height * 2, Bitmap.DT_AlignmentCenter, _cc.ForeColor, _cc.Font);
Core.Screen.Flush();
if (bChecked[0] && bChecked[1] && bChecked[2])
{
Thread.Sleep(100);
return true;
}
}
}
private void DrawCheckbox(int x, int y, bool Checked)
{
Core.Screen.DrawRectangle(Colors.DarkGray, 1, x, y, _cc.ConfirmationBoxSize, _cc.ConfirmationBoxSize, 0, 0, Colors.Wheat, x, y, Colors.LightGray, x, y + 14, 256);
Core.Screen.DrawLine(Colors.Wheat, 1, x, y + _cc.ConfirmationBoxSize, x + _cc.ConfirmationBoxSize, y + _cc.ConfirmationBoxSize);
Core.Screen.DrawLine(Colors.Wheat, 1, x + _cc.ConfirmationBoxSize, y, x + _cc.ConfirmationBoxSize, y + _cc.ConfirmationBoxSize);
if (Checked)
{
Core.Screen.DrawRectangle(ColorUtility.ColorFromRGB(73, 187, 0), 1, x + 4, y + 4, _cc.ConfirmationBoxSize - 8, _cc.ConfirmationBoxSize - 8, 0, 0, ColorUtility.ColorFromRGB(160, 243, 0), x, y, ColorUtility.ColorFromRGB(73, 187, 0), x, y + _cc.ConfirmationBoxSize, 256);
}
}
#endregion
#region GUI
protected override void OnRender(int x, int y, int width, int height)
{
if (_step1)
{
Core.Screen.DrawRectangle(0, 0, 0, 0, Width, Height, 0, 0, _cc.BackgroundGradientTop, 0, 0, _cc.BackgroundGradientBottom, 0, Height, 256);
Core.Screen.DrawTextInRect(_cc.InitialText, 0, Height / 2 - _cc.Font.Height / 2, Width, _cc.Font.Height, Bitmap.DT_AlignmentCenter, _cc.ForeColor, _cc.Font);
}
else
{
Core.Screen.DrawRectangle(0, 0, 0, 0, Width, Height, 0, 0, _cc.BackgroundGradientTop, 0, 0, _cc.BackgroundGradientBottom, 0, Height, 256);
Core.Screen.DrawLine(_cc.CrossHairColor, 1, _calpoints[_currentCalpoint].X - 10, _calpoints[_currentCalpoint].Y, _calpoints[_currentCalpoint].X - 2, _calpoints[_currentCalpoint].Y);
Core.Screen.DrawLine(_cc.CrossHairColor, 1, _calpoints[_currentCalpoint].X + 10, _calpoints[_currentCalpoint].Y, _calpoints[_currentCalpoint].X + 2, _calpoints[_currentCalpoint].Y);
Core.Screen.DrawLine(_cc.CrossHairColor, 1, _calpoints[_currentCalpoint].X, _calpoints[_currentCalpoint].Y - 10, _calpoints[_currentCalpoint].X, _calpoints[_currentCalpoint].Y - 2);
Core.Screen.DrawLine(_cc.CrossHairColor, 1, _calpoints[_currentCalpoint].X, _calpoints[_currentCalpoint].Y + 10, _calpoints[_currentCalpoint].X, _calpoints[_currentCalpoint].Y + 2);
Core.Screen.DrawTextInRect(_cc.CalibrationText, 0, Height - _cc.Font.Height - 8, Width, _cc.Font.Height, Bitmap.DT_AlignmentCenter, _cc.ForeColor, _cc.Font);
}
}
#endregion
}
#endregion
}
#region Calibration Configuration
/// <summary>
/// Configuration to be used for calibration
/// </summary>
/// <remarks>
/// The calibration configuration allows to customize the appearance of the calibration window.
/// </remarks>
public class CalibrationConfiguration
{
#region Constants
// ReSharper disable InconsistentNaming
/// <summary>
/// Default text for initial calibration text
/// </summary>
public const string INIT_CALI_TEXT = "Tap to Begin Calibration";
/// <summary>
/// Default text for calibration instruction
/// </summary>
public const string CNFG_CALI_TEXT = "Tap cross hairs to Calibrate";
/// <summary>
/// Default text for calibration verification
/// </summary>
public const string CONF_CALI_TEXT = "Tap all 3 boxes to confirm calibration.\nRestarting Calibration in [SECONDS] seconds";
// ReSharper restore InconsistentNaming
#endregion
#region Constructor
/// <summary>
/// Creates a new calibration configuration
/// </summary>
public CalibrationConfiguration()
{
BackgroundGradientTop = Colors.White;
BackgroundGradientBottom = Colors.White;
ForeColor = ColorUtility.ColorFromRGB(0, 161, 241);
CrossHairColor = ColorUtility.ColorFromRGB(246, 83, 20);
InitialText = INIT_CALI_TEXT;
CalibrationText = CNFG_CALI_TEXT;
ConfirmationText = CONF_CALI_TEXT;
ConfirmationTimeout = 30;
ConfirmationBoxSize = 20;
Font = Resources.GetFont(Resources.FontResources.droid12);
ConfirmationBoxSpacing = 50;
}
#endregion
#region Properties
/// <summary>
/// Gets/Sets the bottom gradient color of the background
/// </summary>
public Color BackgroundGradientBottom { get; set; }
/// <summary>
/// Gets/Sets the top gradient color of the background
/// </summary>
public Color BackgroundGradientTop { get; set; }
/// <summary>
/// Gets/Sets the calibration instruction text
/// </summary>
public string CalibrationText { get; set; }
/// <summary>
/// Gets/Sets the confirmation box size
/// </summary>
public int ConfirmationBoxSize { get; set; }
/// <summary>
/// Gets/Sets the confirmation box spacing
/// </summary>
public int ConfirmationBoxSpacing { get; set; }
/// <summary>
/// Gets/Sets the confirmation text
/// </summary>
public string ConfirmationText { get; set; }
/// <summary>
/// Gets/Sets the confirmation timeout in seconds.
/// </summary>
public int ConfirmationTimeout { get; set; }
/// <summary>
/// Gets/Sets the color of the cross hairs
/// </summary>
public Color CrossHairColor { get; set; }
/// <summary>
/// Gets/Sets the font to be used to render the text
/// </summary>
public Font Font { get; set; }
/// <summary>
/// Gets/Sets the color to render the text
/// </summary>
public Color ForeColor { get; set; }
/// <summary>
/// Gets/Sets the initial text
/// </summary>
public string InitialText { get; set; }
#endregion
}
#endregion
}
// ReSharper restore StringIndexOfIsCultureSpecific.1
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// NOTE: A vast majority of this code was copied from BCL in
// Namespace: Microsoft.Win32
//
/*
* Notes to PInvoke users: Getting the syntax exactly correct is crucial, and
* more than a little confusing. Here's some guidelines.
*
* For handles, you should use a SafeHandle subclass specific to your handle
* type.
*/
namespace Microsoft.PowerShell.Commands.Internal
{
using System;
using System.Security;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Runtime.Versioning;
using System.Management.Automation;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.ConstrainedExecution;
using BOOL = System.Int32;
using DWORD = System.UInt32;
using ULONG = System.UInt32;
/**
* Win32 encapsulation for MSCORLIB.
*/
// Remove the default demands for all N/Direct methods with this
// global declaration on the class.
//
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class Win32Native
{
#region Integer Const
internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A;
#endregion Integer Const
#region Enum
internal enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin
}
internal enum SID_NAME_USE
{
SidTypeUser = 1,
SidTypeGroup,
SidTypeDomain,
SidTypeAlias,
SidTypeWellKnownGroup,
SidTypeDeletedAccount,
SidTypeInvalid,
SidTypeUnknown,
SidTypeComputer
}
#endregion Enum
#region Struct
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct SID_AND_ATTRIBUTES
{
internal IntPtr Sid;
internal uint Attributes;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct TOKEN_USER
{
internal SID_AND_ATTRIBUTES User;
}
#endregion Struct
#region PInvoke methods
/// <summary>
/// The LookupAccountSid function accepts a security identifier (SID) as input. It retrieves the name
/// of the account for this SID and the name of the first domain on which this SID is found.
/// </summary>
/// <param name="lpSystemName"></param>
/// <param name="sid"></param>
/// <param name="lpName"></param>
/// <param name="cchName"></param>
/// <param name="referencedDomainName"></param>
/// <param name="cchReferencedDomainName"></param>
/// <param name="peUse"></param>
/// <returns></returns>
[DllImport(PinvokeDllNames.LookupAccountSidDllName, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)]
[ResourceExposure(ResourceScope.Machine)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool LookupAccountSid(string lpSystemName,
IntPtr sid,
StringBuilder lpName,
ref int cchName,
StringBuilder referencedDomainName,
ref int cchReferencedDomainName,
out SID_NAME_USE peUse);
[DllImport(PinvokeDllNames.CloseHandleDllName, SetLastError = true)]
[ResourceExposure(ResourceScope.Machine)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CloseHandle(IntPtr handle);
/// <summary>
/// Retrieves the current process token.
/// </summary>
/// <param name="processHandle">Process handle.</param>
/// <param name="desiredAccess">Token access.</param>
/// <param name="tokenHandle">Process token.</param>
/// <returns>The current process token.</returns>
[DllImport(PinvokeDllNames.OpenProcessTokenDllName, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)]
[ResourceExposure(ResourceScope.Machine)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccess, out IntPtr tokenHandle);
/// <summary>
/// The GetTokenInformation function retrieves a specified type of information about an access token.
/// The calling process must have appropriate access rights to obtain the information.
/// </summary>
/// <param name="tokenHandle"></param>
/// <param name="tokenInformationClass"></param>
/// <param name="tokenInformation"></param>
/// <param name="tokenInformationLength"></param>
/// <param name="returnLength"></param>
/// <returns></returns>
[DllImport(PinvokeDllNames.GetTokenInformationDllName, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)]
[ResourceExposure(ResourceScope.Machine)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetTokenInformation(IntPtr tokenHandle,
TOKEN_INFORMATION_CLASS tokenInformationClass,
IntPtr tokenInformation,
int tokenInformationLength,
out int returnLength);
#endregion PInvoke Methods
internal enum SECURITY_IMPERSONATION_LEVEL : short
{
Anonymous = 0,
Identification = 0x1,
Impersonation = 0x2,
Delegation = 0x4
}
// Security Quality of Service flags
internal const int SECURITY_ANONYMOUS = ((int)SECURITY_IMPERSONATION_LEVEL.Anonymous << 16);
internal const int SECURITY_SQOS_PRESENT = 0x00100000;
#if !CORECLR // Only enable/port what is needed by CORE CLR.
private const string resBaseName = "RegistryProviderStrings";
internal const int KEY_QUERY_VALUE = 0x0001;
internal const int KEY_SET_VALUE = 0x0002;
internal const int KEY_CREATE_SUB_KEY = 0x0004;
internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008;
internal const int KEY_NOTIFY = 0x0010;
internal const int KEY_CREATE_LINK = 0x0020;
internal const int KEY_READ = ((STANDARD_RIGHTS_READ |
KEY_QUERY_VALUE |
KEY_ENUMERATE_SUB_KEYS |
KEY_NOTIFY)
&
(~SYNCHRONIZE));
internal const int KEY_WRITE = ((STANDARD_RIGHTS_WRITE |
KEY_SET_VALUE |
KEY_CREATE_SUB_KEY)
&
(~SYNCHRONIZE));
internal const int KEY_WOW64_64KEY = 0x100;
internal const int KEY_WOW64_32KEY = 0x200;
internal const int REG_NONE = 0; // No value type
internal const int REG_SZ = 1; // Unicode nul terminated string
internal const int REG_EXPAND_SZ = 2; // Unicode nul terminated string
// (with environment variable references)
internal const int REG_BINARY = 3; // Free form binary
internal const int REG_DWORD = 4; // 32-bit number
internal const int REG_DWORD_LITTLE_ENDIAN = 4; // 32-bit number (same as REG_DWORD)
internal const int REG_DWORD_BIG_ENDIAN = 5; // 32-bit number
internal const int REG_LINK = 6; // Symbolic Link (unicode)
internal const int REG_MULTI_SZ = 7; // Multiple Unicode strings
internal const int REG_RESOURCE_LIST = 8; // Resource list in the resource map
internal const int REG_FULL_RESOURCE_DESCRIPTOR = 9; // Resource list in the hardware description
internal const int REG_RESOURCE_REQUIREMENTS_LIST = 10;
internal const int REG_QWORD = 11; // 64-bit number
internal const int HWND_BROADCAST = 0xffff;
internal const int WM_SETTINGCHANGE = 0x001A;
// CryptProtectMemory and CryptUnprotectMemory.
internal const uint CRYPTPROTECTMEMORY_BLOCK_SIZE = 16;
internal const uint CRYPTPROTECTMEMORY_SAME_PROCESS = 0x00;
internal const uint CRYPTPROTECTMEMORY_CROSS_PROCESS = 0x01;
internal const uint CRYPTPROTECTMEMORY_SAME_LOGON = 0x02;
// Access Control library.
internal const string MICROSOFT_KERBEROS_NAME = "Kerberos";
internal const uint ANONYMOUS_LOGON_LUID = 0x3e6;
internal const int SECURITY_ANONYMOUS_LOGON_RID = 0x00000007;
internal const int SECURITY_AUTHENTICATED_USER_RID = 0x0000000B;
internal const int SECURITY_LOCAL_SYSTEM_RID = 0x00000012;
internal const int SECURITY_BUILTIN_DOMAIN_RID = 0x00000020;
internal const int DOMAIN_USER_RID_GUEST = 0x000001F5;
internal const uint SE_GROUP_MANDATORY = 0x00000001;
internal const uint SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002;
internal const uint SE_GROUP_ENABLED = 0x00000004;
internal const uint SE_GROUP_OWNER = 0x00000008;
internal const uint SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010;
internal const uint SE_GROUP_LOGON_ID = 0xC0000000;
internal const uint SE_GROUP_RESOURCE = 0x20000000;
internal const uint DUPLICATE_CLOSE_SOURCE = 0x00000001;
internal const uint DUPLICATE_SAME_ACCESS = 0x00000002;
internal const uint DUPLICATE_SAME_ATTRIBUTES = 0x00000004;
// Win32 ACL-related constants:
internal const int READ_CONTROL = 0x00020000;
internal const int SYNCHRONIZE = 0x00100000;
internal const int STANDARD_RIGHTS_READ = READ_CONTROL;
internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL;
// STANDARD_RIGHTS_REQUIRED (0x000F0000L)
// SEMAPHORE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|0x3)
// SEMAPHORE and Event both use 0x0002
// MUTEX uses 0x001 (MUTANT_QUERY_STATE)
// Note that you may need to specify the SYNCHRONIZE bit as well
// to be able to open a synchronization primitive.
internal const int SEMAPHORE_MODIFY_STATE = 0x00000002;
internal const int EVENT_MODIFY_STATE = 0x00000002;
internal const int MUTEX_MODIFY_STATE = 0x00000001;
internal const int MUTEX_ALL_ACCESS = 0x001F0001;
internal const int LMEM_FIXED = 0x0000;
internal const int LMEM_ZEROINIT = 0x0040;
internal const int LPTR = (LMEM_FIXED | LMEM_ZEROINIT);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal class OSVERSIONINFO
{
internal OSVERSIONINFO()
{
OSVersionInfoSize = (int)Marshal.SizeOf(this);
}
// The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
internal int OSVersionInfoSize = 0;
internal int MajorVersion = 0;
internal int MinorVersion = 0;
internal int BuildNumber = 0;
internal int PlatformId = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
internal string CSDVersion = null;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal class OSVERSIONINFOEX
{
public OSVERSIONINFOEX()
{
OSVersionInfoSize = (int)Marshal.SizeOf(this);
}
// The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
internal int OSVersionInfoSize = 0;
internal int MajorVersion = 0;
internal int MinorVersion = 0;
internal int BuildNumber = 0;
internal int PlatformId = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
internal string CSDVersion = null;
internal ushort ServicePackMajor = 0;
internal ushort ServicePackMinor = 0;
internal short SuiteMask = 0;
internal byte ProductType = 0;
internal byte Reserved = 0;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SYSTEM_INFO
{
internal int dwOemId; // This is a union of a DWORD and a struct containing 2 WORDs.
internal int dwPageSize;
internal IntPtr lpMinimumApplicationAddress;
internal IntPtr lpMaximumApplicationAddress;
internal IntPtr dwActiveProcessorMask;
internal int dwNumberOfProcessors;
internal int dwProcessorType;
internal int dwAllocationGranularity;
internal short wProcessorLevel;
internal short wProcessorRevision;
}
[StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES
{
internal int nLength = 0;
internal unsafe byte* pSecurityDescriptor = null;
internal int bInheritHandle = 0;
}
[StructLayout(LayoutKind.Sequential), Serializable]
internal struct WIN32_FILE_ATTRIBUTE_DATA
{
internal int fileAttributes;
internal uint ftCreationTimeLow;
internal uint ftCreationTimeHigh;
internal uint ftLastAccessTimeLow;
internal uint ftLastAccessTimeHigh;
internal uint ftLastWriteTimeLow;
internal uint ftLastWriteTimeHigh;
internal int fileSizeHigh;
internal int fileSizeLow;
}
[StructLayout(LayoutKind.Sequential)]
internal struct FILE_TIME
{
public FILE_TIME(long fileTime)
{
ftTimeLow = (uint)fileTime;
ftTimeHigh = (uint)(fileTime >> 32);
}
public long ToTicks()
{
return ((long)ftTimeHigh << 32) + ftTimeLow;
}
internal uint ftTimeLow;
internal uint ftTimeHigh;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct KERB_S4U_LOGON
{
internal uint MessageType;
internal uint Flags;
internal UNICODE_INTPTR_STRING ClientUpn; // REQUIRED: UPN for client
internal UNICODE_INTPTR_STRING ClientRealm; // Optional: Client Realm, if known
}
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct LSA_OBJECT_ATTRIBUTES
{
internal int Length;
internal IntPtr RootDirectory;
internal IntPtr ObjectName;
internal int Attributes;
internal IntPtr SecurityDescriptor;
internal IntPtr SecurityQualityOfService;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct UNICODE_STRING
{
internal ushort Length;
internal ushort MaximumLength;
[MarshalAs(UnmanagedType.LPWStr)]
internal string Buffer;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct UNICODE_INTPTR_STRING
{
internal UNICODE_INTPTR_STRING(int length, int maximumLength, IntPtr buffer)
{
this.Length = (ushort)length;
this.MaxLength = (ushort)maximumLength;
this.Buffer = buffer;
}
internal ushort Length;
internal ushort MaxLength;
internal IntPtr Buffer;
}
[StructLayout(LayoutKind.Sequential)]
internal struct LSA_TRANSLATED_NAME
{
internal int Use;
internal UNICODE_INTPTR_STRING Name;
internal int DomainIndex;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct LSA_TRANSLATED_SID
{
internal int Use;
internal uint Rid;
internal int DomainIndex;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct LSA_TRANSLATED_SID2
{
internal int Use;
internal IntPtr Sid;
internal int DomainIndex;
private uint Flags;
}
[StructLayout(LayoutKind.Sequential)]
internal struct LSA_TRUST_INFORMATION
{
internal UNICODE_INTPTR_STRING Name;
internal IntPtr Sid;
}
[StructLayout(LayoutKind.Sequential)]
internal struct LSA_REFERENCED_DOMAIN_LIST
{
internal int Entries;
internal IntPtr Domains;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct QUOTA_LIMITS
{
internal IntPtr PagedPoolLimit;
internal IntPtr NonPagedPoolLimit;
internal IntPtr MinimumWorkingSetSize;
internal IntPtr MaximumWorkingSetSize;
internal IntPtr PagefileLimit;
internal IntPtr TimeLimit;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct TOKEN_GROUPS
{
internal uint GroupCount;
internal SID_AND_ATTRIBUTES Groups; // SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY];
}
[StructLayout(LayoutKind.Sequential)]
internal class MEMORYSTATUSEX
{
internal MEMORYSTATUSEX()
{
length = (int)Marshal.SizeOf(this);
}
// The length field must be set to the size of this data structure.
internal int length;
internal int memoryLoad;
internal ulong totalPhys;
internal ulong availPhys;
internal ulong totalPageFile;
internal ulong availPageFile;
internal ulong totalVirtual;
internal ulong availVirtual;
internal ulong availExtendedVirtual;
}
// Use only on Win9x
[StructLayout(LayoutKind.Sequential)]
internal class MEMORYSTATUS
{
internal MEMORYSTATUS()
{
length = (int)Marshal.SizeOf(this);
}
// The length field must be set to the size of this data structure.
internal int length;
internal int memoryLoad;
internal uint totalPhys;
internal uint availPhys;
internal uint totalPageFile;
internal uint availPageFile;
internal uint totalVirtual;
internal uint availVirtual;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct MEMORY_BASIC_INFORMATION
{
internal UIntPtr BaseAddress;
internal UIntPtr AllocationBase;
internal uint AllocationProtect;
internal UIntPtr RegionSize;
internal uint State;
internal uint Protect;
internal uint Type;
}
internal const string KERNEL32 = "kernel32.dll";
internal const string USER32 = "user32.dll";
internal const string ADVAPI32 = "advapi32.dll";
internal const string OLE32 = "ole32.dll";
internal const string OLEAUT32 = "oleaut32.dll";
internal const string SHFOLDER = "shfolder.dll";
internal const string SHIM = "mscoree.dll";
internal const string CRYPT32 = "crypt32.dll";
internal const string SECUR32 = "secur32.dll";
internal const string MSCORWKS = "mscorwks.dll";
internal const string LSTRCPY = "lstrcpy";
internal const string LSTRCPYN = "lstrcpyn";
internal const string LSTRLEN = "lstrlen";
internal const string LSTRLENA = "lstrlenA";
internal const string LSTRLENW = "lstrlenW";
internal const string MOVEMEMORY = "RtlMoveMemory";
// From WinBase.h
internal const int SEM_FAILCRITICALERRORS = 1;
[DllImport(
ADVAPI32,
EntryPoint = "GetSecurityDescriptorLength",
CallingConvention = CallingConvention.Winapi,
SetLastError = true,
CharSet = CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
internal static extern DWORD GetSecurityDescriptorLength(
IntPtr byteArray);
[DllImport(
ADVAPI32,
EntryPoint = "GetSecurityInfo",
CallingConvention = CallingConvention.Winapi,
SetLastError = true,
CharSet = CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
internal static extern DWORD GetSecurityInfoByHandle(
SafeHandle handle,
DWORD objectType,
DWORD securityInformation,
out IntPtr sidOwner,
out IntPtr sidGroup,
out IntPtr dacl,
out IntPtr sacl,
out IntPtr securityDescriptor);
[DllImport(
ADVAPI32,
EntryPoint = "SetSecurityInfo",
CallingConvention = CallingConvention.Winapi,
SetLastError = true,
CharSet = CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
internal static extern DWORD SetSecurityInfoByHandle(
SafeHandle handle,
DWORD objectType,
DWORD securityInformation,
byte[] owner,
byte[] group,
byte[] dacl,
byte[] sacl);
[DllImport(KERNEL32, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern IntPtr LocalFree(IntPtr handle);
internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h
internal static readonly IntPtr NULL = IntPtr.Zero;
// Error codes from WinError.h
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_INVALID_FUNCTION = 0x1;
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_PATH_NOT_FOUND = 0x3;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int ERROR_INVALID_DATA = 0xd;
internal const int ERROR_INVALID_DRIVE = 0xf;
internal const int ERROR_NO_MORE_FILES = 0x12;
internal const int ERROR_NOT_READY = 0x15;
internal const int ERROR_BAD_LENGTH = 0x18;
internal const int ERROR_SHARING_VIOLATION = 0x20;
internal const int ERROR_NOT_SUPPORTED = 0x32;
internal const int ERROR_FILE_EXISTS = 0x50;
internal const int ERROR_INVALID_PARAMETER = 0x57;
internal const int ERROR_CALL_NOT_IMPLEMENTED = 0x78;
internal const int ERROR_INVALID_NAME = 0x7B;
internal const int ERROR_BAD_PATHNAME = 0xA1;
internal const int ERROR_ALREADY_EXISTS = 0xB7;
internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long.
internal const int ERROR_NO_DATA = 0xE8;
internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9;
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_OPERATION_ABORTED = 0x3E3; // 995; For IO Cancellation
internal const int ERROR_NO_TOKEN = 0x3f0;
internal const int ERROR_DLL_INIT_FAILED = 0x45A;
internal const int ERROR_NON_ACCOUNT_SID = 0x4E9;
internal const int ERROR_NOT_ALL_ASSIGNED = 0x514;
internal const int ERROR_UNKNOWN_REVISION = 0x519;
internal const int ERROR_INVALID_OWNER = 0x51B;
internal const int ERROR_INVALID_PRIMARY_GROUP = 0x51C;
internal const int ERROR_NO_SUCH_PRIVILEGE = 0x521;
internal const int ERROR_PRIVILEGE_NOT_HELD = 0x522;
internal const int ERROR_NONE_MAPPED = 0x534;
internal const int ERROR_INVALID_ACL = 0x538;
internal const int ERROR_INVALID_SID = 0x539;
internal const int ERROR_INVALID_SECURITY_DESCR = 0x53A;
internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542;
internal const int ERROR_CANT_OPEN_ANONYMOUS = 0x543;
internal const int ERROR_NO_SECURITY_ON_OBJECT = 0x546;
internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 0x6FD;
// These two values come from comments in WinError.h
internal const int ERROR_MIN_KTM_CODE = 6700; // 0x1A2C
internal const int ERROR_INVALID_TRANSACTION = 6700; // 0x1A2C
internal const int ERROR_MAX_KTM_CODE = 6799; // 0x1A8F;
// Error codes from ntstatus.h
internal const uint STATUS_SUCCESS = 0x00000000;
internal const uint STATUS_SOME_NOT_MAPPED = 0x00000107;
internal const uint STATUS_NO_MEMORY = 0xC0000017;
internal const uint STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034;
internal const uint STATUS_NONE_MAPPED = 0xC0000073;
internal const uint STATUS_INSUFFICIENT_RESOURCES = 0xC000009A;
internal const uint STATUS_ACCESS_DENIED = 0xC0000022;
internal const int INVALID_FILE_SIZE = -1;
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.Machine)]
internal static extern int RegConnectRegistry(string machineName,
SafeRegistryHandle key, out SafeRegistryHandle result);
// Note: RegCreateKeyEx won't set the last error on failure - it returns
// an error code if it fails.
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.Machine)]
internal static extern int RegCreateKeyEx(SafeRegistryHandle hKey, string lpSubKey,
int Reserved, string lpClass, int dwOptions,
int samDesigner, SECURITY_ATTRIBUTES lpSecurityAttributes,
out SafeRegistryHandle hkResult, out int lpdwDisposition);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.Machine)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegDeleteKey(SafeRegistryHandle hKey, string lpSubKey);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.Machine)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegDeleteKeyTransacted(SafeRegistryHandle hKey, string lpSubKey, int samDesired,
DWORD reserved, SafeTransactionHandle hTransaction, IntPtr pExtendedParameter);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.Machine)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegDeleteValue(SafeRegistryHandle hKey, string lpValueName);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegEnumKeyEx(SafeRegistryHandle hKey, int dwIndex,
StringBuilder lpName, out int lpcbName, int[] lpReserved,
StringBuilder lpClass, int[] lpcbClass,
long[] lpftLastWriteTime);
[DllImport(PinvokeDllNames.RegEnumValueDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegEnumValue(SafeRegistryHandle hKey, int dwIndex,
StringBuilder lpValueName, ref int lpcbValueName,
IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData,
int[] lpcbData);
[DllImport(ADVAPI32)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegFlushKey(SafeRegistryHandle hKey);
[DllImport(PinvokeDllNames.RegOpenKeyExDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.Machine)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, string lpSubKey,
int ulOptions, int samDesired, out SafeRegistryHandle hkResult);
[DllImport(PinvokeDllNames.RegOpenKeyTransactedDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.Machine)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegOpenKeyTransacted(SafeRegistryHandle hKey, string lpSubKey,
int ulOptions, int samDesired, out SafeRegistryHandle hkResult,
SafeTransactionHandle hTransaction, IntPtr pExtendedParameter);
[DllImport(PinvokeDllNames.RegQueryInfoKeyDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegQueryInfoKey(SafeRegistryHandle hKey, StringBuilder lpClass,
int[] lpcbClass, IntPtr lpReserved_MustBeZero, ref int lpcSubKeys,
int[] lpcbMaxSubKeyLen, int[] lpcbMaxClassLen,
ref int lpcValues, int[] lpcbMaxValueNameLen,
int[] lpcbMaxValueLen, int[] lpcbSecurityDescriptor,
int[] lpftLastWriteTime);
[DllImport(PinvokeDllNames.RegQueryValueExDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName,
int[] lpReserved, ref int lpType, [Out] byte[] lpData,
ref int lpcbData);
[DllImport(PinvokeDllNames.RegQueryValueExDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName,
int[] lpReserved, ref int lpType, ref int lpData,
ref int lpcbData);
[DllImport(PinvokeDllNames.RegQueryValueExDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName,
int[] lpReserved, ref int lpType, ref long lpData,
ref int lpcbData);
[DllImport(PinvokeDllNames.RegQueryValueExDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName,
int[] lpReserved, ref int lpType, [Out] char[] lpData,
ref int lpcbData);
[DllImport(PinvokeDllNames.RegQueryValueExDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName,
int[] lpReserved, ref int lpType, StringBuilder lpData,
ref int lpcbData);
[DllImport(PinvokeDllNames.RegSetValueExDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName,
int Reserved, RegistryValueKind dwType, byte[] lpData, int cbData);
[DllImport(PinvokeDllNames.RegSetValueExDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName,
int Reserved, RegistryValueKind dwType, ref int lpData, int cbData);
[DllImport(PinvokeDllNames.RegSetValueExDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName,
int Reserved, RegistryValueKind dwType, ref long lpData, int cbData);
[DllImport(PinvokeDllNames.RegSetValueExDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName,
int Reserved, RegistryValueKind dwType, string lpData, int cbData);
[DllImport(PinvokeDllNames.RegCreateKeyTransactedDllName, CharSet = CharSet.Auto, BestFitMapping = false)]
[ResourceExposure(ResourceScope.Machine)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int RegCreateKeyTransacted(SafeRegistryHandle hKey, string lpSubKey,
int Reserved, string lpClass, int dwOptions,
int samDesigner, SECURITY_ATTRIBUTES lpSecurityAttributes,
out SafeRegistryHandle hkResult, out int lpdwDisposition,
SafeTransactionHandle hTransaction, IntPtr pExtendedParameter);
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
[DllImport(KERNEL32, CharSet = CharSet.Unicode, BestFitMapping = true)]
[ResourceExposure(ResourceScope.None)]
// Suppressed because there is no way for arbitrary data to be passed.
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int FormatMessage(int dwFlags, IntPtr lpSource,
int dwMessageId, int dwLanguageId, StringBuilder lpBuffer,
int nSize, IntPtr va_list_arguments);
// Gets an error message for a Win32 error code.
internal static string GetMessage(int errorCode)
{
StringBuilder sb = new StringBuilder(512);
int result = Win32Native.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
Win32Native.NULL, errorCode, 0, sb, sb.Capacity, Win32Native.NULL);
if (result != 0)
{
// result is the # of characters copied to the StringBuilder on NT,
// but on Win9x, it appears to be the number of MBCS bytes.
// Just give up and return the String as-is...
string s = sb.ToString();
return s;
}
else
{
string resourceTemplate = RegistryProviderStrings.UnknownError_Num;
return string.Format(CultureInfo.CurrentCulture, resourceTemplate, errorCode.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
}
[DllImport(KERNEL32, CharSet = CharSet.Auto, EntryPoint = LSTRLEN)]
[ResourceExposure(ResourceScope.None)]
internal static extern int lstrlen(sbyte[] ptr);
[DllImport(KERNEL32, CharSet = CharSet.Auto, EntryPoint = LSTRLEN)]
[ResourceExposure(ResourceScope.None)]
internal static extern int lstrlen(IntPtr ptr);
[DllImport(KERNEL32, CharSet = CharSet.Ansi, EntryPoint = LSTRLENA)]
[ResourceExposure(ResourceScope.None)]
internal static extern int lstrlenA(IntPtr ptr);
[DllImport(KERNEL32, CharSet = CharSet.Unicode, EntryPoint = LSTRLENW)]
[ResourceExposure(ResourceScope.None)]
internal static extern int lstrlenW(IntPtr ptr);
[DllImport(KERNEL32)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern UIntPtr VirtualQuery(UIntPtr lpAddress, ref MEMORY_BASIC_INFORMATION lpBuffer, UIntPtr dwLength);
[DllImport(KERNEL32)]
internal static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
internal static readonly uint PAGE_SIZE;
static Win32Native()
{
SYSTEM_INFO systemInfo;
GetSystemInfo(out systemInfo);
PAGE_SIZE = (uint)systemInfo.dwPageSize;
}
#endif
}
}
| |
// DeflaterHuffman.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// *************************************************************************
//
// Name: DeflaterHuffman.cs
//
// Created: 19-02-2008 SharedCache.com, rschuetz
// Modified: 19-02-2008 SharedCache.com, rschuetz : Creation
// *************************************************************************
using System;
namespace SharedCache.WinServiceCommon.SharpZipLib.Zip.Compression
{
/// <summary>
/// This is the DeflaterHuffman class.
///
/// This class is <i>not</i> thread safe. This is inherent in the API, due
/// to the split of Deflate and SetInput.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class DeflaterHuffman
{
const int BUFSIZE = 1 << (DeflaterConstants.DEFAULT_MEM_LEVEL + 6);
const int LITERAL_NUM = 286;
// Number of distance codes
const int DIST_NUM = 30;
// Number of codes used to transfer bit lengths
const int BITLEN_NUM = 19;
// repeat previous bit length 3-6 times (2 bits of repeat count)
const int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
const int REP_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
const int REP_11_138 = 18;
const int EOF_SYMBOL = 256;
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit length codes.
static readonly int[] BL_ORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
static readonly byte[] bit4Reverse = {
0,
8,
4,
12,
2,
10,
6,
14,
1,
9,
5,
13,
3,
11,
7,
15
};
static short[] staticLCodes;
static byte[] staticLLength;
static short[] staticDCodes;
static byte[] staticDLength;
class Tree
{
#region Instance Fields
public short[] freqs;
public byte[] length;
public int minNumCodes;
public int numCodes;
short[] codes;
int[] bl_counts;
int maxLength;
DeflaterHuffman dh;
#endregion
#region Constructors
public Tree(DeflaterHuffman dh, int elems, int minCodes, int maxLength)
{
this.dh = dh;
this.minNumCodes = minCodes;
this.maxLength = maxLength;
freqs = new short[elems];
bl_counts = new int[maxLength];
}
#endregion
/// <summary>
/// Resets the internal state of the tree
/// </summary>
public void Reset()
{
for (int i = 0; i < freqs.Length; i++)
{
freqs[i] = 0;
}
codes = null;
length = null;
}
public void WriteSymbol(int code)
{
// if (DeflaterConstants.DEBUGGING) {
// freqs[code]--;
// // Console.Write("writeSymbol("+freqs.length+","+code+"): ");
// }
dh.pending.WriteBits(codes[code] & 0xffff, length[code]);
}
/// <summary>
/// Check that all frequencies are zero
/// </summary>
/// <exception cref="SharpZipBaseException">
/// At least one frequency is non-zero
/// </exception>
public void CheckEmpty()
{
bool empty = true;
for (int i = 0; i < freqs.Length; i++)
{
if (freqs[i] != 0)
{
//Console.WriteLine("freqs[" + i + "] == " + freqs[i]);
empty = false;
}
}
if (!empty)
{
throw new SharpZipBaseException("!Empty");
}
}
/// <summary>
/// Set static codes and length
/// </summary>
/// <param name="staticCodes">new codes</param>
/// <param name="staticLengths">length for new codes</param>
public void SetStaticCodes(short[] staticCodes, byte[] staticLengths)
{
codes = staticCodes;
length = staticLengths;
}
/// <summary>
/// Build dynamic codes and lengths
/// </summary>
public void BuildCodes()
{
int numSymbols = freqs.Length;
int[] nextCode = new int[maxLength];
int code = 0;
codes = new short[freqs.Length];
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("buildCodes: "+freqs.Length);
// }
for (int bits = 0; bits < maxLength; bits++)
{
nextCode[bits] = code;
code += bl_counts[bits] << (15 - bits);
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("bits: " + ( bits + 1) + " count: " + bl_counts[bits]
// +" nextCode: "+code);
// }
}
#if DebugDeflation
if ( DeflaterConstants.DEBUGGING && (code != 65536) )
{
throw new SharpZipBaseException("Inconsistent bl_counts!");
}
#endif
for (int i = 0; i < numCodes; i++)
{
int bits = length[i];
if (bits > 0)
{
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("codes["+i+"] = rev(" + nextCode[bits-1]+"),
// +bits);
// }
codes[i] = BitReverse(nextCode[bits - 1]);
nextCode[bits - 1] += 1 << (16 - bits);
}
}
}
public void BuildTree()
{
int numSymbols = freqs.Length;
/* heap is a priority queue, sorted by frequency, least frequent
* nodes first. The heap is a binary tree, with the property, that
* the parent node is smaller than both child nodes. This assures
* that the smallest node is the first parent.
*
* The binary tree is encoded in an array: 0 is root node and
* the nodes 2*n+1, 2*n+2 are the child nodes of node n.
*/
int[] heap = new int[numSymbols];
int heapLen = 0;
int maxCode = 0;
for (int n = 0; n < numSymbols; n++)
{
int freq = freqs[n];
if (freq != 0)
{
// Insert n into heap
int pos = heapLen++;
int ppos;
while (pos > 0 && freqs[heap[ppos = (pos - 1) / 2]] > freq)
{
heap[pos] = heap[ppos];
pos = ppos;
}
heap[pos] = n;
maxCode = n;
}
}
/* We could encode a single literal with 0 bits but then we
* don't see the literals. Therefore we force at least two
* literals to avoid this case. We don't care about order in
* this case, both literals get a 1 bit code.
*/
while (heapLen < 2)
{
int node = maxCode < 2 ? ++maxCode : 0;
heap[heapLen++] = node;
}
numCodes = Math.Max(maxCode + 1, minNumCodes);
int numLeafs = heapLen;
int[] childs = new int[4 * heapLen - 2];
int[] values = new int[2 * heapLen - 1];
int numNodes = numLeafs;
for (int i = 0; i < heapLen; i++)
{
int node = heap[i];
childs[2 * i] = node;
childs[2 * i + 1] = -1;
values[i] = freqs[node] << 8;
heap[i] = i;
}
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
do
{
int first = heap[0];
int last = heap[--heapLen];
// Propagate the hole to the leafs of the heap
int ppos = 0;
int path = 1;
while (path < heapLen)
{
if (path + 1 < heapLen && values[heap[path]] > values[heap[path + 1]])
{
path++;
}
heap[ppos] = heap[path];
ppos = path;
path = path * 2 + 1;
}
/* Now propagate the last element down along path. Normally
* it shouldn't go too deep.
*/
int lastVal = values[last];
while ((path = ppos) > 0 && values[heap[ppos = (path - 1) / 2]] > lastVal)
{
heap[path] = heap[ppos];
}
heap[path] = last;
int second = heap[0];
// Create a new node father of first and second
last = numNodes++;
childs[2 * last] = first;
childs[2 * last + 1] = second;
int mindepth = Math.Min(values[first] & 0xff, values[second] & 0xff);
values[last] = lastVal = values[first] + values[second] - mindepth + 1;
// Again, propagate the hole to the leafs
ppos = 0;
path = 1;
while (path < heapLen)
{
if (path + 1 < heapLen && values[heap[path]] > values[heap[path + 1]])
{
path++;
}
heap[ppos] = heap[path];
ppos = path;
path = ppos * 2 + 1;
}
// Now propagate the new element down along path
while ((path = ppos) > 0 && values[heap[ppos = (path - 1) / 2]] > lastVal)
{
heap[path] = heap[ppos];
}
heap[path] = last;
} while (heapLen > 1);
if (heap[0] != childs.Length / 2 - 1)
{
throw new SharpZipBaseException("Heap invariant violated");
}
BuildLength(childs);
}
/// <summary>
/// Get encoded length
/// </summary>
/// <returns>Encoded length, the sum of frequencies * lengths</returns>
public int GetEncodedLength()
{
int len = 0;
for (int i = 0; i < freqs.Length; i++)
{
len += freqs[i] * length[i];
}
return len;
}
/// <summary>
/// Scan a literal or distance tree to determine the frequencies of the codes
/// in the bit length tree.
/// </summary>
public void CalcBLFreq(Tree blTree)
{
int max_count; /* max repeat count */
int min_count; /* min repeat count */
int count; /* repeat count of the current code */
int curlen = -1; /* length of current code */
int i = 0;
while (i < numCodes)
{
count = 1;
int nextlen = length[i];
if (nextlen == 0)
{
max_count = 138;
min_count = 3;
}
else
{
max_count = 6;
min_count = 3;
if (curlen != nextlen)
{
blTree.freqs[nextlen]++;
count = 0;
}
}
curlen = nextlen;
i++;
while (i < numCodes && curlen == length[i])
{
i++;
if (++count >= max_count)
{
break;
}
}
if (count < min_count)
{
blTree.freqs[curlen] += (short)count;
}
else if (curlen != 0)
{
blTree.freqs[REP_3_6]++;
}
else if (count <= 10)
{
blTree.freqs[REP_3_10]++;
}
else
{
blTree.freqs[REP_11_138]++;
}
}
}
/// <summary>
/// Write tree values
/// </summary>
/// <param name="blTree">Tree to write</param>
public void WriteTree(Tree blTree)
{
int max_count; // max repeat count
int min_count; // min repeat count
int count; // repeat count of the current code
int curlen = -1; // length of current code
int i = 0;
while (i < numCodes)
{
count = 1;
int nextlen = length[i];
if (nextlen == 0)
{
max_count = 138;
min_count = 3;
}
else
{
max_count = 6;
min_count = 3;
if (curlen != nextlen)
{
blTree.WriteSymbol(nextlen);
count = 0;
}
}
curlen = nextlen;
i++;
while (i < numCodes && curlen == length[i])
{
i++;
if (++count >= max_count)
{
break;
}
}
if (count < min_count)
{
while (count-- > 0)
{
blTree.WriteSymbol(curlen);
}
}
else if (curlen != 0)
{
blTree.WriteSymbol(REP_3_6);
dh.pending.WriteBits(count - 3, 2);
}
else if (count <= 10)
{
blTree.WriteSymbol(REP_3_10);
dh.pending.WriteBits(count - 3, 3);
}
else
{
blTree.WriteSymbol(REP_11_138);
dh.pending.WriteBits(count - 11, 7);
}
}
}
void BuildLength(int[] childs)
{
this.length = new byte[freqs.Length];
int numNodes = childs.Length / 2;
int numLeafs = (numNodes + 1) / 2;
int overflow = 0;
for (int i = 0; i < maxLength; i++)
{
bl_counts[i] = 0;
}
// First calculate optimal bit lengths
int[] lengths = new int[numNodes];
lengths[numNodes - 1] = 0;
for (int i = numNodes - 1; i >= 0; i--)
{
if (childs[2 * i + 1] != -1)
{
int bitLength = lengths[i] + 1;
if (bitLength > maxLength)
{
bitLength = maxLength;
overflow++;
}
lengths[childs[2 * i]] = lengths[childs[2 * i + 1]] = bitLength;
}
else
{
// A leaf node
int bitLength = lengths[i];
bl_counts[bitLength - 1]++;
this.length[childs[2 * i]] = (byte)lengths[i];
}
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Tree "+freqs.Length+" lengths:");
// for (int i=0; i < numLeafs; i++) {
// //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]]
// + " len: "+length[childs[2*i]]);
// }
// }
if (overflow == 0)
{
return;
}
int incrBitLen = maxLength - 1;
do
{
// Find the first bit length which could increase:
while (bl_counts[--incrBitLen] == 0)
;
// Move this node one down and remove a corresponding
// number of overflow nodes.
do
{
bl_counts[incrBitLen]--;
bl_counts[++incrBitLen]++;
overflow -= 1 << (maxLength - 1 - incrBitLen);
} while (overflow > 0 && incrBitLen < maxLength - 1);
} while (overflow > 0);
/* We may have overshot above. Move some nodes from maxLength to
* maxLength-1 in that case.
*/
bl_counts[maxLength - 1] += overflow;
bl_counts[maxLength - 2] -= overflow;
/* Now recompute all bit lengths, scanning in increasing
* frequency. It is simpler to reconstruct all lengths instead of
* fixing only the wrong ones. This idea is taken from 'ar'
* written by Haruhiko Okumura.
*
* The nodes were inserted with decreasing frequency into the childs
* array.
*/
int nodePtr = 2 * numLeafs;
for (int bits = maxLength; bits != 0; bits--)
{
int n = bl_counts[bits - 1];
while (n > 0)
{
int childPtr = 2 * childs[nodePtr++];
if (childs[childPtr + 1] == -1)
{
// We found another leaf
length[childs[childPtr]] = (byte)bits;
n--;
}
}
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("*** After overflow elimination. ***");
// for (int i=0; i < numLeafs; i++) {
// //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]]
// + " len: "+length[childs[2*i]]);
// }
// }
}
}
#region Instance Fields
/// <summary>
/// Pending buffer to use
/// </summary>
public DeflaterPending pending;
Tree literalTree;
Tree distTree;
Tree blTree;
// Buffer for distances
short[] d_buf;
byte[] l_buf;
int last_lit;
int extra_bits;
#endregion
static DeflaterHuffman()
{
// See RFC 1951 3.2.6
// Literal codes
staticLCodes = new short[LITERAL_NUM];
staticLLength = new byte[LITERAL_NUM];
int i = 0;
while (i < 144)
{
staticLCodes[i] = BitReverse((0x030 + i) << 8);
staticLLength[i++] = 8;
}
while (i < 256)
{
staticLCodes[i] = BitReverse((0x190 - 144 + i) << 7);
staticLLength[i++] = 9;
}
while (i < 280)
{
staticLCodes[i] = BitReverse((0x000 - 256 + i) << 9);
staticLLength[i++] = 7;
}
while (i < LITERAL_NUM)
{
staticLCodes[i] = BitReverse((0x0c0 - 280 + i) << 8);
staticLLength[i++] = 8;
}
// Distance codes
staticDCodes = new short[DIST_NUM];
staticDLength = new byte[DIST_NUM];
for (i = 0; i < DIST_NUM; i++)
{
staticDCodes[i] = BitReverse(i << 11);
staticDLength[i] = 5;
}
}
/// <summary>
/// Construct instance with pending buffer
/// </summary>
/// <param name="pending">Pending buffer to use</param>
public DeflaterHuffman(DeflaterPending pending)
{
this.pending = pending;
literalTree = new Tree(this, LITERAL_NUM, 257, 15);
distTree = new Tree(this, DIST_NUM, 1, 15);
blTree = new Tree(this, BITLEN_NUM, 4, 7);
d_buf = new short[BUFSIZE];
l_buf = new byte[BUFSIZE];
}
/// <summary>
/// Reset internal state
/// </summary>
public void Reset()
{
last_lit = 0;
extra_bits = 0;
literalTree.Reset();
distTree.Reset();
blTree.Reset();
}
/// <summary>
/// Write all trees to pending buffer
/// </summary>
/// <param name="blTreeCodes">The number/rank of treecodes to send.</param>
public void SendAllTrees(int blTreeCodes)
{
blTree.BuildCodes();
literalTree.BuildCodes();
distTree.BuildCodes();
pending.WriteBits(literalTree.numCodes - 257, 5);
pending.WriteBits(distTree.numCodes - 1, 5);
pending.WriteBits(blTreeCodes - 4, 4);
for (int rank = 0; rank < blTreeCodes; rank++)
{
pending.WriteBits(blTree.length[BL_ORDER[rank]], 3);
}
literalTree.WriteTree(blTree);
distTree.WriteTree(blTree);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
blTree.CheckEmpty();
}
#endif
}
/// <summary>
/// Compress current buffer writing data to pending buffer
/// </summary>
public void CompressBlock()
{
for (int i = 0; i < last_lit; i++)
{
int litlen = l_buf[i] & 0xff;
int dist = d_buf[i];
if (dist-- != 0)
{
// if (DeflaterConstants.DEBUGGING) {
// Console.Write("["+(dist+1)+","+(litlen+3)+"]: ");
// }
int lc = Lcode(litlen);
literalTree.WriteSymbol(lc);
int bits = (lc - 261) / 4;
if (bits > 0 && bits <= 5)
{
pending.WriteBits(litlen & ((1 << bits) - 1), bits);
}
int dc = Dcode(dist);
distTree.WriteSymbol(dc);
bits = dc / 2 - 1;
if (bits > 0)
{
pending.WriteBits(dist & ((1 << bits) - 1), bits);
}
}
else
{
// if (DeflaterConstants.DEBUGGING) {
// if (litlen > 32 && litlen < 127) {
// Console.Write("("+(char)litlen+"): ");
// } else {
// Console.Write("{"+litlen+"}: ");
// }
// }
literalTree.WriteSymbol(litlen);
}
}
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.Write("EOF: ");
}
#endif
literalTree.WriteSymbol(EOF_SYMBOL);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
literalTree.CheckEmpty();
distTree.CheckEmpty();
}
#endif
}
/// <summary>
/// Flush block to output with no compression
/// </summary>
/// <param name="stored">Data to write</param>
/// <param name="storedOffset">Index of first byte to write</param>
/// <param name="storedLength">Count of bytes to write</param>
/// <param name="lastBlock">True if this is the last block</param>
public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock)
{
#if DebugDeflation
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Flushing stored block "+ storedLength);
// }
#endif
pending.WriteBits((DeflaterConstants.STORED_BLOCK << 1) + (lastBlock ? 1 : 0), 3);
pending.AlignToByte();
pending.WriteShort(storedLength);
pending.WriteShort(~storedLength);
pending.WriteBlock(stored, storedOffset, storedLength);
Reset();
}
/// <summary>
/// Flush block to output with compression
/// </summary>
/// <param name="stored">Data to flush</param>
/// <param name="storedOffset">Index of first byte to flush</param>
/// <param name="storedLength">Count of bytes to flush</param>
/// <param name="lastBlock">True if this is the last block</param>
public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock)
{
literalTree.freqs[EOF_SYMBOL]++;
// Build trees
literalTree.BuildTree();
distTree.BuildTree();
// Calculate bitlen frequency
literalTree.CalcBLFreq(blTree);
distTree.CalcBLFreq(blTree);
// Build bitlen tree
blTree.BuildTree();
int blTreeCodes = 4;
for (int i = 18; i > blTreeCodes; i--)
{
if (blTree.length[BL_ORDER[i]] > 0)
{
blTreeCodes = i + 1;
}
}
int opt_len = 14 + blTreeCodes * 3 + blTree.GetEncodedLength() +
literalTree.GetEncodedLength() + distTree.GetEncodedLength() +
extra_bits;
int static_len = extra_bits;
for (int i = 0; i < LITERAL_NUM; i++)
{
static_len += literalTree.freqs[i] * staticLLength[i];
}
for (int i = 0; i < DIST_NUM; i++)
{
static_len += distTree.freqs[i] * staticDLength[i];
}
if (opt_len >= static_len)
{
// Force static trees
opt_len = static_len;
}
if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3)
{
// Store Block
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Storing, since " + storedLength + " < " + opt_len
// + " <= " + static_len);
// }
FlushStoredBlock(stored, storedOffset, storedLength, lastBlock);
}
else if (opt_len == static_len)
{
// Encode with static tree
pending.WriteBits((DeflaterConstants.STATIC_TREES << 1) + (lastBlock ? 1 : 0), 3);
literalTree.SetStaticCodes(staticLCodes, staticLLength);
distTree.SetStaticCodes(staticDCodes, staticDLength);
CompressBlock();
Reset();
}
else
{
// Encode with dynamic tree
pending.WriteBits((DeflaterConstants.DYN_TREES << 1) + (lastBlock ? 1 : 0), 3);
SendAllTrees(blTreeCodes);
CompressBlock();
Reset();
}
}
/// <summary>
/// Get value indicating if internal buffer is full
/// </summary>
/// <returns>true if buffer is full</returns>
public bool IsFull()
{
return last_lit >= BUFSIZE;
}
/// <summary>
/// Add literal to buffer
/// </summary>
/// <param name="literal">Literal value to add to buffer.</param>
/// <returns>Value indicating internal buffer is full</returns>
public bool TallyLit(int literal)
{
// if (DeflaterConstants.DEBUGGING) {
// if (lit > 32 && lit < 127) {
// //Console.WriteLine("("+(char)lit+")");
// } else {
// //Console.WriteLine("{"+lit+"}");
// }
// }
d_buf[last_lit] = 0;
l_buf[last_lit++] = (byte)literal;
literalTree.freqs[literal]++;
return IsFull();
}
/// <summary>
/// Add distance code and length to literal and distance trees
/// </summary>
/// <param name="distance">Distance code</param>
/// <param name="length">Length</param>
/// <returns>Value indicating if internal buffer is full</returns>
public bool TallyDist(int distance, int length)
{
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("[" + distance + "," + length + "]");
// }
d_buf[last_lit] = (short)distance;
l_buf[last_lit++] = (byte)(length - 3);
int lc = Lcode(length - 3);
literalTree.freqs[lc]++;
if (lc >= 265 && lc < 285)
{
extra_bits += (lc - 261) / 4;
}
int dc = Dcode(distance - 1);
distTree.freqs[dc]++;
if (dc >= 4)
{
extra_bits += dc / 2 - 1;
}
return IsFull();
}
/// <summary>
/// Reverse the bits of a 16 bit value.
/// </summary>
/// <param name="toReverse">Value to reverse bits</param>
/// <returns>Value with bits reversed</returns>
public static short BitReverse(int toReverse)
{
return (short)(bit4Reverse[toReverse & 0xF] << 12 |
bit4Reverse[(toReverse >> 4) & 0xF] << 8 |
bit4Reverse[(toReverse >> 8) & 0xF] << 4 |
bit4Reverse[toReverse >> 12]);
}
static int Lcode(int length)
{
if (length == 255)
{
return 285;
}
int code = 257;
while (length >= 8)
{
code += 4;
length >>= 1;
}
return code + length;
}
static int Dcode(int distance)
{
int code = 0;
while (distance >= 4)
{
code += 2;
distance >>= 1;
}
return code + distance;
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Core.DialogWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// 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.Reflection;
using System.Diagnostics;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.MethodInfos;
using Internal.Reflection.Core.Execution;
//
// It is common practice for app code to compare Type objects using reference equality with the expectation that reference equality
// is equivalent to semantic equality. To support this, all RuntimeTypeObject objects are interned using weak references.
//
// This assumption is baked into the codebase in these places:
//
// - RuntimeTypeInfo.Equals(object) implements itself as Object.ReferenceEquals(this, obj)
//
// - RuntimeTypeInfo.GetHashCode() is implemented in a flavor-specific manner (We can't use Object.GetHashCode()
// because we don't want the hash value to change if a type is collected and resurrected later.)
//
// This assumption is actualized as follows:
//
// - RuntimeTypeInfo classes hide their constructor. The only way to instantiate a RuntimeTypeInfo
// is through its public static factory method which ensures the interning and are collected in this one
// file for easy auditing and to help ensure that they all operate in a consistent manner.
//
// - The TypeUnifier extension class provides a more friendly interface to the rest of the codebase.
//
namespace System.Reflection.Runtime.General
{
internal static partial class TypeUnifier
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo GetArrayType(this RuntimeTypeInfo elementType)
{
return elementType.GetArrayType(default(RuntimeTypeHandle));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo GetMultiDimArrayType(this RuntimeTypeInfo elementType, int rank)
{
return elementType.GetMultiDimArrayType(rank, default(RuntimeTypeHandle));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo GetByRefType(this RuntimeTypeInfo targetType)
{
return targetType.GetByRefType(default(RuntimeTypeHandle));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo GetPointerType(this RuntimeTypeInfo targetType)
{
return targetType.GetPointerType(default(RuntimeTypeHandle));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo GetConstructedGenericType(this RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments)
{
return genericTypeDefinition.GetConstructedGenericType(genericTypeArguments, default(RuntimeTypeHandle));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo GetTypeForRuntimeTypeHandle(this RuntimeTypeHandle typeHandle)
{
Type type = Type.GetTypeFromHandle(typeHandle);
return type.CastToRuntimeTypeInfo();
}
//======================================================================================================
// This next group services the Type.GetTypeFromHandle() path. Since we already have a RuntimeTypeHandle
// in that case, we pass it in as an extra argument as an optimization (otherwise, the unifier will
// waste cycles looking up the handle again from the mapping tables.)
//======================================================================================================
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo GetArrayType(this RuntimeTypeInfo elementType, RuntimeTypeHandle precomputedTypeHandle)
{
return RuntimeArrayTypeInfo.GetArrayTypeInfo(elementType, multiDim: false, rank: 1, precomputedTypeHandle: precomputedTypeHandle);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo GetMultiDimArrayType(this RuntimeTypeInfo elementType, int rank, RuntimeTypeHandle precomputedTypeHandle)
{
return RuntimeArrayTypeInfo.GetArrayTypeInfo(elementType, multiDim: true, rank: rank, precomputedTypeHandle: precomputedTypeHandle);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo GetPointerType(this RuntimeTypeInfo targetType, RuntimeTypeHandle precomputedTypeHandle)
{
return RuntimePointerTypeInfo.GetPointerTypeInfo(targetType, precomputedTypeHandle);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo GetByRefType(this RuntimeTypeInfo targetType, RuntimeTypeHandle precomputedTypeHandle)
{
return RuntimeByRefTypeInfo.GetByRefTypeInfo(targetType, precomputedTypeHandle);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static RuntimeTypeInfo GetConstructedGenericType(this RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments, RuntimeTypeHandle precomputedTypeHandle)
{
return RuntimeConstructedGenericTypeInfo.GetRuntimeConstructedGenericTypeInfo(genericTypeDefinition, genericTypeArguments, precomputedTypeHandle);
}
}
}
namespace System.Reflection.Runtime.TypeInfos
{
//-----------------------------------------------------------------------------------------------------------
// TypeInfos for type definitions (i.e. "Foo" and "Foo<>" but not "Foo<int>") that aren't opted into metadata.
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimeNoMetadataNamedTypeInfo
{
internal static RuntimeNoMetadataNamedTypeInfo GetRuntimeNoMetadataNamedTypeInfo(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition)
{
RuntimeNoMetadataNamedTypeInfo type;
if (isGenericTypeDefinition)
type = GenericNoMetadataNamedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle));
else
type = NoMetadataNamedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle));
type.EstablishDebugName();
return type;
}
private sealed class NoMetadataNamedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeNoMetadataNamedTypeInfo>
{
protected sealed override RuntimeNoMetadataNamedTypeInfo Factory(RuntimeTypeHandleKey key)
{
return new RuntimeNoMetadataNamedTypeInfo(key.TypeHandle, isGenericTypeDefinition: false);
}
public static readonly NoMetadataNamedTypeTable Table = new NoMetadataNamedTypeTable();
}
private sealed class GenericNoMetadataNamedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeNoMetadataNamedTypeInfo>
{
protected sealed override RuntimeNoMetadataNamedTypeInfo Factory(RuntimeTypeHandleKey key)
{
return new RuntimeNoMetadataNamedTypeInfo(key.TypeHandle, isGenericTypeDefinition: true);
}
public static readonly GenericNoMetadataNamedTypeTable Table = new GenericNoMetadataNamedTypeTable();
}
}
//-----------------------------------------------------------------------------------------------------------
// TypeInfos that represent type definitions (i.e. Foo or Foo<>) or constructed generic types (Foo<int>)
// that can never be reflection-enabled due to the framework Reflection block.
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimeBlockedTypeInfo
{
internal static RuntimeBlockedTypeInfo GetRuntimeBlockedTypeInfo(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition)
{
RuntimeBlockedTypeInfo type;
if (isGenericTypeDefinition)
type = GenericBlockedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle));
else
type = BlockedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle));
type.EstablishDebugName();
return type;
}
private sealed class BlockedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeBlockedTypeInfo>
{
protected sealed override RuntimeBlockedTypeInfo Factory(RuntimeTypeHandleKey key)
{
return new RuntimeBlockedTypeInfo(key.TypeHandle, isGenericTypeDefinition: false);
}
public static readonly BlockedTypeTable Table = new BlockedTypeTable();
}
private sealed class GenericBlockedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeBlockedTypeInfo>
{
protected sealed override RuntimeBlockedTypeInfo Factory(RuntimeTypeHandleKey key)
{
return new RuntimeBlockedTypeInfo(key.TypeHandle, isGenericTypeDefinition: true);
}
public static readonly GenericBlockedTypeTable Table = new GenericBlockedTypeTable();
}
}
//-----------------------------------------------------------------------------------------------------------
// TypeInfos for Sz and multi-dim Array types.
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimeArrayTypeInfo : RuntimeHasElementTypeInfo
{
internal static RuntimeArrayTypeInfo GetArrayTypeInfo(RuntimeTypeInfo elementType, bool multiDim, int rank, RuntimeTypeHandle precomputedTypeHandle)
{
Debug.Assert(multiDim || rank == 1);
RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(elementType, multiDim, rank) : precomputedTypeHandle;
UnificationKey key = new UnificationKey(elementType, typeHandle);
RuntimeArrayTypeInfo type;
if (!multiDim)
type = ArrayTypeTable.Table.GetOrAdd(key);
else
type = TypeTableForMultiDimArrayTypeTables.Table.GetOrAdd(rank).GetOrAdd(key);
type.EstablishDebugName();
return type;
}
private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo elementType, bool multiDim, int rank)
{
Debug.Assert(multiDim || rank == 1);
RuntimeTypeHandle elementTypeHandle = elementType.InternalTypeHandleIfAvailable;
if (elementTypeHandle.IsNull())
return default(RuntimeTypeHandle);
RuntimeTypeHandle typeHandle;
if (!multiDim)
{
if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetArrayTypeForElementType(elementTypeHandle, out typeHandle))
return default(RuntimeTypeHandle);
}
else
{
if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetMultiDimArrayTypeForElementType(elementTypeHandle, rank, out typeHandle))
return default(RuntimeTypeHandle);
}
return typeHandle;
}
private sealed class ArrayTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeArrayTypeInfo>
{
protected sealed override RuntimeArrayTypeInfo Factory(UnificationKey key)
{
ValidateElementType(key.ElementType, key.TypeHandle, multiDim: false, rank: 1);
return new RuntimeArrayTypeInfo(key, multiDim: false, rank: 1);
}
public static readonly ArrayTypeTable Table = new ArrayTypeTable();
}
private sealed class MultiDimArrayTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeArrayTypeInfo>
{
public MultiDimArrayTypeTable(int rank)
{
_rank = rank;
}
protected sealed override RuntimeArrayTypeInfo Factory(UnificationKey key)
{
ValidateElementType(key.ElementType, key.TypeHandle, multiDim: true, rank: _rank);
return new RuntimeArrayTypeInfo(key, multiDim: true, rank: _rank);
}
private readonly int _rank;
}
//
// For the hopefully rare case of multidim arrays, we have a dictionary of dictionaries.
//
private sealed class TypeTableForMultiDimArrayTypeTables : ConcurrentUnifier<int, MultiDimArrayTypeTable>
{
protected sealed override MultiDimArrayTypeTable Factory(int rank)
{
Debug.Assert(rank > 0);
return new MultiDimArrayTypeTable(rank);
}
public static readonly TypeTableForMultiDimArrayTypeTables Table = new TypeTableForMultiDimArrayTypeTables();
}
private static void ValidateElementType(RuntimeTypeInfo elementType, RuntimeTypeHandle typeHandle, bool multiDim, int rank)
{
Debug.Assert(multiDim || rank == 1);
if (elementType.IsByRef)
throw new TypeLoadException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType));
if (elementType.IsGenericTypeDefinition)
throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType));
// We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result
// type would be an open type.
if (typeHandle.IsNull() && !elementType.ContainsGenericParameters)
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingArrayTypeException(elementType, multiDim, rank);
}
}
//-----------------------------------------------------------------------------------------------------------
// TypeInfos for ByRef types.
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimeByRefTypeInfo : RuntimeHasElementTypeInfo
{
internal static RuntimeByRefTypeInfo GetByRefTypeInfo(RuntimeTypeInfo elementType, RuntimeTypeHandle precomputedTypeHandle)
{
RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(elementType) : precomputedTypeHandle;
RuntimeByRefTypeInfo type = ByRefTypeTable.Table.GetOrAdd(new UnificationKey(elementType, typeHandle));
type.EstablishDebugName();
return type;
}
private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo elementType)
{
RuntimeTypeHandle elementTypeHandle = elementType.InternalTypeHandleIfAvailable;
if (elementTypeHandle.IsNull())
return default(RuntimeTypeHandle);
RuntimeTypeHandle typeHandle;
if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetByRefTypeForTargetType(elementTypeHandle, out typeHandle))
return default(RuntimeTypeHandle);
return typeHandle;
}
private sealed class ByRefTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeByRefTypeInfo>
{
protected sealed override RuntimeByRefTypeInfo Factory(UnificationKey key)
{
return new RuntimeByRefTypeInfo(key);
}
public static readonly ByRefTypeTable Table = new ByRefTypeTable();
}
}
//-----------------------------------------------------------------------------------------------------------
// TypeInfos for Pointer types.
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimePointerTypeInfo : RuntimeHasElementTypeInfo
{
internal static RuntimePointerTypeInfo GetPointerTypeInfo(RuntimeTypeInfo elementType, RuntimeTypeHandle precomputedTypeHandle)
{
RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(elementType) : precomputedTypeHandle;
RuntimePointerTypeInfo type = PointerTypeTable.Table.GetOrAdd(new UnificationKey(elementType, typeHandle));
type.EstablishDebugName();
return type;
}
private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo elementType)
{
RuntimeTypeHandle elementTypeHandle = elementType.InternalTypeHandleIfAvailable;
if (elementTypeHandle.IsNull())
return default(RuntimeTypeHandle);
RuntimeTypeHandle typeHandle;
if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetPointerTypeForTargetType(elementTypeHandle, out typeHandle))
return default(RuntimeTypeHandle);
return typeHandle;
}
private sealed class PointerTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimePointerTypeInfo>
{
protected sealed override RuntimePointerTypeInfo Factory(UnificationKey key)
{
return new RuntimePointerTypeInfo(key);
}
public static readonly PointerTypeTable Table = new PointerTypeTable();
}
}
//-----------------------------------------------------------------------------------------------------------
// TypeInfos for Constructed generic types ("Foo<int>")
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimeConstructedGenericTypeInfo : RuntimeTypeInfo, IKeyedItem<RuntimeConstructedGenericTypeInfo.UnificationKey>
{
internal static RuntimeConstructedGenericTypeInfo GetRuntimeConstructedGenericTypeInfo(RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments, RuntimeTypeHandle precomputedTypeHandle)
{
RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(genericTypeDefinition, genericTypeArguments) : precomputedTypeHandle;
UnificationKey key = new UnificationKey(genericTypeDefinition, genericTypeArguments, typeHandle);
RuntimeConstructedGenericTypeInfo typeInfo = ConstructedGenericTypeTable.Table.GetOrAdd(key);
typeInfo.EstablishDebugName();
return typeInfo;
}
private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments)
{
RuntimeTypeHandle genericTypeDefinitionHandle = genericTypeDefinition.InternalTypeHandleIfAvailable;
if (genericTypeDefinitionHandle.IsNull())
return default(RuntimeTypeHandle);
if (ReflectionCoreExecution.ExecutionEnvironment.IsReflectionBlocked(genericTypeDefinitionHandle))
return default(RuntimeTypeHandle);
int count = genericTypeArguments.Length;
RuntimeTypeHandle[] genericTypeArgumentHandles = new RuntimeTypeHandle[count];
for (int i = 0; i < count; i++)
{
RuntimeTypeHandle genericTypeArgumentHandle = genericTypeArguments[i].InternalTypeHandleIfAvailable;
if (genericTypeArgumentHandle.IsNull())
return default(RuntimeTypeHandle);
genericTypeArgumentHandles[i] = genericTypeArgumentHandle;
}
RuntimeTypeHandle typeHandle;
if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetConstructedGenericTypeForComponents(genericTypeDefinitionHandle, genericTypeArgumentHandles, out typeHandle))
return default(RuntimeTypeHandle);
return typeHandle;
}
private sealed class ConstructedGenericTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeConstructedGenericTypeInfo>
{
protected sealed override RuntimeConstructedGenericTypeInfo Factory(UnificationKey key)
{
bool atLeastOneOpenType = false;
foreach (RuntimeTypeInfo genericTypeArgument in key.GenericTypeArguments)
{
if (genericTypeArgument.IsByRef || genericTypeArgument.IsGenericTypeDefinition)
throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidTypeArgument, genericTypeArgument));
if (genericTypeArgument.ContainsGenericParameters)
atLeastOneOpenType = true;
}
// We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result
// type would be an open type.
if (key.TypeHandle.IsNull() && !atLeastOneOpenType)
throw ReflectionCoreExecution.ExecutionDomain.CreateMissingConstructedGenericTypeException(key.GenericTypeDefinition, key.GenericTypeArguments.CloneTypeArray());
return new RuntimeConstructedGenericTypeInfo(key);
}
public static readonly ConstructedGenericTypeTable Table = new ConstructedGenericTypeTable();
}
}
internal sealed partial class RuntimeCLSIDTypeInfo
{
public static RuntimeCLSIDTypeInfo GetRuntimeCLSIDTypeInfo(Guid clsid, string server)
{
UnificationKey key = new UnificationKey(clsid, server);
return ClsIdTypeTable.Table.GetOrAdd(key);
}
private sealed class ClsIdTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeCLSIDTypeInfo>
{
protected sealed override RuntimeCLSIDTypeInfo Factory(UnificationKey key)
{
return new RuntimeCLSIDTypeInfo(key.ClsId, key.Server);
}
public static readonly ClsIdTypeTable Table = new ClsIdTypeTable();
}
}
}
| |
using System;
using System.Collections;
namespace JayPascal
{
public class Scanner : TokenStream
{
internal const int MAX_DIGITS = 64;
internal const int MAX_IDENTIFIER = 128;
internal const int MAX_STRING = 1024;
internal CharStream cs;
internal Hashtable idsAndKeywords;
internal Token buffer;
internal bool dotdot_next = false;
public Scanner(CharStream cs)
{
this.cs = cs;
try
{
this.skipSpaces();
}
catch (Exception e)
{
throw new ScannerException(e.Message);
}
this.idsAndKeywords = Hashtable.Synchronized(new Hashtable());
this.idsAndKeywords["and"] = PascalTokens.TAND;
this.idsAndKeywords["array"] = PascalTokens.TARRAY;
this.idsAndKeywords["begin"] = PascalTokens.TBEGIN;
this.idsAndKeywords["const"] = PascalTokens.TCONST;
this.idsAndKeywords["div"] = PascalTokens.TINTDIV;
this.idsAndKeywords["do"] = PascalTokens.TDO;
this.idsAndKeywords["downto"] = PascalTokens.TDOWNTO;
this.idsAndKeywords["else"] = PascalTokens.TELSE;
this.idsAndKeywords["end"] = PascalTokens.TEND;
this.idsAndKeywords["for"] = PascalTokens.TFOR;
this.idsAndKeywords["goto"] = PascalTokens.TGOTO;
this.idsAndKeywords["if"] = PascalTokens.TIF;
this.idsAndKeywords["in"] = PascalTokens.TIN;
this.idsAndKeywords["label"] = PascalTokens.TLABEL;
this.idsAndKeywords["not"] = PascalTokens.TNOT;
this.idsAndKeywords["of"] = PascalTokens.TOF;
this.idsAndKeywords["or"] = PascalTokens.TOR;
this.idsAndKeywords["procedure"] = PascalTokens.TPROCEDURE;
this.idsAndKeywords["program"] = PascalTokens.TPROGRAM;
this.idsAndKeywords["repeat"] = PascalTokens.TREPEAT;
this.idsAndKeywords["then"] = PascalTokens.TTHEN;
this.idsAndKeywords["to"] = PascalTokens.TTO;
this.idsAndKeywords["type"] = PascalTokens.TTYPE;
this.idsAndKeywords["until"] = PascalTokens.TUNTIL;
this.idsAndKeywords["var"] = PascalTokens.TVAR;
this.idsAndKeywords["while"] = PascalTokens.TWHILE;
this.idsAndKeywords["boolean"] = PascalTokens.TBOOLEAN;
this.idsAndKeywords["char"] = PascalTokens.TCHAR;
this.idsAndKeywords["integer"] = PascalTokens.TINTEGER;
this.idsAndKeywords["real"] = PascalTokens.TREAL;
this.idsAndKeywords["false"] = PascalTokens.TFALSE;
this.idsAndKeywords["true"] = PascalTokens.TTRUE;
}
internal virtual void scannerError(String message)
{
this.skipSpaces();
throw new ScannerException(message);
}
internal virtual void fillBuffer()
{
if (buffer != null)
return ;
if (this.dotdot_next)
{
buffer = PascalTokens.TDOTDOT;
this.dotdot_next = false;
return ;
}
if (!cs.hasMore())
return ;
char ch = cs.next();
if (isAlpha(ch))
{
char[] chars = new char[MAX_IDENTIFIER];
int len = 1;
chars[0] = ch;
while ((len < MAX_IDENTIFIER) && (cs.hasMore()) && (isIdChar(cs.peek())))
{
chars[len++] = cs.next();
}
if (len == MAX_IDENTIFIER)
scannerError("Identifiers are limited to " + MAX_IDENTIFIER + " chars.");
String str = (new String(chars, 0, len)).ToLower();
Token tok = (Token) idsAndKeywords[str];
if (tok != null)
{
buffer = tok;
}
else
{
tok = new Identifier(str);
idsAndKeywords[str] = tok;
buffer = tok;
}
}
else if (isDigit(ch))
{
char[] digits = new char[MAX_DIGITS];
digits[0] = ch;
int len = 1;
bool isReal = false;
while ((len < MAX_DIGITS) && (isDigit(cs.peek())))
digits[len++] = cs.next();
if (len == MAX_DIGITS)
scannerError("Numbers are limited to " + MAX_DIGITS + " characters.");
if (cs.peek() == '.')
{
cs.next();
if (cs.peek() == '.')
{
cs.next();
this.dotdot_next = true;
buffer = new IntegerToken(new String(digits, 0, len));
}
else if (isDigit(cs.peek()))
{
if ((len + 2) >= MAX_DIGITS)
scannerError("Numbers are limited to " + MAX_DIGITS + " characters.");
isReal = true;
digits[len++] = '.';
digits[len++] = cs.next();
while ((len < MAX_DIGITS) && (isDigit(cs.peek())))
digits[len++] = cs.next();
}
else
{
scannerError("Sorry, Pascal doesn't allow number dot " + cs.peek());
}
}
if (len == MAX_DIGITS)
scannerError("Numbers are limited to " + MAX_DIGITS + " characters.");
if ((buffer == null) && ((cs.peek() == 'E') || (cs.peek() == 'e')))
{
if (len + 2 >= MAX_DIGITS)
scannerError("Numbers are limited to " + MAX_DIGITS + " characters.");
isReal = true;
digits[len++] = cs.next(); // 'E'
if ((cs.peek() == '+') || (cs.peek() == '-'))
digits[len++] = cs.next(); // '+' or '-'
if (len + 1 >= MAX_DIGITS)
scannerError("Numbers are limited to " + MAX_DIGITS + " characters.");
if (!isDigit(cs.peek()))
scannerError("Sorry, Pascal doesn't allow number dot " + cs.peek());
digits[len++] = cs.next();
while ((len < MAX_DIGITS) && (isDigit(cs.peek())))
digits[len++] = cs.next();
if (len == MAX_DIGITS)
scannerError("Numbers are limited to " + MAX_DIGITS + " characters.");
}
String number = new String(digits, 0, len);
if (isReal)
{
try
{
buffer = new RealToken(number);
}
catch (FormatException e)
{
Console.Write(e.Message);
scannerError("Invalid integer: " + number);
}
}
else
{
try
{
buffer = new IntegerToken(number);
}
catch (FormatException e)
{
Console.Write(e.Message);
scannerError("Invalid real: " + number);
}
}
}
else if (ch == '\'')
{
char[] chars = new char[MAX_STRING];
int len = 0;
while ((len < MAX_STRING) && ((ch = cs.next()) != '\''))
{
if (ch == '\\')
chars[len++] = cs.next();
else
chars[len++] = ch;
}
if (len == MAX_STRING)
scannerError("Strings are limited to " + MAX_STRING + " chars.");
if (len == 1)
{
buffer = new CharToken(chars[0]);
}
else
{
buffer = new StringToken(new String(chars, 0, len));
}
}
else
{
switch (ch)
{
case '+': buffer = PascalTokens.TPLUS; break;
case '-': buffer = PascalTokens.TMINUS; break;
case '*': buffer = PascalTokens.TTIMES; break;
case '/': buffer = PascalTokens.TDIVIDE; break;
/*
case '/':
if (cs.hasMore() && (cs.peek() == '/'))
{
// comment found
do
{
ch =cs.next();
} while (cs.hasMore() && (ch != '\n'));
buffer = PascalTokens.TCOMMENT;
}
else
buffer = PascalTokens.TDIVIDE;
break;
* */
case '(': buffer = PascalTokens.TOPENPAREN; break;
case ')': buffer = PascalTokens.TCLOSEPAREN; break;
case ',': buffer = PascalTokens.TCOMMA; break;
case ';': buffer = PascalTokens.TSEMICOLON; break;
case '=': buffer = PascalTokens.TEQUALS; break;
case '[': buffer = PascalTokens.TOPENBRACKET; break;
case ']': buffer = PascalTokens.TCLOSEBRACKET; break;
case ':':
if (cs.hasMore() && (cs.peek() == '='))
{
cs.next();
buffer = PascalTokens.TBECOMES;
}
else
buffer = PascalTokens.TCOLON;
break;
case '.':
if (cs.hasMore() && (cs.peek() == '.'))
{
cs.next();
buffer = PascalTokens.TDOTDOT;
}
else
buffer = PascalTokens.TDOT;
break;
case '<':
if (cs.hasMore() && (cs.peek() == '='))
{
cs.next();
buffer = PascalTokens.TLESSEQ;
}
else if (cs.hasMore() && (cs.peek() == '>'))
{
cs.next();
buffer = PascalTokens.TNOTEQUALS;
}
else
buffer = PascalTokens.TLESSTHAN;
break;
case '>':
if (cs.hasMore() && (cs.peek() == '='))
{
cs.next();
buffer = PascalTokens.TGREATEREQ;
}
else
buffer = PascalTokens.TGREATERTHAN;
break;
default:
scannerError("Unknown char '" + ch + "'\n");
break;
}
}
this.skipSpaces();
}
internal virtual bool isAlpha(char ch)
{
return Char.IsLetter(ch);
}
internal virtual bool isDigit(char ch)
{
return Char.IsDigit(ch);
}
internal virtual bool isIdChar(char ch)
{
return isAlpha(ch) || (ch == '_') || isDigit(ch);
}
internal virtual bool isSpace(char ch)
{
if (ch == '\n')
{
cursorPosition.rowNumber++;
cursorPosition.colNumber = 1;
}
return (ch == ' ') || (ch == '\n') || (ch == '\t') || (ch == 10) || (ch == 13);
}
internal virtual void skipSpaces()
{
while (cs.hasMore() && isSpace(cs.peek()))
cs.next();
if (!cs.hasMore())
return ;
if (cs.peek() == '{')
{
while (cs.hasMore() && (cs.peek() != '}'))
cs.next();
if (!cs.hasMore())
return ;
cs.next();
skipSpaces();
}
}
public virtual bool hasMore()
{
return (this.buffer != null) || (this.cs.hasMore());
}
public virtual Token peek()
{
this.fillBuffer();
return this.buffer;
}
public virtual void addToken(String name, Token tok)
{
this.idsAndKeywords[name] = tok;
}
public virtual Token next()
{
this.fillBuffer();
Token tok = this.buffer;
this.buffer = null;
return tok;
}
}
}
| |
/*
* 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.Xml;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes.Scripting;
using OpenSim.Region.Framework.Scenes.Serialization;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.Framework.Scenes
{
public class SceneObjectPartInventory : IEntityInventory
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_inventoryFileName = String.Empty;
private byte[] m_inventoryFileData = new byte[0];
private uint m_inventoryFileNameSerial = 0;
/// <value>
/// The part to which the inventory belongs.
/// </value>
private SceneObjectPart m_part;
/// <summary>
/// Serial count for inventory file , used to tell if inventory has changed
/// no need for this to be part of Database backup
/// </summary>
protected uint m_inventorySerial = 0;
/// <summary>
/// Holds in memory prim inventory
/// </summary>
protected TaskInventoryDictionary m_items = new TaskInventoryDictionary();
/// <summary>
/// Tracks whether inventory has changed since the last persistent backup
/// </summary>
internal bool HasInventoryChanged;
/// <value>
/// Inventory serial number
/// </value>
protected internal uint Serial
{
get { return m_inventorySerial; }
set { m_inventorySerial = value; }
}
/// <value>
/// Raw inventory data
/// </value>
protected internal TaskInventoryDictionary Items
{
get { return m_items; }
set
{
m_items = value;
m_inventorySerial++;
QueryScriptStates();
}
}
public int Count
{
get
{
lock (m_items)
return m_items.Count;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="part">
/// A <see cref="SceneObjectPart"/>
/// </param>
public SceneObjectPartInventory(SceneObjectPart part)
{
m_part = part;
}
/// <summary>
/// Force the task inventory of this prim to persist at the next update sweep
/// </summary>
public void ForceInventoryPersistence()
{
HasInventoryChanged = true;
}
/// <summary>
/// Reset UUIDs for all the items in the prim's inventory.
/// </summary>
/// <remarks>
/// This involves either generating
/// new ones or setting existing UUIDs to the correct parent UUIDs.
///
/// If this method is called and there are inventory items, then we regard the inventory as having changed.
/// </remarks>
public void ResetInventoryIDs()
{
if (null == m_part)
return;
lock (m_items)
{
if (0 == m_items.Count)
return;
IList<TaskInventoryItem> items = GetInventoryItems();
m_items.Clear();
foreach (TaskInventoryItem item in items)
{
item.ResetIDs(m_part.UUID);
m_items.Add(item.ItemID, item);
}
}
}
public void ResetObjectID()
{
lock (Items)
{
IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
Items.Clear();
foreach (TaskInventoryItem item in items)
{
item.ParentPartID = m_part.UUID;
item.ParentID = m_part.UUID;
Items.Add(item.ItemID, item);
}
}
}
/// <summary>
/// Change every item in this inventory to a new owner.
/// </summary>
/// <param name="ownerId"></param>
public void ChangeInventoryOwner(UUID ownerId)
{
lock (Items)
{
if (0 == Items.Count)
{
return;
}
}
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
List<TaskInventoryItem> items = GetInventoryItems();
foreach (TaskInventoryItem item in items)
{
if (ownerId != item.OwnerID)
item.LastOwnerID = item.OwnerID;
item.OwnerID = ownerId;
item.PermsMask = 0;
item.PermsGranter = UUID.Zero;
item.OwnerChanged = true;
}
}
/// <summary>
/// Change every item in this inventory to a new group.
/// </summary>
/// <param name="groupID"></param>
public void ChangeInventoryGroup(UUID groupID)
{
lock (Items)
{
if (0 == Items.Count)
{
return;
}
}
// Don't let this set the HasGroupChanged flag for attachments
// as this happens during rez and we don't want a new asset
// for each attachment each time
if (!m_part.ParentGroup.IsAttachment)
{
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
}
List<TaskInventoryItem> items = GetInventoryItems();
foreach (TaskInventoryItem item in items)
{
if (groupID != item.GroupID)
item.GroupID = groupID;
}
}
private void QueryScriptStates()
{
if (m_part == null || m_part.ParentGroup == null || m_part.ParentGroup.Scene == null)
return;
lock (Items)
{
foreach (TaskInventoryItem item in Items.Values)
{
bool running;
if (TryGetScriptInstanceRunning(m_part.ParentGroup.Scene, item, out running))
item.ScriptRunning = running;
}
}
}
public bool TryGetScriptInstanceRunning(UUID itemId, out bool running)
{
running = false;
TaskInventoryItem item = GetInventoryItem(itemId);
if (item == null)
return false;
return TryGetScriptInstanceRunning(m_part.ParentGroup.Scene, item, out running);
}
public static bool TryGetScriptInstanceRunning(Scene scene, TaskInventoryItem item, out bool running)
{
running = false;
if (item.InvType != (int)InventoryType.LSL)
return false;
IScriptModule[] engines = scene.RequestModuleInterfaces<IScriptModule>();
if (engines == null) // No engine at all
return false;
foreach (IScriptModule e in engines)
{
if (e.HasScript(item.ItemID, out running))
return true;
}
return false;
}
public int CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource)
{
int scriptsValidForStarting = 0;
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
if (CreateScriptInstance(item, startParam, postOnRez, engine, stateSource))
scriptsValidForStarting++;
return scriptsValidForStarting;
}
public ArrayList GetScriptErrors(UUID itemID)
{
ArrayList ret = new ArrayList();
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
foreach (IScriptModule e in engines)
{
if (e != null)
{
ArrayList errors = e.GetScriptErrors(itemID);
foreach (Object line in errors)
ret.Add(line);
}
}
return ret;
}
/// <summary>
/// Stop and remove all the scripts in this prim.
/// </summary>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if these scripts are being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void RemoveScriptInstances(bool sceneObjectBeingDeleted)
{
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted);
}
/// <summary>
/// Stop all the scripts in this prim.
/// </summary>
public void StopScriptInstances()
{
GetInventoryItems(InventoryType.LSL).ForEach(i => StopScriptInstance(i));
}
/// <summary>
/// Start a script which is in this prim's inventory.
/// </summary>
/// <param name="item"></param>
/// <returns>true if the script instance was created, false otherwise</returns>
public bool CreateScriptInstance(TaskInventoryItem item, int startParam, bool postOnRez, string engine, int stateSource)
{
// m_log.DebugFormat("[PRIM INVENTORY]: Starting script {0} {1} in prim {2} {3} in {4}",
// item.Name, item.ItemID, m_part.Name, m_part.UUID, m_part.ParentGroup.Scene.RegionInfo.RegionName);
if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID))
return false;
m_part.AddFlag(PrimFlags.Scripted);
if (m_part.ParentGroup.Scene.RegionInfo.RegionSettings.DisableScripts)
return false;
if (stateSource == 2 && // Prim crossing
m_part.ParentGroup.Scene.m_trustBinaries)
{
lock (m_items)
{
m_items[item.ItemID].PermsMask = 0;
m_items[item.ItemID].PermsGranter = UUID.Zero;
}
m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource);
m_part.ParentGroup.AddActiveScriptCount(1);
m_part.ScheduleFullUpdate();
return true;
}
AssetBase asset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString());
if (null == asset)
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found",
item.Name, item.ItemID, m_part.AbsolutePosition,
m_part.ParentGroup.Scene.RegionInfo.RegionName, item.AssetID);
return false;
}
else
{
if (m_part.ParentGroup.m_savedScriptState != null)
item.OldItemID = RestoreSavedScriptState(item.LoadedItemID, item.OldItemID, item.ItemID);
lock (m_items)
{
m_items[item.ItemID].OldItemID = item.OldItemID;
m_items[item.ItemID].PermsMask = 0;
m_items[item.ItemID].PermsGranter = UUID.Zero;
}
string script = Utils.BytesToString(asset.Data);
m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource);
if (!item.ScriptRunning)
m_part.ParentGroup.Scene.EventManager.TriggerStopScript(
m_part.LocalId, item.ItemID);
m_part.ParentGroup.AddActiveScriptCount(1);
m_part.ScheduleFullUpdate();
return true;
}
}
private UUID RestoreSavedScriptState(UUID loadedID, UUID oldID, UUID newID)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Restoring scripted state for item {0}, oldID {1}, loadedID {2}",
// newID, oldID, loadedID);
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines.Length == 0) // No engine at all
return oldID;
UUID stateID = oldID;
if (!m_part.ParentGroup.m_savedScriptState.ContainsKey(oldID))
stateID = loadedID;
if (m_part.ParentGroup.m_savedScriptState.ContainsKey(stateID))
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(m_part.ParentGroup.m_savedScriptState[stateID]);
////////// CRUFT WARNING ///////////////////////////////////
//
// Old objects will have <ScriptState><State> ...
// This format is XEngine ONLY
//
// New objects have <State Engine="...." ...><ScriptState>...
// This can be passed to any engine
//
XmlNode n = doc.SelectSingleNode("ScriptState");
if (n != null) // Old format data
{
XmlDocument newDoc = new XmlDocument();
XmlElement rootN = newDoc.CreateElement("", "State", "");
XmlAttribute uuidA = newDoc.CreateAttribute("", "UUID", "");
uuidA.Value = stateID.ToString();
rootN.Attributes.Append(uuidA);
XmlAttribute engineA = newDoc.CreateAttribute("", "Engine", "");
engineA.Value = "XEngine";
rootN.Attributes.Append(engineA);
newDoc.AppendChild(rootN);
XmlNode stateN = newDoc.ImportNode(n, true);
rootN.AppendChild(stateN);
// This created document has only the minimun data
// necessary for XEngine to parse it successfully
// m_log.DebugFormat("[PRIM INVENTORY]: Adding legacy state {0} in {1}", stateID, newID);
m_part.ParentGroup.m_savedScriptState[stateID] = newDoc.OuterXml;
}
foreach (IScriptModule e in engines)
{
if (e != null)
{
if (e.SetXMLState(newID, m_part.ParentGroup.m_savedScriptState[stateID]))
break;
}
}
m_part.ParentGroup.m_savedScriptState.Remove(stateID);
}
return stateID;
}
public bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
{
TaskInventoryItem item = GetInventoryItem(itemId);
if (item != null)
{
return CreateScriptInstance(item, startParam, postOnRez, engine, stateSource);
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
itemId, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
return false;
}
}
/// <summary>
/// Stop and remove a script which is in this prim's inventory.
/// </summary>
/// <param name="itemId"></param>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if this script is being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted)
{
bool scriptPresent = false;
lock (m_items)
{
if (m_items.ContainsKey(itemId))
scriptPresent = true;
}
if (scriptPresent)
{
if (!sceneObjectBeingDeleted)
m_part.RemoveScriptEvents(itemId);
m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemId);
m_part.ParentGroup.AddActiveScriptCount(-1);
}
else
{
m_log.WarnFormat(
"[PRIM INVENTORY]: " +
"Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
itemId, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
}
/// <summary>
/// Stop a script which is in this prim's inventory.
/// </summary>
/// <param name="itemId"></param>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if this script is being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void StopScriptInstance(UUID itemId)
{
TaskInventoryItem scriptItem;
lock (m_items)
m_items.TryGetValue(itemId, out scriptItem);
if (scriptItem != null)
{
StopScriptInstance(scriptItem);
}
else
{
m_log.WarnFormat(
"[PRIM INVENTORY]: " +
"Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
itemId, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
}
/// <summary>
/// Stop a script which is in this prim's inventory.
/// </summary>
/// <param name="itemId"></param>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if this script is being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void StopScriptInstance(TaskInventoryItem item)
{
if (m_part.ParentGroup.Scene != null)
m_part.ParentGroup.Scene.EventManager.TriggerStopScript(m_part.LocalId, item.ItemID);
// At the moment, even stopped scripts are counted as active, which is probably wrong.
// m_part.ParentGroup.AddActiveScriptCount(-1);
}
/// <summary>
/// Check if the inventory holds an item with a given name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private bool InventoryContainsName(string name)
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.Name == name)
return true;
}
}
return false;
}
/// <summary>
/// For a given item name, return that name if it is available. Otherwise, return the next available
/// similar name (which is currently the original name with the next available numeric suffix).
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private string FindAvailableInventoryName(string name)
{
if (!InventoryContainsName(name))
return name;
int suffix=1;
while (suffix < 256)
{
string tryName=String.Format("{0} {1}", name, suffix);
if (!InventoryContainsName(tryName))
return tryName;
suffix++;
}
return String.Empty;
}
/// <summary>
/// Add an item to this prim's inventory. If an item with the same name already exists, then an alternative
/// name is chosen.
/// </summary>
/// <param name="item"></param>
public void AddInventoryItem(TaskInventoryItem item, bool allowedDrop)
{
AddInventoryItem(item.Name, item, allowedDrop);
}
/// <summary>
/// Add an item to this prim's inventory. If an item with the same name already exists, it is replaced.
/// </summary>
/// <param name="item"></param>
public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop)
{
List<TaskInventoryItem> il = GetInventoryItems();
foreach (TaskInventoryItem i in il)
{
if (i.Name == item.Name)
{
if (i.InvType == (int)InventoryType.LSL)
RemoveScriptInstance(i.ItemID, false);
RemoveInventoryItem(i.ItemID);
break;
}
}
AddInventoryItem(item.Name, item, allowedDrop);
}
/// <summary>
/// Add an item to this prim's inventory.
/// </summary>
/// <param name="name">The name that the new item should have.</param>
/// <param name="item">
/// The item itself. The name within this structure is ignored in favour of the name
/// given in this method's arguments
/// </param>
/// <param name="allowedDrop">
/// Item was only added to inventory because AllowedDrop is set
/// </param>
protected void AddInventoryItem(string name, TaskInventoryItem item, bool allowedDrop)
{
name = FindAvailableInventoryName(name);
if (name == String.Empty)
return;
item.ParentID = m_part.UUID;
item.ParentPartID = m_part.UUID;
item.Name = name;
item.GroupID = m_part.GroupID;
lock (m_items)
m_items.Add(item.ItemID, item);
if (allowedDrop)
m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP);
else
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
m_inventorySerial++;
//m_inventorySerial += 2;
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
}
/// <summary>
/// Restore a whole collection of items to the prim's inventory at once.
/// We assume that the items already have all their fields correctly filled out.
/// The items are not flagged for persistence to the database, since they are being restored
/// from persistence rather than being newly added.
/// </summary>
/// <param name="items"></param>
public void RestoreInventoryItems(ICollection<TaskInventoryItem> items)
{
lock (m_items)
{
foreach (TaskInventoryItem item in items)
{
m_items.Add(item.ItemID, item);
// m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
}
m_inventorySerial++;
}
}
/// <summary>
/// Returns an existing inventory item. Returns the original, so any changes will be live.
/// </summary>
/// <param name="itemID"></param>
/// <returns>null if the item does not exist</returns>
public TaskInventoryItem GetInventoryItem(UUID itemId)
{
TaskInventoryItem item;
lock (m_items)
m_items.TryGetValue(itemId, out item);
return item;
}
public TaskInventoryItem GetInventoryItem(string name)
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.Name == name)
return item;
}
}
return null;
}
public List<TaskInventoryItem> GetInventoryItems(string name)
{
List<TaskInventoryItem> items = new List<TaskInventoryItem>();
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.Name == name)
items.Add(item);
}
}
return items;
}
public bool GetRezReadySceneObjects(TaskInventoryItem item, out List<SceneObjectGroup> objlist, out List<Vector3> veclist)
{
AssetBase rezAsset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString());
if (null == rezAsset)
{
m_log.WarnFormat(
"[PRIM INVENTORY]: Could not find asset {0} for inventory item {1} in {2}",
item.AssetID, item.Name, m_part.Name);
objlist = null;
veclist = null;
return false;
}
Vector3 bbox;
float offsetHeight;
m_part.ParentGroup.Scene.GetObjectsToRez(rezAsset.Data, false, out objlist, out veclist, out bbox, out offsetHeight);
for (int i = 0; i < objlist.Count; i++)
{
SceneObjectGroup group = objlist[i];
group.ResetIDs();
SceneObjectPart rootPart = group.GetPart(group.UUID);
// Since renaming the item in the inventory does not affect the name stored
// in the serialization, transfer the correct name from the inventory to the
// object itself before we rez.
// Only do these for the first object if we are rezzing a coalescence.
if (i == 0)
{
rootPart.Name = item.Name;
rootPart.Description = item.Description;
}
group.SetGroup(m_part.GroupID, null);
foreach (SceneObjectPart part in group.Parts)
{
// Convert between InventoryItem classes. You can never have too many similar but slightly different classes :)
InventoryItemBase dest = new InventoryItemBase(item.ItemID, item.OwnerID);
dest.BasePermissions = item.BasePermissions;
dest.CurrentPermissions = item.CurrentPermissions;
dest.EveryOnePermissions = item.EveryonePermissions;
dest.GroupPermissions = item.GroupPermissions;
dest.NextPermissions = item.NextPermissions;
dest.Flags = item.Flags;
part.ApplyPermissionsOnRez(dest, false, m_part.ParentGroup.Scene);
}
rootPart.TrimPermissions();
}
return true;
}
/// <summary>
/// Update an existing inventory item.
/// </summary>
/// <param name="item">The updated item. An item with the same id must already exist
/// in this prim's inventory.</param>
/// <returns>false if the item did not exist, true if the update occurred successfully</returns>
public bool UpdateInventoryItem(TaskInventoryItem item)
{
return UpdateInventoryItem(item, true, true);
}
public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents)
{
return UpdateInventoryItem(item, fireScriptEvents, true);
}
public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged)
{
TaskInventoryItem it = GetInventoryItem(item.ItemID);
if (it != null)
{
// m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name);
item.ParentID = m_part.UUID;
item.ParentPartID = m_part.UUID;
// If group permissions have been set on, check that the groupID is up to date in case it has
// changed since permissions were last set.
if (item.GroupPermissions != (uint)PermissionMask.None)
item.GroupID = m_part.GroupID;
if (item.AssetID == UUID.Zero)
item.AssetID = it.AssetID;
lock (m_items)
{
m_items[item.ItemID] = item;
m_inventorySerial++;
}
if (fireScriptEvents)
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
if (considerChanged)
{
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
}
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Tried to retrieve item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory",
item.ItemID, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
return false;
}
/// <summary>
/// Remove an item from this prim's inventory
/// </summary>
/// <param name="itemID"></param>
/// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist
/// in this prim's inventory.</returns>
public int RemoveInventoryItem(UUID itemID)
{
TaskInventoryItem item = GetInventoryItem(itemID);
if (item != null)
{
int type = m_items[itemID].InvType;
if (type == 10) // Script
{
// route it through here, to handle script cleanup tasks
RemoveScriptInstance(itemID, false);
}
m_items.Remove(itemID);
m_inventorySerial++;
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
if (!ContainsScripts())
m_part.RemFlag(PrimFlags.Scripted);
m_part.ScheduleFullUpdate();
return type;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Tried to remove item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory",
itemID, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
return -1;
}
private bool CreateInventoryFile()
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Creating inventory file for {0} {1} {2}, serial {3}",
// m_part.Name, m_part.UUID, m_part.LocalId, m_inventorySerial);
if (m_inventoryFileName == String.Empty ||
m_inventoryFileNameSerial < m_inventorySerial)
{
// Something changed, we need to create a new file
m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp";
m_inventoryFileNameSerial = m_inventorySerial;
InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Adding item {0} {1} for serial {2} on prim {3} {4} {5}",
// item.Name, item.ItemID, m_inventorySerial, m_part.Name, m_part.UUID, m_part.LocalId);
UUID ownerID = item.OwnerID;
uint everyoneMask = 0;
uint baseMask = item.BasePermissions;
uint ownerMask = item.CurrentPermissions;
uint groupMask = item.GroupPermissions;
invString.AddItemStart();
invString.AddNameValueLine("item_id", item.ItemID.ToString());
invString.AddNameValueLine("parent_id", m_part.UUID.ToString());
invString.AddPermissionsStart();
invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask));
invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
invString.AddNameValueLine("owner_id", ownerID.ToString());
invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());
invString.AddNameValueLine("group_id", item.GroupID.ToString());
invString.AddSectionEnd();
invString.AddNameValueLine("asset_id", item.AssetID.ToString());
invString.AddNameValueLine("type", Utils.AssetTypeToString((AssetType)item.Type));
invString.AddNameValueLine("inv_type", Utils.InventoryTypeToString((InventoryType)item.InvType));
invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags));
invString.AddSaleStart();
invString.AddNameValueLine("sale_type", "not");
invString.AddNameValueLine("sale_price", "0");
invString.AddSectionEnd();
invString.AddNameValueLine("name", item.Name + "|");
invString.AddNameValueLine("desc", item.Description + "|");
invString.AddNameValueLine("creation_date", item.CreationDate.ToString());
invString.AddSectionEnd();
}
}
m_inventoryFileData = Utils.StringToBytes(invString.BuildString);
return true;
}
// No need to recreate, the existing file is fine
return false;
}
/// <summary>
/// Serialize all the metadata for the items in this prim's inventory ready for sending to the client
/// </summary>
/// <param name="xferManager"></param>
public void RequestInventoryFile(IClientAPI client, IXfer xferManager)
{
lock (m_items)
{
// Don't send a inventory xfer name if there are no items. Doing so causes viewer 3 to crash when rezzing
// a new script if any previous deletion has left the prim inventory empty.
if (m_items.Count == 0) // No inventory
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Not sending inventory data for part {0} {1} {2} for {3} since no items",
// m_part.Name, m_part.LocalId, m_part.UUID, client.Name);
client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
return;
}
CreateInventoryFile();
// In principle, we should only do the rest if the inventory changed;
// by sending m_inventorySerial to the client, it ought to know
// that nothing changed and that it doesn't need to request the file.
// Unfortunately, it doesn't look like the client optimizes this;
// the client seems to always come back and request the Xfer,
// no matter what value m_inventorySerial has.
// FIXME: Could probably be > 0 here rather than > 2
if (m_inventoryFileData.Length > 2)
{
// Add the file for Xfer
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Adding inventory file {0} (length {1}) for transfer on {2} {3} {4}",
// m_inventoryFileName, m_inventoryFileData.Length, m_part.Name, m_part.UUID, m_part.LocalId);
xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData);
}
// Tell the client we're ready to Xfer the file
client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
Util.StringToBytes256(m_inventoryFileName));
}
}
/// <summary>
/// Process inventory backup
/// </summary>
/// <param name="datastore"></param>
public void ProcessInventoryBackup(ISimulationDataService datastore)
{
if (HasInventoryChanged)
{
HasInventoryChanged = false;
List<TaskInventoryItem> items = GetInventoryItems();
datastore.StorePrimInventory(m_part.UUID, items);
}
}
public class InventoryStringBuilder
{
public string BuildString = String.Empty;
public InventoryStringBuilder(UUID folderID, UUID parentID)
{
BuildString += "\tinv_object\t0\n\t{\n";
AddNameValueLine("obj_id", folderID.ToString());
AddNameValueLine("parent_id", parentID.ToString());
AddNameValueLine("type", "category");
AddNameValueLine("name", "Contents|");
AddSectionEnd();
}
public void AddItemStart()
{
BuildString += "\tinv_item\t0\n";
AddSectionStart();
}
public void AddPermissionsStart()
{
BuildString += "\tpermissions 0\n";
AddSectionStart();
}
public void AddSaleStart()
{
BuildString += "\tsale_info\t0\n";
AddSectionStart();
}
protected void AddSectionStart()
{
BuildString += "\t{\n";
}
public void AddSectionEnd()
{
BuildString += "\t}\n";
}
public void AddLine(string addLine)
{
BuildString += addLine;
}
public void AddNameValueLine(string name, string value)
{
BuildString += "\t\t";
BuildString += name + "\t";
BuildString += value + "\n";
}
public void Close()
{
}
}
public uint MaskEffectivePermissions()
{
uint mask=0x7fffffff;
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0)
mask &= ~((uint)PermissionMask.Copy >> 13);
if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0)
mask &= ~((uint)PermissionMask.Transfer >> 13);
if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0)
mask &= ~((uint)PermissionMask.Modify >> 13);
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
mask &= ~(uint)PermissionMask.Copy;
if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
mask &= ~(uint)PermissionMask.Transfer;
if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0)
mask &= ~(uint)PermissionMask.Modify;
}
}
return mask;
}
public void ApplyNextOwnerPermissions()
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
// m_log.DebugFormat (
// "[SCENE OBJECT PART INVENTORY]: Applying next permissions {0} to {1} in {2} with current {3}, base {4}, everyone {5}",
// item.NextPermissions, item.Name, m_part.Name, item.CurrentPermissions, item.BasePermissions, item.EveryonePermissions);
if (item.InvType == (int)InventoryType.Object)
{
uint perms = item.CurrentPermissions;
PermissionsUtil.ApplyFoldedPermissions(perms, ref perms);
item.CurrentPermissions = perms;
}
item.CurrentPermissions &= item.NextPermissions;
item.BasePermissions &= item.NextPermissions;
item.EveryonePermissions &= item.NextPermissions;
item.OwnerChanged = true;
item.PermsMask = 0;
item.PermsGranter = UUID.Zero;
}
}
}
public void ApplyGodPermissions(uint perms)
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
item.CurrentPermissions = perms;
item.BasePermissions = perms;
}
}
m_inventorySerial++;
HasInventoryChanged = true;
}
/// <summary>
/// Returns true if this part inventory contains any scripts. False otherwise.
/// </summary>
/// <returns></returns>
public bool ContainsScripts()
{
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.InvType == (int)InventoryType.LSL)
{
return true;
}
}
}
return false;
}
/// <summary>
/// Returns the count of scripts in this parts inventory.
/// </summary>
/// <returns></returns>
public int ScriptCount()
{
int count = 0;
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.InvType == (int)InventoryType.LSL)
{
count++;
}
}
}
return count;
}
/// <summary>
/// Returns the count of running scripts in this parts inventory.
/// </summary>
/// <returns></returns>
public int RunningScriptCount()
{
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines.Length == 0)
return 0;
int count = 0;
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
{
foreach (IScriptModule engine in engines)
{
if (engine != null)
{
if (engine.GetScriptState(item.ItemID))
{
count++;
}
}
}
}
return count;
}
public List<UUID> GetInventoryList()
{
List<UUID> ret = new List<UUID>();
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
ret.Add(item.ItemID);
}
return ret;
}
public List<TaskInventoryItem> GetInventoryItems()
{
List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
lock (m_items)
ret = new List<TaskInventoryItem>(m_items.Values);
return ret;
}
public List<TaskInventoryItem> GetInventoryItems(InventoryType type)
{
List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
lock (m_items)
{
foreach (TaskInventoryItem item in m_items.Values)
if (item.InvType == (int)type)
ret.Add(item);
}
return ret;
}
public Dictionary<UUID, string> GetScriptStates()
{
Dictionary<UUID, string> ret = new Dictionary<UUID, string>();
if (m_part.ParentGroup.Scene == null) // Group not in a scene
return ret;
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines.Length == 0) // No engine at all
return ret;
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
{
foreach (IScriptModule e in engines)
{
if (e != null)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Getting script state from engine {0} for {1} in part {2} in group {3} in {4}",
// e.Name, item.Name, m_part.Name, m_part.ParentGroup.Name, m_part.ParentGroup.Scene.Name);
string n = e.GetXMLState(item.ItemID);
if (n != String.Empty)
{
if (!ret.ContainsKey(item.ItemID))
ret[item.ItemID] = n;
break;
}
}
}
}
return ret;
}
public void ResumeScripts()
{
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines.Length == 0)
return;
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
{
foreach (IScriptModule engine in engines)
{
if (engine != null)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Resuming script {0} {1} for {2}, OwnerChanged {3}",
// item.Name, item.ItemID, item.OwnerID, item.OwnerChanged);
engine.ResumeScript(item.ItemID);
if (item.OwnerChanged)
engine.PostScriptEvent(item.ItemID, "changed", new Object[] { (int)Changed.OWNER });
item.OwnerChanged = false;
}
}
}
}
}
}
| |
// 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.Generic;
using System.Diagnostics;
using System.Globalization;
using mshtml;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.HtmlEditor.Marshalling;
using OpenLiveWriter.Mshtml;
namespace OpenLiveWriter.HtmlEditor
{
public class BoldApplier
{
private MshtmlMarkupServices markupServices;
private MarkupRange markupRange;
private IMshtmlCommand boldCommand;
public BoldApplier(MshtmlMarkupServices markupServices, MarkupRange markupRange, IMshtmlCommand boldCommand)
{
this.markupServices = markupServices;
this.markupRange = markupRange.Clone();
this.boldCommand = boldCommand;
}
public void Execute()
{
if (!boldCommand.Enabled)
{
Debug.Fail("Attempted to execute bold command when it is not enabled!");
return;
}
bool turnBold = boldCommand.Latched == false;
// First let mshtml do its thing
boldCommand.Execute();
// Now fix up necessary header elements with right tags
FixupHeaders(turnBold);
}
/// <summary>
/// Fixes up all the headers in the entire markupRange.
/// </summary>
/// <param name="turnBold">Whether or not the text should be turning bold.</param>
private void FixupHeaders(bool turnBold)
{
IHTMLElement elementStartHeader = markupRange.Start.GetParentElement(ElementFilters.HEADER_ELEMENTS);
IHTMLElement elementEndHeader = markupRange.End.GetParentElement(ElementFilters.HEADER_ELEMENTS);
MarkupRange currentRange = markupRange.Clone();
if (elementStartHeader != null)
{
// Takes care of the following cases:
// <h1>...|blah|...</h1>
// <h1>...|blah...</h1>...|...
MarkupRange startRange = markupServices.CreateMarkupRange(elementStartHeader, false);
startRange.Start.MoveToPointer(markupRange.Start);
if (startRange.End.IsRightOf(markupRange.End))
{
startRange.End.MoveToPointer(markupRange.End);
}
FixupHeaderRange(startRange, turnBold);
currentRange.Start.MoveAdjacentToElement(elementStartHeader, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
if (currentRange.End.IsLeftOf(currentRange.Start))
{
currentRange.End.MoveToPointer(currentRange.Start);
}
}
if (elementEndHeader != null && !HTMLElementHelper.ElementsAreEqual(elementStartHeader, elementEndHeader))
{
// Takes care of the following case:
// ...|...<h1>...blah|...</h1>
MarkupRange endRange = markupServices.CreateMarkupRange(elementEndHeader, false);
endRange.End.MoveToPointer(markupRange.End);
FixupHeaderRange(endRange, turnBold);
currentRange.End.MoveAdjacentToElement(elementEndHeader, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
if (currentRange.Start.IsRightOf(currentRange.End))
{
currentRange.Start.MoveToPointer(currentRange.End);
}
}
if (!markupRange.InRange(currentRange))
{
return;
}
IHTMLElement[] headerElements = currentRange.GetElements(ElementFilters.HEADER_ELEMENTS, true);
if (headerElements != null && headerElements.Length > 0)
{
foreach (IHTMLElement element in headerElements)
{
MarkupRange headerRange = markupServices.CreateMarkupRange(element, false);
FixupHeaderRange(headerRange, turnBold);
}
}
}
/// <summary>
/// Fixes up a range that is contained in a single header element.
/// </summary>
/// <param name="range">A range that is contained in a single header element.</param>
/// <param name="turnBold">Whether or not the text should be turning bold.</param>
private void FixupHeaderRange(MarkupRange range, bool turnBold)
{
IHTMLElement parentHeaderElement = range.ParentBlockElement();
if (parentHeaderElement == null || !ElementFilters.IsHeaderElement(parentHeaderElement))
{
Debug.Fail("Expected entire range to be inside a single header element.");
return;
}
MarkupRange expandedRange = range.Clone();
// Make sure we expand the selection to include any <font> tags that may be wrapping us.
MarkupPointerMoveHelper.MoveUnitBounded(expandedRange.Start, MarkupPointerMoveHelper.MoveDirection.LEFT,
MarkupPointerAdjacency.BeforeVisible, parentHeaderElement);
MarkupPointerMoveHelper.MoveUnitBounded(expandedRange.End, MarkupPointerMoveHelper.MoveDirection.RIGHT,
MarkupPointerAdjacency.BeforeVisible, parentHeaderElement);
// Walks in-scope elements and clears out any elements or styles that might affect the bold formatting.
var elementsToRemove = new List<IHTMLElement>();
expandedRange.WalkRange(
delegate (MarkupRange currentexpandedRange, MarkupContext context, string text)
{
IHTMLElement currentElement = context.Element;
if (currentElement != null && context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope)
{
if (IsStrongOrBold(currentElement))
{
elementsToRemove.Add(currentElement);
}
else if (IsFontableElement(currentElement) && HTMLElementHelper.IsBold((IHTMLElement2)currentElement) != turnBold)
{
currentElement.style.fontWeight = String.Empty;
}
}
return true;
}, true);
elementsToRemove.ForEach(e => markupServices.RemoveElement(e));
// Walks the range to find any segments of text that need to be fixed up.
var rangesToWrap = new List<MarkupRange>();
range.WalkRange(
delegate (MarkupRange currentRange, MarkupContext context, string text)
{
if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_Text)
{
TextStyles currentTextStyles = new TextStyles(currentRange.Start);
if (currentTextStyles.Bold != turnBold)
{
rangesToWrap.Add(currentRange.Clone());
}
}
return true;
}, true);
rangesToWrap.ForEach(r => WrapRangeInFontIfNecessary(r, turnBold));
}
/// <summary>
/// Inspects the range if a new font tag need to be added to apply formatting for the range.
/// Call this only for ranges that are inside a header element
/// </summary>
private void WrapRangeInFontIfNecessary(MarkupRange currentRange, bool turnBold)
{
// Check if there is an existing font/span tag that completely wraps this range,
// we can just use that instead of inserting a new one
MarkupContext workingContext = new MarkupContext();
bool wrapFont = true;
MarkupPointer start = currentRange.Start.Clone();
start.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Left;
start.Right(false, workingContext); // Look to the right to see what we have there
if (workingContext.Element != null && workingContext.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope &&
IsFontableElement(workingContext.Element))
{
start.MoveAdjacentToElement(workingContext.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
if (currentRange.End.IsEqualTo(start))
{
// There is an existing <FONT>/<SPAN> enclosing the range, no need to wrap again
wrapFont = false;
// set its font-weight
workingContext.Element.style.fontWeight = turnBold ? "bold" : "normal";
}
}
if (wrapFont)
{
string weightAttribute = String.Format(CultureInfo.InvariantCulture, "style=\"font-weight: {0}\"", turnBold ? "bold" : "normal");
HtmlStyleHelper.WrapRangeInElement(markupServices, currentRange, _ELEMENT_TAG_ID.TAGID_FONT, weightAttribute);
}
}
/// <summary>
/// FONT/SPAN tags are fontable tags within header
/// </summary>
private static bool IsFontableElement(IHTMLElement e)
{
return e.tagName.Equals("FONT", StringComparison.OrdinalIgnoreCase) ||
e.tagName.Equals("SPAN", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Checks if the given element is a STRONG/B tags
/// </summary>
private static bool IsStrongOrBold(IHTMLElement e)
{
return e.tagName.Equals("STRONG", StringComparison.OrdinalIgnoreCase) ||
e.tagName.Equals("B", StringComparison.OrdinalIgnoreCase);
}
}
}
| |
/*
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 ESRI.ArcGIS.Geometry;
using System;
namespace MultiPatchExamples
{
public static class TriangleStripExamples
{
private static object _missing = Type.Missing;
public static IGeometry GetExample1()
{
//TriangleStrip: Square Lying On XY Plane
IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass();
IPointCollection triangleStripPointCollection = new TriangleStripClass();
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-6, -6, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-6, 6, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(6, -6, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(6, 6, 0), ref _missing, ref _missing);
multiPatchGeometryCollection.AddGeometry(triangleStripPointCollection as IGeometry, ref _missing, ref _missing);
return multiPatchGeometryCollection as IGeometry;
}
public static IGeometry GetExample2()
{
//TriangleStrip: Multi-Paneled Vertical Plane
IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass();
IPointCollection triangleStripPointCollection = new TriangleStripClass();
//Panel 1
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, 7.5, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-7.5, 7.5, 7.5), ref _missing, ref _missing);
//Panel 2
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-2.5, 2.5, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-2.5, 2.5, 7.5), ref _missing, ref _missing);
//Panel 3
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, -2.5, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2.5, -2.5, 7.5), ref _missing, ref _missing);
//Panel 4
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, -7.5, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(7.5, -7.5, 7.5), ref _missing, ref _missing);
multiPatchGeometryCollection.AddGeometry(triangleStripPointCollection as IGeometry, ref _missing, ref _missing);
return multiPatchGeometryCollection as IGeometry;
}
public static IGeometry GetExample3()
{
//TriangleStrip: Stairs
IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass();
IPointCollection triangleStripPointCollection = new TriangleStripClass();
//First Step
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 10, 10), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 10, 10), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 7.5, 10), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 7.5, 10), ref _missing, ref _missing);
//Second Step
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 7.5, 7.5), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 7.5, 7.5), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 5, 7.5), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 5, 7.5), ref _missing, ref _missing);
//Third Step
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 5, 5), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 5, 5), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 2.5, 5), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 2.5, 5), ref _missing, ref _missing);
//Fourth Step
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 2.5, 2.5), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 2.5, 2.5), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 2.5), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 0, 2.5), ref _missing, ref _missing);
//End
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(10, 0, 0), ref _missing, ref _missing);
multiPatchGeometryCollection.AddGeometry(triangleStripPointCollection as IGeometry, ref _missing, ref _missing);
return multiPatchGeometryCollection as IGeometry;
}
public static IGeometry GetExample4()
{
//TriangleStrip: Box Without Top or Bottom
IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass();
IPointCollection triangleStripPointCollection = new TriangleStripClass();
//Start
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 10), ref _missing, ref _missing);
//First Panel
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 10), ref _missing, ref _missing);
//Second Panel
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 5, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 5, 10), ref _missing, ref _missing);
//Third Panel
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 5, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 5, 10), ref _missing, ref _missing);
//End, To Close Box
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 0, 10), ref _missing, ref _missing);
multiPatchGeometryCollection.AddGeometry(triangleStripPointCollection as IGeometry, ref _missing, ref _missing);
return multiPatchGeometryCollection as IGeometry;
}
public static IGeometry GetExample5()
{
//TriangleStrip: Star Shaped Box Without Top or Bottom
IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass();
IPointCollection triangleStripPointCollection = new TriangleStripClass();
//Start
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 2, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 2, 5), ref _missing, ref _missing);
//First Panel
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1 * Math.Sqrt(10), Math.Sqrt(10), 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1 * Math.Sqrt(10), Math.Sqrt(10), 5), ref _missing, ref _missing);
//Second Panel
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-2, 0, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-2, 0, 5), ref _missing, ref _missing);
//Third Panel
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1 * Math.Sqrt(10), -1 * Math.Sqrt(10), 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1 * Math.Sqrt(10), -1 * Math.Sqrt(10), 5), ref _missing, ref _missing);
//Fourth Panel
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, -2, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, -2, 5), ref _missing, ref _missing);
//Fifth Panel
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(Math.Sqrt(10), -1 * Math.Sqrt(10), 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(Math.Sqrt(10), -1 * Math.Sqrt(10), 5), ref _missing, ref _missing);
//Sixth Panel
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2, 0, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2, 0, 5), ref _missing, ref _missing);
//Seventh Panel
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(Math.Sqrt(10), Math.Sqrt(10), 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(Math.Sqrt(10), Math.Sqrt(10), 5), ref _missing, ref _missing);
//End, To Close Box
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 2, 0), ref _missing, ref _missing);
triangleStripPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0, 2, 5), ref _missing, ref _missing);
multiPatchGeometryCollection.AddGeometry(triangleStripPointCollection as IGeometry, ref _missing, ref _missing);
return multiPatchGeometryCollection as IGeometry;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using System.Runtime.Serialization;
namespace Newtonsoft.Json.Tests.TestObjects
{
#if !(NETFX_CORE || ASPNETCORE50)
public struct Ratio : IConvertible, IFormattable, ISerializable
{
private readonly int _numerator;
private readonly int _denominator;
public Ratio(int numerator, int denominator)
{
_numerator = numerator;
_denominator = denominator;
}
#region Properties
public int Numerator
{
get { return _numerator; }
}
public int Denominator
{
get { return _denominator; }
}
public bool IsNan
{
get { return _denominator == 0; }
}
#endregion
#region Serialization operations
public Ratio(SerializationInfo info, StreamingContext context)
{
_numerator = info.GetInt32("n");
_denominator = info.GetInt32("d");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("n", _numerator);
info.AddValue("d", _denominator);
}
#endregion
#region IConvertible Members
public TypeCode GetTypeCode()
{
return TypeCode.Object;
}
public bool ToBoolean(IFormatProvider provider)
{
return _numerator == 0;
}
public byte ToByte(IFormatProvider provider)
{
return (byte)(_numerator / _denominator);
}
public char ToChar(IFormatProvider provider)
{
return Convert.ToChar(_numerator / _denominator);
}
public DateTime ToDateTime(IFormatProvider provider)
{
return Convert.ToDateTime(_numerator / _denominator);
}
public decimal ToDecimal(IFormatProvider provider)
{
return (decimal)_numerator / _denominator;
}
public double ToDouble(IFormatProvider provider)
{
return _denominator == 0
? double.NaN
: (double)_numerator / _denominator;
}
public short ToInt16(IFormatProvider provider)
{
return (short)(_numerator / _denominator);
}
public int ToInt32(IFormatProvider provider)
{
return _numerator / _denominator;
}
public long ToInt64(IFormatProvider provider)
{
return _numerator / _denominator;
}
public sbyte ToSByte(IFormatProvider provider)
{
return (sbyte)(_numerator / _denominator);
}
public float ToSingle(IFormatProvider provider)
{
return _denominator == 0
? float.NaN
: (float)_numerator / _denominator;
}
public string ToString(IFormatProvider provider)
{
return _denominator == 1
? _numerator.ToString(provider)
: _numerator.ToString(provider) + "/" + _denominator.ToString(provider);
}
public object ToType(Type conversionType, IFormatProvider provider)
{
return Convert.ChangeType(ToDouble(provider), conversionType, provider);
}
public ushort ToUInt16(IFormatProvider provider)
{
return (ushort)(_numerator / _denominator);
}
public uint ToUInt32(IFormatProvider provider)
{
return (uint)(_numerator / _denominator);
}
public ulong ToUInt64(IFormatProvider provider)
{
return (ulong)(_numerator / _denominator);
}
#endregion
#region String operations
public override string ToString()
{
return ToString(CultureInfo.InvariantCulture);
}
public string ToString(string format, IFormatProvider formatProvider)
{
return ToString(CultureInfo.InvariantCulture);
}
public static Ratio Parse(string input)
{
return Parse(input, CultureInfo.InvariantCulture);
}
public static Ratio Parse(string input, IFormatProvider formatProvider)
{
Ratio result;
if (!TryParse(input, formatProvider, out result))
{
throw new FormatException(
string.Format(
CultureInfo.InvariantCulture,
"Text '{0}' is invalid text representation of ratio",
input));
}
return result;
}
public static bool TryParse(string input, out Ratio result)
{
return TryParse(input, CultureInfo.InvariantCulture, out result);
}
public static bool TryParse(string input, IFormatProvider formatProvider, out Ratio result)
{
if (input != null)
{
var fractionIndex = input.IndexOf('/');
int numerator;
if (fractionIndex < 0)
{
if (int.TryParse(input, NumberStyles.Integer, formatProvider, out numerator))
{
result = new Ratio(numerator, 1);
return true;
}
}
else
{
int denominator;
if (int.TryParse(input.Substring(0, fractionIndex), NumberStyles.Integer, formatProvider, out numerator) &&
int.TryParse(input.Substring(fractionIndex + 1), NumberStyles.Integer, formatProvider, out denominator))
{
result = new Ratio(numerator, denominator);
return true;
}
}
}
result = default(Ratio);
return false;
}
#endregion
}
#endif
}
| |
/*
* 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 Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Services.Connectors.Inventory
{
public class HGInventoryServiceConnector : ISessionAuthInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<string, InventoryServicesConnector> m_connectors = new Dictionary<string, InventoryServicesConnector>();
public HGInventoryServiceConnector(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
IConfig inventoryConfig = source.Configs["InventoryService"];
if (inventoryConfig == null)
{
m_log.Error("[HG INVENTORY SERVICE]: InventoryService missing from OpenSim.ini");
return;
}
m_log.Info("[HG INVENTORY SERVICE]: HG inventory service enabled");
}
}
private bool StringToUrlAndUserID(string id, out string url, out string userID)
{
url = String.Empty;
userID = String.Empty;
Uri assetUri;
if (Uri.TryCreate(id, UriKind.Absolute, out assetUri) &&
assetUri.Scheme == Uri.UriSchemeHttp)
{
url = "http://" + assetUri.Authority;
userID = assetUri.LocalPath.Trim(new char[] { '/' });
return true;
}
return false;
}
private ISessionAuthInventoryService GetConnector(string url)
{
InventoryServicesConnector connector = null;
lock (m_connectors)
{
if (m_connectors.ContainsKey(url))
{
connector = m_connectors[url];
}
else
{
// We're instantiating this class explicitly, but this won't
// work in general, because the remote grid may be running
// an inventory server that has a different protocol.
// Eventually we will want a piece of protocol asking
// the remote server about its kind. Definitely cool thing to do!
connector = new InventoryServicesConnector(url);
m_connectors.Add(url, connector);
}
}
return connector;
}
public string Host
{
get { return string.Empty; }
}
public void GetUserInventory(string id, UUID sessionID, InventoryReceiptCallback callback)
{
m_log.Debug("[HGInventory]: GetUserInventory " + id);
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
connector.GetUserInventory(userID, sessionID, callback);
}
}
/// <summary>
/// Gets the user folder for the given folder-type
/// </summary>
/// <param name="userID"></param>
/// <param name="type"></param>
/// <returns></returns>
public Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(string id, UUID sessionID)
{
m_log.Debug("[HGInventory]: GetSystemFolders " + id);
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.GetSystemFolders(userID, sessionID);
}
return new Dictionary<AssetType, InventoryFolderBase>();
}
/// <summary>
/// Gets everything (folders and items) inside a folder
/// </summary>
/// <param name="userId"></param>
/// <param name="folderID"></param>
/// <returns></returns>
public InventoryCollection GetFolderContent(string id, UUID folderID, UUID sessionID)
{
m_log.Debug("[HGInventory]: GetFolderContent " + id);
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.GetFolderContent(userID, folderID, sessionID);
}
return null;
}
public bool AddFolder(string id, InventoryFolderBase folder, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.AddFolder(userID, folder, sessionID);
}
return false;
}
public bool UpdateFolder(string id, InventoryFolderBase folder, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.UpdateFolder(userID, folder, sessionID);
}
return false;
}
public bool MoveFolder(string id, InventoryFolderBase folder, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.MoveFolder(userID, folder, sessionID);
}
return false;
}
public bool DeleteFolders(string id, List<UUID> folders, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.DeleteFolders(userID, folders, sessionID);
}
return false;
}
public bool PurgeFolder(string id, InventoryFolderBase folder, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.PurgeFolder(userID, folder, sessionID);
}
return false;
}
public List<InventoryItemBase> GetFolderItems(string id, UUID folderID, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.GetFolderItems(userID, folderID, sessionID);
}
return new List<InventoryItemBase>();
}
public bool AddItem(string id, InventoryItemBase item, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.AddItem(userID, item, sessionID);
}
return false;
}
public bool UpdateItem(string id, InventoryItemBase item, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.UpdateItem(userID, item, sessionID);
}
return false;
}
public bool MoveItems(string id, List<InventoryItemBase> items, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.MoveItems(userID, items, sessionID);
}
return false;
}
public bool DeleteItems(string id, List<UUID> itemIDs, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.DeleteItems(userID, itemIDs, sessionID);
}
return false;
}
public InventoryItemBase QueryItem(string id, InventoryItemBase item, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
//m_log.DebugFormat("[HGInventory CONNECTOR]: calling {0}", url);
ISessionAuthInventoryService connector = GetConnector(url);
return connector.QueryItem(userID, item, sessionID);
}
return null;
}
public InventoryFolderBase QueryFolder(string id, InventoryFolderBase folder, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.QueryFolder(userID, folder, sessionID);
}
return null;
}
public int GetAssetPermissions(string id, UUID assetID, UUID sessionID)
{
string url = string.Empty;
string userID = string.Empty;
if (StringToUrlAndUserID(id, out url, out userID))
{
ISessionAuthInventoryService connector = GetConnector(url);
return connector.GetAssetPermissions(userID, assetID, sessionID);
}
return 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.
namespace System.Net.Http.HPack
{
internal class Huffman
{
// TODO: this can be constructed from _decodingTable
private static readonly (uint code, int bitLength)[] s_encodingTable = new (uint code, int bitLength)[]
{
(0b11111111_11000000_00000000_00000000, 13),
(0b11111111_11111111_10110000_00000000, 23),
(0b11111111_11111111_11111110_00100000, 28),
(0b11111111_11111111_11111110_00110000, 28),
(0b11111111_11111111_11111110_01000000, 28),
(0b11111111_11111111_11111110_01010000, 28),
(0b11111111_11111111_11111110_01100000, 28),
(0b11111111_11111111_11111110_01110000, 28),
(0b11111111_11111111_11111110_10000000, 28),
(0b11111111_11111111_11101010_00000000, 24),
(0b11111111_11111111_11111111_11110000, 30),
(0b11111111_11111111_11111110_10010000, 28),
(0b11111111_11111111_11111110_10100000, 28),
(0b11111111_11111111_11111111_11110100, 30),
(0b11111111_11111111_11111110_10110000, 28),
(0b11111111_11111111_11111110_11000000, 28),
(0b11111111_11111111_11111110_11010000, 28),
(0b11111111_11111111_11111110_11100000, 28),
(0b11111111_11111111_11111110_11110000, 28),
(0b11111111_11111111_11111111_00000000, 28),
(0b11111111_11111111_11111111_00010000, 28),
(0b11111111_11111111_11111111_00100000, 28),
(0b11111111_11111111_11111111_11111000, 30),
(0b11111111_11111111_11111111_00110000, 28),
(0b11111111_11111111_11111111_01000000, 28),
(0b11111111_11111111_11111111_01010000, 28),
(0b11111111_11111111_11111111_01100000, 28),
(0b11111111_11111111_11111111_01110000, 28),
(0b11111111_11111111_11111111_10000000, 28),
(0b11111111_11111111_11111111_10010000, 28),
(0b11111111_11111111_11111111_10100000, 28),
(0b11111111_11111111_11111111_10110000, 28),
(0b01010000_00000000_00000000_00000000, 6),
(0b11111110_00000000_00000000_00000000, 10),
(0b11111110_01000000_00000000_00000000, 10),
(0b11111111_10100000_00000000_00000000, 12),
(0b11111111_11001000_00000000_00000000, 13),
(0b01010100_00000000_00000000_00000000, 6),
(0b11111000_00000000_00000000_00000000, 8),
(0b11111111_01000000_00000000_00000000, 11),
(0b11111110_10000000_00000000_00000000, 10),
(0b11111110_11000000_00000000_00000000, 10),
(0b11111001_00000000_00000000_00000000, 8),
(0b11111111_01100000_00000000_00000000, 11),
(0b11111010_00000000_00000000_00000000, 8),
(0b01011000_00000000_00000000_00000000, 6),
(0b01011100_00000000_00000000_00000000, 6),
(0b01100000_00000000_00000000_00000000, 6),
(0b00000000_00000000_00000000_00000000, 5),
(0b00001000_00000000_00000000_00000000, 5),
(0b00010000_00000000_00000000_00000000, 5),
(0b01100100_00000000_00000000_00000000, 6),
(0b01101000_00000000_00000000_00000000, 6),
(0b01101100_00000000_00000000_00000000, 6),
(0b01110000_00000000_00000000_00000000, 6),
(0b01110100_00000000_00000000_00000000, 6),
(0b01111000_00000000_00000000_00000000, 6),
(0b01111100_00000000_00000000_00000000, 6),
(0b10111000_00000000_00000000_00000000, 7),
(0b11111011_00000000_00000000_00000000, 8),
(0b11111111_11111000_00000000_00000000, 15),
(0b10000000_00000000_00000000_00000000, 6),
(0b11111111_10110000_00000000_00000000, 12),
(0b11111111_00000000_00000000_00000000, 10),
(0b11111111_11010000_00000000_00000000, 13),
(0b10000100_00000000_00000000_00000000, 6),
(0b10111010_00000000_00000000_00000000, 7),
(0b10111100_00000000_00000000_00000000, 7),
(0b10111110_00000000_00000000_00000000, 7),
(0b11000000_00000000_00000000_00000000, 7),
(0b11000010_00000000_00000000_00000000, 7),
(0b11000100_00000000_00000000_00000000, 7),
(0b11000110_00000000_00000000_00000000, 7),
(0b11001000_00000000_00000000_00000000, 7),
(0b11001010_00000000_00000000_00000000, 7),
(0b11001100_00000000_00000000_00000000, 7),
(0b11001110_00000000_00000000_00000000, 7),
(0b11010000_00000000_00000000_00000000, 7),
(0b11010010_00000000_00000000_00000000, 7),
(0b11010100_00000000_00000000_00000000, 7),
(0b11010110_00000000_00000000_00000000, 7),
(0b11011000_00000000_00000000_00000000, 7),
(0b11011010_00000000_00000000_00000000, 7),
(0b11011100_00000000_00000000_00000000, 7),
(0b11011110_00000000_00000000_00000000, 7),
(0b11100000_00000000_00000000_00000000, 7),
(0b11100010_00000000_00000000_00000000, 7),
(0b11100100_00000000_00000000_00000000, 7),
(0b11111100_00000000_00000000_00000000, 8),
(0b11100110_00000000_00000000_00000000, 7),
(0b11111101_00000000_00000000_00000000, 8),
(0b11111111_11011000_00000000_00000000, 13),
(0b11111111_11111110_00000000_00000000, 19),
(0b11111111_11100000_00000000_00000000, 13),
(0b11111111_11110000_00000000_00000000, 14),
(0b10001000_00000000_00000000_00000000, 6),
(0b11111111_11111010_00000000_00000000, 15),
(0b00011000_00000000_00000000_00000000, 5),
(0b10001100_00000000_00000000_00000000, 6),
(0b00100000_00000000_00000000_00000000, 5),
(0b10010000_00000000_00000000_00000000, 6),
(0b00101000_00000000_00000000_00000000, 5),
(0b10010100_00000000_00000000_00000000, 6),
(0b10011000_00000000_00000000_00000000, 6),
(0b10011100_00000000_00000000_00000000, 6),
(0b00110000_00000000_00000000_00000000, 5),
(0b11101000_00000000_00000000_00000000, 7),
(0b11101010_00000000_00000000_00000000, 7),
(0b10100000_00000000_00000000_00000000, 6),
(0b10100100_00000000_00000000_00000000, 6),
(0b10101000_00000000_00000000_00000000, 6),
(0b00111000_00000000_00000000_00000000, 5),
(0b10101100_00000000_00000000_00000000, 6),
(0b11101100_00000000_00000000_00000000, 7),
(0b10110000_00000000_00000000_00000000, 6),
(0b01000000_00000000_00000000_00000000, 5),
(0b01001000_00000000_00000000_00000000, 5),
(0b10110100_00000000_00000000_00000000, 6),
(0b11101110_00000000_00000000_00000000, 7),
(0b11110000_00000000_00000000_00000000, 7),
(0b11110010_00000000_00000000_00000000, 7),
(0b11110100_00000000_00000000_00000000, 7),
(0b11110110_00000000_00000000_00000000, 7),
(0b11111111_11111100_00000000_00000000, 15),
(0b11111111_10000000_00000000_00000000, 11),
(0b11111111_11110100_00000000_00000000, 14),
(0b11111111_11101000_00000000_00000000, 13),
(0b11111111_11111111_11111111_11000000, 28),
(0b11111111_11111110_01100000_00000000, 20),
(0b11111111_11111111_01001000_00000000, 22),
(0b11111111_11111110_01110000_00000000, 20),
(0b11111111_11111110_10000000_00000000, 20),
(0b11111111_11111111_01001100_00000000, 22),
(0b11111111_11111111_01010000_00000000, 22),
(0b11111111_11111111_01010100_00000000, 22),
(0b11111111_11111111_10110010_00000000, 23),
(0b11111111_11111111_01011000_00000000, 22),
(0b11111111_11111111_10110100_00000000, 23),
(0b11111111_11111111_10110110_00000000, 23),
(0b11111111_11111111_10111000_00000000, 23),
(0b11111111_11111111_10111010_00000000, 23),
(0b11111111_11111111_10111100_00000000, 23),
(0b11111111_11111111_11101011_00000000, 24),
(0b11111111_11111111_10111110_00000000, 23),
(0b11111111_11111111_11101100_00000000, 24),
(0b11111111_11111111_11101101_00000000, 24),
(0b11111111_11111111_01011100_00000000, 22),
(0b11111111_11111111_11000000_00000000, 23),
(0b11111111_11111111_11101110_00000000, 24),
(0b11111111_11111111_11000010_00000000, 23),
(0b11111111_11111111_11000100_00000000, 23),
(0b11111111_11111111_11000110_00000000, 23),
(0b11111111_11111111_11001000_00000000, 23),
(0b11111111_11111110_11100000_00000000, 21),
(0b11111111_11111111_01100000_00000000, 22),
(0b11111111_11111111_11001010_00000000, 23),
(0b11111111_11111111_01100100_00000000, 22),
(0b11111111_11111111_11001100_00000000, 23),
(0b11111111_11111111_11001110_00000000, 23),
(0b11111111_11111111_11101111_00000000, 24),
(0b11111111_11111111_01101000_00000000, 22),
(0b11111111_11111110_11101000_00000000, 21),
(0b11111111_11111110_10010000_00000000, 20),
(0b11111111_11111111_01101100_00000000, 22),
(0b11111111_11111111_01110000_00000000, 22),
(0b11111111_11111111_11010000_00000000, 23),
(0b11111111_11111111_11010010_00000000, 23),
(0b11111111_11111110_11110000_00000000, 21),
(0b11111111_11111111_11010100_00000000, 23),
(0b11111111_11111111_01110100_00000000, 22),
(0b11111111_11111111_01111000_00000000, 22),
(0b11111111_11111111_11110000_00000000, 24),
(0b11111111_11111110_11111000_00000000, 21),
(0b11111111_11111111_01111100_00000000, 22),
(0b11111111_11111111_11010110_00000000, 23),
(0b11111111_11111111_11011000_00000000, 23),
(0b11111111_11111111_00000000_00000000, 21),
(0b11111111_11111111_00001000_00000000, 21),
(0b11111111_11111111_10000000_00000000, 22),
(0b11111111_11111111_00010000_00000000, 21),
(0b11111111_11111111_11011010_00000000, 23),
(0b11111111_11111111_10000100_00000000, 22),
(0b11111111_11111111_11011100_00000000, 23),
(0b11111111_11111111_11011110_00000000, 23),
(0b11111111_11111110_10100000_00000000, 20),
(0b11111111_11111111_10001000_00000000, 22),
(0b11111111_11111111_10001100_00000000, 22),
(0b11111111_11111111_10010000_00000000, 22),
(0b11111111_11111111_11100000_00000000, 23),
(0b11111111_11111111_10010100_00000000, 22),
(0b11111111_11111111_10011000_00000000, 22),
(0b11111111_11111111_11100010_00000000, 23),
(0b11111111_11111111_11111000_00000000, 26),
(0b11111111_11111111_11111000_01000000, 26),
(0b11111111_11111110_10110000_00000000, 20),
(0b11111111_11111110_00100000_00000000, 19),
(0b11111111_11111111_10011100_00000000, 22),
(0b11111111_11111111_11100100_00000000, 23),
(0b11111111_11111111_10100000_00000000, 22),
(0b11111111_11111111_11110110_00000000, 25),
(0b11111111_11111111_11111000_10000000, 26),
(0b11111111_11111111_11111000_11000000, 26),
(0b11111111_11111111_11111001_00000000, 26),
(0b11111111_11111111_11111011_11000000, 27),
(0b11111111_11111111_11111011_11100000, 27),
(0b11111111_11111111_11111001_01000000, 26),
(0b11111111_11111111_11110001_00000000, 24),
(0b11111111_11111111_11110110_10000000, 25),
(0b11111111_11111110_01000000_00000000, 19),
(0b11111111_11111111_00011000_00000000, 21),
(0b11111111_11111111_11111001_10000000, 26),
(0b11111111_11111111_11111100_00000000, 27),
(0b11111111_11111111_11111100_00100000, 27),
(0b11111111_11111111_11111001_11000000, 26),
(0b11111111_11111111_11111100_01000000, 27),
(0b11111111_11111111_11110010_00000000, 24),
(0b11111111_11111111_00100000_00000000, 21),
(0b11111111_11111111_00101000_00000000, 21),
(0b11111111_11111111_11111010_00000000, 26),
(0b11111111_11111111_11111010_01000000, 26),
(0b11111111_11111111_11111111_11010000, 28),
(0b11111111_11111111_11111100_01100000, 27),
(0b11111111_11111111_11111100_10000000, 27),
(0b11111111_11111111_11111100_10100000, 27),
(0b11111111_11111110_11000000_00000000, 20),
(0b11111111_11111111_11110011_00000000, 24),
(0b11111111_11111110_11010000_00000000, 20),
(0b11111111_11111111_00110000_00000000, 21),
(0b11111111_11111111_10100100_00000000, 22),
(0b11111111_11111111_00111000_00000000, 21),
(0b11111111_11111111_01000000_00000000, 21),
(0b11111111_11111111_11100110_00000000, 23),
(0b11111111_11111111_10101000_00000000, 22),
(0b11111111_11111111_10101100_00000000, 22),
(0b11111111_11111111_11110111_00000000, 25),
(0b11111111_11111111_11110111_10000000, 25),
(0b11111111_11111111_11110100_00000000, 24),
(0b11111111_11111111_11110101_00000000, 24),
(0b11111111_11111111_11111010_10000000, 26),
(0b11111111_11111111_11101000_00000000, 23),
(0b11111111_11111111_11111010_11000000, 26),
(0b11111111_11111111_11111100_11000000, 27),
(0b11111111_11111111_11111011_00000000, 26),
(0b11111111_11111111_11111011_01000000, 26),
(0b11111111_11111111_11111100_11100000, 27),
(0b11111111_11111111_11111101_00000000, 27),
(0b11111111_11111111_11111101_00100000, 27),
(0b11111111_11111111_11111101_01000000, 27),
(0b11111111_11111111_11111101_01100000, 27),
(0b11111111_11111111_11111111_11100000, 28),
(0b11111111_11111111_11111101_10000000, 27),
(0b11111111_11111111_11111101_10100000, 27),
(0b11111111_11111111_11111101_11000000, 27),
(0b11111111_11111111_11111101_11100000, 27),
(0b11111111_11111111_11111110_00000000, 27),
(0b11111111_11111111_11111011_10000000, 26),
(0b11111111_11111111_11111111_11111100, 30)
};
private static readonly (int codeLength, int[] codes)[] s_decodingTable = new[]
{
(5, new[] { 48, 49, 50, 97, 99, 101, 105, 111, 115, 116 }),
(6, new[] { 32, 37, 45, 46, 47, 51, 52, 53, 54, 55, 56, 57, 61, 65, 95, 98, 100, 102, 103, 104, 108, 109, 110, 112, 114, 117 }),
(7, new[] { 58, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 89, 106, 107, 113, 118, 119, 120, 121, 122 }),
(8, new[] { 38, 42, 44, 59, 88, 90 }),
(10, new[] { 33, 34, 40, 41, 63 }),
(11, new[] { 39, 43, 124 }),
(12, new[] { 35, 62 }),
(13, new[] { 0, 36, 64, 91, 93, 126 }),
(14, new[] { 94, 125 }),
(15, new[] { 60, 96, 123 }),
(19, new[] { 92, 195, 208 }),
(20, new[] { 128, 130, 131, 162, 184, 194, 224, 226 }),
(21, new[] { 153, 161, 167, 172, 176, 177, 179, 209, 216, 217, 227, 229, 230 }),
(22, new[] { 129, 132, 133, 134, 136, 146, 154, 156, 160, 163, 164, 169, 170, 173, 178, 181, 185, 186, 187, 189, 190, 196, 198, 228, 232, 233 }),
(23, new[] { 1, 135, 137, 138, 139, 140, 141, 143, 147, 149, 150, 151, 152, 155, 157, 158, 165, 166, 168, 174, 175, 180, 182, 183, 188, 191, 197, 231, 239 }),
(24, new[] { 9, 142, 144, 145, 148, 159, 171, 206, 215, 225, 236, 237 }),
(25, new[] { 199, 207, 234, 235 }),
(26, new[] { 192, 193, 200, 201, 202, 205, 210, 213, 218, 219, 238, 240, 242, 243, 255 }),
(27, new[] { 203, 204, 211, 212, 214, 221, 222, 223, 241, 244, 245, 246, 247, 248, 250, 251, 252, 253, 254 }),
(28, new[] { 2, 3, 4, 5, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 220, 249 }),
(30, new[] { 10, 13, 22, 256 })
};
public static (uint encoded, int bitLength) Encode(int data)
{
return s_encodingTable[data];
}
/// <summary>
/// Decodes a Huffman encoded string from a byte array.
/// </summary>
/// <param name="src">The source byte array containing the encoded data.</param>
/// <param name="offset">The offset in the byte array where the coded data starts.</param>
/// <param name="count">The number of bytes to decode.</param>
/// <param name="dst">The destination byte array to store the decoded data.</param>
/// <returns>The number of decoded symbols.</returns>
public static int Decode(ReadOnlySpan<byte> src, Span<byte> dst)
{
int i = 0;
int j = 0;
int lastDecodedBits = 0;
while (i < src.Length)
{
// Note that if lastDecodeBits is 3 or more, then we will only get 5 bits (or less)
// from src[i]. Thus we need to read 5 bytes here to ensure that we always have
// at least 30 bits available for decoding.
// TODO ISSUE 31751: Rework this as part of Huffman perf improvements
uint next = (uint)(src[i] << 24 + lastDecodedBits);
next |= (i + 1 < src.Length ? (uint)(src[i + 1] << 16 + lastDecodedBits) : 0);
next |= (i + 2 < src.Length ? (uint)(src[i + 2] << 8 + lastDecodedBits) : 0);
next |= (i + 3 < src.Length ? (uint)(src[i + 3] << lastDecodedBits) : 0);
next |= (i + 4 < src.Length ? (uint)(src[i + 4] >> (8 - lastDecodedBits)) : 0);
uint ones = (uint)(int.MinValue >> (8 - lastDecodedBits - 1));
if (i == src.Length - 1 && lastDecodedBits > 0 && (next & ones) == ones)
{
// The remaining 7 or less bits are all 1, which is padding.
// We specifically check that lastDecodedBits > 0 because padding
// longer than 7 bits should be treated as a decoding error.
// http://httpwg.org/specs/rfc7541.html#rfc.section.5.2
break;
}
// The longest possible symbol size is 30 bits. If we're at the last 4 bytes
// of the input, we need to make sure we pass the correct number of valid bits
// left, otherwise the trailing 0s in next may form a valid symbol.
int validBits = Math.Min(30, (8 - lastDecodedBits) + (src.Length - i - 1) * 8);
int ch = DecodeValue(next, validBits, out int decodedBits);
if (ch == -1)
{
// No valid symbol could be decoded with the bits in next
throw new HuffmanDecodingException();
}
else if (ch == 256)
{
// A Huffman-encoded string literal containing the EOS symbol MUST be treated as a decoding error.
// http://httpwg.org/specs/rfc7541.html#rfc.section.5.2
throw new HuffmanDecodingException();
}
if (j == dst.Length)
{
// Destination is too small.
throw new HuffmanDecodingException();
}
dst[j++] = (byte)ch;
// If we crossed a byte boundary, advance i so we start at the next byte that's not fully decoded.
lastDecodedBits += decodedBits;
i += lastDecodedBits / 8;
// Modulo 8 since we only care about how many bits were decoded in the last byte that we processed.
lastDecodedBits %= 8;
}
return j;
}
/// <summary>
/// Decodes a single symbol from a 32-bit word.
/// </summary>
/// <param name="data">A 32-bit word containing a Huffman encoded symbol.</param>
/// <param name="validBits">
/// The number of bits in <paramref name="data"/> that may contain an encoded symbol.
/// This is not the exact number of bits that encode the symbol. Instead, it prevents
/// decoding the lower bits of <paramref name="data"/> if they don't contain any
/// encoded data.
/// </param>
/// <param name="decodedBits">The number of bits decoded from <paramref name="data"/>.</param>
/// <returns>The decoded symbol.</returns>
private static int DecodeValue(uint data, int validBits, out int decodedBits)
{
// The code below implements the decoding logic for a canonical Huffman code.
//
// To decode a symbol, we scan the decoding table, which is sorted by ascending symbol bit length.
// For each bit length b, we determine the maximum b-bit encoded value, plus one (that is codeMax).
// This is done with the following logic:
//
// if we're at the first entry in the table,
// codeMax = the # of symbols encoded in b bits
// else,
// left-shift codeMax by the difference between b and the previous entry's bit length,
// then increment codeMax by the # of symbols encoded in b bits
//
// Next, we look at the value v encoded in the highest b bits of data. If v is less than codeMax,
// those bits correspond to a Huffman encoded symbol. We find the corresponding decoded
// symbol in the list of values associated with bit length b in the decoding table by indexing it
// with codeMax - v.
int codeMax = 0;
for (int i = 0; i < s_decodingTable.Length && s_decodingTable[i].codeLength <= validBits; i++)
{
(int codeLength, int[] codes) = s_decodingTable[i];
if (i > 0)
{
codeMax <<= codeLength - s_decodingTable[i - 1].codeLength;
}
codeMax += codes.Length;
int mask = int.MinValue >> (codeLength - 1);
long masked = (data & mask) >> (32 - codeLength);
if (masked < codeMax)
{
decodedBits = codeLength;
return codes[codes.Length - (codeMax - masked)];
}
}
decodedBits = 0;
return -1;
}
}
}
| |
// Copyright (c) 2009 Bohumir Zamecnik <bohumir@zamecnik.org>
// License: The MIT License, see the LICENSE file
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace HalftoneLab
{
/// <summary>
/// Configuration manager holds module configurations and takes care
/// of its persistence.
/// </summary>
/// <remarks>
/// <para>
/// Module configuration consist of stucture of
/// how module objects are interconnected and of their parameter
/// settings. Each configuration is accessible via its type and textual
/// name.
/// </para>
/// <para>
/// Module configuration is persisted to a file. Binary serialization
/// method from .NET is used for persistence. File name must be given
/// using ConfigFileName property before .
/// </para>
/// </remarks>
public class ConfigManager
{
private List<Module> _savedModules;
/// <summary>
/// Configuration file name.
/// </summary>
public string ConfigFileName { get; set; }
/// <summary>
/// Create a configuration manager instance.
/// </summary>
public ConfigManager() {
_savedModules = new List<Module>();
}
/// <summary>
/// Load configuration from file to memory.
/// </summary>
/// <remarks>
/// Configuration file name is taken from ConfigFileName property.
/// If there is any module in the file this function overwrites any
/// modules held by the configuration manager in memory.
/// </remarks>
public void load() {
Stream streamRead = null;
try {
streamRead = File.OpenRead(ConfigFileName);
BinaryFormatter binaryRead = new BinaryFormatter();
List<Module> loadedModules = binaryRead.Deserialize(streamRead) as List<Module>;
if (loadedModules != null) {
_savedModules = loadedModules;
}
// else: report an error
} catch (System.Runtime.Serialization.SerializationException ex) {
Console.Out.WriteLine(
"Cannot deserialize the contents of the configuration file: {0}. Its format might be old.",
ConfigFileName);
Console.Out.WriteLine(ex.Message);
} catch (FileNotFoundException ex) {
Console.Out.WriteLine(ex.Message);
Console.Out.WriteLine(
"A default configuration file was created: {0}",
ConfigFileName);
HalftoneLab.SampleConfig.SampleConfig.makeSampleConfig(this);
} finally {
if (null != streamRead) {
streamRead.Close();
}
}
}
/// <summary>
/// Save configuration from memory to file (possibly creating a new
/// file or overwriting an existing file).
/// </summary>
/// <remarks>
/// Configuration file name is taken from ConfigFileName property.
/// </remarks>
public void save() {
Stream streamWrite = null;
try {
streamWrite = File.Create(ConfigFileName);
BinaryFormatter binaryWrite = new BinaryFormatter();
binaryWrite.Serialize(streamWrite, _savedModules);
} finally {
if (null != streamWrite) {
streamWrite.Close();
}
}
}
/// <summary>
/// Find all modules of given type matching a predicate.
/// </summary>
/// <param name="predicate">Predicate taking a module a returning true
/// if modules is accepted.</param>
/// <returns>List of modules matching a predicate</returns>
public List<ModuleType> findAllModules<ModuleType>(
Predicate<ModuleType> predicate) where ModuleType : class
{
return _savedModules.FindAll(
module => (module is ModuleType)
).ConvertAll<ModuleType>(module => module as ModuleType)
.FindAll(predicate);
}
/// <summary>
/// Find all modules matching a predicate.
/// </summary>
/// <param name="predicate">Predicate taking a module a returning true
/// if modules is accepted.</param>
/// <returns>List of modules matching a predicate</returns>
public List<Module> findAllModules(Predicate<Module> predicate) {
return _savedModules.FindAll(predicate);
}
public ModuleType getModule<ModuleType>(string moduleName)
where ModuleType : Module
{
if (moduleName == null) {
return null;
}
List<ModuleType> modules = findAllModules<ModuleType>(
module => module.Name == moduleName);
return (modules.Count > 0) ?
(ModuleType)(modules.First().deepCopy()) : null;
}
/// <summary>
/// Get a list of all module configurations held by the manager.
/// </summary>
/// <returns>List of all module configurations.</returns>
public List<Module> listAllModules() {
return _savedModules;
}
/// <summary>
/// Persistently remove all the module configurations.
/// </summary>
public void clear() {
_savedModules.Clear();
save();
}
/// <summary>
/// Save a module configuration to the manager.
/// Changes are persisted automatically.
/// </summary>
/// <param name="module">Module to be saved.</param>
/// <see cref="saveModule(Module module, bool saveImmediately)"/>
public void saveModule(Module module) {
saveModule(module, true);
}
/// <summary>
/// Save a module configuration to the manager. Choose whether to
/// persist the change automatically or manually using save()
/// function. Manual saving can be useful when adding modules to the
/// manager in a batch. Then persistence is done at the end once for
/// all modules.
/// </summary>
/// <param name="module">Module to be saved.</param>
/// <param name="saveImmediately">Save automatically now or manually then?</param>
public void saveModule(Module module, bool saveImmediately) {
Module moduleCopy = module.deepCopy();
int index = _savedModules.FindIndex(
(mod) => (mod.GetType() == moduleCopy.GetType())
&& (mod.Name == moduleCopy.Name)
);
if (index < 0) {
// not found, add a new item
_savedModules.Add(moduleCopy);
} else {
// found, overwrite
_savedModules[index] = moduleCopy;
}
if (saveImmediately) {
save(); // immediately save to a file
}
}
/// <summary>
/// Delete a module matching a type and name.
/// Changes are persisted automatically.
/// </summary>
/// <param name="name">Module configuration name</param>
public void deleteModule<ModuleType>(string name) {
_savedModules.RemoveAll(
(module) => (module is ModuleType) && (name == module.Name)
);
save();
}
}
}
| |
// Copyright 2020 by PeopleWare n.v..
// 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.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NHibernate;
using NHibernate.Linq;
using NUnit.Framework;
using PPWCode.Vernacular.NHibernate.III.Tests.Model.Common;
using PPWCode.Vernacular.Persistence.IV;
namespace PPWCode.Vernacular.NHibernate.III.Tests.IntegrationTests.Async.Linq.Common
{
public class CompanyTests : BaseCompanyTests
{
[TestCase(1, 0, 1)]
[TestCase(5, 2, 3)]
public async Task Can_Find_Companies_With_Skip_And_Count(int numberOfTuples, int skip, int count)
{
Assert.That(numberOfTuples, Is.GreaterThanOrEqualTo(skip + count));
IList<Company> companies = new List<Company>();
for (int i = 0; i < numberOfTuples; i++)
{
companies.Add(await CreateCompanyAsync(CompanyCreationType.NO_CHILDREN, CancellationToken));
}
SessionProviderAsync.Session.Clear();
IList<Company> foundCompanies =
await Repository
.FindAsync(
query => query.OrderBy(c => c.Id),
skip,
count,
CancellationToken)
.ConfigureAwait(false);
Assert.That(foundCompanies, Is.Not.Null);
Assert.That(foundCompanies.Count, Is.EqualTo(count));
for (int i = 0; i < count; i++)
{
Assert.That(foundCompanies[i].Id, Is.EqualTo(companies[skip + i].Id));
}
}
[TestCase(1, 0)]
[TestCase(2, 0)]
[TestCase(2, 1)]
public async Task Can_Get_Company_At_Index(int numberOfTuples, int index)
{
Assert.That(numberOfTuples, Is.GreaterThanOrEqualTo(index));
IList<Company> companies = new List<Company>();
for (int i = 0; i < numberOfTuples; i++)
{
companies.Add(await CreateCompanyAsync(CompanyCreationType.NO_CHILDREN, CancellationToken));
}
SessionProviderAsync.Session.Clear();
Company companyAtIndex =
await Repository
.GetAtIndexAsync(
query => query.OrderBy(c => c.Id),
index,
CancellationToken);
Assert.That(companyAtIndex, Is.Not.Null);
Assert.AreEqual(companyAtIndex.Id, companies[index].Id);
}
[Test]
public async Task Can_Count_Companies()
{
Company company = await CreateCompanyAsync(CompanyCreationType.WITH_2_CHILDREN, CancellationToken);
int count =
await Repository
.CountAsync(
query => query.Where(c => c.Id == company.Id),
CancellationToken);
Assert.AreEqual(1, count);
}
[Test]
public async Task Can_Find_All_Companies()
{
await CreateCompanyAsync(CompanyCreationType.WITH_2_CHILDREN, CancellationToken);
SessionProviderAsync.Session.Clear();
IList<Company> companies =
await Repository
.FindAllAsync(CancellationToken)
.ConfigureAwait(false);
Assert.That(companies, Is.Not.Null);
Assert.That(companies.Count, Is.EqualTo(1));
Assert.That(companies.Any(c => NHibernateUtil.IsInitialized(c.Identifications)), Is.False);
}
[Test]
public async Task Can_Find_Companies_By_Ids()
{
Company company1 = await CreateCompanyAsync(CompanyCreationType.WITH_2_CHILDREN, CancellationToken);
Company company2 = await CreateCompanyAsync(CompanyCreationType.NO_CHILDREN, CancellationToken);
Company company3 = await CreateCompanyAsync(CompanyCreationType.NO_CHILDREN, CancellationToken);
IList<Company> companies = await Repository.FindByIdsAsync(new[] { company1.Id, company2.Id, company3.Id }, CancellationToken);
Assert.That(companies, Is.Not.Null);
Assert.AreEqual(3, companies.Count);
}
[Test]
public async Task Can_FindPaged_Company()
{
await CreateCompanyAsync(CompanyCreationType.WITH_2_CHILDREN, CancellationToken);
IPagedList<Company> pagedList =
await Repository
.FindPagedAsync(
query =>
query
.Where(c => c.Name == "Peopleware NV")
.OrderBy(c => c.Name),
1,
20,
CancellationToken);
Assert.That(pagedList, Is.Not.Null);
Assert.That(pagedList.HasPreviousPage, Is.False);
Assert.That(pagedList.HasNextPage, Is.False);
Assert.That(pagedList.Items.Count, Is.EqualTo(1));
Assert.That(pagedList.TotalCount, Is.EqualTo(1));
Assert.That(pagedList.TotalPages, Is.EqualTo(1));
}
[Test]
public async Task Can_Get_Company_By_Id()
{
Company company = await CreateCompanyAsync(CompanyCreationType.NO_CHILDREN, CancellationToken);
SessionProviderAsync.Session.Clear();
Company loadedCompany = await Repository.GetByIdAsync(company.Id, CancellationToken);
Assert.That(loadedCompany, Is.Not.Null);
Assert.AreEqual(loadedCompany.Id, company.Id);
}
[Test]
public async Task Can_Get_Company_with_Eager_Identifications()
{
await CreateCompanyAsync(CompanyCreationType.WITH_2_CHILDREN, CancellationToken);
SessionProviderAsync.Session.Clear();
Company company =
await Repository
.GetAsync(
query =>
query
.Where(c => c.Name == "Peopleware NV")
.FetchMany(c => c.Identifications),
CancellationToken);
Assert.That(company, Is.Not.Null);
Assert.That(NHibernateUtil.IsInitialized(company.Identifications), Is.True);
}
[Test]
public async Task Can_Get_Company_with_Identification_1()
{
await CreateCompanyAsync(CompanyCreationType.WITH_2_CHILDREN, CancellationToken);
SessionProviderAsync.Session.Clear();
Company company =
await Repository
.GetAsync(
qry => qry.Where(c => c.Identifications.Any(i => i.Identification == "1")),
CancellationToken);
Assert.That(company, Is.Not.Null);
Assert.That(NHibernateUtil.IsInitialized(company.Identifications), Is.False);
}
[Test]
public async Task Can_Get_Company_with_Identification_1_with_explicit_join()
{
await CreateCompanyAsync(CompanyCreationType.WITH_2_CHILDREN, CancellationToken);
SessionProviderAsync.Session.Clear();
Company company =
await Repository
.GetAsync(
qry =>
qry
.SelectMany(c => c.Identifications, (c, ci) => new { c, ci })
.Where(t => t.ci.Identification == "1")
.Select(t => t.c)
.Distinct(),
CancellationToken);
Assert.That(company, Is.Not.Null);
Assert.That(NHibernateUtil.IsInitialized(company.Identifications), Is.False);
}
[Test]
public async Task Can_Get_Company_with_Lazy_Identifications()
{
await CreateCompanyAsync(CompanyCreationType.WITH_2_CHILDREN, CancellationToken);
SessionProviderAsync.Session.Clear();
Company company =
await Repository
.GetAsync(
query => query.Where(c => c.Name == "Peopleware NV"),
CancellationToken);
await SessionProviderAsync.FlushAsync(CancellationToken);
Assert.That(company, Is.Not.Null);
Assert.That(NHibernateUtil.IsInitialized(company.Identifications), Is.False);
}
[Test]
public async Task Can_Load_Company_By_Id()
{
Company company = await CreateCompanyAsync(CompanyCreationType.NO_CHILDREN, CancellationToken);
SessionProviderAsync.Session.Clear();
Company loadedCompany = await Repository.LoadByIdAsync(company.Id, CancellationToken);
await NHibernateUtil.InitializeAsync(loadedCompany, CancellationToken);
Assert.That(loadedCompany, Is.Not.Null);
Assert.AreEqual(loadedCompany.Id, company.Id);
}
[Test]
public async Task Can_Page_All_Companies()
{
await CreateCompanyAsync(CompanyCreationType.WITH_2_CHILDREN, CancellationToken);
IPagedList<Company> pagedList =
await Repository
.FindPagedAsync(
query => query,
1,
20,
CancellationToken);
Assert.That(pagedList, Is.Not.Null);
Assert.That(pagedList.HasPreviousPage, Is.False);
Assert.That(pagedList.HasNextPage, Is.False);
Assert.That(pagedList.Items.Count, Is.EqualTo(1));
Assert.That(pagedList.TotalCount, Is.EqualTo(1));
Assert.That(pagedList.TotalPages, Is.EqualTo(1));
}
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Collections;
using System.Net;
using log4net;
using Org.Mentalis.Security.Ssl;
namespace OpenADK.Web.Http
{
/// <summary>
/// Summary description for HttpHost.
/// </summary>
public class AdkHttpServer
{
private ILog fLog;
private string fServerName;
private ArrayList fBindings = new ArrayList();
private AdkHttpListener fListener;
private bool fIsStarted = false;
protected AdkHttpServer()
{
Type type = this.GetType();
fServerName = "OpenADK Library ADK(r); Version " +
type.Assembly.GetName().Version.ToString();
// Default the log
fLog = LogManager.GetLogger( this.GetType() );
fListener = new AdkHttpListener( this );
}
public virtual string Name
{
get { return fServerName; }
}
public virtual AdkHttpRequestContext CreateContext( AdkHttpConnection connection,
AdkHttpRequest request,
AdkHttpResponse response )
{
return new AdkHttpRequestContext( connection, request, response, this );
}
/// <summary>
/// Adds a handler for a virtual directory
/// </summary>
/// <param name="hostName">The host name to use for this handler ( currently only "" is supported )</param>
/// <param name="virtualPath">The virtual path to respond to requests on</param>
/// <param name="contextHandler">The handler that should respond to requests in this path</param>
/// <param name="force">True if an existing handler should be replaced by this one</param>
public void AddHandlerContext( string hostName,
string virtualPath,
IAdkHttpHandlerFactory contextHandler,
bool force )
{
fListener.AddHandlerContext( hostName, virtualPath, contextHandler, force );
}
/// <summary>
/// Removes a context handler for the specified virtual path
/// </summary>
/// <param name="hostname">The host name to use for this handler ( currently only "" is supported )</param>
/// <param name="virtualPath">The virtual path</param>
public void RemoveHandlerContext( string hostname,
string virtualPath )
{
fListener.RemoveHandlerContext( hostname, virtualPath );
}
public virtual void AddListener( AdkSocketBinding binding )
{
lock ( fBindings.SyncRoot ) {
if ( GetListener( binding.Port ) != null ) {
throw new ArgumentException
( string.Format( "Port {0} is already in use", binding.Port ) );
}
fListener.Attach( binding );
fBindings.Add( binding );
}
}
public virtual AdkSocketBinding CreateHttpListener()
{
AdkSocketBinding binding =
new AdkSocketBinding( new AdkDefaultAcceptSocket(), this.Log );
return binding;
}
/// <summary>
/// Creates an HTTPS socket binding to the specified port
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
public virtual AdkSocketBinding CreateHttpsListener( SecurityOptions options )
{
AdkSSLAcceptSocket socket = new AdkSSLAcceptSocket( options );
AdkSocketBinding binding = new AdkSocketBinding( socket );
return binding;
}
public AdkSocketBinding GetListener( int port )
{
lock ( fBindings.SyncRoot ) {
foreach ( AdkSocketBinding binding in fBindings ) {
if ( binding.Port == port ) {
return binding;
}
}
}
return null;
}
protected void RemoveBinding( int port )
{
lock ( fBindings.SyncRoot ) {
AdkSocketBinding server = GetListener( port );
if ( server != null ) {
server.Stop();
fBindings.Remove( server );
}
}
}
protected AdkHttpListener Listener
{
get { return fListener; }
}
protected AdkSocketBinding [] GetPortBindings()
{
lock ( fBindings.SyncRoot ) {
AdkSocketBinding [] bindings = new AdkSocketBinding[fBindings.Count];
fBindings.CopyTo( bindings );
return bindings;
}
}
protected void StartServer()
{
lock ( fBindings.SyncRoot ) {
if ( !IsStarted ) {
foreach ( AdkSocketBinding server in fBindings ) {
try {
server.Start();
}
catch ( Exception ex ) {
this.Error( ex.Message, ex );
}
}
fIsStarted = true;
}
}
}
public bool IsStarted
{
get { return fIsStarted; }
}
protected void StopServer( bool clearAllListeners )
{
lock ( fBindings.SyncRoot ) {
if ( IsStarted ) {
foreach ( AdkSocketBinding server in fBindings ) {
try {
server.Stop();
}
catch ( Exception ex ) {
this.Error( ex.Message, ex );
}
}
if( clearAllListeners )
{
fBindings.Clear();
}
fIsStarted = false;
}
}
}
public ILog Log
{
get { return fLog; }
set { fLog = value; }
}
public void Error( string message,
Exception ex )
{
if ( fLog != null && fLog.IsErrorEnabled ) {
fLog.Error( message, ex );
}
}
}
}
| |
// 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.Diagnostics;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.ApplicationFramework.Skinning;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
//using OpenLiveWriter.SpellChecker;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.ApplicationFramework.Preferences;
using OpenLiveWriter.PostEditor.WordCount;
namespace OpenLiveWriter.PostEditor
{
public class PostEditorPreferencesPanel : PreferencesPanel
{
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
private GroupBox groupBoxPublishing;
private CheckBox checkBoxViewWeblog;
private PostEditorPreferences _postEditorPreferences;
private System.Windows.Forms.CheckBox checkBoxCloseWindow;
private System.Windows.Forms.GroupBox groupBoxPostWindows;
private System.Windows.Forms.RadioButton radioButtonOpenNewWindowIfDirty;
private System.Windows.Forms.RadioButton radioButtonUseSameWindow;
private System.Windows.Forms.RadioButton radioButtonOpenNewWindow;
private System.Windows.Forms.CheckBox checkBoxCategoryReminder;
private System.Windows.Forms.CheckBox checkBoxTagReminder;
private System.Windows.Forms.CheckBox checkBoxTitleReminder;
private System.Windows.Forms.CheckBox checkBoxAutoSaveDrafts;
private System.Windows.Forms.GroupBox groupBoxGeneral;
private System.Windows.Forms.CheckBox checkBoxWordCount;
private WordCountPreferences _wordCountPreferences;
public PostEditorPreferencesPanel()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
if (!DesignMode)
{
this.groupBoxPostWindows.Text = Res.Get(StringId.PostEditorPrefPostWindows);
this.groupBoxPublishing.Text = Res.Get(StringId.PostEditorPrefPublishing);
checkBoxTagReminder.Text = Res.Get(StringId.PostEditorPrefRemind);
checkBoxCategoryReminder.Text = Res.Get(StringId.PostEditorPrefRemindCat);
checkBoxCloseWindow.Text = Res.Get(StringId.PostEditorPrefClose);
checkBoxViewWeblog.Text = Res.Get(StringId.PostEditorPrefView);
radioButtonOpenNewWindowIfDirty.Text = Res.Get(StringId.PostEditorPrefUnsave);
radioButtonUseSameWindow.Text = Res.Get(StringId.PostEditorPrefSingle);
radioButtonOpenNewWindow.Text = Res.Get(StringId.PostEditorPrefNew);
checkBoxTitleReminder.Text = Res.Get(StringId.PostEditorPrefTitle);
groupBoxGeneral.Text = Res.Get(StringId.PostEditorPrefGeneral);
checkBoxAutoSaveDrafts.Text = Res.Get(StringId.PostEditorPrefAuto);
checkBoxWordCount.Text = Res.Get(StringId.ShowRealTimeWordCount);
PanelName = Res.Get(StringId.PostEditorPrefName);
}
PanelBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.PreferencesOther.png");
_postEditorPreferences = new PostEditorPreferences();
_postEditorPreferences.PreferencesModified += _writerPreferences_PreferencesModified;
switch (_postEditorPreferences.PostWindowBehavior)
{
case PostWindowBehavior.UseSameWindow:
radioButtonUseSameWindow.Checked = true;
break;
case PostWindowBehavior.OpenNewWindow:
radioButtonOpenNewWindow.Checked = true;
break;
case PostWindowBehavior.OpenNewWindowIfDirty:
this.radioButtonOpenNewWindowIfDirty.Checked = true;
break;
}
checkBoxViewWeblog.Checked = _postEditorPreferences.ViewPostAfterPublish;
checkBoxCloseWindow.Checked = _postEditorPreferences.CloseWindowOnPublish;
checkBoxTitleReminder.Checked = _postEditorPreferences.TitleReminder;
checkBoxCategoryReminder.Checked = _postEditorPreferences.CategoryReminder;
checkBoxTagReminder.Checked = _postEditorPreferences.TagReminder;
checkBoxAutoSaveDrafts.Checked = _postEditorPreferences.AutoSaveDrafts;
checkBoxAutoSaveDrafts.CheckedChanged += new EventHandler(checkBoxAutoSaveDrafts_CheckedChanged);
_wordCountPreferences = new WordCountPreferences();
_wordCountPreferences.PreferencesModified += _wordCountPreferences_PreferencesModified;
checkBoxWordCount.Checked = _wordCountPreferences.EnableRealTimeWordCount;
checkBoxWordCount.CheckedChanged += new EventHandler(checkBoxWordCount_CheckedChanged);
radioButtonUseSameWindow.CheckedChanged += new EventHandler(radioButtonPostWindowBehavior_CheckedChanged);
radioButtonOpenNewWindow.CheckedChanged += new EventHandler(radioButtonPostWindowBehavior_CheckedChanged);
radioButtonOpenNewWindowIfDirty.CheckedChanged += new EventHandler(radioButtonPostWindowBehavior_CheckedChanged);
checkBoxViewWeblog.CheckedChanged += new EventHandler(checkBoxViewWeblog_CheckedChanged);
checkBoxCloseWindow.CheckedChanged += new EventHandler(checkBoxCloseWindow_CheckedChanged);
checkBoxTitleReminder.CheckedChanged += new EventHandler(checkBoxTitleReminder_CheckedChanged);
checkBoxCategoryReminder.CheckedChanged += new EventHandler(checkBoxCategoryReminder_CheckedChanged);
checkBoxTagReminder.CheckedChanged += new EventHandler(checkBoxTagReminder_CheckedChanged);
}
private bool _layedOut = false;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!DesignMode && !_layedOut)
{
LayoutHelper.FixupGroupBox(this.groupBoxPostWindows);
LayoutHelper.FixupGroupBox(this.groupBoxPublishing);
LayoutHelper.FixupGroupBox(this.groupBoxGeneral);
LayoutHelper.NaturalizeHeightAndDistribute(8, groupBoxPostWindows, groupBoxPublishing, groupBoxGeneral);
_layedOut = true;
}
}
public override void Save()
{
if (_postEditorPreferences.IsModified())
_postEditorPreferences.Save();
if (_wordCountPreferences.IsModified())
_wordCountPreferences.Save();
}
private void checkBoxViewWeblog_CheckedChanged(object sender, EventArgs e)
{
_postEditorPreferences.ViewPostAfterPublish = checkBoxViewWeblog.Checked;
}
private void radioButtonPostWindowBehavior_CheckedChanged(object sender, EventArgs e)
{
if (radioButtonUseSameWindow.Checked)
_postEditorPreferences.PostWindowBehavior = PostWindowBehavior.UseSameWindow;
else if (radioButtonOpenNewWindow.Checked)
_postEditorPreferences.PostWindowBehavior = PostWindowBehavior.OpenNewWindow;
else if (radioButtonOpenNewWindowIfDirty.Checked)
_postEditorPreferences.PostWindowBehavior = PostWindowBehavior.OpenNewWindowIfDirty;
}
private void checkBoxCloseWindow_CheckedChanged(object sender, EventArgs e)
{
UpdateClosePreferences();
}
private void UpdateClosePreferences()
{
_postEditorPreferences.CloseWindowOnPublish = checkBoxCloseWindow.Checked;
}
private void _writerPreferences_PreferencesModified(object sender, EventArgs e)
{
OnModified(EventArgs.Empty);
}
private void checkBoxTitleReminder_CheckedChanged(object sender, EventArgs e)
{
_postEditorPreferences.TitleReminder = checkBoxTitleReminder.Checked;
}
private void checkBoxCategoryReminder_CheckedChanged(object sender, EventArgs e)
{
_postEditorPreferences.CategoryReminder = checkBoxCategoryReminder.Checked;
}
private void checkBoxTagReminder_CheckedChanged(object sender, EventArgs e)
{
_postEditorPreferences.TagReminder = checkBoxTagReminder.Checked;
}
private void checkBoxAutoSaveDrafts_CheckedChanged(object sender, EventArgs e)
{
_postEditorPreferences.AutoSaveDrafts = checkBoxAutoSaveDrafts.Checked;
}
void _wordCountPreferences_PreferencesModified(object sender, EventArgs e)
{
OnModified(EventArgs.Empty);
}
void checkBoxWordCount_CheckedChanged(object sender, EventArgs e)
{
_wordCountPreferences.EnableRealTimeWordCount = checkBoxWordCount.Checked;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_postEditorPreferences.PreferencesModified -= new EventHandler(_writerPreferences_PreferencesModified);
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBoxPublishing = new System.Windows.Forms.GroupBox();
this.checkBoxTitleReminder = new System.Windows.Forms.CheckBox();
this.checkBoxTagReminder = new System.Windows.Forms.CheckBox();
this.checkBoxCategoryReminder = new System.Windows.Forms.CheckBox();
this.checkBoxCloseWindow = new System.Windows.Forms.CheckBox();
this.checkBoxViewWeblog = new System.Windows.Forms.CheckBox();
this.groupBoxPostWindows = new System.Windows.Forms.GroupBox();
this.radioButtonOpenNewWindowIfDirty = new System.Windows.Forms.RadioButton();
this.radioButtonUseSameWindow = new System.Windows.Forms.RadioButton();
this.radioButtonOpenNewWindow = new System.Windows.Forms.RadioButton();
this.groupBoxGeneral = new System.Windows.Forms.GroupBox();
this.checkBoxAutoSaveDrafts = new System.Windows.Forms.CheckBox();
this.checkBoxWordCount = new System.Windows.Forms.CheckBox();
this.groupBoxPublishing.SuspendLayout();
this.groupBoxPostWindows.SuspendLayout();
this.groupBoxGeneral.SuspendLayout();
this.SuspendLayout();
//
// groupBoxPublishing
//
this.groupBoxPublishing.Controls.Add(this.checkBoxTitleReminder);
this.groupBoxPublishing.Controls.Add(this.checkBoxTagReminder);
this.groupBoxPublishing.Controls.Add(this.checkBoxCategoryReminder);
this.groupBoxPublishing.Controls.Add(this.checkBoxCloseWindow);
this.groupBoxPublishing.Controls.Add(this.checkBoxViewWeblog);
this.groupBoxPublishing.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBoxPublishing.Location = new System.Drawing.Point(8, 154);
this.groupBoxPublishing.Name = "groupBoxPublishing";
this.groupBoxPublishing.Size = new System.Drawing.Size(345, 174);
this.groupBoxPublishing.TabIndex = 2;
this.groupBoxPublishing.TabStop = false;
this.groupBoxPublishing.Text = "Publishing";
//
// checkBoxTitleReminder
//
this.checkBoxTitleReminder.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBoxTitleReminder.Location = new System.Drawing.Point(16, 93);
this.checkBoxTitleReminder.Name = "checkBoxTitleReminder";
this.checkBoxTitleReminder.Size = new System.Drawing.Size(312, 21);
this.checkBoxTitleReminder.TabIndex = 3;
this.checkBoxTitleReminder.Text = "&Remind me to specify a title before publishing";
this.checkBoxTitleReminder.TextAlign = System.Drawing.ContentAlignment.TopLeft;
//
// checkBoxTagReminder
//
this.checkBoxTagReminder.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBoxTagReminder.Location = new System.Drawing.Point(16, 135);
this.checkBoxTagReminder.Name = "checkBoxTagReminder";
this.checkBoxTagReminder.Size = new System.Drawing.Size(312, 21);
this.checkBoxTagReminder.TabIndex = 5;
this.checkBoxTagReminder.Text = "Remind me to add &tags before publishing";
this.checkBoxTagReminder.TextAlign = System.Drawing.ContentAlignment.TopLeft;
//
// checkBoxCategoryReminder
//
this.checkBoxCategoryReminder.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBoxCategoryReminder.Location = new System.Drawing.Point(16, 114);
this.checkBoxCategoryReminder.Name = "checkBoxCategoryReminder";
this.checkBoxCategoryReminder.Size = new System.Drawing.Size(312, 21);
this.checkBoxCategoryReminder.TabIndex = 4;
this.checkBoxCategoryReminder.Text = "Remind me to add &categories before publishing";
this.checkBoxCategoryReminder.TextAlign = System.Drawing.ContentAlignment.TopLeft;
//
// checkBoxCloseWindow
//
this.checkBoxCloseWindow.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBoxCloseWindow.Location = new System.Drawing.Point(16, 42);
this.checkBoxCloseWindow.Name = "checkBoxCloseWindow";
this.checkBoxCloseWindow.Size = new System.Drawing.Size(312, 24);
this.checkBoxCloseWindow.TabIndex = 1;
this.checkBoxCloseWindow.Text = "Close &window after publishing: ";
this.checkBoxCloseWindow.TextAlign = System.Drawing.ContentAlignment.TopLeft;
//
// checkBoxViewWeblog
//
this.checkBoxViewWeblog.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBoxViewWeblog.Location = new System.Drawing.Point(16, 21);
this.checkBoxViewWeblog.Name = "checkBoxViewWeblog";
this.checkBoxViewWeblog.Size = new System.Drawing.Size(312, 21);
this.checkBoxViewWeblog.TabIndex = 0;
this.checkBoxViewWeblog.Text = "&View post after publishing";
this.checkBoxViewWeblog.TextAlign = System.Drawing.ContentAlignment.TopLeft;
//
// groupBoxPostWindows
//
this.groupBoxPostWindows.Controls.Add(this.radioButtonOpenNewWindowIfDirty);
this.groupBoxPostWindows.Controls.Add(this.radioButtonUseSameWindow);
this.groupBoxPostWindows.Controls.Add(this.radioButtonOpenNewWindow);
this.groupBoxPostWindows.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBoxPostWindows.Location = new System.Drawing.Point(8, 32);
this.groupBoxPostWindows.Name = "groupBoxPostWindows";
this.groupBoxPostWindows.Size = new System.Drawing.Size(345, 116);
this.groupBoxPostWindows.TabIndex = 1;
this.groupBoxPostWindows.TabStop = false;
this.groupBoxPostWindows.Text = "Post Windows";
//
// radioButtonOpenNewWindowIfDirty
//
this.radioButtonOpenNewWindowIfDirty.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.radioButtonOpenNewWindowIfDirty.Location = new System.Drawing.Point(16, 69);
this.radioButtonOpenNewWindowIfDirty.Name = "radioButtonOpenNewWindowIfDirty";
this.radioButtonOpenNewWindowIfDirty.Size = new System.Drawing.Size(312, 30);
this.radioButtonOpenNewWindowIfDirty.TabIndex = 2;
this.radioButtonOpenNewWindowIfDirty.Text = "Open a new window &only when there are unsaved changes to the current post";
this.radioButtonOpenNewWindowIfDirty.TextAlign = System.Drawing.ContentAlignment.TopLeft;
//
// radioButtonUseSameWindow
//
this.radioButtonUseSameWindow.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.radioButtonUseSameWindow.Location = new System.Drawing.Point(16, 21);
this.radioButtonUseSameWindow.Name = "radioButtonUseSameWindow";
this.radioButtonUseSameWindow.Size = new System.Drawing.Size(312, 24);
this.radioButtonUseSameWindow.TabIndex = 0;
this.radioButtonUseSameWindow.Text = "Use a &single window for editing all posts";
this.radioButtonUseSameWindow.TextAlign = System.Drawing.ContentAlignment.TopLeft;
//
// radioButtonOpenNewWindow
//
this.radioButtonOpenNewWindow.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.radioButtonOpenNewWindow.Location = new System.Drawing.Point(16, 44);
this.radioButtonOpenNewWindow.Name = "radioButtonOpenNewWindow";
this.radioButtonOpenNewWindow.Size = new System.Drawing.Size(312, 24);
this.radioButtonOpenNewWindow.TabIndex = 1;
this.radioButtonOpenNewWindow.Text = "Open a new window for &each post";
this.radioButtonOpenNewWindow.TextAlign = System.Drawing.ContentAlignment.TopLeft;
//
// groupBoxGeneral
//
this.groupBoxGeneral.Controls.Add(this.checkBoxAutoSaveDrafts);
this.groupBoxGeneral.Controls.Add(this.checkBoxWordCount);
this.groupBoxGeneral.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBoxGeneral.Location = new System.Drawing.Point(8, 154);
this.groupBoxGeneral.Name = "groupBoxGeneral";
this.groupBoxGeneral.Size = new System.Drawing.Size(345, 174);
this.groupBoxGeneral.TabIndex = 3;
this.groupBoxGeneral.TabStop = false;
this.groupBoxGeneral.Text = "General";
//
// checkBoxAutoSaveDrafts
//
this.checkBoxAutoSaveDrafts.CheckAlign = System.Drawing.ContentAlignment.TopLeft;
this.checkBoxAutoSaveDrafts.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBoxAutoSaveDrafts.Location = new System.Drawing.Point(16, 21);
this.checkBoxAutoSaveDrafts.Name = "checkBoxAutoSaveDrafts";
this.checkBoxAutoSaveDrafts.Size = new System.Drawing.Size(312, 18);
this.checkBoxAutoSaveDrafts.TabIndex = 0;
this.checkBoxAutoSaveDrafts.Text = "Automatically save &drafts every:";
this.checkBoxAutoSaveDrafts.TextAlign = System.Drawing.ContentAlignment.TopLeft;
//
// checkBoxWordCount
//
this.checkBoxWordCount.CheckAlign = System.Drawing.ContentAlignment.TopLeft;
this.checkBoxWordCount.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBoxWordCount.Location = new System.Drawing.Point(16, 156);
this.checkBoxWordCount.Name = "checkBoxWordCount";
this.checkBoxWordCount.Size = new System.Drawing.Size(312, 18);
this.checkBoxWordCount.TabIndex = 1;
this.checkBoxWordCount.Text = "Show real time &word count in status bar";
this.checkBoxWordCount.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.checkBoxWordCount.UseVisualStyleBackColor = true;
//
// PostEditorPreferencesPanel
//
this.AccessibleName = "Preferences";
this.Controls.Add(this.groupBoxPostWindows);
this.Controls.Add(this.groupBoxPublishing);
this.Controls.Add(this.groupBoxGeneral);
this.Name = "PostEditorPreferencesPanel";
this.PanelName = "Preferences";
this.Size = new System.Drawing.Size(370, 521);
this.Controls.SetChildIndex(this.groupBoxPublishing, 0);
this.Controls.SetChildIndex(this.groupBoxPostWindows, 0);
this.Controls.SetChildIndex(this.groupBoxGeneral, 0);
this.groupBoxPublishing.ResumeLayout(false);
this.groupBoxPostWindows.ResumeLayout(false);
this.groupBoxGeneral.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
}
}
| |
#region License
// Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Xunit;
using crypt = System.Security.Cryptography;
namespace SourceCode.Clay.Tests
{
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public static class Sha1Tests
{
private static readonly crypt.SHA1 s_sha1 = crypt.SHA1.Create();
[Trait("Type", "Unit")]
[Fact]
public static void When_check_default()
{
var expected = default(Sha1);
var actual = Sha1.Parse(Sha1TestVectors.Zero);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_check_empty()
{
var expected = Sha1.Parse(Sha1TestVectors.Empty);
// Empty Array singleton
Sha1 actual = s_sha1.HashData(Array.Empty<byte>());
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty Array
actual = s_sha1.HashData(new byte[0]);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty default ArraySegment
actual = s_sha1.HashData(default(ArraySegment<byte>));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty new ArraySegment
actual = s_sha1.HashData(new ArraySegment<byte>(new byte[0], 0, 0));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty default Span
actual = s_sha1.HashData(default(Span<byte>));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty new Span
actual = s_sha1.HashData(new Span<byte>(new byte[0], 0, 0));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty default ReadOnlySpan
actual = s_sha1.HashData(default(ReadOnlySpan<byte>));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty new ReadOnlySpan
actual = s_sha1.HashData(new ReadOnlySpan<byte>(new byte[0], 0, 0));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Empty String
actual = s_sha1.HashData(string.Empty);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_null_sha1()
{
var expected = default(Sha1);
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha1(null));
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha1(new Span<byte>()));
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha1(new Span<byte>(new byte[0])));
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha1(new Span<byte>(new byte[1] { 0 })));
Assert.True(default == expected);
Assert.False(default != expected);
Assert.True(expected.Equals((object)expected));
Assert.Equal(new KeyValuePair<string, string>("", Sha1TestVectors.Zero), expected.Split(0, false));
Assert.Equal(new KeyValuePair<string, string>("", Sha1TestVectors.Zero), expected.Split(0, true));
Assert.Equal(new KeyValuePair<string, string>("00", Sha1TestVectors.Zero.Left(Sha1.HexLength - 2)), expected.Split(2, false));
Assert.Equal(new KeyValuePair<string, string>("00", Sha1TestVectors.Zero.Left(Sha1.HexLength - 2).ToUpperInvariant()), expected.Split(2, true));
Assert.Equal(new KeyValuePair<string, string>(Sha1TestVectors.Zero, ""), expected.Split(Sha1.HexLength, false));
Assert.Equal(new KeyValuePair<string, string>(Sha1TestVectors.Zero, ""), expected.Split(Sha1.HexLength, true));
// Null string
Assert.Throws<ArgumentNullException>(() => s_sha1.HashData((string)null));
// Null bytes
Assert.Throws<ArgumentNullException>(() => s_sha1.HashData((byte[])null));
Assert.Throws<ArgumentNullException>(() => s_sha1.HashData(null, 0, 0));
// Stream
Assert.Throws<ArgumentNullException>(() => s_sha1.HashData((Stream)null));
// Roundtrip string
var actual = Sha1.Parse(expected.ToString());
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Roundtrip formatted
actual = Sha1.Parse(expected.ToString("D"));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = Sha1.Parse(expected.ToString("S"));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// With hex specifier
actual = Sha1.Parse("0x" + expected.ToString("D"));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = Sha1.Parse("0x" + expected.ToString("S"));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha1_from_Bytes()
{
Sha1 expected = s_sha1.HashData("abc");
byte[] buffer = new byte[Sha1.ByteLength + 10];
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha1(new byte[Sha1.ByteLength - 1])); // Too short
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha1(new byte[Sha1.ByteLength].AsSpan().Slice(1))); // Bad offset
// Construct Byte[]
expected.CopyTo(buffer.AsSpan());
var actual = new Sha1(buffer);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Byte[] with offset 0
expected.CopyTo(buffer.AsSpan());
actual = new Sha1(buffer);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Byte[] with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
actual = new Sha1(buffer.AsSpan().Slice(5));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha1_from_ArraySegment()
{
Sha1 expected = s_sha1.HashData("abc");
byte[] buffer = new byte[Sha1.ByteLength + 10];
// Construct Byte[] with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
var actual = new Sha1(buffer.AsSpan().Slice(5));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Segment
expected.CopyTo(buffer.AsSpan());
var seg = new ArraySegment<byte>(buffer);
actual = new Sha1(seg);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Segment with offset 0
expected.CopyTo(buffer.AsSpan());
seg = new ArraySegment<byte>(buffer, 0, Sha1.ByteLength);
actual = new Sha1(seg);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Segment with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
seg = new ArraySegment<byte>(buffer, 5, Sha1.ByteLength);
actual = new Sha1(seg);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha1_from_Memory()
{
Sha1 expected = s_sha1.HashData("abc");
byte[] buffer = new byte[Sha1.ByteLength + 10];
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha1(Memory<byte>.Empty.Span)); // Empty
Assert.Throws<ArgumentOutOfRangeException>(() => new Sha1(new Memory<byte>(new byte[Sha1.ByteLength - 1]).Span)); // Too short
// Construct Memory
expected.CopyTo(buffer.AsSpan());
var mem = new Memory<byte>(buffer);
var actual = new Sha1(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Memory with offset 0
expected.CopyTo(buffer.AsSpan());
mem = new Memory<byte>(buffer, 0, Sha1.ByteLength);
actual = new Sha1(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Memory with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
mem = new Memory<byte>(buffer, 5, Sha1.ByteLength);
actual = new Sha1(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha1_from_ReadOnlyMemory()
{
Sha1 expected = s_sha1.HashData("abc");
byte[] buffer = new byte[Sha1.ByteLength + 10];
// Construct ReadOnlyMemory
expected.CopyTo(buffer.AsSpan());
var mem = new ReadOnlyMemory<byte>(buffer);
var actual = new Sha1(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct ReadOnlyMemory with offset 0
expected.CopyTo(buffer.AsSpan());
mem = new ReadOnlyMemory<byte>(buffer, 0, Sha1.ByteLength);
actual = new Sha1(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct ReadOnlyMemory with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
mem = new ReadOnlyMemory<byte>(buffer, 5, Sha1.ByteLength);
actual = new Sha1(mem.Span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha1_from_Stream()
{
byte[] buffer = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
// Construct MemoryStream
var mem = new MemoryStream(buffer);
Sha1 expected = s_sha1.HashData(buffer);
Sha1 actual = s_sha1.HashData(mem);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct MemoryStream with offset 0
mem = new MemoryStream(buffer, 0, buffer.Length);
expected = s_sha1.HashData(buffer, 0, buffer.Length);
actual = s_sha1.HashData(mem);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct MemoryStream with offset N
mem = new MemoryStream(buffer, 5, buffer.Length - 5);
expected = s_sha1.HashData(buffer, 5, buffer.Length - 5);
actual = s_sha1.HashData(mem);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha1_from_Span()
{
Sha1 expected = s_sha1.HashData("abc");
byte[] buffer = new byte[Sha1.ByteLength + 10];
// Construct Span
expected.CopyTo(buffer.AsSpan());
var span = new Span<byte>(buffer);
var actual = new Sha1(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Span with offset 0
expected.CopyTo(buffer.AsSpan());
span = new Span<byte>(buffer, 0, Sha1.ByteLength);
actual = new Sha1(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct Span with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
span = new Span<byte>(buffer, 5, Sha1.ByteLength);
actual = new Sha1(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_copyto_with_null_buffer()
{
// Arrange
byte[] buffer = null;
var sha1 = new Sha1();
// Action
ArgumentException actual = Assert.Throws<ArgumentException>(() => sha1.CopyTo(buffer.AsSpan()));
}
[Trait("Type", "Unit")]
[Fact]
public static void When_construct_sha1_from_ReadOnlySpan()
{
Sha1 expected = s_sha1.HashData("abc");
byte[] buffer = new byte[Sha1.ByteLength + 10];
// Construct ReadOnlySpan
expected.CopyTo(buffer.AsSpan());
var span = new ReadOnlySpan<byte>(buffer);
var actual = new Sha1(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct ReadOnlySpan with offset 0
expected.CopyTo(buffer.AsSpan());
span = new ReadOnlySpan<byte>(buffer, 0, Sha1.ByteLength);
actual = new Sha1(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Construct ReadOnlySpan with offset N
expected.CopyTo(buffer.AsSpan().Slice(5));
span = new ReadOnlySpan<byte>(buffer, 5, Sha1.ByteLength);
actual = new Sha1(span);
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Theory]
[ClassData(typeof(Sha1TestVectors))] // http://www.di-mgt.com.au/sha_testvectors.html
public static void When_create_test_vectors(string input, string expected)
{
var sha1 = Sha1.Parse(expected);
{
// String
string actual = s_sha1.HashData(input).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
Assert.Equal(Sha1.HexLength, Encoding.UTF8.GetByteCount(actual));
// Bytes
byte[] bytes = Encoding.UTF8.GetBytes(input);
actual = s_sha1.HashData(bytes).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = s_sha1.HashData(bytes, 0, bytes.Length).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Object
Assert.True(expected.Equals((object)actual));
// Roundtrip string
actual = sha1.ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Roundtrip formatted
actual = Sha1.Parse(sha1.ToString("D")).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = Sha1.Parse(sha1.ToString("S")).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// With hex specifier
actual = Sha1.Parse("0x" + sha1.ToString("D")).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
actual = Sha1.Parse("0x" + sha1.ToString("S")).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Get Byte[]
byte[] buffer = new byte[Sha1.ByteLength];
sha1.CopyTo(buffer.AsSpan());
// Roundtrip Byte[]
actual = new Sha1(buffer).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
// Roundtrip Segment
actual = new Sha1(new ArraySegment<byte>(buffer)).ToString();
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_sha1_from_empty_ArraySegment()
{
Sha1 expected = s_sha1.HashData(Array.Empty<byte>());
// Empty segment
Sha1 actual = s_sha1.HashData(default(ArraySegment<byte>));
Assert.Equal(expected, actual);
Assert.Equal(expected.GetHashCode(), actual.GetHashCode());
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_sha_from_bytes()
{
byte[] buffer = new byte[Sha1.ByteLength];
byte[] tinyBuffer = new byte[Sha1.ByteLength - 1];
for (int i = 1; i < 200; i++)
{
string str = new string(char.MinValue, i);
byte[] byt = Encoding.UTF8.GetBytes(str);
Sha1 sha = s_sha1.HashData(byt);
Assert.NotEqual(default, sha);
Assert.Equal(Sha1.HexLength, Encoding.UTF8.GetByteCount(sha.ToString()));
bool copied = sha.TryCopyTo(buffer);
Assert.True(copied);
var shb = new Sha1(buffer);
Assert.Equal(sha, shb);
copied = sha.TryCopyTo(tinyBuffer);
Assert.False(copied);
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_sha_from_empty_string()
{
const string expected = Sha1TestVectors.Empty; // http://www.di-mgt.com.au/sha_testvectors.html
var sha1 = Sha1.Parse(expected);
{
const string input = "";
// String
string actual = s_sha1.HashData(input).ToString();
Assert.Equal(expected, actual);
Assert.Equal(Sha1.HexLength, Encoding.UTF8.GetByteCount(actual));
// Empty array
actual = s_sha1.HashData(Array.Empty<byte>()).ToString();
Assert.Equal(expected, actual);
actual = s_sha1.HashData(Array.Empty<byte>(), 0, 0).ToString();
Assert.Equal(expected, actual);
// Empty segment
actual = s_sha1.HashData(new ArraySegment<byte>(Array.Empty<byte>())).ToString();
Assert.Equal(expected, actual);
// Bytes
byte[] bytes = Encoding.UTF8.GetBytes(input);
actual = s_sha1.HashData(bytes).ToString();
Assert.Equal(expected, actual);
// Object
Assert.True(expected.Equals((object)actual));
// Roundtrip string
actual = sha1.ToString();
Assert.Equal(expected, actual);
// Roundtrip formatted
actual = Sha1.Parse(sha1.ToString("d")).ToString();
Assert.Equal(expected, actual);
actual = Sha1.Parse(sha1.ToString("s")).ToString();
Assert.Equal(expected, actual);
// With hex specifier
actual = Sha1.Parse("0x" + sha1.ToString("d")).ToString();
Assert.Equal(expected, actual);
actual = Sha1.Parse("0x" + sha1.ToString("s")).ToString();
Assert.Equal(expected, actual);
// Get Byte[]
byte[] buffer = new byte[Sha1.ByteLength];
sha1.CopyTo(buffer.AsSpan());
// Roundtrip Byte[]
actual = new Sha1(buffer).ToString();
Assert.Equal(expected, actual);
// Roundtrip Segment
actual = new Sha1(new ArraySegment<byte>(buffer)).ToString();
Assert.Equal(expected, actual);
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_sha_from_narrow_string()
{
for (int i = 1; i < 200; i++)
{
string str = new string(char.MinValue, i);
Sha1 sha1 = s_sha1.HashData(str);
Assert.NotEqual(default, sha1);
Assert.Equal(Sha1.HexLength, Encoding.UTF8.GetByteCount(sha1.ToString()));
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_sha_from_wide_string_1()
{
for (int i = 1; i < 200; i++)
{
string str = new string(char.MaxValue, i);
Sha1 sha1 = s_sha1.HashData(str);
Assert.NotEqual(default, sha1);
Assert.Equal(Sha1.HexLength, Encoding.UTF8.GetByteCount(sha1.ToString()));
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_create_sha_from_wide_string_2()
{
string str = string.Empty;
for (int i = 1; i < 200; i++)
{
str += TestConstants.SurrogatePair;
Sha1 sha1 = s_sha1.HashData(str);
Assert.NotEqual(default, sha1);
Assert.Equal(Sha1.HexLength, Encoding.UTF8.GetByteCount(sha1.ToString()));
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_format_sha1()
{
// http://www.di-mgt.com.au/sha_testvectors.html
const string expected_N = "a9993e364706816aba3e25717850c26c9cd0d89d";
var sha1 = Sha1.Parse(expected_N);
// ("N")
{
string actual = sha1.ToString(); // Default format
Assert.Equal(expected_N, actual);
actual = sha1.ToString("N");
Assert.Equal(expected_N.ToUpperInvariant(), actual);
actual = sha1.ToString("n");
Assert.Equal(expected_N, actual);
}
// ("D")
{
const string expected_D = "a9993e36-4706816a-ba3e2571-7850c26c-9cd0d89d";
string actual = sha1.ToString("D");
Assert.Equal(expected_D.ToUpperInvariant(), actual);
actual = sha1.ToString("d");
Assert.Equal(expected_D, actual);
}
// ("S")
{
const string expected_S = "a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d";
string actual = sha1.ToString("S");
Assert.Equal(expected_S.ToUpperInvariant(), actual);
actual = sha1.ToString("s");
Assert.Equal(expected_S, actual);
}
// (null)
{
Assert.Throws<FormatException>(() => sha1.ToString(null));
}
// ("")
{
Assert.Throws<FormatException>(() => sha1.ToString(""));
}
// (" ")
{
Assert.Throws<FormatException>(() => sha1.ToString(" "));
}
// ("x")
{
Assert.Throws<FormatException>(() => sha1.ToString("x"));
}
// ("ss")
{
Assert.Throws<FormatException>(() => sha1.ToString("nn"));
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_parse_sha1()
{
// http://www.di-mgt.com.au/sha_testvectors.html
const string expected_N = "a9993e364706816aba3e25717850c26c9cd0d89d";
var sha1 = Sha1.Parse(expected_N);
Assert.True(Sha1.TryParse(expected_N, out _));
Assert.True(Sha1.TryParse(expected_N.AsSpan(), out _));
Assert.True(Sha1.TryParse("0x" + expected_N, out _));
Assert.True(Sha1.TryParse("0X" + expected_N, out _));
Assert.False(Sha1.TryParse(expected_N.Substring(10), out _));
Assert.False(Sha1.TryParse("0x" + expected_N.Substring(10), out _));
Assert.False(Sha1.TryParse("0X" + expected_N.Substring(10), out _));
Assert.False(Sha1.TryParse("0x" + expected_N.Substring(Sha1.HexLength - 2), out _));
Assert.False(Sha1.TryParse("0X" + expected_N.Substring(Sha1.HexLength - 2), out _));
Assert.False(Sha1.TryParse(expected_N.Replace('8', 'G'), out _));
Assert.False(Sha1.TryParse(expected_N.Replace('8', 'G').AsSpan(), out _));
Assert.Throws<FormatException>(() => Sha1.Parse(expected_N.Replace('8', 'G').AsSpan()));
Assert.False(Sha1.TryParse($"0x{new string('1', Sha1.HexLength - 2)}", out _));
Assert.False(Sha1.TryParse($"0x{new string('1', Sha1.HexLength - 1)}", out _));
Assert.True(Sha1.TryParse($"0x{new string('1', Sha1.HexLength)}", out _));
// "N"
{
var actual = Sha1.Parse(sha1.ToString()); // Default format
Assert.Equal(sha1, actual);
actual = Sha1.Parse(sha1.ToString("N"));
Assert.Equal(sha1, actual);
actual = Sha1.Parse("0x" + sha1.ToString("N"));
Assert.Equal(sha1, actual);
Assert.Throws<FormatException>(() => Sha1.Parse(sha1.ToString("N") + "a"));
}
// "D"
{
var actual = Sha1.Parse(sha1.ToString("D"));
Assert.Equal(sha1, actual);
actual = Sha1.Parse("0x" + sha1.ToString("D"));
Assert.Equal(sha1, actual);
Assert.Throws<FormatException>(() => Sha1.Parse(sha1.ToString("D") + "a"));
}
// "S"
{
var actual = Sha1.Parse(sha1.ToString("S"));
Assert.Equal(sha1, actual);
actual = Sha1.Parse("0x" + sha1.ToString("S"));
Assert.Equal(sha1, actual);
Assert.Throws<FormatException>(() => Sha1.Parse(sha1.ToString("S") + "a"));
}
// null
{
Assert.Throws<ArgumentNullException>(() => Sha1.Parse(null));
}
// Empty
{
Assert.Throws<FormatException>(() => Sha1.Parse(""));
}
// Whitespace
{
Assert.Throws<FormatException>(() => Sha1.Parse(" "));
Assert.Throws<FormatException>(() => Sha1.Parse("\t"));
}
// "0x"
{
Assert.Throws<FormatException>(() => Sha1.Parse("0x"));
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_lexographic_compare_sha1()
{
byte[] byt1 = new byte[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
var sha1 = new Sha1(byt1);
string str1 = sha1.ToString();
Assert.Equal("000102030405060708090a0b0c0d0e0f10111213", str1);
for (int n = 0; n < 20; n++)
{
for (int i = n + 1; i <= byte.MaxValue; i++)
{
// Bump blit[n]
byt1[n] = (byte)i;
var sha2 = new Sha1(byt1);
Assert.True(sha2 > sha1);
}
byt1[n] = (byte)n;
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_compare_sha1()
{
Sha1 sha1 = s_sha1.HashData("abc"); // a9993e36-4706816a-ba3e2571-7850c26c-9cd0d89d
Assert.True(default(Sha1) < sha1);
Assert.True(sha1 > default(Sha1));
Sha1 sha2 = sha1; // a9993e36-4706816a-ba3e2571-7850c26c-9cd0d89d
Assert.True(sha2 <= sha1);
Assert.True(sha2 >= sha1);
Assert.False(sha2 < sha1);
Assert.False(sha2 > sha1);
Sha1 sha3 = s_sha1.HashData("def"); // 589c2233-5a381f12-2d129225-f5c0ba30-56ed5811
Assert.True(sha1.CompareTo(sha2) == 0);
Assert.True(sha1.CompareTo(sha3) != 0);
var span = new Span<byte>(new byte[Sha1.ByteLength]);
sha1.CopyTo(span);
span[Sha1.ByteLength - 1]++;
var sha4 = new Sha1(span); // a9993e36-4706816a-ba3e2571-7850c26c-9cd0d89e
Assert.True(sha4 >= sha1);
Assert.True(sha4 > sha1);
Assert.False(sha4 < sha1);
Assert.False(sha4 <= sha1);
Assert.True(sha1.CompareTo(sha4) < 0);
Sha1[] list = new[] { sha4, sha1, sha2, sha3 };
Sha1Comparer comparer = Sha1Comparer.Default;
Array.Sort(list, comparer.Compare);
Assert.True(list[0] < list[1]);
Assert.True(list[1] == list[2]);
Assert.True(list[3] > list[2]);
}
[Trait("Type", "Unit")]
[Fact]
public static void When_parse_sha1_whitespace()
{
const string whitespace = " \n \t \r ";
Sha1 expected = s_sha1.HashData("abc"); // a9993e36-4706816a-ba3e2571-7850c26c-9cd0d89d
string str = expected.ToString();
// Leading whitespace
var actual = Sha1.Parse(whitespace + str);
Assert.Equal(expected, actual);
// Trailing whitespace
actual = Sha1.Parse(str + whitespace);
Assert.Equal(expected, actual);
// Both
actual = Sha1.Parse(whitespace + str + whitespace);
Assert.Equal(expected, actual);
// Fail
Assert.False(Sha1.TryParse("1" + str, out _));
Assert.False(Sha1.TryParse(str + "1", out _));
Assert.False(Sha1.TryParse("1" + whitespace + str, out _));
Assert.False(Sha1.TryParse(str + whitespace + "1", out _));
Assert.False(Sha1.TryParse("1" + whitespace + str + whitespace, out _));
Assert.False(Sha1.TryParse(whitespace + str + whitespace + "1", out _));
}
[Trait("Type", "Unit")]
[Fact]
public static void When_sha1_equality()
{
var sha0 = default(Sha1);
Sha1 sha1 = s_sha1.HashData("abc");
Sha1 sha2 = s_sha1.HashData("abc");
Sha1 sha3 = s_sha1.HashData("def");
Assert.True(sha1 == sha2);
Assert.False(sha1 != sha2);
Assert.True(sha1.Equals((object)sha2));
Assert.False(sha1.Equals(new object()));
Assert.Equal(sha1, sha2);
Assert.Equal(sha1.GetHashCode(), sha2.GetHashCode());
Assert.Equal(sha1.ToString(), sha2.ToString());
Assert.NotEqual(sha0, sha1);
Assert.NotEqual(sha0.GetHashCode(), sha1.GetHashCode());
Assert.NotEqual(sha0.ToString(), sha1.ToString());
Assert.NotEqual(sha3, sha1);
Assert.NotEqual(sha3.GetHashCode(), sha1.GetHashCode());
Assert.NotEqual(sha3.ToString(), sha1.ToString());
}
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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.Diagnostics.CodeAnalysis;
using System.IO;
using System.Security;
namespace Alphaleonis.Win32.Filesystem
{
/// <summary>Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.</summary>
[SerializableAttribute]
public sealed partial class DirectoryInfo : FileSystemInfo
{
#region Constructors
#region .NET
/// <summary>Initializes a new instance of the <see cref="Alphaleonis.Win32.Filesystem.DirectoryInfo"/> class on the specified path.</summary>
/// <param name="path">The path on which to create the <see cref="Alphaleonis.Win32.Filesystem.DirectoryInfo"/>.</param>
/// <remarks>
/// This constructor does not check if a directory exists. This constructor is a placeholder for a string that is used to access the disk in subsequent operations.
/// The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.
/// </remarks>
public DirectoryInfo(string path) : this(null, path, PathFormat.RelativePath)
{
}
#endregion // .NET
#region AlphaFS
/// <summary>[AlphaFS] Initializes a new instance of the <see cref="Alphaleonis.Win32.Filesystem.DirectoryInfo"/> class on the specified path.</summary>
/// <param name="path">The path on which to create the <see cref="Alphaleonis.Win32.Filesystem.DirectoryInfo"/>.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
/// <remarks>This constructor does not check if a directory exists. This constructor is a placeholder for a string that is used to access the disk in subsequent operations.</remarks>
public DirectoryInfo(string path, PathFormat pathFormat) : this(null, path, pathFormat)
{
}
/// <summary>[AlphaFS] Special internal implementation.</summary>
/// <param name="transaction">The transaction.</param>
/// <param name="fullPath">The full path on which to create the <see cref="Alphaleonis.Win32.Filesystem.DirectoryInfo"/>.</param>
/// <param name="junk1">Not used.</param>
/// <param name="junk2">Not used.</param>
/// <remarks>This constructor does not check if a directory exists. This constructor is a placeholder for a string that is used to access the disk in subsequent operations.</remarks>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "junk1")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "junk2")]
private DirectoryInfo(KernelTransaction transaction, string fullPath, bool junk1, bool junk2)
{
IsDirectory = true;
Transaction = transaction;
LongFullName = Path.GetLongPathCore(fullPath, GetFullPathOptions.None);
OriginalPath = Path.GetFileName(fullPath, true);
FullPath = fullPath;
DisplayPath = OriginalPath.Length != 2 || OriginalPath[1] != Path.VolumeSeparatorChar ? OriginalPath : Path.CurrentDirectoryPrefix;
}
#region Transactional
/// <summary>[AlphaFS] Initializes a new instance of the <see cref="Alphaleonis.Win32.Filesystem.DirectoryInfo"/> class on the specified path.</summary>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The path on which to create the <see cref="Alphaleonis.Win32.Filesystem.DirectoryInfo"/>.</param>
/// <remarks>This constructor does not check if a directory exists. This constructor is a placeholder for a string that is used to access the disk in subsequent operations.</remarks>
public DirectoryInfo(KernelTransaction transaction, string path) : this(transaction, path, PathFormat.RelativePath)
{
}
/// <summary>[AlphaFS] Initializes a new instance of the <see cref="Alphaleonis.Win32.Filesystem.DirectoryInfo"/> class on the specified path.</summary>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The path on which to create the <see cref="Alphaleonis.Win32.Filesystem.DirectoryInfo"/>.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
/// <remarks>This constructor does not check if a directory exists. This constructor is a placeholder for a string that is used to access the disk in subsequent operations.</remarks>
public DirectoryInfo(KernelTransaction transaction, string path, PathFormat pathFormat)
{
InitializeCore(true, transaction, path, pathFormat);
}
#endregion // Transactional
#endregion // AlphaFS
#endregion // Constructors
#region Properties
#region .NET
#region Exists
/// <summary>Gets a value indicating whether the directory exists.</summary>
/// <remarks>
/// <para>The <see cref="Exists"/> property returns <see langword="false"/> if any error occurs while trying to determine if the
/// specified directory exists.</para>
/// <para>This can occur in situations that raise exceptions such as passing a directory name with invalid characters or too many
/// characters,</para>
/// <para>a failing or missing disk, or if the caller does not have permission to read the directory.</para>
/// </remarks>
/// <value><see langword="true"/> if the directory exists; otherwise, <see langword="false"/>.</value>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public override bool Exists
{
[SecurityCritical]
get
{
try
{
if (DataInitialised == -1)
Refresh();
FileAttributes attrs = Win32AttributeData.dwFileAttributes;
return DataInitialised == 0 && attrs != (FileAttributes) (-1) && (attrs & FileAttributes.Directory) != 0;
}
catch
{
return false;
}
}
}
#endregion // Exists
#region Name
/// <summary>Gets the name of this <see cref="DirectoryInfo"/> instance.</summary>
/// <value>The directory name.</value>
/// <remarks>
/// <para>This Name property returns only the name of the directory, such as "Bin".</para>
/// <para>To get the full path, such as "c:\public\Bin", use the FullName property.</para>
/// </remarks>
public override string Name
{
get
{
// GetDirName()
return FullPath.Length > 3
? Path.GetFileName(Path.RemoveTrailingDirectorySeparator(FullPath, false), true)
: FullPath;
}
}
#endregion // Name
#region Parent
/// <summary>Gets the parent directory of a specified subdirectory.</summary>
/// <value>The parent directory, or null if the path is null or if the file path denotes a root (such as "\", "C:", or * "\\server\share").</value>
public DirectoryInfo Parent
{
[SecurityCritical]
get
{
string path = FullPath;
if (path.Length > 3)
path = Path.RemoveTrailingDirectorySeparator(FullPath, false);
string dirName = Path.GetDirectoryName(path, false);
return dirName == null ? null : new DirectoryInfo(Transaction, dirName, true, true);
}
}
#endregion // Parent
#region Root
/// <summary>Gets the root portion of the directory.</summary>
/// <value>An object that represents the root of the directory.</value>
public DirectoryInfo Root
{
[SecurityCritical]
get { return new DirectoryInfo(Transaction, Path.GetPathRoot(FullPath, false), PathFormat.RelativePath); }
}
#endregion // Root
#endregion // .NET
#endregion // Properties
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*
* A Simple Framework to manage the life time of of objects
* Objects are required to implement LifeTime Interface in order to keep track of their lifetime.
* TODO: we need to add flexibility to the framework to control the type of datastructure used to keep track
* of the objects. Right now we are using a simple 1 D array , but other interesting datastructures can be
* used instead like a HashTable.
*/
using System;
using System.Collections.Generic;
namespace LifeTimeFX
{
public enum LifeTimeENUM
{
Short,
Medium,
Long
}
public interface LifeTime
{
LifeTimeENUM LifeTime
{
get;
set;
}
}
public interface LifeTimeStrategy
{
int NextObject(LifeTimeENUM lifeTime);
bool ShouldDie(LifeTime o, int index);
}
/// <summary>
/// This interfact abstract the object contaienr , allowing us to specify differnt datastructures
/// implementation.
/// The only restriction on the ObjectContainer is that the objects contained in it must implement
/// LifeTime interface.
/// Right now we have a simple array container as a stock implementation for that. for more information
/// see code:#ArrayContainer
/// </summary>
/// <param name="o"></param>
/// <param name="index"></param>
public interface ObjectContainer<T> where T:LifeTime
{
void Init(int numberOfObjects);
void AddObjectAt(T o, int index);
T GetObject(int index);
T SetObjectAt(T o , int index);
int Count
{
get;
}
}
public sealed class BinaryTreeObjectContainer<T> : ObjectContainer<T> where T:LifeTime
{
class Node
{
public Node LeftChild;
public Node RightChild;
public int id;
public T Data;
}
private Node root;
private int count;
public BinaryTreeObjectContainer()
{
root = null;
count = 0;
}
public void Init(int numberOfObjects)
{
if (numberOfObjects<=0)
{
return;
}
root = new Node();
root.id = 0;
count = numberOfObjects;
if (numberOfObjects>1)
{
int depth = (int)Math.Log(numberOfObjects,2)+1;
root.LeftChild = CreateTree(depth-1, 1);
root.RightChild = CreateTree(depth-1, 2);
}
}
public void AddObjectAt(T o, int index)
{
Node node = Find(index);
if (node!=null)
{
node.Data = o;
}
}
public T GetObject(int index)
{
Node node = Find(index);
if (node==null)
{
return default(T);
}
return node.Data;
}
public T SetObjectAt(T o , int index)
{
Node node = Find(index);
if (node==null)
{
return default(T);
}
T old = node.Data;
node.Data = o;
return old;
}
public int Count
{
get
{
return count;
}
}
private Node CreateTree(int depth, int id)
{
if (depth<=0)
{
return null;
}
Node node = new Node();
node.id = id;
node.LeftChild = CreateTree(depth-1, id*2+1);
node.RightChild = CreateTree(depth-1, id*2+2);
return node;
}
private Node Find(int id)
{
List<int> path = new List<int>();
// find the path from node to root
int n=id;
while (n>0)
{
path.Add(n);
n = (int)Math.Ceiling( ((double)n/2.0) ) - 1;
}
// follow the path from root to node
Node node = root;
for (int i=path.Count-1; i>=0; i--)
{
if (path[i]==(id*2+1))
{
node = node.LeftChild;
}
else
{
node = node.RightChild;
}
}
return node;
}
}
//#ArrayContainer Simple Array Stock Implemntation for ObjectContainer
public sealed class ArrayObjectContainer<T> : ObjectContainer<T> where T:LifeTime
{
private T[] objContainer = null;
public void Init(int numberOfObjects)
{
objContainer = new T[numberOfObjects];
}
public void AddObjectAt(T o, int index)
{
objContainer[index] = o;
}
public T GetObject(int index)
{
return objContainer[index];
}
public T SetObjectAt(T o, int index)
{
T old = objContainer[index];
objContainer[index] = o;
return old;
}
public int Count
{
get
{
return objContainer.Length;
}
}
}
public delegate void ObjectDiedEventHandler(LifeTime o, int index );
public sealed class ObjectLifeTimeManager
{
private LifeTimeStrategy strategy;
private ObjectContainer<LifeTime> objectContainer = null;
//
public void SetObjectContainer (ObjectContainer<LifeTime> objectContainer)
{
this.objectContainer = objectContainer;
}
public event ObjectDiedEventHandler objectDied;
public void Init(int numberObjects)
{
objectContainer.Init(numberObjects);
//objContainer = new object[numberObjects];
}
public LifeTimeStrategy LifeTimeStrategy
{
set
{
strategy = value;
}
}
public void AddObject(LifeTime o, int index)
{
objectContainer.AddObjectAt(o, index);
//objContainer[index] = o;
}
public void Run()
{
LifeTime objLifeTime;
for (int i = 0; i < objectContainer.Count; ++i)
{
objLifeTime = objectContainer.GetObject(i);
//object o = objContainer[i];
//objLifeTime = o as LifeTime;
if (strategy.ShouldDie(objLifeTime, i))
{
int index = strategy.NextObject(objLifeTime.LifeTime);
LifeTime oldObject = objectContainer.SetObjectAt(null, index);
//objContainer[index] = null;
// fire the event
objectDied(oldObject, index);
}
}
}
}
}
| |
// 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.CustomerInsights
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ConnectorsOperations operations.
/// </summary>
internal partial class ConnectorsOperations : IServiceOperations<CustomerInsightsManagementClient>, IConnectorsOperations
{
/// <summary>
/// Initializes a new instance of the ConnectorsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ConnectorsOperations(CustomerInsightsManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the CustomerInsightsManagementClient
/// </summary>
public CustomerInsightsManagementClient Client { get; private set; }
/// <summary>
/// Creates a connector or updates an existing connector in the hub.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='connectorName'>
/// The name of the connector.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate Connector operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ConnectorResourceFormat>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string hubName, string connectorName, ConnectorResourceFormat parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ConnectorResourceFormat> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, hubName, connectorName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a connector in the hub.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='connectorName'>
/// The name of the connector.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ConnectorResourceFormat>> GetWithHttpMessagesAsync(string resourceGroupName, string hubName, string connectorName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (hubName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "hubName");
}
if (connectorName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "connectorName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("hubName", hubName);
tracingParameters.Add("connectorName", connectorName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/connectors/{connectorName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{hubName}", System.Uri.EscapeDataString(hubName));
_url = _url.Replace("{connectorName}", System.Uri.EscapeDataString(connectorName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ConnectorResourceFormat>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ConnectorResourceFormat>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a connector in the hub.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='connectorName'>
/// The name of the connector.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string hubName, string connectorName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, hubName, connectorName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all the connectors in the specified hub.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ConnectorResourceFormat>>> ListByHubWithHttpMessagesAsync(string resourceGroupName, string hubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (hubName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "hubName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("hubName", hubName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByHub", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/connectors").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{hubName}", System.Uri.EscapeDataString(hubName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ConnectorResourceFormat>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ConnectorResourceFormat>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates a connector or updates an existing connector in the hub.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='connectorName'>
/// The name of the connector.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate Connector operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ConnectorResourceFormat>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string hubName, string connectorName, ConnectorResourceFormat parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (hubName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "hubName");
}
if (connectorName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "connectorName");
}
if (connectorName != null)
{
if (connectorName.Length > 128)
{
throw new ValidationException(ValidationRules.MaxLength, "connectorName", 128);
}
if (connectorName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "connectorName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(connectorName, "^[a-zA-Z][a-zA-Z0-9_]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "connectorName", "^[a-zA-Z][a-zA-Z0-9_]+$");
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("hubName", hubName);
tracingParameters.Add("connectorName", connectorName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/connectors/{connectorName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{hubName}", System.Uri.EscapeDataString(hubName));
_url = _url.Replace("{connectorName}", System.Uri.EscapeDataString(connectorName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ConnectorResourceFormat>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ConnectorResourceFormat>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a connector in the hub.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='connectorName'>
/// The name of the connector.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string hubName, string connectorName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (hubName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "hubName");
}
if (connectorName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "connectorName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("hubName", hubName);
tracingParameters.Add("connectorName", connectorName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/connectors/{connectorName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{hubName}", System.Uri.EscapeDataString(hubName));
_url = _url.Replace("{connectorName}", System.Uri.EscapeDataString(connectorName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the connectors in the specified hub.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ConnectorResourceFormat>>> ListByHubNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByHubNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ConnectorResourceFormat>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ConnectorResourceFormat>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraTreeList.Nodes;
using bv.common.Configuration;
using bv.common.Diagnostics;
using bv.common.Resources;
using bv.model.Model.Core;
using bv.winclient.BasePanel.ListPanelComponents;
using bv.winclient.Core;
using DevExpress.LookAndFeel;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Mask;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraNavBar;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraTab;
using DevExpress.XtraTreeList;
namespace bv.winclient.Localization
{
public static class DxControlsHelper
{
/// <summary>
///
/// </summary>
public static void InitDefaultFont()
{
if (!AppearanceObject.DefaultFont.Equals(WinClientContext.CurrentFont))
{
AppearanceObject.DefaultFont = WinClientContext.CurrentFont;
AppearanceObject.ControlAppearance.Font = WinClientContext.CurrentFont;
}
}
/// <summary>
///
/// </summary>
/// <param name="controller"></param>
public static void InitStyleController(this StyleController controller)
{
InitDefaultFont();
InitAppearance(controller.Appearance);
InitAppearance(controller.AppearanceDisabled);
InitAppearance(controller.AppearanceDropDown);
InitAppearance(controller.AppearanceDropDownHeader);
InitAppearance(controller.AppearanceFocused);
InitAppearance(controller.AppearanceReadOnly);
}
/// <summary>
///
/// </summary>
/// <param name="controller"></param>
public static void InitTooltipController(this DefaultToolTipController controller)
{
InitDefaultFont();
InitAppearance(controller.DefaultController.Appearance);
InitAppearance(controller.DefaultController.AppearanceTitle);
}
/// <summary>
///
/// </summary>
/// <param name="appearance"></param>
public static void InitAppearance(this AppearanceObject appearance)
{
bool bold = appearance.Font.Bold;
if (bold)
appearance.Font = WinClientContext.CurrentBoldFont;
else
appearance.Font = WinClientContext.CurrentFont;
appearance.Options.UseFont = true;
}
/// <summary>
///
/// </summary>
/// <param name="grid"></param>
/// <param name="showDateTimeFormatAsNullText"></param>
public static void InitXtraGridAppearance(this GridControl grid, bool showDateTimeFormatAsNullText)
{
grid.MainView.BeginUpdate();
InitDefaultFont();
if (grid.MainView is GridView)
{
var view = (GridView)grid.MainView;
view.OptionsFilter.AllowColumnMRUFilterList = false;
view.OptionsFilter.AllowMRUFilterList = false;
var isOldFramework = !(grid.Parent is BaseListGridControl);
if (isOldFramework)
{
view.OptionsMenu.EnableColumnMenu = false;
view.OptionsCustomization.AllowQuickHideColumns = false;
view.OptionsCustomization.AllowColumnMoving = false;
}
view.OptionsMenu.EnableFooterMenu = false;
view.OptionsMenu.EnableGroupPanelMenu = false;
view.InvalidRowException -= InvalidRowException;
view.InvalidRowException += InvalidRowException;
}
foreach (GridColumn col in ((GridView)grid.MainView).Columns)
{
if (col.ColumnEdit == null)
{
continue;
}
if ((col.ColumnEdit) is RepositoryItemLookUpEdit)
{
InitRepositoryLookupItemAppearance((RepositoryItemLookUpEdit)col.ColumnEdit);
}
else
{
InitReposiroryItemAppearance(col.ColumnEdit);
var edit = col.ColumnEdit as RepositoryItemDateEdit;
if (edit != null)
{
InitRepositoryDateEdit(edit, showDateTimeFormatAsNullText);
}
}
}
foreach (AppearanceObject apperance in grid.MainView.Appearance)
{
InitAppearance(apperance);
}
foreach (GridColumn col in ((GridView)grid.MainView).Columns)
{
InitAppearance(col.AppearanceCell);
InitAppearance(col.AppearanceHeader);
}
grid.MainView.EndUpdate();
}
private static void InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
{
e.WindowCaption = BvMessages.Get("Warning");
}
/// <summary>
///
/// </summary>
/// <param name="tree"></param>
/// <param name="showDateTimeFormatAsNullText"></param>
public static void InitXtraTreeAppearance(this TreeList tree, bool showDateTimeFormatAsNullText)
{
tree.BeginUpdate();
InitDefaultFont();
tree.Font = WinClientContext.CurrentFont; //
tree.LookAndFeel.UseDefaultLookAndFeel = true;
tree.LookAndFeel.Style = LookAndFeelStyle.Skin;
foreach (RepositoryItem item in tree.RepositoryItems)
{
if (item is RepositoryItemLookUpEdit)
{
InitRepositoryLookupItemAppearance((RepositoryItemLookUpEdit)item);
}
else
{
InitReposiroryItemAppearance(item);
if (item is RepositoryItemDateEdit)
{
if (showDateTimeFormatAsNullText)
{
item.NullText = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
}
if (((RepositoryItemDateEdit)item).MinValue == DateTime.MinValue)
{
((RepositoryItemDateEdit)item).MinValue = new DateTime(1900, 1, 1);
}
if (((RepositoryItemDateEdit)item).MaxValue == DateTime.MinValue)
{
((RepositoryItemDateEdit)item).MaxValue = new DateTime(2050, 1, 1);
}
}
}
}
foreach (AppearanceObject apperance in tree.Appearance)
{
InitAppearance(apperance);
}
tree.EndUpdate();
}
/// <summary>
///
/// </summary>
/// <param name="page"></param>
public static void InitXtraTabAppearance(this XtraTabPage page)
{
InitDefaultFont();
page.Font = WinClientContext.CurrentFont; //
InitAppearance(page.Appearance.Header);
InitAppearance(page.Appearance.HeaderActive);
InitAppearance(page.Appearance.HeaderHotTracked);
InitAppearance(page.Appearance.HeaderDisabled);
}
public static void InitXtraTabControlAppearance(this XtraTabControl tab)
{
InitDefaultFont();
tab.Font = WinClientContext.CurrentFont; //
InitAppearance(tab.Appearance);
InitAppearance(tab.AppearancePage.Header);
InitAppearance(tab.AppearancePage.HeaderHotTracked);
InitAppearance(tab.AppearancePage.HeaderDisabled);
}
/// <summary>
///
/// </summary>
/// <param name="group"></param>
public static void InitRadioGroupAppearance(this RadioGroup group)
{
InitDefaultFont();
InitAppearance(group.Properties.Appearance);
InitAppearance(group.Properties.AppearanceDisabled);
InitAppearance(group.Properties.AppearanceFocused);
InitAppearance(group.Properties.AppearanceReadOnly);
}
/// <summary>
///
/// </summary>
/// <param name="edit"></param>
public static void InitCheckEditAppearance(this CheckEdit edit)
{
InitDefaultFont();
edit.Font = WinClientContext.CurrentFont;
InitAppearance(edit.Properties.Appearance);
InitAppearance(edit.Properties.AppearanceDisabled);
InitAppearance(edit.Properties.AppearanceFocused);
InitAppearance(edit.Properties.AppearanceReadOnly);
edit.Properties.AllowFocused = true;
edit.Properties.FullFocusRect = true;
//edit.Properties.CheckStyle = CheckStyles.Style1;
if (string.IsNullOrWhiteSpace(edit.Text))
edit.Properties.FullFocusRect = true;
}
/// <summary>
///
/// </summary>
/// <param name="ctl"></param>
public static void InitRepositoryLookupItemAppearance(this RepositoryItemLookUpEdit ctl)
{
InitDefaultFont();
InitAppearance(ctl.Appearance);
InitAppearance(ctl.AppearanceDisabled);
InitAppearance(ctl.AppearanceDropDown);
InitAppearance(ctl.AppearanceDropDownHeader);
InitAppearance(ctl.AppearanceFocused);
if (ctl.ShowDropDown != ShowDropDown.Never)
{
if (BaseSettings.InplaceShowDropDown == "DoubleClick")
{
ctl.ShowDropDown = ShowDropDown.DoubleClick;
}
else
{
ctl.ShowDropDown = ShowDropDown.SingleClick;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="ctl"></param>
/// <param name="force"></param>
public static void SetPopupControlBehavior(this PopupBaseEdit ctl, bool force)
{
if (force || ctl.Properties.ShowDropDown != ShowDropDown.Never)
{
if (BaseSettings.ShowDropDown == "DoubleClick")
{
ctl.Properties.ShowDropDown = ShowDropDown.DoubleClick;
}
else
{
ctl.Properties.ShowDropDown = ShowDropDown.SingleClick;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="ctl"></param>
public static void InitReposiroryItemAppearance(this RepositoryItem ctl)
{
InitDefaultFont();
InitAppearance(ctl.Appearance);
InitAppearance(ctl.AppearanceDisabled);
InitAppearance(ctl.AppearanceFocused);
}
/// <summary>
///
/// </summary>
/// <param name="ctl"></param>
public static void InitGroupControlAppearance(this GroupControl ctl)
{
InitDefaultFont();
InitAppearance(ctl.Appearance);
InitAppearance(ctl.AppearanceCaption);
ctl.AppearanceCaption.Reset();
ctl.Appearance.Reset();
ctl.LookAndFeel.Style = LookAndFeelStyle.Skin;
ctl.LookAndFeel.UseDefaultLookAndFeel = true;
}
public static void InitBarAppearance(this DefaultBarAndDockingController controller)
{
InitDefaultFont();
InitAppearance(controller.Controller.AppearancesBar.Bar);
InitAppearance(controller.Controller.AppearancesBar.Dock);
InitAppearance(controller.Controller.AppearancesBar.MainMenu);
InitAppearance(controller.Controller.AppearancesBar.StatusBar);
InitAppearance(controller.Controller.AppearancesBar.SubMenu.Menu);
InitAppearance(controller.Controller.AppearancesBar.SubMenu.MenuBar);
InitAppearance(controller.Controller.AppearancesBar.SubMenu.SideStrip);
InitAppearance(controller.Controller.AppearancesBar.SubMenu.SideStripNonRecent);
InitAppearance(controller.Controller.AppearancesDocking.ActiveTab);
InitAppearance(controller.Controller.AppearancesDocking.FloatFormCaption);
InitAppearance(controller.Controller.AppearancesDocking.FloatFormCaptionActive);
InitAppearance(controller.Controller.AppearancesDocking.HideContainer);
InitAppearance(controller.Controller.AppearancesDocking.HidePanelButton);
InitAppearance(controller.Controller.AppearancesDocking.HidePanelButtonActive);
InitAppearance(controller.Controller.AppearancesDocking.Panel);
InitAppearance(controller.Controller.AppearancesDocking.PanelCaption);
InitAppearance(controller.Controller.AppearancesDocking.PanelCaptionActive);
InitAppearance(controller.Controller.AppearancesDocking.Tabs);
controller.Controller.AppearancesBar.ItemsFont = WinClientContext.CurrentFont;
//New System.Drawing.Font(m_DefaultFontFamily, m_DefaultFontSize)
}
/// <summary>
///
/// </summary>
/// <param name="grid"></param>
public static void InitPivotGridAppearance(this PivotGridControl grid)
{
InitDefaultFont();
foreach (RepositoryItem item in grid.RepositoryItems)
{
if (item is RepositoryItemLookUpEdit)
{
InitRepositoryLookupItemAppearance((RepositoryItemLookUpEdit)item);
}
else
{
InitReposiroryItemAppearance(item);
}
}
foreach (AppearanceObject apperance in grid.Appearance)
{
InitAppearance(apperance);
}
foreach (AppearanceObject apperance in grid.AppearancePrint)
{
InitAppearance(apperance);
}
foreach (AppearanceObject apperance in grid.PaintAppearance)
{
InitAppearance(apperance);
}
foreach (AppearanceObject apperance in grid.PaintAppearancePrint)
{
InitAppearance(apperance);
}
}
/// <summary>
///
/// </summary>
/// <param name="bar"></param>
public static void InitNavAppearance(this NavBarControl bar)
{
InitDefaultFont();
foreach (AppearanceObject apperance in bar.Appearance)
{
InitAppearance(apperance);
}
foreach (NavBarGroup group in bar.Groups)
{
InitAppearance(group.Appearance);
InitAppearance(group.AppearanceBackground);
InitAppearance(group.AppearanceHotTracked);
InitAppearance(group.AppearancePressed);
}
}
/// <summary>
///
/// </summary>
/// <param name="cbFont"></param>
public static void InitFontItems(ImageComboBoxEdit cbFont)
{
const int width = 20;
const int height = 16;
const int offset = 1;
var il = new ImageList { ImageSize = new Size(width, height) };
var r = new Rectangle(offset, offset, width - offset * 2, height - offset * 2);
cbFont.Properties.BeginUpdate();
try
{
cbFont.Properties.Items.Clear();
cbFont.Properties.SmallImages = il;
int i;
int j = 0;
for (i = 0; i <= FontFamily.Families.Length - 1; i++)
{
try
{
var f = new Font(FontFamily.Families[i].Name, 8);
string s = (FontFamily.Families[i].Name);
var im = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(im))
{
g.FillRectangle(Brushes.White, r);
g.DrawString("abc", f, Brushes.Black, offset, offset);
g.DrawRectangle(Pens.Black, r);
}
il.Images.Add(im);
cbFont.Properties.Items.Add(new ImageComboBoxItem(s, f, j));
j++;
}
catch (Exception ex)
{
Dbg.Debug("font items creation error:{0}", ex.ToString());
}
}
}
finally
{
cbFont.Properties.CancelUpdate();
}
}
/// <summary>
///
/// </summary>
/// <param name="cbFont"></param>
/// <param name="fontName"></param>
/// <returns></returns>
public static ImageComboBoxItem FindFontItem(ImageComboBoxEdit cbFont, string fontName)
{
return cbFont.Properties.Items.Cast<ImageComboBoxItem>().FirstOrDefault(item => item.Description == fontName);
}
/// <summary>
///
/// </summary>
/// <param name="cbFontSize"></param>
/// <param name="fontSize"></param>
/// <returns></returns>
public static object FindFontSizeItem(ComboBoxEdit cbFontSize, float fontSize)
{
return cbFontSize.Properties.Items.Cast<string>().FirstOrDefault(item => fontSize.ToString().StartsWith(item));
}
/// <summary>
///
/// </summary>
/// <param name="view"></param>
/// <param name="row"></param>
/// <param name="pkColName"></param>
public static void SetRowHandleForDataRow(GridView view, DataRow row, string pkColName)
{
for (int i = 0; i <= view.RowCount - 1; i++)
{
var gridRow = view.GetDataRow(i);
if (gridRow[pkColName].Equals(row[pkColName]))
{
view.FocusedRowHandle = i;
break;
}
}
view.Focus();
}
public static bool SetRowHandleForDataRow(TreeList list, TreeListNodes nodes, DataRow row, string pkColName)
{
if (nodes == null)
nodes = list.Nodes;
if (nodes == null)
return false;
foreach (TreeListNode node in nodes)
{
var gridRow = list.GetDataRecordByNode(node) as DataRowView;
if (gridRow != null && gridRow[pkColName].Equals(row[pkColName]))
{
list.FocusedNode = node;
list.Focus();
return true;
}
if (SetRowHandleForDataRow(list, node.Nodes, row, pkColName))
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void OnSpinEditEditValueChanging(Object sender, ChangingEventArgs e)
{
var ctl = (SpinEdit)sender;
if (ctl.Properties.MinValue != 0 || ctl.Properties.MaxValue != 0)
{
e.Cancel = Convert.ToBoolean(ctl.Value < ctl.Properties.MinValue || ctl.Value > ctl.Properties.MaxValue);
}
}
/// <summary>
///
/// </summary>
/// <param name="ctl"></param>
public static void HidePlusButton(this ButtonEdit ctl)
{
foreach (EditorButton btn in ctl.Properties.Buttons)
{
if (btn.Kind == ButtonPredefines.Plus)
{
btn.Visible = false;
break;
}
}
}
public static void SetButtonTooltip(this EditorButtonCollection buttons, ButtonPredefines kind, string tooltip)
{
foreach (EditorButton btn in buttons)
{
if (btn.Kind == kind)
{
btn.ToolTip = tooltip;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="ctl"></param>
public static void HidePlusButton(this RepositoryItemButtonEdit ctl)
{
foreach (EditorButton btn in ctl.Buttons)
{
if (btn.Kind == ButtonPredefines.Plus)
{
btn.Visible = false;
break;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="ctl"></param>
/// <param name="enabled"></param>
public static void EnableButtons(this ButtonEdit ctl, bool enabled)
{
foreach (EditorButton btn in ctl.Properties.Buttons)
{
btn.Enabled = enabled;
}
}
public static void SetButtonsVisibility(this ButtonEdit ctl, bool visible)
{
foreach (EditorButton btn in ctl.Properties.Buttons)
{
btn.Visible = visible;
}
}
/// <summary>
///
/// </summary>
/// <param name="ctl"></param>
/// <param name="enabled"></param>
public static void EnableButtons(this RepositoryItemButtonEdit ctl, bool enabled)
{
foreach (EditorButton btn in ctl.Buttons)
{
btn.Enabled = enabled;
}
}
/// <summary>
///
/// </summary>
/// <param name="editorMask"></param>
public static void SetEnglishEditorMask(this MaskProperties editorMask)
{
editorMask.MaskType = MaskType.RegEx;
editorMask.EditMask = @"[a-zA-Z0-9\+\-\ \(\)\.\,\;\_\/\>\<\=\&\!\@\#\%\^\&\*\~\?]*";
editorMask.BeepOnError = true;
}
public static void SetGridConstraints(GridControl grid, IObjectMeta meta = null)
{
foreach (var view in grid.Views)
{
SetGridViewConstraints(view as GridView, meta);
}
}
public static void SetGridViewConstraints(GridView grid, IObjectMeta meta = null)
{
if (grid == null || grid.GridControl.DataSource == null || !grid.OptionsBehavior.Editable || grid.OptionsBehavior.ReadOnly)
return;
DataTable table = null;
if (grid.GridControl.DataSource is DataView)
table = ((DataView)grid.GridControl.DataSource).Table;
else if (grid.GridControl.DataSource is DataTable)
table = (DataTable)grid.GridControl.DataSource;
if(table == null && meta == null)
{
return;
}
foreach (GridColumn col in grid.Columns)
{
if (!string.IsNullOrEmpty(col.FieldName))
{
int? len = 0;
if (meta != null)
len = meta.MaxSize(col.FieldName);
else
len = GetFieldLength(table, col.FieldName);
if (len.HasValue && len.Value > 0 && col.OptionsColumn.AllowEdit && !col.OptionsColumn.ReadOnly)
{
if (col.ColumnEdit == null)
col.ColumnEdit = GetTextColumnEdit(len.Value);
else if (col.ColumnEdit is RepositoryItemTextEdit)
((RepositoryItemTextEdit)col.ColumnEdit).MaxLength = len.Value;
}
}
}
}
public static int GetFieldLength( DataTable table, string fieldName)
{
DataColumn col = table.Columns[fieldName];
if(col ==null)
return 0;
if (col.DataType == typeof(string) && col.MaxLength > 0 )
return col.MaxLength;
return 0;
}
public static RepositoryItemTextEdit GetTextColumnEdit(int len)
{
return new RepositoryItemTextEdit() { MaxLength = len };
}
public static void InitDateEdit(DateEdit dateEdit)
{
if (BaseSettings.ShowDateTimeFormatAsNullText)
{
dateEdit.Properties.NullText = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
}
if (dateEdit.Properties.MinValue == DateTime.MinValue)
{
dateEdit.Properties.MinValue = new DateTime(1900, 1, 1);
}
if (dateEdit.Properties.MaxValue == DateTime.MinValue)
{
dateEdit.Properties.MaxValue = new DateTime(2050, 1, 1);
}
}
public static void InitRepositoryDateEdit(RepositoryItemDateEdit dateEdit, bool showDateTimeFormatAsNullText)
{
if (showDateTimeFormatAsNullText)
{
dateEdit.NullText = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
}
if (dateEdit.MinValue == DateTime.MinValue)
{
dateEdit.MinValue = new DateTime(1900, 1, 1);
}
if (dateEdit.MaxValue == DateTime.MinValue)
{
dateEdit.MaxValue = new DateTime(2050, 1, 1);
}
}
private static void SetButtonEditButtonVisibility(ButtonEdit edit, ButtonPredefines buttonKind, bool visible)
{
foreach (EditorButton button in edit.Properties.Buttons)
{
if (button.Kind == buttonKind)
{
button.Visible = visible;
return;
}
}
}
public static void HideButtonEditButton(ButtonEdit edit, ButtonPredefines buttonKind)
{
SetButtonEditButtonVisibility(edit, buttonKind, false);
}
public static void ShowButtonEditButton(ButtonEdit edit, ButtonPredefines buttonKind)
{
SetButtonEditButtonVisibility(edit, buttonKind, true);
}
private static void SetButtonEditButtonEnabledState(ButtonEdit edit, ButtonPredefines buttonKind, bool enabled)
{
foreach (EditorButton button in edit.Properties.Buttons)
{
if (button.Kind == buttonKind)
{
button.Visible = enabled;
return;
}
}
}
public static void EnableButtonEditButton(ButtonEdit edit, ButtonPredefines buttonKind)
{
SetButtonEditButtonEnabledState(edit, buttonKind, true);
}
public static void DisableButtonEditButton(ButtonEdit edit, ButtonPredefines buttonKind)
{
SetButtonEditButtonEnabledState(edit, buttonKind, false);
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.IO;
using System.Collections;
using System.Globalization;
using Xunit;
public class File_Copy_str_str_b
{
public static String s_strActiveBugNums = "";
public static String s_strDtTmVer = "2000/03/11 14:37";
public static String s_strClassMethod = "File.CopyTo(String, Boolean)";
public static String s_strTFName = "Copy_str_str_b.cool";
public static String s_strTFPath = Directory.GetCurrentDirectory();
[Fact]
public static void runTest()
{
int iCountErrors = 0;
int iCountTestcases = 0;
String strLoc = "Loc_000oo";
String strValue = String.Empty;
String filName = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName());
try
{
///////////////////////// START TESTS ////////////////////////////
///////////////////////////////////////////////////////////////////
FileInfo fil2 = null;
FileInfo fil1 = null;
Char[] cWriteArr, cReadArr;
StreamWriter sw2;
StreamReader sr2;
FileStream fs2;
try
{
new FileInfo(filName).Delete();
}
catch (Exception) { }
// [] ArgumentNullException if null is passed in for source file
strLoc = "Loc_498yg";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(null, fil2.FullName, false);
iCountErrors++;
printerr("Error_209uz! Expected exception not thrown, fil2==" + fil1.FullName);
fil1.Delete();
}
catch (ArgumentNullException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_21x99! Incorrect exception thrown, exc==" + exc.ToString());
}
fil2.Delete();
// [] ArgumentNullException if null is passed in for destination file
strLoc = "Loc_898gc";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(fil2.FullName, null, false);
iCountErrors++;
printerr("Error_8yt85! Expected exception not thrown");
}
catch (ArgumentNullException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_1298s! Incorrect exception thrown, exc==" + exc.ToString());
}
// [] String.Empty should throw ArgumentException
strLoc = "Loc_298vy";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(fil2.FullName, String.Empty, false);
iCountErrors++;
printerr("Error_092u9! Expected exception not thrown, fil2==" + fil1.FullName);
}
catch (ArgumentException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_109uc! Incorrect exception thrown, exc==" + exc.ToString());
}
fil2.Delete();
// [] Try to copy onto directory
strLoc = "Loc_289vy";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(fil2.FullName, TestInfo.CurrentDirectory, false);
iCountErrors++;
printerr("Error_301ju! Expected exception not thrown, fil2==" + fil1.FullName);
}
catch (IOException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_23r78af! Incorrect exception thrown, exc==" + exc.ToString());
}
fil2.Delete();
// [] Copy onto itself should fail
strLoc = "Loc_r7yd9";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(fil2.FullName, fil2.FullName, false);
iCountErrors++;
printerr("Error_2387ag! Expected exception not thrown, fil2==" + fil1.FullName);
}
catch (IOException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_f588y! Unexpected exception thrown, exc==" + exc.ToString());
}
fil2.Delete();
// [] Vanilla copy operation
strLoc = "Loc_f548y";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
string destFile = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName());
try
{
File.Copy(fil2.FullName, destFile, false);
fil1 = new FileInfo(destFile);
if (!File.Exists(fil1.FullName))
{
iCountErrors++;
printerr("Error_2978y! File not copied");
}
if (!File.Exists(fil2.FullName))
{
iCountErrors++;
printerr("Error_239vr! Source file gone");
}
fil1.Delete();
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_2987v! Unexpected exception, exc==" + exc.ToString());
}
fil2.Delete();
fil1.Delete();
// [] Filename with illiegal characters
strLoc = "Loc_984hg";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(fil2.FullName, "*\0*", false);
iCountErrors++;
printerr("Error_298xh! Expected exception not thrown, fil2==" + fil1.FullName);
fil1.Delete();
}
catch (ArgumentException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_2091s! Incorrect exception thrown, exc==" + exc.ToString());
}
fil2.Delete();
// [] Move a file containing data
strLoc = "Loc_f888m";
try
{
new FileInfo(destFile).Delete();
}
catch (Exception) { }
try
{
sw2 = new StreamWriter(File.Create(filName));
cWriteArr = new Char[26];
int j = 0;
for (Char i = 'A'; i <= 'Z'; i++)
cWriteArr[j++] = i;
sw2.Write(cWriteArr, 0, cWriteArr.Length);
sw2.Flush();
sw2.Dispose();
fil2 = new FileInfo(filName);
File.Copy(fil2.FullName, destFile, false);
fil1 = new FileInfo(destFile);
iCountTestcases++;
if (!File.Exists(fil1.FullName))
{
iCountErrors++;
printerr("Error_9u99s! File not copied correctly: " + fil1.FullName);
}
if (!File.Exists(fil2.FullName))
{
iCountErrors++;
printerr("Error_29h7b! Source file gone");
}
FileStream fs = new FileStream(destFile, FileMode.Open);
sr2 = new StreamReader(fs);
cReadArr = new Char[cWriteArr.Length];
sr2.Read(cReadArr, 0, cReadArr.Length);
iCountTestcases++;
for (int i = 0; i < cReadArr.Length; i++)
{
iCountTestcases++;
if (cReadArr[i] != cWriteArr[i])
{
iCountErrors++;
printerr("Error_98yv7! Expected==" + cWriteArr[i] + ", got value==" + cReadArr[i]);
}
}
sr2.Dispose();
fs.Dispose();
fil1.Delete();
fil2.Delete();
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_28vc8! Unexpected exception, exc==" + exc.ToString());
}
/* Scenario disabled while porting because it accesses a file outside the test's working directory
#if !TEST_WINRT // Cannot access root
// [] Unecessary long but valid string
strLoc = "Loc_478yb";
File.Delete("\\TestFile.tmp");
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
File.Copy(fil2.Name, "..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\TestFile.tmp", false);
fil1 = new FileInfo(fil2.FullName.Substring(0, fil2.FullName.IndexOf("\\") + 1) + fil2.Name);
iCountTestcases++;
if (!fil1.FullName.Equals(fil2.FullName.Substring(0, fil2.FullName.IndexOf("\\") + 1) + fil2.Name))
{
Console.WriteLine(fil1.FullName);
iCountErrors++;
printerr("Error_298gc! Incorrect fullname set during copy");
}
new FileInfo(filName).Delete();
fil1.Delete();
File.Delete("\\TestFile.tmp");
#endif
*/
// [] Copy over a file that already exists
strLoc = "Loc_37tgy";
destFile = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName());
fs2 = new FileStream(filName, FileMode.Create);
sw2 = new StreamWriter(fs2);
for (Char i = (Char)65; i < (Char)75; i++)
sw2.Write(i);
sw2.Flush();
sw2.Dispose();
fs2 = new FileStream(destFile, FileMode.Create);
sw2 = new StreamWriter(fs2);
for (Char i = (Char)74; i >= (Char)65; i--)
sw2.Write(i);
sw2.Flush();
sw2.Dispose();
fil2 = new FileInfo(destFile);
File.Copy(fil2.FullName, Path.ChangeExtension(destFile, ".tmp"), true);
fil1 = new FileInfo(Path.ChangeExtension(destFile, ".tmp"));
fil2.Delete();
FileStream fs3 = new FileStream(filName, FileMode.Open);
sr2 = new StreamReader(fs3);
int tmp = 0;
for (Char i = (Char)65; i < (Char)75; i++)
{
iCountTestcases++;
if ((tmp = sr2.Read()) != i)
{
iCountErrors++;
printerr("Error_498vy! Expected==" + i + ", got==" + tmp);
}
}
sr2.Dispose();
fs3.Dispose();
fil2.Delete();
fil1.Delete();
File.Delete(destFile);
File.Delete(filName);
///////////////////////////////////////////////////////////////////
/////////////////////////// END TESTS /////////////////////////////
}
catch (Exception exc_general)
{
++iCountErrors;
Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString());
}
//// Finish Diagnostics
if (iCountErrors != 0)
{
Console.WriteLine("FAiL! " + s_strTFName + " ,iCountErrors==" + iCountErrors.ToString());
}
FailSafeDirectoryOperations.DeleteDirectory(filName, true);
Assert.Equal(0, iCountErrors);
}
public static void printerr(String err, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
{
Console.WriteLine("ERROR: ({0}, {1}, {2}) {3}", memberName, filePath, lineNumber, err);
}
}
| |
// Copyright (C) 2009-2017 Luca Piccioni
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// ReSharper disable InheritdocConsiderUsage
// ReSharper disable ConvertIfStatementToReturnStatement
namespace OpenGL
{
/// <summary>
/// List of pixel format descriptions.
/// </summary>
[DebuggerDisplay("DevicePixelFormatCollection: Count={" + nameof(Count) + "}")]
public class DevicePixelFormatCollection : List<DevicePixelFormat>
{
/// <summary>
/// Choose a <see cref="DevicePixelFormat"/>
/// </summary>
/// <param name="pixelFormat">
/// A <see cref="DevicePixelFormat"/> that specify the minimum requirements
/// </param>
/// <returns></returns>
public List<DevicePixelFormat> Choose(DevicePixelFormat pixelFormat)
{
if (pixelFormat == null)
throw new ArgumentNullException(nameof(pixelFormat));
List<DevicePixelFormat> pixelFormats = new List<DevicePixelFormat>(this);
pixelFormats.RemoveAll(delegate (DevicePixelFormat item) {
if (pixelFormat.RgbaUnsigned != item.RgbaUnsigned)
return true;
if (pixelFormat.RgbaFloat != item.RgbaFloat)
return true;
if (pixelFormat.RenderWindow && !item.RenderWindow)
return true;
if (pixelFormat.RenderPBuffer && !item.RenderPBuffer)
return true;
if (pixelFormat.RenderBuffer && !item.RenderBuffer)
return true;
if (item.ColorBits < pixelFormat.ColorBits)
return true;
if (item.RedBits < pixelFormat.RedBits)
return true;
if (item.GreenBits < pixelFormat.GreenBits)
return true;
if (item.BlueBits < pixelFormat.BlueBits)
return true;
if (item.AlphaBits < pixelFormat.AlphaBits)
return true;
if (item.DepthBits < pixelFormat.DepthBits)
return true;
if (item.StencilBits < pixelFormat.StencilBits)
return true;
if (item.MultisampleBits < pixelFormat.MultisampleBits)
return true;
if (pixelFormat.DoubleBuffer && !item.DoubleBuffer)
return true;
if (pixelFormat.SRGBCapable && !item.SRGBCapable)
return true;
return false;
});
List<DevicePixelFormat> pixelFormatsCopy = pixelFormats.Select(devicePixelFormat => devicePixelFormat.Copy()).ToList();
// Sort (ascending by resource occupation)
pixelFormatsCopy.Sort(delegate (DevicePixelFormat x, DevicePixelFormat y) {
int compare;
if ((compare = x.ColorBits.CompareTo(y.ColorBits)) != 0)
return compare;
if ((compare = x.DepthBits.CompareTo(y.DepthBits)) != 0)
return compare;
if ((compare = x.StencilBits.CompareTo(y.StencilBits)) != 0)
return compare;
if ((compare = x.MultisampleBits.CompareTo(y.MultisampleBits)) != 0)
return compare;
if ((compare = y.DoubleBuffer.CompareTo(x.DoubleBuffer)) != 0)
return compare;
return 0;
});
return pixelFormatsCopy;
}
/// <summary>
/// Try to guess why <see cref="Choose(DevicePixelFormat)"/> is not returning any pixel format.
/// </summary>
/// <param name="pixelFormat">
/// A <see cref="DevicePixelFormat"/> that specify the minimum requirements
/// </param>
/// <returns>
/// It returns a string indicating the actual reason behind a failure in pixel format selection using <paramref name="pixelFormat"/>.
/// </returns>
public string GuessChooseError(DevicePixelFormat pixelFormat)
{
if (pixelFormat == null)
throw new ArgumentNullException(nameof(pixelFormat));
List<DevicePixelFormat> pixelFormats = new List<DevicePixelFormat>(this);
pixelFormats.RemoveAll(delegate (DevicePixelFormat item) {
if (pixelFormat.RgbaUnsigned != item.RgbaUnsigned)
return true;
if (pixelFormat.RgbaFloat != item.RgbaFloat)
return true;
return false;
});
if (pixelFormats.Count == 0)
return $"no RGBA pixel type matching (RGBAui={pixelFormat.RgbaUnsigned}, RGBAf={pixelFormat.RgbaFloat})";
pixelFormats.RemoveAll(delegate (DevicePixelFormat item) {
if (pixelFormat.RenderWindow && !item.RenderWindow)
return true;
if (pixelFormat.RenderPBuffer && !item.RenderPBuffer)
return true;
if (pixelFormat.RenderBuffer && !item.RenderBuffer)
return true;
return false;
});
if (pixelFormats.Count == 0)
return
$"no surface matching (Window={pixelFormat.RenderWindow}, PBuffer={pixelFormat.RenderPBuffer}, RenderBuffer={pixelFormat.RenderBuffer})";
pixelFormats.RemoveAll(delegate (DevicePixelFormat item) {
if (item.ColorBits < pixelFormat.ColorBits)
return true;
if (item.RedBits < pixelFormat.RedBits)
return true;
if (item.GreenBits < pixelFormat.GreenBits)
return true;
if (item.BlueBits < pixelFormat.BlueBits)
return true;
if (item.AlphaBits < pixelFormat.AlphaBits)
return true;
return false;
});
if (pixelFormats.Count == 0)
return
$"no color bits combination matching ({pixelFormat.ColorBits} bits, {{{pixelFormat.RedBits}|{pixelFormat.BlueBits}|{pixelFormat.GreenBits}|{pixelFormat.AlphaBits}}})";
pixelFormats.RemoveAll(item => item.DepthBits < pixelFormat.DepthBits);
if (pixelFormats.Count == 0)
return $"no depth bits matching (Depth >= {pixelFormat.DepthBits})";
pixelFormats.RemoveAll(item => item.StencilBits < pixelFormat.StencilBits);
if (pixelFormats.Count == 0)
return $"no stencil bits matching (Bits >= {pixelFormat.StencilBits})";
pixelFormats.RemoveAll(item => item.MultisampleBits < pixelFormat.MultisampleBits);
if (pixelFormats.Count == 0)
return $"no multisample bits matching (Samples >= {pixelFormat.MultisampleBits})";
pixelFormats.RemoveAll(item => pixelFormat.DoubleBuffer && !item.DoubleBuffer);
if (pixelFormats.Count == 0)
return $"no double-buffer matching (DB={pixelFormat.DoubleBuffer})";
pixelFormats.RemoveAll(item => pixelFormat.SRGBCapable && !item.SRGBCapable);
if (pixelFormats.Count == 0)
return $"no sRGB matching (sRGB={pixelFormat.SRGBCapable})";
return "no error";
}
/// <summary>
/// Copy this DevicePixelFormatCollection.
/// </summary>
/// <returns>
/// It returns a <see cref="DevicePixelFormatCollection"/> equivalent to this DevicePixelFormatCollection.
/// </returns>
public DevicePixelFormatCollection Copy()
{
DevicePixelFormatCollection pixelFormats = new DevicePixelFormatCollection();
pixelFormats.AddRange(this.Select(devicePixelFormat => devicePixelFormat.Copy()));
return pixelFormats;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
[assembly: PythonModule("_collections", typeof(IronPython.Modules.PythonCollections))]
namespace IronPython.Modules {
public class PythonCollections {
public const string __doc__ = "High performance data structures\n";
[PythonType]
[DontMapIEnumerableToContains, DebuggerDisplay("deque, {__len__()} items"), DebuggerTypeProxy(typeof(CollectionDebugProxy))]
public class deque : IEnumerable, ICodeFormattable, IStructuralEquatable, ICollection, IReversible, IWeakReferenceable {
private object[] _data;
private readonly object _lockObj = new object();
private int _head, _tail;
private int _itemCnt, _maxLen, _version;
public deque() : this(-1) { }
private deque(int maxlen) {
// internal private constructor accepts maxlen < 0
_maxLen = maxlen;
_data = _maxLen < 0 ? new object[8] : new object[Math.Min(_maxLen, 8)];
}
public static object __new__(CodeContext/*!*/ context, PythonType cls, [ParamDictionary]IDictionary<object, object> dict, params object[] args) {
if (cls == DynamicHelpers.GetPythonTypeFromType(typeof(deque))) return new deque();
return cls.CreateInstance(context);
}
public void __init__() {
_maxLen = -1;
clear();
}
public void __init__([ParamDictionary]IDictionary<object, object> dict) {
_maxLen = VerifyMaxLen(dict);
clear();
}
public void __init__(object iterable) {
_maxLen = -1;
clear();
extend(iterable);
}
public void __init__(object iterable, object maxlen) {
_maxLen = VerifyMaxLenValue(maxlen);
clear();
extend(iterable);
}
public void __init__(object iterable, [ParamDictionary]IDictionary<object, object> dict) {
if (VerifyMaxLen(dict) < 0) {
__init__(iterable);
} else {
__init__(iterable, VerifyMaxLen(dict));
}
}
private static int VerifyMaxLen(IDictionary<object, object> dict) {
if (dict.Count != 1) {
throw PythonOps.TypeError("deque() takes at most 1 keyword argument ({0} given)", dict.Count);
}
object value;
if (!dict.TryGetValue("maxlen", out value)) {
IEnumerator<object> e = dict.Keys.GetEnumerator();
if (e.MoveNext()) {
throw PythonOps.TypeError("deque(): '{0}' is an invalid keyword argument", e.Current);
}
}
return VerifyMaxLenValue(value);
}
private static int VerifyMaxLenValue(object value) {
if (value is null) {
return -1;
}
int res = value switch {
int i32 => i32,
BigInteger bi => (int)bi,
Extensible<BigInteger> ebi => (int)ebi.Value,
_ => throw PythonOps.TypeError("an integer is required")
};
if (res < 0) throw PythonOps.ValueError("maxlen must be non-negative");
return res;
}
#region core deque APIs
public void append(object x) {
lock (_lockObj) {
_version++;
// overwrite head if queue is at max length
if (_itemCnt == _maxLen) {
if (_maxLen == 0) {
return;
}
_data[_tail++] = x;
if (_tail == _data.Length) {
_tail = 0;
}
_head = _tail;
return;
}
if (_itemCnt == _data.Length) {
GrowArray();
}
_itemCnt++;
_data[_tail++] = x;
if (_tail == _data.Length) {
_tail = 0;
}
}
}
public void appendleft(object x) {
lock (_lockObj) {
_version++;
// overwrite tail if queue is full
if (_itemCnt == _maxLen) {
if (_maxLen == 0) {
return;
}
_head--;
if (_head < 0) {
_head = _data.Length - 1;
}
_tail = _head;
_data[_head] = x;
return;
}
if (_itemCnt == _data.Length) {
GrowArray();
}
_itemCnt++;
--_head;
if (_head < 0) {
_head = _data.Length - 1;
}
_data[_head] = x;
}
}
public void clear() {
lock (_lockObj) {
_version++;
_head = _tail = 0;
_itemCnt = 0;
if (_maxLen < 0) _data = new object[8];
else _data = new object[Math.Min(_maxLen, 8)];
}
}
public object copy(CodeContext context)
=> __copy__(context);
public void extend(object iterable) {
// d.extend(d)
if (ReferenceEquals(iterable, this)) {
WalkDeque(idx => {
append(_data[idx]);
return true;
});
return;
}
IEnumerator e = PythonOps.GetEnumerator(iterable);
while (e.MoveNext()) {
append(e.Current);
}
}
public void extendleft(object iterable) {
// d.extendleft(d)
if (ReferenceEquals(iterable, this)) {
WalkDeque(idx => {
appendleft(_data[idx]);
return true;
});
return;
}
IEnumerator e = PythonOps.GetEnumerator(iterable);
while (e.MoveNext()) {
appendleft(e.Current);
}
}
public int index(CodeContext context, object value) {
lock (_lockObj) {
return index(context, value, 0, _itemCnt);
}
}
public int index(CodeContext context, object value, int start) {
lock (_lockObj) {
return index(context, value, start, _itemCnt);
}
}
public int index(CodeContext context, object value, int start, int stop) {
lock (_lockObj) {
if (start < 0) {
start += _itemCnt;
if (start < 0) start = 0;
}
if (stop < 0) {
stop += _itemCnt;
if (stop < 0) stop = 0;
}
int found = -1;
int cnt = 0;
var startVersion = _version;
try {
WalkDeque((int index) => {
if (cnt >= start) {
if (cnt >= stop) return false;
if (PythonOps.IsOrEqualsRetBool(_data[index], value)) {
found = index;
return false;
}
}
cnt += 1;
return true;
});
} catch (IndexOutOfRangeException) {
Debug.Assert(startVersion != _version);
}
if (startVersion != _version) {
throw PythonOps.RuntimeError("deque mutated during iteration");
}
if (found == -1) {
throw PythonOps.ValueError($"{value} not in deque");
}
return cnt;
}
}
public int index(CodeContext context, object item, object start)
=> index(context, item, Converter.ConvertToIndex(start));
public int index(CodeContext context, object item, object start, object stop)
=> index(context, item, Converter.ConvertToIndex(start), Converter.ConvertToIndex(stop));
public void insert(CodeContext context, int index, object @object) {
lock (_lockObj) {
if (_itemCnt == _maxLen) throw PythonOps.IndexError("deque already at its maximum size");
if (index >= _itemCnt) {
append(@object);
} else if (index <= -_itemCnt || index == 0) {
appendleft(@object);
} else {
rotate(context, -index);
if (index < 0) {
append(@object);
} else {
appendleft(@object);
}
rotate(context, index);
}
}
}
public object pop() {
lock (_lockObj) {
if (_itemCnt == 0) {
throw PythonOps.IndexError("pop from an empty deque");
}
_version++;
if (_tail != 0) {
_tail--;
} else {
_tail = _data.Length - 1;
}
_itemCnt--;
object res = _data[_tail];
_data[_tail] = null;
return res;
}
}
public object popleft() {
lock (_lockObj) {
if (_itemCnt == 0) {
throw PythonOps.IndexError("pop from an empty deque");
}
_version++;
object res = _data[_head];
_data[_head] = null;
if (_head != _data.Length - 1) {
_head++;
} else {
_head = 0;
}
_itemCnt--;
return res;
}
}
public void remove(object value) {
lock (_lockObj) {
int found = -1;
int startVersion = _version;
try {
WalkDeque((int index) => {
if (PythonOps.IsOrEqualsRetBool(_data[index], value)) {
found = index;
return false;
}
return true;
});
} catch (IndexOutOfRangeException) {
Debug.Assert(_version != startVersion);
}
if (_version != startVersion) {
throw PythonOps.IndexError("deque mutated during remove().");
}
if (found == _head) {
popleft();
} else if (found == (_tail > 0 ? _tail - 1 : _data.Length - 1)) {
pop();
} else if (found == -1) {
throw PythonOps.ValueError("deque.remove(value): value not in deque");
} else {
// otherwise we're removing from the middle and need to slide the values over...
_version++;
int start;
if (_head >= _tail) {
start = 0;
} else {
start = _head;
}
bool finished = false;
object copying = _tail != 0 ? _data[_tail - 1] : _data[_data.Length - 1];
for (int i = _tail - 2; i >= start; i--) {
object tmp = _data[i];
_data[i] = copying;
if (i == found) {
finished = true;
break;
}
copying = tmp;
}
if (_head >= _tail && !finished) {
for (int i = _data.Length - 1; i >= _head; i--) {
object tmp = _data[i];
_data[i] = copying;
if (i == found) break;
copying = tmp;
}
}
// we're one smaller now
_tail--;
_itemCnt--;
if (_tail < 0) {
// and tail just wrapped to the beginning
_tail = _data.Length - 1;
}
}
}
}
public void rotate(CodeContext/*!*/ context) {
rotate(context, 1);
}
public void rotate(CodeContext/*!*/ context, object n) {
lock (_lockObj) {
// rotation is easy if we have no items!
if (_itemCnt == 0) return;
// set rot to the appropriate positive int
int rot = context.LanguageContext.ConvertToInt32(n) % _itemCnt;
rot = rot % _itemCnt;
if (rot == 0) return; // no need to rotate if we'll end back up where we started
if (rot < 0) rot += _itemCnt;
_version++;
if (_itemCnt == _data.Length) {
// if all indices are filled no moves are required
_head = _tail = (_tail - rot + _data.Length) % _data.Length;
} else {
// too bad, we got gaps, looks like we'll be doing some real work.
object[] newData = new object[_itemCnt]; // we re-size to itemCnt so that future rotates don't require work
int curWriteIndex = rot;
WalkDeque(delegate(int curIndex) {
newData[curWriteIndex] = _data[curIndex];
curWriteIndex = (curWriteIndex + 1) % _itemCnt;
return true;
});
_head = _tail = 0;
_data = newData;
}
}
}
public object this[CodeContext/*!*/ context, object index] {
get {
lock (_lockObj) {
return _data[IndexToSlot(context, index)];
}
}
set {
lock (_lockObj) {
_data[IndexToSlot(context, index)] = value;
}
}
}
public int count(CodeContext/*!*/ context, object x) {
int cnt = 0;
foreach (var o in this) {
if (PythonOps.IsOrEqualsRetBool(o, x)) {
cnt++;
}
}
return cnt;
}
public object reverse(CodeContext/*!*/ context) {
lock (_lockObj) {
if (_itemCnt == 0) return null;
_version++;
var cnt = _itemCnt >> 1;
var newIndex = _tail;
WalkDeque((curIndex) => {
if (--cnt < 0) return false;
newIndex--;
if (newIndex < 0) {
newIndex = _data.Length - 1;
}
var tmp = _data[curIndex];
_data[curIndex] = _data[newIndex];
_data[newIndex] = tmp;
return true;
});
}
return null;
}
public object maxlen => _maxLen == -1 ? null : (object)_maxLen;
#endregion
public bool __contains__(CodeContext/*!*/ context, object key) {
lock (_lockObj) {
int found = -1;
var startVersion = _version;
try {
WalkDeque((int index) => {
if (PythonOps.IsOrEqualsRetBool(_data[index], key)) {
found = index;
return false;
}
return true;
});
} catch (IndexOutOfRangeException) {
Debug.Assert(startVersion != _version);
}
if (startVersion != _version) {
throw PythonOps.RuntimeError("deque mutated during iteration");
}
return found != -1;
}
}
public object __copy__(CodeContext/*!*/ context) {
if (GetType() == typeof(deque)) {
deque res = new deque(_maxLen);
res.extend(((IEnumerable)this).GetEnumerator());
return res;
} else {
return PythonCalls.Call(context, DynamicHelpers.GetPythonType(this), ((IEnumerable)this).GetEnumerator());
}
}
public void __delitem__(CodeContext/*!*/ context, object index) {
lock (_lockObj) {
int realIndex = IndexToSlot(context, index);
_version++;
if (realIndex == _head) {
popleft();
} else if (realIndex == (_tail - 1) ||
(realIndex == (_data.Length - 1) && _tail == _data.Length)) {
pop();
} else {
// we're removing an index from the middle, what a pain...
// we'll just recreate our data by walking the data once.
object[] newData = new object[_data.Length];
int writeIndex = 0;
WalkDeque(delegate(int curIndex) {
if (curIndex != realIndex) {
newData[writeIndex++] = _data[curIndex];
}
return true;
});
_head = 0;
_tail = writeIndex;
_data = newData;
_itemCnt--;
}
}
}
public PythonTuple __reduce__() {
lock (_lockObj) {
object[] items = new object[_itemCnt];
int curItem = 0;
WalkDeque(delegate(int curIndex) {
items[curItem++] = _data[curIndex];
return true;
});
return PythonTuple.MakeTuple(
DynamicHelpers.GetPythonType(this),
PythonTuple.MakeTuple(PythonList.FromArrayNoCopy(items))
);
}
}
public int __len__() {
return _itemCnt;
}
[SpecialName]
public deque InPlaceAdd(object other) {
extend(other);
return this;
}
#region binary operators
public static deque operator +([NotNull] deque x, object y) {
if (y is deque t) return x + t;
throw PythonOps.TypeError($"can only concatenate deque (not \"{PythonOps.GetPythonTypeName(y)}\") to deque");
}
public static deque operator +([NotNull] deque x, [NotNull] deque y) {
var d = new deque(x._maxLen);
d.extend(x);
d.extend(y);
return d;
}
private static deque MultiplyWorker(deque self, int count) {
var d = new deque(self._maxLen);
if (count <= 0 || self._itemCnt == 0) return d;
d.extend(self);
if (count == 1) return d;
if (d._maxLen < 0 || d._itemCnt * count <= d._maxLen) {
var data = ArrayOps.Multiply(d._data, d._itemCnt, count);
d._data = data;
d._itemCnt = data.Length;
Debug.Assert(d._head == 0);
d._tail = 0;
} else {
var tempdata = ArrayOps.Multiply(d._data, d._itemCnt, (d._maxLen + (d._itemCnt - 1)) / d._itemCnt);
var data = new object[d._maxLen];
Array.Copy(tempdata, tempdata.Length - d._maxLen, data, 0, data.Length);
d._data = data;
d._itemCnt = data.Length;
Debug.Assert(d._head == 0);
d._tail = 0;
}
return d;
}
public static deque operator *([NotNull] deque x, int n) {
return MultiplyWorker(x, n);
}
public static deque operator *(int n, [NotNull] deque x) {
return MultiplyWorker(x, n);
}
public static object operator *([NotNull] deque self, [NotNull] Runtime.Index count) {
return PythonOps.MultiplySequence(MultiplyWorker, self, count, true);
}
public static object operator *([NotNull] Runtime.Index count, [NotNull] deque self) {
return PythonOps.MultiplySequence(MultiplyWorker, self, count, false);
}
public static object operator *([NotNull] deque self, object count) {
if (Converter.TryConvertToIndex(count, out int index)) {
return self * index;
}
throw PythonOps.TypeErrorForUnIndexableObject(count);
}
public static object operator *(object count, [NotNull] deque self) {
if (Converter.TryConvertToIndex(count, out int index)) {
return index * self;
}
throw PythonOps.TypeErrorForUnIndexableObject(count);
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
return new _deque_iterator(this);
}
[PythonType]
public sealed class _deque_iterator : IEnumerable, IEnumerator {
private readonly deque _deque;
private int _curIndex;
private int _moveCnt;
private readonly int _version;
private int IndexToRealIndex(int index) {
index += _deque._head;
if (index > _deque._data.Length) {
index -= _deque._data.Length;
}
return index;
}
public _deque_iterator(deque d, int index = 0) {
lock (d._lockObj) {
// clamp index to range
if (index < 0) index = 0;
else if (index > d._itemCnt) index = d._itemCnt;
_deque = d;
_curIndex = IndexToRealIndex(index) - 1;
_moveCnt = index;
_version = d._version;
}
}
#region IEnumerator Members
object IEnumerator.Current {
get {
return _deque._data[_curIndex];
}
}
bool IEnumerator.MoveNext() {
lock (_deque._lockObj) {
if (_version != _deque._version) {
throw PythonOps.RuntimeError("deque mutated during iteration");
}
if (_moveCnt < _deque._itemCnt) {
_curIndex++;
_moveCnt++;
if (_curIndex == _deque._data.Length) {
_curIndex = 0;
}
return true;
}
return false;
}
}
void IEnumerator.Reset() {
_moveCnt = 0;
_curIndex = _deque._head - 1;
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator() => this;
#endregion
public int __length_hint__() {
lock (_deque._lockObj) {
if (_version != _deque._version) {
return 0;
}
}
return _deque._itemCnt - _moveCnt;
}
public PythonTuple __reduce__(CodeContext context) {
return PythonTuple.MakeTuple(
DynamicHelpers.GetPythonType(this),
PythonTuple.MakeTuple(
_deque,
_moveCnt
)
);
}
}
#endregion
#region __reversed__ implementation
public virtual IEnumerator __reversed__() {
return new _deque_reverse_iterator(this);
}
[PythonType]
public class _deque_reverse_iterator : IEnumerable, IEnumerator {
private readonly deque _deque;
private int _curIndex;
private int _moveCnt;
private readonly int _version;
public _deque_reverse_iterator(deque d) {
lock (d._lockObj) {
_deque = d;
_curIndex = d._tail;
_version = d._version;
}
}
#region IEnumerator Members
object IEnumerator.Current {
get {
return _deque._data[_curIndex];
}
}
bool IEnumerator.MoveNext() {
lock (_deque._lockObj) {
if (_version != _deque._version) {
throw PythonOps.RuntimeError("deque mutated during iteration");
}
if (_moveCnt < _deque._itemCnt) {
_curIndex--;
_moveCnt++;
if (_curIndex < 0) {
_curIndex = _deque._data.Length - 1;
}
return true;
}
return false;
}
}
void IEnumerator.Reset() {
_moveCnt = 0;
_curIndex = _deque._tail;
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator() => this;
#endregion
public int __length_hint__() {
lock (_deque._lockObj) {
if (_version != _deque._version) {
return 0;
}
}
return _deque._itemCnt - _moveCnt;
}
}
#endregion
#region private members
private void GrowArray() {
// do nothing if array is already at its max length
if (_data.Length == _maxLen) return;
object[] newData;
if (_maxLen < 0) newData = new object[_data.Length * 2];
else newData = new object[Math.Min(_maxLen, _data.Length * 2)];
// make the array completely sequential again
// by starting head back at 0.
int cnt1, cnt2;
if (_head >= _tail) {
cnt1 = _data.Length - _head;
cnt2 = _data.Length - cnt1;
} else {
cnt1 = _tail - _head;
cnt2 = _data.Length - cnt1;
}
Array.Copy(_data, _head, newData, 0, cnt1);
Array.Copy(_data, 0, newData, cnt1, cnt2);
_head = 0;
_tail = _data.Length;
_data = newData;
}
private int IndexToSlot(CodeContext/*!*/ context, object index) {
if (_itemCnt == 0) {
throw PythonOps.IndexError("deque index out of range");
}
int intIndex = context.LanguageContext.ConvertToInt32(index);
if (intIndex >= 0) {
if (intIndex >= _itemCnt) {
throw PythonOps.IndexError("deque index out of range");
}
int realIndex = _head + intIndex;
if (realIndex >= _data.Length) {
realIndex -= _data.Length;
}
return realIndex;
} else {
if ((intIndex * -1) > _itemCnt) {
throw PythonOps.IndexError("deque index out of range");
}
int realIndex = _tail + intIndex;
if (realIndex < 0) {
realIndex += _data.Length;
}
return realIndex;
}
}
private delegate bool DequeWalker(int curIndex);
/// <summary>
/// Walks the queue calling back to the specified delegate for
/// each populated index in the queue.
/// </summary>
private bool WalkDeque(DequeWalker walker) {
if (_itemCnt != 0) {
// capture these at the start so we can mutate
int head = _head;
int tail = _tail;
int end;
if (head >= tail) {
end = _data.Length;
} else {
end = tail;
}
for (int i = head; i < end; i++) {
if (!walker(i)) {
return false;
}
}
if (head >= tail) {
for (int i = 0; i < tail; i++) {
if (!walker(i)) {
return false;
}
}
}
}
return true;
}
#endregion
#region ICodeFormattable Members
public virtual string/*!*/ __repr__(CodeContext/*!*/ context) {
List<object> infinite = PythonOps.GetAndCheckInfinite(this);
if (infinite == null) {
return "[...]";
}
int infiniteIndex = infinite.Count;
infinite.Add(this);
try {
StringBuilder sb = new StringBuilder();
sb.Append("deque([");
string comma = "";
lock (_lockObj) {
WalkDeque(delegate(int index) {
sb.Append(comma);
sb.Append(PythonOps.Repr(context, _data[index]));
comma = ", ";
return true;
});
}
if (_maxLen < 0) {
sb.Append("])");
} else {
sb.Append("], maxlen=");
sb.Append(_maxLen);
sb.Append(')');
}
return sb.ToString();
} finally {
System.Diagnostics.Debug.Assert(infiniteIndex == infinite.Count - 1);
infinite.RemoveAt(infiniteIndex);
}
}
#endregion
#region IStructuralEquatable Members
public const object __hash__ = null;
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
if (CompareUtil.Check(this)) {
return 0;
}
int res;
CompareUtil.Push(this);
try {
res = ((IStructuralEquatable)new PythonTuple(this)).GetHashCode(comparer);
} finally {
CompareUtil.Pop(this);
}
return res;
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
=> other is deque d && EqualsWorker(d, comparer);
private bool EqualsWorker(deque otherDeque, IEqualityComparer comparer = null) {
Assert.NotNull(otherDeque);
if (otherDeque._itemCnt != _itemCnt) {
// number of items is different, deques can't be equal
return false;
} else if (otherDeque._itemCnt == 0) {
// two empty deques are equal
return true;
}
if (CompareUtil.Check(this)) return true;
CompareUtil.Push(this);
try {
int otherIndex = otherDeque._head;
return WalkDeque(ourIndex => {
bool result;
var ourData = _data[ourIndex];
var otherData = otherDeque._data[otherIndex];
if (comparer == null) {
result = PythonOps.IsOrEqualsRetBool(ourData, otherData);
} else {
result = ReferenceEquals(ourData, otherData) || comparer.Equals(ourData, otherData);
}
if (!result) {
return false;
}
otherIndex++;
if (otherIndex == otherDeque._data.Length) {
otherIndex = 0;
}
return true;
});
} finally {
CompareUtil.Pop(this);
}
}
#endregion
#region Rich Comparison Members
private object CompareToWorker(CodeContext context, deque other, PythonOperationKind op) {
if (_itemCnt == 0 || other._itemCnt == 0) {
return PythonOps.RichCompare(context, _itemCnt, other._itemCnt, op);
}
if (CompareUtil.Check(this)) return 0;
CompareUtil.Push(this);
try {
int otherIndex = other._head, ourIndex = _head;
for (; ; ) {
var ourData = _data[ourIndex];
var otherData = other._data[otherIndex];
if (!PythonOps.IsOrEqualsRetBool(context, ourData, otherData)) {
return PythonOps.RichCompare(context, ourData, otherData, op);
}
// advance both indexes
otherIndex++;
if (otherIndex == other._data.Length) {
otherIndex = 0;
}
if (otherIndex == other._tail) {
break;
}
ourIndex++;
if (ourIndex == _data.Length) {
ourIndex = 0;
}
if (ourIndex == _tail) {
break;
}
}
// all items are equal, but # of items may be different.
return PythonOps.RichCompare(context, _itemCnt, other._itemCnt, op);
} finally {
CompareUtil.Pop(this);
}
}
public static object operator >([NotNull] deque self, [NotNull] deque other)
=> self.CompareToWorker(DefaultContext.Default, other, PythonOperationKind.GreaterThan);
public static object operator <([NotNull] deque self, [NotNull] deque other)
=> self.CompareToWorker(DefaultContext.Default, other, PythonOperationKind.LessThan);
public static object operator >=([NotNull] deque self, [NotNull] deque other)
=> self.CompareToWorker(DefaultContext.Default, other, PythonOperationKind.GreaterThanOrEqual);
public static object operator <=([NotNull] deque self, [NotNull] deque other)
=> self.CompareToWorker(DefaultContext.Default, other, PythonOperationKind.LessThanOrEqual);
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index) {
int i = 0;
foreach (object o in this) {
array.SetValue(o, index + i++);
}
}
int ICollection.Count {
get { return this._itemCnt; }
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get { return this; }
}
#endregion
#region IWeakReferenceable Members
private WeakRefTracker _tracker;
WeakRefTracker IWeakReferenceable.GetWeakRef() {
return _tracker;
}
bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) {
_tracker = value;
return true;
}
void IWeakReferenceable.SetFinalizer(WeakRefTracker value) {
_tracker = value;
}
#endregion
}
public static PythonType _deque_iterator {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(deque._deque_iterator));
}
}
public static PythonType _deque_reversed_iterator {
get {
return DynamicHelpers.GetPythonTypeFromType(typeof(deque._deque_reverse_iterator));
}
}
[PythonType]
public class defaultdict : PythonDictionary {
private readonly CallSite<Func<CallSite, CodeContext, object, object>> _missingSite;
public defaultdict(CodeContext/*!*/ context) {
_missingSite = CallSite<Func<CallSite, CodeContext, object, object>>.Create(
new PythonInvokeBinder(
context.LanguageContext,
new CallSignature(0)
)
);
}
public new void __init__(CodeContext/*!*/ context, object default_factory) {
if (default_factory != null && !PythonOps.IsCallable(context, default_factory))
throw PythonOps.TypeError("first argument must be callable or None");
this.default_factory = default_factory;
}
public void __init__(CodeContext/*!*/ context, object default_factory, [NotNull]params object[] args) {
__init__(context, default_factory);
foreach (object o in args) {
update(context, o);
}
}
public void __init__(CodeContext/*!*/ context, object default_factory, [ParamDictionary, NotNull]IDictionary<object, object> dict, [NotNull]params object[] args) {
__init__(context, default_factory, args);
foreach (KeyValuePair<object , object> kvp in dict) {
this[kvp.Key] = kvp.Value;
}
}
public object default_factory { get; set; }
public object __missing__(CodeContext context, object key) {
object factory = default_factory;
if (factory == null) {
throw PythonOps.KeyError(key);
}
return this[key] = _missingSite.Target.Invoke(_missingSite, context, factory);
}
public object __copy__(CodeContext/*!*/ context) {
return copy(context);
}
public override PythonDictionary copy(CodeContext/*!*/ context) {
defaultdict res = new defaultdict(context);
res.default_factory = this.default_factory;
res.update(context, this);
return res;
}
public override string __repr__(CodeContext context) {
return string.Format("defaultdict({0}, {1})", ReprFactory(context, default_factory), base.__repr__(context));
static string ReprFactory(CodeContext context, object factory) {
var infinite = PythonOps.GetAndCheckInfinite(factory);
if (infinite == null) {
return "...";
}
int index = infinite.Count;
infinite.Add(factory);
try {
return PythonOps.Repr(context, factory);
} finally {
Debug.Assert(index == infinite.Count - 1);
infinite.RemoveAt(index);
}
}
}
public PythonTuple __reduce__(CodeContext context) {
return PythonTuple.MakeTuple(
DynamicHelpers.GetPythonType(this),
PythonTuple.MakeTuple(default_factory),
null,
null,
Builtin.iter(context, PythonOps.Invoke(context, this, nameof(PythonDictionary.items)))
);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web.UI.WebControls;
using DataAccess;
using FCSAmerica.DifferenceMaker.Models;
partial class review : System.Web.UI.UserControl
{
//**********************************************
//* Name: Page_Load
//* Description: Handles the logic for the logging user control
//****VARIABLES****
//* lblPresenter -variable for holding presenter's name
//* lblPresenterTeam-variable for holding presenter's team name
//* lblRecipient -variable for holding recipient's name
//* lblRecipientTeam-variable for holding recipient's team name
//* lblDatePresented-variable for holding date presented
//* lblReason -variable for holding the reason for the award
//*********************************************
override protected void OnInit(EventArgs e)
{
base.OnInit(e);
btnReturn.Click += new System.EventHandler(btnReturn_Click);
btnSubmit.Click += new System.EventHandler(btnSubmit_Click);
}
//ORIGINAL LINE: Protected Sub Page_PreRender(ByVal Sender As Object, ByVal e As System.EventArgs) Handles this.PreRender
override protected void OnPreRender(System.EventArgs e)
{
base.OnPreRender(e);
this.lblPresenter.Text = SessionHelper.GetValue<string>(Session["Presenter_Name"]);
this.lblPresenterTeam.Text = SessionHelper.GetValue<string>(Session["Presenter_Team"]);
this.lblRecipient.Text = SessionHelper.GetValue<string>(Session["Recipient_Name"]);
this.lblRecipientTeam.Text = SessionHelper.GetValue<string>(Session["Recipient_Team"]);
this.lblDatePresented.Text = Session["Date_Presented"].ToString();
this.lblReason.Text = SessionHelper.GetValue<string>(Session["Reason"]);
this.lblAwardAmount.Text = SessionHelper.GetValue<decimal>(Session["AwardAmount"]).ToString("c");
if (SessionHelper.GetValue<bool>(Session["IsOtherAmount"]))
{
this.rowAwardDescription.Visible = true;
this.lblAwardDescription.Text = SessionHelper.GetValue<string>(Session["AwardDescription"]);
}
else
{
this.lblAwardDescription.Text = string.Empty;
}
}
//**********************************************
//* Name: btnReturn_Click
//* Description: Returns to logging page
//****VARIABLES****
//* webTab -local handle of UltraWebTab on main page
//* loggingTab -local handle for current logging tab
//* newPage -variable holding location to logging page
//*********************************************
protected void btnReturn_Click(object sender, System.EventArgs e)
{
MultiView mvLogging = null;
View loggingActiveView;
try
{
mvLogging = (MultiView)this.Parent.FindControl("mvGiveAnAward");
loggingActiveView = (View)mvLogging.FindControl("logForm");
mvLogging.SetActiveView(loggingActiveView);
}
catch (Exception)
{
}
}
//**********************************************
//* Name: btnSubmit_Click
//* Description: Handles the logic if the submit button is clicked
//****VARIABLES****
//* webTab -local handle of UltraWebTab on main page
//* loggingTab -local handle for current logging tab
//*********************************************
protected void btnSubmit_Click(object sender, System.EventArgs e)
{
MultiView mvLogging = null;
View loggingActiveView = new View();
mvLogging = (MultiView)this.Parent.FindControl("mvGiveAnAward");
string newPage = null;
if (!SessionHelper.GetValue<bool>(Session["Record_Submitted"]))
{
try
{
// Insert record into database
//sqlAYB_Insert.Insert();
var responseMessage = InsertRecognitionDetail();
//string seedValue = null;
//SqlCommand command = null;
//MultiView mvLogging = null;
//View loggingActiveView = new View();
if (responseMessage.IsSuccessStatusCode)
{
// Send email to accounts payable if award is any award type other than $25.00
SendAccountsPayableEmail();
// seedValue = command.Parameters["@Award_ID"].Value.ToString();
var insertedRedemptionDetail = responseMessage.Content.ReadAsAsync<RecognitionInsertDto>().Result;
if (insertedRedemptionDetail != null)
{
Session["seedValue"]= insertedRedemptionDetail.Award_Id.ToString();
}
newPage = "success";
}
else
{
//If there was a problem adding the record, go to fail page
Session["errorMsg"] = responseMessage.ReasonPhrase;
newPage = "fail";
}
loggingActiveView = (View)mvLogging.FindControl(newPage);
mvLogging.SetActiveView(loggingActiveView);
}
catch (Exception ex)
{
}
}
}
private HttpResponseMessage InsertRecognitionDetail()
{
var response = new HttpResponseMessage();
try
{
using (var client = new HttpClient())
{
var url = "redemption/insertRedemption/";
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]);
var recognitionDetail = GetToBeInsertedRecognitionDetail();
//return client.PostAsJsonAsync(url, recognitionDetail).Result;
try
{
response = client.PostAsJsonAsync(url, recognitionDetail).Result;
}
catch (HttpRequestException httpEx)
{
response.ReasonPhrase = httpEx.Message;
}
}
}
catch (Exception ex)
{
//var badResponse = request.CreateResponse(HttpStatusCode.BadRequest);
//badResponse.ReasonPhrase = "include ex.StackTrace here just for debugging";
}
return response;
}
private RecognitionInsertDto GetToBeInsertedRecognitionDetail()
{
var awardAmt = SessionHelper.GetValue<decimal>(Session["AwardAmount"]);
var date = SessionHelper.GetValue<string>(Session["Date_Presented"]);
DateTime datePresented = Convert.ToDateTime(date);
var currentUser = Session["currentUser_EmpID"];
//var recipientId = this.GetEmployeeId(SessionHelper.GetValue<string>(Session["Recipient_Name"]));
var recipientId = SessionHelper.GetValue<string>(Session["Recipient_SV"]);
var isAyb = SessionHelper.GetValue<bool>(Session["IsAtYourBest"]);
var reason = Session["Reason"];
var recognitionDetail = new RecognitionInsertDto()
{
Presenter_Emp_SV = SessionHelper.GetValue<int>(currentUser),
Recipient_Emp_SV = Convert.ToInt32(recipientId),
DatePresented_DT = datePresented,
Reason_TX = SessionHelper.GetValue<string>(reason),
IsAYB_yn = isAyb,
AwardAmt_cur = awardAmt,
Description_tx = lblAwardDescription.Text
};
return recognitionDetail;
}
/// <summary>
/// Sends an email to accounts payable.
/// </summary>
private void SendAccountsPayableEmail()
{
string mailFrom = ConfigurationManager.AppSettings["APMailFrom"].ToString();
string mailTo = ConfigurationManager.AppSettings["APMailTo"].ToString();
string mailCC = string.Empty;
string mailSubject = null;
StringBuilder mailBody = new StringBuilder();
if (SessionHelper.GetValue<bool>(Session["IsOtherAmount"]) || SessionHelper.GetValue<decimal>(Session["AwardAmount"]) != 25M)
{
mailCC = GetLeaderEmail();
if (SessionHelper.GetValue<bool>(Session["IsOtherAmount"]))
{
// Award is an "other" award
mailSubject = "Other Recognition Award - " + SessionHelper.GetValue<string>(Session["Recipient_Name"]);
}
else
{
// Award is $100, $175 or $250
mailSubject = "Recognition - " + SessionHelper.GetValue<string>(Session["Recipient_Name"]);
}
mailBody.Append("<table border=\"0\">");
mailBody.Append("<tr>");
mailBody.Append("<td>");
mailBody.Append("<strong>Recipient Name:</strong> ");
mailBody.Append("</td>");
mailBody.Append("<td>");
mailBody.Append(SessionHelper.GetValue<string>(Session["Recipient_Name"]));
mailBody.Append("</td>");
mailBody.Append("</tr>");
mailBody.Append("<tr>");
mailBody.Append("<td>");
mailBody.Append("<strong>Recognition Description:</strong> ");
mailBody.Append("</td>");
mailBody.Append("<td>");
mailBody.Append(SessionHelper.GetValue<string>(Session["AwardDescription"]));
mailBody.Append("</td>");
mailBody.Append("</tr>");
mailBody.Append("<tr>");
mailBody.Append("<td>");
mailBody.Append("<strong>Recognition Cost:</strong> ");
mailBody.Append("</td>");
mailBody.Append("<td>");
mailBody.Append(SessionHelper.GetValue<decimal>(Session["AwardAmount"]).ToString("c"));
mailBody.Append("</td>");
mailBody.Append("</tr>");
mailBody.Append("<tr>");
mailBody.Append("<td>");
mailBody.Append("<strong>Description:</strong> ");
mailBody.Append("</td>");
mailBody.Append("<td>");
mailBody.Append(System.DateTime.Now.ToString("MM/dd/yyyy"));
mailBody.Append(" ");
mailBody.Append(SessionHelper.GetValue<string>(Session["Recipient_Name"]));
mailBody.Append("</td>");
mailBody.Append("</tr>");
mailBody.Append("<tr>");
mailBody.Append("<td>");
mailBody.Append("<strong>Reason:</strong> ");
mailBody.Append("</td>");
mailBody.Append("<td>");
mailBody.Append(SessionHelper.GetValue<string>(Session["Reason"]));
mailBody.Append("</td>");
mailBody.Append("</tr>");
mailBody.Append("<tr>");
mailBody.Append("<td>");
mailBody.Append("<strong>Recognition Purchaser:</strong> ");
mailBody.Append("</td>");
mailBody.Append("<td>");
mailBody.Append(SessionHelper.GetValue<string>(Session["Presenter_Name"]));
mailBody.Append("</td>");
mailBody.Append("</tr>");
mailBody.Append("</table>");
// Send the email
Mailer.SendEmail(mailFrom, mailTo, mailCC, mailSubject, mailBody.ToString(), true);
}
}
private string GetLeaderEmail()
{
var currentEmployeeId = SessionHelper.GetValue<int>(Session["currentUser_EmpID"]);
using (var client = new HttpClient())
{
var url = "employee/employeeLeaders/" + currentEmployeeId;
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]);
var apiResponse = client.GetAsync(url).Result;
if (!apiResponse.IsSuccessStatusCode)
{
// TODO: find proper way of displaying error/warning messages
// Response.Write("Unable to find employee leader. Contact technical support for more help.");
return string.Empty;
}
var records = apiResponse.Content.ReadAsAsync<List<Leader_OfEmployee_Result>>().Result;
if (records.Count > 0)
{
return records.Single().LeaderEmail;
}
}
return string.Empty;
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Resources;
using System.Text;
using System.Threading;
namespace System.Management.Automation
{
/// <summary>
/// EventLogLogProvider is a class to implement Msh Provider interface using EventLog technology.
///
/// EventLogLogProvider will be the provider to use if Monad is running in early windows releases
/// from 2000 to 2003.
///
/// EventLogLogProvider will be packaged in the same dll as Msh Log Engine since EventLog should
/// always be available.
/// </summary>
internal class EventLogLogProvider : LogProvider
{
/// <summary>
/// Constructor.
/// </summary>
/// <returns></returns>
internal EventLogLogProvider(string shellId)
{
string source = SetupEventSource(shellId);
_eventLog = new EventLog();
_eventLog.Source = source;
_resourceManager = new ResourceManager("System.Management.Automation.resources.Logging", System.Reflection.Assembly.GetExecutingAssembly());
}
internal string SetupEventSource(string shellId)
{
string source;
// In case shellId == null, use the "Default" source.
if (string.IsNullOrEmpty(shellId))
{
source = "Default";
}
else
{
int index = shellId.LastIndexOf('.');
if (index < 0)
source = shellId;
else
source = shellId.Substring(index + 1);
// There may be a situation where ShellId ends with a '.'.
// In that case, use the default source.
if (string.IsNullOrEmpty(source))
source = "Default";
}
if (EventLog.SourceExists(source))
{
return source;
}
string message = string.Format(Thread.CurrentThread.CurrentCulture, "Event source '{0}' is not registered", source);
throw new InvalidOperationException(message);
}
/// <summary>
/// This represent a handle to EventLog.
/// </summary>
private EventLog _eventLog;
private ResourceManager _resourceManager;
#region Log Provider Api
private const int EngineHealthCategoryId = 1;
private const int CommandHealthCategoryId = 2;
private const int ProviderHealthCategoryId = 3;
private const int EngineLifecycleCategoryId = 4;
private const int CommandLifecycleCategoryId = 5;
private const int ProviderLifecycleCategoryId = 6;
private const int SettingsCategoryId = 7;
private const int PipelineExecutionDetailCategoryId = 8;
/// <summary>
/// Log engine health event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="eventId"></param>
/// <param name="exception"></param>
/// <param name="additionalInfo"></param>
internal override void LogEngineHealthEvent(LogContext logContext, int eventId, Exception exception, Dictionary<string, string> additionalInfo)
{
Hashtable mapArgs = new Hashtable();
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
{
mapArgs["ExceptionClass"] = exception.GetType().Name;
mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category;
mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId;
if (icer.ErrorRecord.ErrorDetails != null)
{
mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message;
}
else
{
mapArgs["ErrorMessage"] = exception.Message;
}
}
else
{
mapArgs["ExceptionClass"] = exception.GetType().Name;
mapArgs["ErrorCategory"] = string.Empty;
mapArgs["ErrorId"] = string.Empty;
mapArgs["ErrorMessage"] = exception.Message;
}
FillEventArgs(mapArgs, logContext);
FillEventArgs(mapArgs, additionalInfo);
EventInstance entry = new EventInstance(eventId, EngineHealthCategoryId);
entry.EntryType = GetEventLogEntryType(logContext);
string detail = GetEventDetail("EngineHealthContext", mapArgs);
LogEvent(entry, mapArgs["ErrorMessage"], detail);
}
private static EventLogEntryType GetEventLogEntryType(LogContext logContext)
{
switch (logContext.Severity)
{
case "Critical":
case "Error":
return EventLogEntryType.Error;
case "Warning":
return EventLogEntryType.Warning;
default:
return EventLogEntryType.Information;
}
}
/// <summary>
/// Log engine lifecycle event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="newState"></param>
/// <param name="previousState"></param>
internal override void LogEngineLifecycleEvent(LogContext logContext, EngineState newState, EngineState previousState)
{
int eventId = GetEngineLifecycleEventId(newState);
if (eventId == _invalidEventId)
return;
Hashtable mapArgs = new Hashtable();
mapArgs["NewEngineState"] = newState.ToString();
mapArgs["PreviousEngineState"] = previousState.ToString();
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, EngineLifecycleCategoryId);
entry.EntryType = EventLogEntryType.Information;
string detail = GetEventDetail("EngineLifecycleContext", mapArgs);
LogEvent(entry, newState, previousState, detail);
}
private const int _baseEngineLifecycleEventId = 400;
private const int _invalidEventId = -1;
/// <summary>
/// Get engine lifecycle event id based on engine state.
/// </summary>
/// <param name="engineState"></param>
/// <returns></returns>
private static int GetEngineLifecycleEventId(EngineState engineState)
{
switch (engineState)
{
case EngineState.None:
return _invalidEventId;
case EngineState.Available:
return _baseEngineLifecycleEventId;
case EngineState.Degraded:
return _baseEngineLifecycleEventId + 1;
case EngineState.OutOfService:
return _baseEngineLifecycleEventId + 2;
case EngineState.Stopped:
return _baseEngineLifecycleEventId + 3;
}
return _invalidEventId;
}
private const int _commandHealthEventId = 200;
/// <summary>
/// Provider interface function for logging command health event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="exception"></param>
internal override void LogCommandHealthEvent(LogContext logContext, Exception exception)
{
int eventId = _commandHealthEventId;
Hashtable mapArgs = new Hashtable();
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
{
mapArgs["ExceptionClass"] = exception.GetType().Name;
mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category;
mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId;
if (icer.ErrorRecord.ErrorDetails != null)
{
mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message;
}
else
{
mapArgs["ErrorMessage"] = exception.Message;
}
}
else
{
mapArgs["ExceptionClass"] = exception.GetType().Name;
mapArgs["ErrorCategory"] = string.Empty;
mapArgs["ErrorId"] = string.Empty;
mapArgs["ErrorMessage"] = exception.Message;
}
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, CommandHealthCategoryId);
entry.EntryType = GetEventLogEntryType(logContext);
string detail = GetEventDetail("CommandHealthContext", mapArgs);
LogEvent(entry, mapArgs["ErrorMessage"], detail);
}
/// <summary>
/// Log command life cycle event.
/// </summary>
/// <param name="getLogContext"></param>
/// <param name="newState"></param>
internal override void LogCommandLifecycleEvent(Func<LogContext> getLogContext, CommandState newState)
{
LogContext logContext = getLogContext();
int eventId = GetCommandLifecycleEventId(newState);
if (eventId == _invalidEventId)
return;
Hashtable mapArgs = new Hashtable();
mapArgs["NewCommandState"] = newState.ToString();
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, CommandLifecycleCategoryId);
entry.EntryType = EventLogEntryType.Information;
string detail = GetEventDetail("CommandLifecycleContext", mapArgs);
LogEvent(entry, logContext.CommandName, newState, detail);
}
private const int _baseCommandLifecycleEventId = 500;
/// <summary>
/// Get command lifecycle event id based on command state.
/// </summary>
/// <param name="commandState"></param>
/// <returns></returns>
private static int GetCommandLifecycleEventId(CommandState commandState)
{
switch (commandState)
{
case CommandState.Started:
return _baseCommandLifecycleEventId;
case CommandState.Stopped:
return _baseCommandLifecycleEventId + 1;
case CommandState.Terminated:
return _baseCommandLifecycleEventId + 2;
}
return _invalidEventId;
}
private const int _pipelineExecutionDetailEventId = 800;
/// <summary>
/// Log pipeline execution detail event.
///
/// This may end of logging more than one event if the detail string is too long to be fit in 64K.
/// </summary>
/// <param name="logContext"></param>
/// <param name="pipelineExecutionDetail"></param>
internal override void LogPipelineExecutionDetailEvent(LogContext logContext, List<string> pipelineExecutionDetail)
{
List<string> details = GroupMessages(pipelineExecutionDetail);
for (int i = 0; i < details.Count; i++)
{
LogPipelineExecutionDetailEvent(logContext, details[i], i + 1, details.Count);
}
}
private const int MaxLength = 16000;
private List<string> GroupMessages(List<string> messages)
{
List<string> result = new List<string>();
if (messages == null || messages.Count == 0)
return result;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < messages.Count; i++)
{
if (sb.Length + messages[i].Length < MaxLength)
{
sb.AppendLine(messages[i]);
continue;
}
result.Add(sb.ToString());
sb = new StringBuilder();
sb.AppendLine(messages[i]);
}
result.Add(sb.ToString());
return result;
}
/// <summary>
/// Log one pipeline execution detail event. Detail message is already chopped up so that it will
/// fit in 64K.
/// </summary>
/// <param name="logContext"></param>
/// <param name="pipelineExecutionDetail"></param>
/// <param name="detailSequence"></param>
/// <param name="detailTotal"></param>
private void LogPipelineExecutionDetailEvent(LogContext logContext, string pipelineExecutionDetail, int detailSequence, int detailTotal)
{
int eventId = _pipelineExecutionDetailEventId;
Hashtable mapArgs = new Hashtable();
mapArgs["PipelineExecutionDetail"] = pipelineExecutionDetail;
mapArgs["DetailSequence"] = detailSequence;
mapArgs["DetailTotal"] = detailTotal;
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, PipelineExecutionDetailCategoryId);
entry.EntryType = EventLogEntryType.Information;
string pipelineInfo = GetEventDetail("PipelineExecutionDetailContext", mapArgs);
LogEvent(entry, logContext.CommandLine, pipelineInfo, pipelineExecutionDetail);
}
private const int _providerHealthEventId = 300;
/// <summary>
/// Provider interface function for logging provider health event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="providerName"></param>
/// <param name="exception"></param>
internal override void LogProviderHealthEvent(LogContext logContext, string providerName, Exception exception)
{
int eventId = _providerHealthEventId;
Hashtable mapArgs = new Hashtable();
mapArgs["ProviderName"] = providerName;
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
{
mapArgs["ExceptionClass"] = exception.GetType().Name;
mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category;
mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId;
if (icer.ErrorRecord.ErrorDetails != null
&& !string.IsNullOrEmpty(icer.ErrorRecord.ErrorDetails.Message))
{
mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message;
}
else
{
mapArgs["ErrorMessage"] = exception.Message;
}
}
else
{
mapArgs["ExceptionClass"] = exception.GetType().Name;
mapArgs["ErrorCategory"] = string.Empty;
mapArgs["ErrorId"] = string.Empty;
mapArgs["ErrorMessage"] = exception.Message;
}
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, ProviderHealthCategoryId);
entry.EntryType = GetEventLogEntryType(logContext);
string detail = GetEventDetail("ProviderHealthContext", mapArgs);
LogEvent(entry, mapArgs["ErrorMessage"], detail);
}
/// <summary>
/// Log provider lifecycle event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="providerName"></param>
/// <param name="newState"></param>
internal override void LogProviderLifecycleEvent(LogContext logContext, string providerName, ProviderState newState)
{
int eventId = GetProviderLifecycleEventId(newState);
if (eventId == _invalidEventId)
return;
Hashtable mapArgs = new Hashtable();
mapArgs["ProviderName"] = providerName;
mapArgs["NewProviderState"] = newState.ToString();
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, ProviderLifecycleCategoryId);
entry.EntryType = EventLogEntryType.Information;
string detail = GetEventDetail("ProviderLifecycleContext", mapArgs);
LogEvent(entry, providerName, newState, detail);
}
private const int _baseProviderLifecycleEventId = 600;
/// <summary>
/// Get provider lifecycle event id based on provider state.
/// </summary>
/// <param name="providerState"></param>
/// <returns></returns>
private static int GetProviderLifecycleEventId(ProviderState providerState)
{
switch (providerState)
{
case ProviderState.Started:
return _baseProviderLifecycleEventId;
case ProviderState.Stopped:
return _baseProviderLifecycleEventId + 1;
}
return _invalidEventId;
}
private const int _settingsEventId = 700;
/// <summary>
/// Log settings event.
/// </summary>
/// <param name="logContext"></param>
/// <param name="variableName"></param>
/// <param name="value"></param>
/// <param name="previousValue"></param>
internal override void LogSettingsEvent(LogContext logContext, string variableName, string value, string previousValue)
{
int eventId = _settingsEventId;
Hashtable mapArgs = new Hashtable();
mapArgs["VariableName"] = variableName;
mapArgs["NewValue"] = value;
mapArgs["PreviousValue"] = previousValue;
FillEventArgs(mapArgs, logContext);
EventInstance entry = new EventInstance(eventId, SettingsCategoryId);
entry.EntryType = EventLogEntryType.Information;
string detail = GetEventDetail("SettingsContext", mapArgs);
LogEvent(entry, variableName, value, previousValue, detail);
}
#endregion Log Provider Api
#region EventLog helper functions
/// <summary>
/// This is the helper function for logging an event with localizable message
/// to event log. It will trace all exception thrown by eventlog.
/// </summary>
/// <param name="entry"></param>
/// <param name="args"></param>
private void LogEvent(EventInstance entry, params object[] args)
{
try
{
_eventLog.WriteEvent(entry, args);
}
catch (ArgumentException)
{
return;
}
catch (InvalidOperationException)
{
return;
}
catch (Win32Exception)
{
return;
}
}
#endregion
#region Event Arguments
/// <summary>
/// Fill event arguments with logContext info.
///
/// In EventLog Api, arguments are passed in as an array of objects.
/// </summary>
/// <param name="mapArgs">An ArrayList to contain the event arguments.</param>
/// <param name="logContext">The log context containing the info to fill in.</param>
private static void FillEventArgs(Hashtable mapArgs, LogContext logContext)
{
mapArgs["Severity"] = logContext.Severity;
mapArgs["SequenceNumber"] = logContext.SequenceNumber;
mapArgs["HostName"] = logContext.HostName;
mapArgs["HostVersion"] = logContext.HostVersion;
mapArgs["HostId"] = logContext.HostId;
mapArgs["HostApplication"] = logContext.HostApplication;
mapArgs["EngineVersion"] = logContext.EngineVersion;
mapArgs["RunspaceId"] = logContext.RunspaceId;
mapArgs["PipelineId"] = logContext.PipelineId;
mapArgs["CommandName"] = logContext.CommandName;
mapArgs["CommandType"] = logContext.CommandType;
mapArgs["ScriptName"] = logContext.ScriptName;
mapArgs["CommandPath"] = logContext.CommandPath;
mapArgs["CommandLine"] = logContext.CommandLine;
mapArgs["User"] = logContext.User;
mapArgs["Time"] = logContext.Time;
}
/// <summary>
/// Fill event arguments with additionalInfo stored in a string dictionary.
/// </summary>
/// <param name="mapArgs">An arraylist to contain the event arguments.</param>
/// <param name="additionalInfo">A string dictionary to fill in.</param>
private static void FillEventArgs(Hashtable mapArgs, Dictionary<string, string> additionalInfo)
{
if (additionalInfo == null)
{
for (int i = 0; i < 3; i++)
{
string id = ((int)(i + 1)).ToString("d1", CultureInfo.CurrentCulture);
mapArgs["AdditionalInfo_Name" + id] = string.Empty;
mapArgs["AdditionalInfo_Value" + id] = string.Empty;
}
return;
}
string[] keys = new string[additionalInfo.Count];
string[] values = new string[additionalInfo.Count];
additionalInfo.Keys.CopyTo(keys, 0);
additionalInfo.Values.CopyTo(values, 0);
for (int i = 0; i < 3; i++)
{
string id = ((int)(i + 1)).ToString("d1", CultureInfo.CurrentCulture);
if (i < keys.Length)
{
mapArgs["AdditionalInfo_Name" + id] = keys[i];
mapArgs["AdditionalInfo_Value" + id] = values[i];
}
else
{
mapArgs["AdditionalInfo_Name" + id] = string.Empty;
mapArgs["AdditionalInfo_Value" + id] = string.Empty;
}
}
return;
}
#endregion Event Arguments
#region Event Message
private string GetEventDetail(string contextId, Hashtable mapArgs)
{
return GetMessage(contextId, mapArgs);
}
private string GetMessage(string messageId, Hashtable mapArgs)
{
if (_resourceManager == null)
return string.Empty;
string messageTemplate = _resourceManager.GetString(messageId);
if (string.IsNullOrEmpty(messageTemplate))
return string.Empty;
return FillMessageTemplate(messageTemplate, mapArgs);
}
private static string FillMessageTemplate(string messageTemplate, Hashtable mapArgs)
{
StringBuilder message = new StringBuilder();
int cursor = 0;
while (true)
{
int startIndex = messageTemplate.IndexOf('[', cursor);
if (startIndex < 0)
{
message.Append(messageTemplate.Substring(cursor));
return message.ToString();
}
int endIndex = messageTemplate.IndexOf(']', startIndex + 1);
if (endIndex < 0)
{
message.Append(messageTemplate.Substring(cursor));
return message.ToString();
}
message.Append(messageTemplate.Substring(cursor, startIndex - cursor));
cursor = startIndex;
string placeHolder = messageTemplate.Substring(startIndex + 1, endIndex - startIndex - 1);
if (mapArgs.Contains(placeHolder))
{
message.Append(mapArgs[placeHolder]);
cursor = endIndex + 1;
}
else
{
message.Append("[");
cursor++;
}
}
}
#endregion Event Message
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Modules;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Runtime {
/// <summary>
/// Importer class - used for importing modules. Used by Ops and __builtin__
/// Singleton living on Python engine.
/// </summary>
public static class Importer {
internal const string ModuleReloadMethod = "PerformModuleReload";
#region Internal API Surface
/// <summary>
/// Gateway into importing ... called from Ops. Performs the initial import of
/// a module and returns the module.
/// </summary>
public static object Import(CodeContext/*!*/ context, string fullName, PythonTuple from, int level) {
return LightExceptions.CheckAndThrow(ImportLightThrow(context, fullName, from, level));
}
/// <summary>
/// Gateway into importing ... called from Ops. Performs the initial import of
/// a module and returns the module. This version returns light exceptions instead of throwing.
/// </summary>
[LightThrowing]
internal static object ImportLightThrow(CodeContext/*!*/ context, string fullName, PythonTuple from, int level) {
PythonContext pc = PythonContext.GetContext(context);
if (level == -1) {
// no specific level provided, call the 4 param version so legacy code continues to work
var site = pc.OldImportSite;
return site.Target(
site,
context,
FindImportFunction(context),
fullName,
Builtin.globals(context),
context.Dict,
from
);
} else {
// relative import or absolute import, in other words:
//
// from . import xyz
// or
// from __future__ import absolute_import
var site = pc.ImportSite;
return site.Target(
site,
context,
FindImportFunction(context),
fullName,
Builtin.globals(context),
context.Dict,
from,
level
);
}
}
/// <summary>
/// Gateway into importing ... called from Ops. This is called after
/// importing the module and is used to return individual items from
/// the module. The outer modules dictionary is then updated with the
/// result.
/// </summary>
public static object ImportFrom(CodeContext/*!*/ context, object from, string name) {
PythonModule scope = from as PythonModule;
PythonType pt;
NamespaceTracker nt;
if (scope != null) {
object ret;
if (scope.GetType() == typeof(PythonModule)) {
if (scope.__dict__.TryGetValue(name, out ret)) {
return ret;
}
} else {
// subclass of module, it could have overridden __getattr__ or __getattribute__
if (PythonOps.TryGetBoundAttr(context, scope, name, out ret)) {
return ret;
}
}
object path;
List listPath;
if (scope.__dict__._storage.TryGetPath(out path) && (listPath = path as List) != null) {
return ImportNestedModule(context, scope, new [] {name}, 0, listPath);
}
} else if ((pt = from as PythonType) != null) {
PythonTypeSlot pts;
object res;
if (pt.TryResolveSlot(context, name, out pts) &&
pts.TryGetValue(context, null, pt, out res)) {
return res;
}
} else if ((nt = from as NamespaceTracker) != null) {
object res = NamespaceTrackerOps.GetCustomMember(context, nt, name);
if (res != OperationFailed.Value) {
return res;
}
} else {
// This is too lax, for example it allows from module.class import member
object ret;
if (PythonOps.TryGetBoundAttr(context, from, name, out ret)) {
return ret;
}
}
throw PythonOps.ImportError("Cannot import name {0}", name);
}
private static object ImportModuleFrom(CodeContext/*!*/ context, object from, string[] parts, int current) {
PythonModule scope = from as PythonModule;
if (scope != null) {
object path;
List listPath;
if (scope.__dict__._storage.TryGetPath(out path) && (listPath = path as List) != null) {
return ImportNestedModule(context, scope, parts, current, listPath);
}
}
NamespaceTracker ns = from as NamespaceTracker;
if (ns != null) {
object val;
if (ns.TryGetValue(parts[current], out val)) {
return MemberTrackerToPython(context, val);
}
}
throw PythonOps.ImportError("No module named {0}", parts[current]);
}
/// <summary>
/// Called by the __builtin__.__import__ functions (general importing) and ScriptEngine (for site.py)
///
/// level indiciates whether to perform absolute or relative imports.
/// -1 indicates both should be performed
/// 0 indicates only absolute imports should be performed
/// Positive numbers indicate the # of parent directories to search relative to the calling module
/// </summary>
public static object ImportModule(CodeContext/*!*/ context, object globals, string/*!*/ modName, bool bottom, int level) {
if (modName.IndexOf(Path.DirectorySeparatorChar) != -1) {
throw PythonOps.ImportError("Import by filename is not supported.", modName);
}
string package = null;
object attribute;
PythonDictionary pyGlobals = globals as PythonDictionary;
if (pyGlobals != null) {
if (pyGlobals._storage.TryGetPackage(out attribute)) {
package = attribute as string;
if (package == null && attribute != null) {
throw PythonOps.ValueError("__package__ set to non-string");
}
} else {
package = null;
if (level > 0) {
// explicit relative import, calculate and store __package__
object pathAttr, nameAttr;
if (pyGlobals._storage.TryGetName(out nameAttr) && nameAttr is string) {
if (pyGlobals._storage.TryGetPath(out pathAttr)) {
pyGlobals["__package__"] = nameAttr;
} else {
pyGlobals["__package__"] = ((string)nameAttr).rpartition(".")[0];
}
}
}
}
}
object newmod = null;
string firstName;
int firstDot = modName.IndexOf('.');
if (firstDot == -1) {
firstName = modName;
} else {
firstName = modName.Substring(0, firstDot);
}
string finalName = null;
if (level != 0) {
// try a relative import
// if importing a.b.c, import "a" first and then import b.c from a
string name; // name of the module we are to import in relation to the current module
PythonModule parentModule;
List path; // path to search
if (TryGetNameAndPath(context, globals, firstName, level, package, out name, out path, out parentModule)) {
finalName = name;
// import relative
if (!TryGetExistingOrMetaPathModule(context, name, path, out newmod)) {
newmod = ImportFromPath(context, firstName, name, path);
if (newmod == null) {
// add an indirection entry saying this module does not exist
// see http://www.python.org/doc/essays/packages.html "Dummy Entries"
context.LanguageContext.SystemStateModules[name] = null;
} else if (parentModule != null) {
parentModule.__dict__[firstName] = newmod;
}
} else if (firstDot == -1) {
// if we imported before having the assembly
// loaded and then loaded the assembly we want
// to make the assembly available now.
if (newmod is NamespaceTracker) {
context.ShowCls = true;
}
}
}
}
if (level <= 0) {
// try an absolute import
if (newmod == null) {
object parentPkg;
if (!String.IsNullOrEmpty(package) && !PythonContext.GetContext(context).SystemStateModules.TryGetValue(package, out parentPkg)) {
PythonModule warnModule = new PythonModule();
warnModule.__dict__["__file__"] = package;
warnModule.__dict__["__name__"] = package;
ModuleContext modContext = new ModuleContext(warnModule.__dict__, context.LanguageContext);
PythonOps.Warn(
modContext.GlobalContext,
PythonExceptions.RuntimeWarning,
"Parent module '{0}' not found while handling absolute import",
package);
}
newmod = ImportTopAbsolute(context, firstName);
finalName = firstName;
if (newmod == null) {
return null;
}
}
}
// now import the a.b.c etc. a needs to be included here
// because the process of importing could have modified
// sys.modules.
string[] parts = modName.Split('.');
object next = newmod;
string curName = null;
for (int i = 0; i < parts.Length; i++) {
curName = i == 0 ? finalName : curName + "." + parts[i];
object tmpNext;
if (TryGetExistingModule(context, curName, out tmpNext)) {
next = tmpNext;
if (i == 0) {
// need to update newmod if we pulled it out of sys.modules
// just in case we're in bottom mode.
newmod = next;
}
} else if (i != 0) {
// child module isn't loaded yet, import it.
next = ImportModuleFrom(context, next, parts, i);
} else {
// top-level module doesn't exist in sys.modules, probably
// came from some weird meta path hook.
newmod = next;
}
}
return bottom ? next : newmod;
}
/// <summary>
/// Interrogates the importing module for __name__ and __path__, which determine
/// whether the imported module (whose name is 'name') is being imported as nested
/// module (__path__ is present) or as sibling.
///
/// For sibling import, the full name of the imported module is parent.sibling
/// For nested import, the full name of the imported module is parent.module.nested
/// where parent.module is the mod.__name__
/// </summary>
/// <param name="context"></param>
/// <param name="globals">the globals dictionary</param>
/// <param name="name">Name of the module to be imported</param>
/// <param name="full">Output - full name of the module being imported</param>
/// <param name="path">Path to use to search for "full"</param>
/// <param name="level">the import level for relaive imports</param>
/// <param name="parentMod">the parent module</param>
/// <param name="package">the global __package__ value</param>
/// <returns></returns>
private static bool TryGetNameAndPath(CodeContext/*!*/ context, object globals, string name, int level, string package, out string full, out List path, out PythonModule parentMod) {
Debug.Assert(level != 0); // shouldn't be here for absolute imports
// Unless we can find enough information to perform relative import,
// we are going to import the module whose name we got
full = name;
path = null;
parentMod = null;
// We need to get __name__ to find the name of the imported module.
// If absent, fall back to absolute import
object attribute;
PythonDictionary pyGlobals = globals as PythonDictionary;
if (pyGlobals == null || !pyGlobals._storage.TryGetName(out attribute)) {
return false;
}
// And the __name__ needs to be string
string modName = attribute as string;
if (modName == null) {
return false;
}
string pn;
if (package == null) {
// If the module has __path__ (and __path__ is list), nested module is being imported
// otherwise, importing sibling to the importing module
if (pyGlobals._storage.TryGetPath(out attribute) && (path = attribute as List) != null) {
// found __path__, importing nested module. The actual name of the nested module
// is the name of the mod plus the name of the imported module
if (level == -1) {
// absolute import of some module
full = modName + "." + name;
object parentModule;
if (PythonContext.GetContext(context).SystemStateModules.TryGetValue(modName, out parentModule)) {
parentMod = parentModule as PythonModule;
}
} else if (String.IsNullOrEmpty(name)) {
// relative import of ancestor
full = (StringOps.rsplit(modName, ".", level - 1)[0] as string);
} else {
// relative import of some ancestors child
string parentName = (StringOps.rsplit(modName, ".", level - 1)[0] as string);
full = parentName + "." + name;
object parentModule;
if (PythonContext.GetContext(context).SystemStateModules.TryGetValue(parentName, out parentModule)) {
parentMod = parentModule as PythonModule;
}
}
return true;
}
// importing sibling. The name of the imported module replaces
// the last element in the importing module name
int lastDot = modName.LastIndexOf('.');
if (lastDot == -1) {
// name doesn't include dot, only absolute import possible
if (level > 0) {
throw PythonOps.ValueError("Attempted relative import in non-package");
}
return false;
}
// need to remove more than one name
int tmpLevel = level;
while (tmpLevel > 1 && lastDot != -1) {
lastDot = modName.LastIndexOf('.', lastDot - 1);
tmpLevel--;
}
if (lastDot == -1) {
pn = modName;
} else {
pn = modName.Substring(0, lastDot);
}
} else {
// __package__ doesn't include module name, so level is - 1.
pn = GetParentPackageName(level - 1, package.Split('.'));
}
path = GetParentPathAndModule(context, pn, out parentMod);
if (path != null) {
if (String.IsNullOrEmpty(name)) {
full = pn;
} else {
full = pn + "." + name;
}
return true;
}
if (level > 0) {
throw PythonOps.SystemError("Parent module '{0}' not loaded, cannot perform relative import", pn);
}
// not enough information - absolute import
return false;
}
private static string GetParentPackageName(int level, string[] names) {
StringBuilder parentName = new StringBuilder(names[0]);
if (level < 0) level = 1;
for (int i = 1; i < names.Length - level; i++) {
parentName.Append('.');
parentName.Append(names[i]);
}
return parentName.ToString();
}
public static object ReloadModule(CodeContext/*!*/ context, PythonModule/*!*/ module) {
return ReloadModule(context, module, null);
}
internal static object ReloadModule(CodeContext/*!*/ context, PythonModule/*!*/ module, PythonFile file) {
PythonContext pc = PythonContext.GetContext(context);
// We created the module and it only contains Python code. If the user changes
// __file__ we'll reload from that file.
string fileName = module.GetFile() as string;
// built-in module:
if (fileName == null) {
ReloadBuiltinModule(context, module);
return module;
}
string name = module.GetName() as string;
if (name != null) {
List path = null;
// find the parent module and get it's __path__ property
int dotIndex = name.LastIndexOf('.');
if (dotIndex != -1) {
PythonModule parentModule;
path = GetParentPathAndModule(context, name.Substring(0, dotIndex), out parentModule);
}
object reloaded;
if (TryLoadMetaPathModule(context, module.GetName() as string, path, out reloaded) && reloaded != null) {
return module;
}
List sysPath;
if (PythonContext.GetContext(context).TryGetSystemPath(out sysPath)) {
object ret = ImportFromPathHook(context, name, name, sysPath, null);
if (ret != null) {
return ret;
}
}
}
SourceUnit sourceUnit;
if (file != null) {
sourceUnit = pc.CreateSourceUnit(new PythonFileStreamContentProvider(file), fileName, file.Encoding, SourceCodeKind.File);
} else {
if (!pc.DomainManager.Platform.FileExists(fileName)) {
throw PythonOps.SystemError("module source file not found");
}
sourceUnit = pc.CreateFileUnit(fileName, pc.DefaultEncoding, SourceCodeKind.File);
}
pc.GetScriptCode(sourceUnit, name, ModuleOptions.None, Compiler.CompilationMode.Lookup).Run(module.Scope);
return module;
}
class PythonFileStreamContentProvider : StreamContentProvider {
private readonly PythonFile _file;
public PythonFileStreamContentProvider(PythonFile file) {
_file = file;
}
public override Stream GetStream() {
return _file._stream;
}
}
/// <summary>
/// Given the parent module name looks up the __path__ property.
/// </summary>
private static List GetParentPathAndModule(CodeContext/*!*/ context, string/*!*/ parentModuleName, out PythonModule parentModule) {
List path = null;
object parentModuleObj;
parentModule = null;
// Try lookup parent module in the sys.modules
if (PythonContext.GetContext(context).SystemStateModules.TryGetValue(parentModuleName, out parentModuleObj)) {
// see if it's a module
parentModule = parentModuleObj as PythonModule;
if (parentModule != null) {
object objPath;
// get its path as a List if it's there
if (parentModule.__dict__._storage.TryGetPath(out objPath)) {
path = objPath as List;
}
}
}
return path;
}
private static void ReloadBuiltinModule(CodeContext/*!*/ context, PythonModule/*!*/ module) {
Assert.NotNull(module);
Debug.Assert(module.GetName() is string, "Module is reloadable only if its name is a non-null string");
Type type;
string name = (string)module.GetName();
PythonContext pc = PythonContext.GetContext(context);
if (!pc.BuiltinModules.TryGetValue(name, out type)) {
throw PythonOps.ImportError("no module named {0}", module.GetName());
}
// should be a built-in module which we can reload.
Debug.Assert(((PythonDictionary)module.__dict__)._storage is ModuleDictionaryStorage);
((ModuleDictionaryStorage)module.__dict__._storage).Reload();
}
/// <summary>
/// Trys to get an existing module and if that fails fall backs to searching
/// </summary>
private static bool TryGetExistingOrMetaPathModule(CodeContext/*!*/ context, string fullName, List path, out object ret) {
if (TryGetExistingModule(context, fullName, out ret)) {
return true;
}
return TryLoadMetaPathModule(context, fullName, path, out ret);
}
/// <summary>
/// Attempts to load a module from sys.meta_path as defined in PEP 302.
///
/// The meta_path provides a list of importer objects which can be used to load modules before
/// searching sys.path but after searching built-in modules.
/// </summary>
private static bool TryLoadMetaPathModule(CodeContext/*!*/ context, string fullName, List path, out object ret) {
List metaPath = PythonContext.GetContext(context).GetSystemStateValue("meta_path") as List;
if (metaPath != null) {
foreach (object importer in (IEnumerable)metaPath) {
if (FindAndLoadModuleFromImporter(context, importer, fullName, path, out ret)) {
return true;
}
}
}
ret = null;
return false;
}
/// <summary>
/// Given a user defined importer object as defined in PEP 302 tries to load a module.
///
/// First the find_module(fullName, path) is invoked to get a loader, then load_module(fullName) is invoked
/// </summary>
private static bool FindAndLoadModuleFromImporter(CodeContext/*!*/ context, object importer, string fullName, List path, out object ret) {
object find_module = PythonOps.GetBoundAttr(context, importer, "find_module");
PythonContext pycontext = PythonContext.GetContext(context);
object loader = pycontext.Call(context, find_module, fullName, path);
if (loader != null) {
object findMod = PythonOps.GetBoundAttr(context, loader, "load_module");
ret = pycontext.Call(context, findMod, fullName);
return ret != null;
}
ret = null;
return false;
}
internal static bool TryGetExistingModule(CodeContext/*!*/ context, string/*!*/ fullName, out object ret) {
if (PythonContext.GetContext(context).SystemStateModules.TryGetValue(fullName, out ret)) {
return true;
}
return false;
}
#endregion
#region Private Implementation Details
private static object ImportTopAbsolute(CodeContext/*!*/ context, string/*!*/ name) {
object ret;
if (TryGetExistingModule(context, name, out ret)) {
if (IsReflected(ret)) {
// Even though we found something in sys.modules, we need to check if a
// clr.AddReference has invalidated it. So try ImportReflected again.
ret = ImportReflected(context, name) ?? ret;
}
NamespaceTracker rp = ret as NamespaceTracker;
if (rp != null || ret == PythonContext.GetContext(context).ClrModule) {
context.ShowCls = true;
}
return ret;
}
if (TryLoadMetaPathModule(context, name, null, out ret)) {
return ret;
}
ret = ImportBuiltin(context, name);
if (ret != null) return ret;
List path;
if (PythonContext.GetContext(context).TryGetSystemPath(out path)) {
ret = ImportFromPath(context, name, name, path);
if (ret != null) return ret;
}
ret = ImportReflected(context, name);
if (ret != null) return ret;
return null;
}
private static string [] SubArray(string[] t, int len) {
var ret = new string[len];
Array.Copy(t, ret, len);
return ret;
}
private static bool TryGetNestedModule(CodeContext/*!*/ context, PythonModule/*!*/ scope,
string[]/*!*/ parts, int current, out object nested) {
string name = parts[current];
Assert.NotNull(context, scope, name);
if (scope.__dict__.TryGetValue(name, out nested)) {
var pm = nested as PythonModule;
if (pm != null) {
var fullPath = ".".join(SubArray(parts, current));
// double check, some packages mess with package namespace
// see cp35116
if (pm.GetName() == fullPath) {
return true;
}
}
// This allows from System.Math import *
PythonType dt = nested as PythonType;
if (dt != null && dt.IsSystemType) {
return true;
}
}
return false;
}
private static object ImportNestedModule(CodeContext/*!*/ context, PythonModule/*!*/ module,
string[] parts, int current, List/*!*/ path) {
object ret;
string name = parts[current];
string fullName = CreateFullName(module.GetName() as string, name);
if (TryGetExistingOrMetaPathModule(context, fullName, path, out ret)) {
module.__dict__[name] = ret;
return ret;
}
if (TryGetNestedModule(context, module, parts, current, out ret)) {
return ret;
}
ImportFromPath(context, name, fullName, path);
object importedModule;
if (PythonContext.GetContext(context).SystemStateModules.TryGetValue(fullName, out importedModule)) {
module.__dict__[name] = importedModule;
return importedModule;
}
throw PythonOps.ImportError("cannot import {0} from {1}", name, module.GetName());
}
private static object FindImportFunction(CodeContext/*!*/ context) {
PythonDictionary builtins = context.GetBuiltinsDict() ?? PythonContext.GetContext(context).BuiltinModuleDict;
object import;
if (builtins._storage.TryGetImport(out import)) {
return import;
}
throw PythonOps.ImportError("cannot find __import__");
}
internal static object ImportBuiltin(CodeContext/*!*/ context, string/*!*/ name) {
Assert.NotNull(context, name);
PythonContext pc = PythonContext.GetContext(context);
if (name == "sys") {
return pc.SystemState;
} else if (name == "clr") {
context.ShowCls = true;
pc.SystemStateModules["clr"] = pc.ClrModule;
return pc.ClrModule;
}
return pc.GetBuiltinModule(name);
}
private static object ImportReflected(CodeContext/*!*/ context, string/*!*/ name) {
object ret;
PythonContext pc = PythonContext.GetContext(context);
if (!PythonOps.ScopeTryGetMember(context, pc.DomainManager.Globals, name, out ret) &&
(ret = pc.TopNamespace.TryGetPackageAny(name)) == null) {
ret = TryImportSourceFile(pc, name);
}
ret = MemberTrackerToPython(context, ret);
if (ret != null) {
PythonContext.GetContext(context).SystemStateModules[name] = ret;
}
return ret;
}
internal static object MemberTrackerToPython(CodeContext/*!*/ context, object ret) {
MemberTracker res = ret as MemberTracker;
if (res != null) {
context.ShowCls = true;
object realRes = res;
switch (res.MemberType) {
case TrackerTypes.Type: realRes = DynamicHelpers.GetPythonTypeFromType(((TypeTracker)res).Type); break;
case TrackerTypes.Field: realRes = PythonTypeOps.GetReflectedField(((FieldTracker)res).Field); break;
case TrackerTypes.Event: realRes = PythonTypeOps.GetReflectedEvent((EventTracker)res); break;
case TrackerTypes.Method:
MethodTracker mt = res as MethodTracker;
realRes = PythonTypeOps.GetBuiltinFunction(mt.DeclaringType, mt.Name, new MemberInfo[] { mt.Method });
break;
}
ret = realRes;
}
return ret;
}
internal static PythonModule TryImportSourceFile(PythonContext/*!*/ context, string/*!*/ name) {
var sourceUnit = TryFindSourceFile(context, name);
PlatformAdaptationLayer pal = context.DomainManager.Platform;
if (sourceUnit == null ||
GetFullPathAndValidateCase(context, pal.CombinePaths(pal.GetDirectoryName(sourceUnit.Path), name + pal.GetExtension(sourceUnit.Path)), false) == null) {
return null;
}
var scope = ExecuteSourceUnit(context, sourceUnit);
if (sourceUnit.LanguageContext != context) {
// foreign language, we should publish in sys.modules too
context.SystemStateModules[name] = scope;
}
PythonOps.ScopeSetMember(context.SharedContext, sourceUnit.LanguageContext.DomainManager.Globals, name, scope);
return scope;
}
internal static PythonModule ExecuteSourceUnit(PythonContext context, SourceUnit/*!*/ sourceUnit) {
ScriptCode compiledCode = sourceUnit.Compile();
Scope scope = compiledCode.CreateScope();
PythonModule res = ((PythonScopeExtension)context.EnsureScopeExtension(scope)).Module;
compiledCode.Run(scope);
return res;
}
internal static SourceUnit TryFindSourceFile(PythonContext/*!*/ context, string/*!*/ name) {
List paths;
if (!context.TryGetSystemPath(out paths)) {
return null;
}
foreach (object dirObj in paths) {
string directory = dirObj as string;
if (directory == null) continue; // skip invalid entries
string candidatePath = null;
LanguageContext candidateLanguage = null;
foreach (string extension in context.DomainManager.Configuration.GetFileExtensions()) {
string fullPath;
try {
fullPath = context.DomainManager.Platform.CombinePaths(directory, name + extension);
} catch (ArgumentException) {
// skip invalid paths
continue;
}
if (context.DomainManager.Platform.FileExists(fullPath)) {
if (candidatePath != null) {
throw PythonOps.ImportError(String.Format("Found multiple modules of the same name '{0}': '{1}' and '{2}'",
name, candidatePath, fullPath));
}
candidatePath = fullPath;
candidateLanguage = context.DomainManager.GetLanguageByExtension(extension);
}
}
if (candidatePath != null) {
return candidateLanguage.CreateFileUnit(candidatePath);
}
}
return null;
}
private static bool IsReflected(object module) {
// corresponds to the list of types that can be returned by ImportReflected
return module is MemberTracker
|| module is PythonType
|| module is ReflectedEvent
|| module is ReflectedField
|| module is BuiltinFunction;
}
private static string CreateFullName(string/*!*/ baseName, string name) {
if (baseName == null || baseName.Length == 0 || baseName == "__main__") {
return name;
}
return baseName + "." + name;
}
#endregion
private static object ImportFromPath(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ fullName, List/*!*/ path) {
return ImportFromPathHook(context, name, fullName, path, LoadFromDisk);
}
private static object ImportFromPathHook(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ fullName, List/*!*/ path, Func<CodeContext, string, string, string, object> defaultLoader) {
Assert.NotNull(context, name, fullName, path);
IDictionary<object, object> importCache = PythonContext.GetContext(context).GetSystemStateValue("path_importer_cache") as IDictionary<object, object>;
if (importCache == null) {
return null;
}
foreach (object dirname in (IEnumerable)path) {
string str = dirname as string;
if (str != null || (Converter.TryConvertToString(dirname, out str) && str != null)) { // ignore non-string
object importer;
if (!importCache.TryGetValue(str, out importer)) {
importCache[str] = importer = FindImporterForPath(context, str);
}
if (importer != null) {
// user defined importer object, get the loader and use it.
object ret;
if (FindAndLoadModuleFromImporter(context, importer, fullName, null, out ret)) {
return ret;
}
} else if (defaultLoader != null) {
object res = defaultLoader(context, name, fullName, str);
if (res != null) {
return res;
}
}
}
}
return null;
}
internal static bool TryImportMainFromZip(CodeContext/*!*/ context, string/*!*/ path, out object importer) {
Assert.NotNull(context, path);
var importCache = PythonContext.GetContext(context).GetSystemStateValue("path_importer_cache") as IDictionary<object, object>;
if (importCache == null) {
importer = null;
return false;
}
importCache[path] = importer = FindImporterForPath(context, path);
if (importer == null) {
return false;
}
// for consistency with cpython, insert zip as a first entry into sys.path
var syspath = PythonContext.GetContext(context).GetSystemStateValue("path") as List;
if (syspath != null) {
syspath.Insert(0, path);
}
object dummy;
return FindAndLoadModuleFromImporter(context, importer, "__main__", null, out dummy);
}
private static object LoadFromDisk(CodeContext context, string name, string fullName, string str) {
// default behavior
PythonModule module;
string pathname = context.LanguageContext.DomainManager.Platform.CombinePaths(str, name);
module = LoadPackageFromSource(context, fullName, pathname);
if (module != null) {
return module;
}
string filename = pathname + ".py";
module = LoadModuleFromSource(context, fullName, filename);
if (module != null) {
return module;
}
return null;
}
/// <summary>
/// Finds a user defined importer for the given path or returns null if no importer
/// handles this path.
/// </summary>
private static object FindImporterForPath(CodeContext/*!*/ context, string dirname) {
List pathHooks = PythonContext.GetContext(context).GetSystemStateValue("path_hooks") as List;
foreach (object hook in (IEnumerable)pathHooks) {
try {
object handler = PythonCalls.Call(context, hook, dirname);
if (handler != null) {
return handler;
}
} catch (ImportException) {
// we can't handle the path
}
}
#if !SILVERLIGHT // DirectoryExists isn't implemented on Silverlight
if (!context.LanguageContext.DomainManager.Platform.DirectoryExists(dirname)) {
return new PythonImport.NullImporter(dirname);
}
#endif
return null;
}
private static PythonModule LoadModuleFromSource(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ path) {
Assert.NotNull(context, name, path);
PythonContext pc = PythonContext.GetContext(context);
string fullPath = GetFullPathAndValidateCase(pc, path, false);
if (fullPath == null || !pc.DomainManager.Platform.FileExists(fullPath)) {
return null;
}
SourceUnit sourceUnit = pc.CreateFileUnit(fullPath, pc.DefaultEncoding, SourceCodeKind.File);
return LoadFromSourceUnit(context, sourceUnit, name, sourceUnit.Path);
}
private static string GetFullPathAndValidateCase(LanguageContext/*!*/ context, string path, bool isDir) {
#if !SILVERLIGHT
// check for a match in the case of the filename, unfortunately we can't do this
// in Silverlight becauase there's no way to get the original filename.
PlatformAdaptationLayer pal = context.DomainManager.Platform;
string dir = pal.GetDirectoryName(path);
if (!pal.DirectoryExists(dir)) {
return null;
}
try {
string file = pal.GetFileName(path);
string[] files = pal.GetFileSystemEntries(dir, file, !isDir, isDir);
if (files.Length != 1 || pal.GetFileName(files[0]) != file) {
return null;
}
return pal.GetFullPath(files[0]);
} catch (IOException) {
return null;
}
#else
return path;
#endif
}
internal static PythonModule LoadPackageFromSource(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ path) {
Assert.NotNull(context, name, path);
path = GetFullPathAndValidateCase(PythonContext.GetContext(context), path, true);
if (path == null) {
return null;
}
return LoadModuleFromSource(context, name, context.LanguageContext.DomainManager.Platform.CombinePaths(path, "__init__.py"));
}
private static PythonModule/*!*/ LoadFromSourceUnit(CodeContext/*!*/ context, SourceUnit/*!*/ sourceCode, string/*!*/ name, string/*!*/ path) {
Assert.NotNull(sourceCode, name, path);
return PythonContext.GetContext(context).CompileModule(path, name, sourceCode, ModuleOptions.Initialize | ModuleOptions.Optimized);
}
}
}
| |
// 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>
/// PublicIPAddressesOperations operations.
/// </summary>
public partial interface IPublicIPAddressesOperations
{
/// <summary>
/// Deletes the specified public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </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 publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified public IP address in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </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<PublicIPAddress>> GetWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a static or dynamic public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the public IP address.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update public IP address
/// 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<PublicIPAddress>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the public IP addresses in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all public IP addresses in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource 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<PublicIPAddress>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </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 publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a static or dynamic public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the public IP address.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update public IP address
/// 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<PublicIPAddress>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the public IP addresses in a subscription.
/// </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<PublicIPAddress>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all public IP addresses in a resource 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<PublicIPAddress>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using NUnit.Framework;
using Braintree.Exceptions;
namespace Braintree.Tests
{
//NOTE: good
[TestFixture]
public class CreditCardTest
{
private BraintreeGateway gateway;
private BraintreeService service;
static readonly string EXP_MONTH_YEAR = "5/22";
static readonly string EXP_MONTH = "05";
static readonly string EXP_YEAR = "2022";
static CreditCardTest()
{
EXP_MONTH = DateTime.Today.Month.ToString();
EXP_YEAR = (DateTime.Today.Year + 5).ToString();
EXP_MONTH_YEAR = EXP_MONTH + "/" + EXP_YEAR;
}
[SetUp]
public void Setup()
{
gateway = new BraintreeGateway();
service = new BraintreeService(gateway.Configuration);
}
#pragma warning disable 0618
[Test]
public void TransparentRedirectURLForCreate_ReturnsCorrectValue()
{
Assert.AreEqual(service.BaseMerchantURL() + "/payment_methods/all/create_via_transparent_redirect_request",
gateway.CreditCard.TransparentRedirectURLForCreate());
}
#pragma warning restore 0618
#pragma warning disable 0618
[Test]
public void TransparentRedirectURLForUpdate_ReturnsCorrectValue()
{
Assert.AreEqual(service.BaseMerchantURL() + "/payment_methods/all/update_via_transparent_redirect_request",
gateway.CreditCard.TransparentRedirectURLForUpdate());
}
#pragma warning restore 0618
[Test]
public void TrData_ReturnsValidTrDataHash()
{
string trData = gateway.TrData(new CreditCardRequest(), "http://example.com");
Assert.IsTrue(TrUtil.IsTrDataValid(trData, service));
}
[Test]
public void Create_CreatesCreditCardForGivenCustomerId()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123",
CardholderName = "Michael Angelo",
BillingAddress = new CreditCardAddressRequest
{
FirstName = "John",
CountryName = "Chad",
CountryCodeAlpha2 = "TD",
CountryCodeAlpha3 = "TCD",
CountryCodeNumeric = "148"
}
};
CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target;
Assert.AreEqual("555555", creditCard.Bin);
Assert.AreEqual("4444", creditCard.LastFour);
Assert.AreEqual("555555******4444", creditCard.MaskedNumber);
Assert.AreEqual(EXP_MONTH, creditCard.ExpirationMonth);
Assert.AreEqual(EXP_YEAR, creditCard.ExpirationYear);
Assert.AreEqual("Michael Angelo", creditCard.CardholderName);
Assert.IsTrue(creditCard.IsDefault.Value);
Assert.IsFalse(creditCard.IsVenmoSdk.Value);
Assert.AreEqual(DateTime.Now.Year, creditCard.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, creditCard.UpdatedAt.Value.Year);
Assert.IsNotNull(creditCard.ImageUrl);
Address billingAddress = creditCard.BillingAddress;
Assert.AreEqual("Chad", billingAddress.CountryName);
Assert.AreEqual("TD", billingAddress.CountryCodeAlpha2);
Assert.AreEqual("TCD", billingAddress.CountryCodeAlpha3);
Assert.AreEqual("148", billingAddress.CountryCodeNumeric);
Assert.IsTrue(Regex.IsMatch(creditCard.UniqueNumberIdentifier, "\\A\\w{32}\\z"));
}
[Test]
public void Create_CreatesCreditCardWithAVenmoSdkPaymentMethodCode()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
VenmoSdkPaymentMethodCode = SandboxValues.VenmoSdk.VISA_PAYMENT_METHOD_CODE,
};
Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest);
Assert.IsTrue(result.IsSuccess());
CreditCard creditCard = result.Target;
Assert.AreEqual("1111", creditCard.LastFour);
Assert.IsTrue(creditCard.IsVenmoSdk.Value);
}
[Test]
public void Create_CreatesCreditCardWithSecurityParams()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
DeviceSessionId = "abc123",
FraudMerchantId = "7",
CardholderName = "John Doe",
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
BillingAddress = new CreditCardAddressRequest
{
CountryName = "Greece",
CountryCodeAlpha2 = "GR",
CountryCodeAlpha3 = "GRC",
CountryCodeNumeric = "300"
}
};
Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest);
Assert.IsTrue(result.IsSuccess());
}
[Test]
public void Create_CreatesCreditCardWithDeviceData()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
DeviceData = "{\"device_session_id\":\"my_dsid\", \"fraud_merchant_id\":\"7\"}",
CardholderName = "John Doe",
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
BillingAddress = new CreditCardAddressRequest
{
CountryName = "Greece",
CountryCodeAlpha2 = "GR",
CountryCodeAlpha3 = "GRC",
CountryCodeNumeric = "300"
}
};
Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest);
Assert.IsTrue(result.IsSuccess());
}
[Test]
public void Create_FailsToCreateCreditCardWithInvalidVenmoSdkPaymentMethodCode()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
VenmoSdkPaymentMethodCode = SandboxValues.VenmoSdk.INVALID_PAYMENT_METHOD_CODE,
};
Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual("Invalid VenmoSDK payment method code", result.Message);
Assert.AreEqual(
ValidationErrorCode.CREDIT_CARD_INVALID_VENMO_SDK_PAYMENT_METHOD_CODE,
result.Errors.ForObject("CreditCard").OnField("VenmoSdkPaymentMethodCode")[0].Code
);
}
[Test]
public void Create_AddsCardToVenmoSdkWithValidSession()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VenmoSdkSession = SandboxValues.VenmoSdk.SESSION
}
};
Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest);
CreditCard card = result.Target;
Assert.IsTrue(result.IsSuccess());
Assert.IsTrue(card.IsVenmoSdk.Value);
}
[Test]
public void Create_DoesNotAddCardToVenmoSdkWithInvalidSession()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VenmoSdkSession = SandboxValues.VenmoSdk.INVALID_SESSION
}
};
Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest);
CreditCard card = result.Target;
Assert.IsTrue(result.IsSuccess());
Assert.IsFalse(card.IsVenmoSdk.Value);
}
[Test]
public void Create_AcceptsBillingAddressId()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest addressRequest = new AddressRequest
{
FirstName = "John",
CountryName = "Chad",
CountryCodeAlpha2 = "TD",
CountryCodeAlpha3 = "TCD",
CountryCodeNumeric = "148"
};
Address address = gateway.Address.Create(customer.Id, addressRequest).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123",
CardholderName = "Michael Angelo",
BillingAddressId = address.Id,
};
CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target;
Address billingAddress = creditCard.BillingAddress;
Assert.AreEqual(address.Id, billingAddress.Id);
Assert.AreEqual("Chad", billingAddress.CountryName);
Assert.AreEqual("TD", billingAddress.CountryCodeAlpha2);
Assert.AreEqual("TCD", billingAddress.CountryCodeAlpha3);
Assert.AreEqual("148", billingAddress.CountryCodeNumeric);
}
#pragma warning disable 0618
[Test]
public void ConfirmTransparentRedirectCreate_CreatesTheCreditCard()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest trParams = new CreditCardRequest { CustomerId = customer.Id };
CreditCardRequest request = new CreditCardRequest
{
CardholderName = "John Doe",
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
BillingAddress = new CreditCardAddressRequest
{
CountryName = "Greece",
CountryCodeAlpha2 = "GR",
CountryCodeAlpha3 = "GRC",
CountryCodeNumeric = "300"
}
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.CreditCard.TransparentRedirectURLForCreate(), service);
Result<CreditCard> result = gateway.CreditCard.ConfirmTransparentRedirect(queryString);
Assert.IsTrue(result.IsSuccess());
CreditCard card = result.Target;
Assert.AreEqual("John Doe", card.CardholderName);
Assert.AreEqual("555555", card.Bin);
Assert.AreEqual(EXP_MONTH, card.ExpirationMonth);
Assert.AreEqual(EXP_YEAR, card.ExpirationYear);
Assert.AreEqual(EXP_MONTH_YEAR, card.ExpirationDate);
Assert.AreEqual("4444", card.LastFour);
Assert.IsTrue(card.Token != null);
Address billingAddress = card.BillingAddress;
Assert.AreEqual("Greece", billingAddress.CountryName);
Assert.AreEqual("GR", billingAddress.CountryCodeAlpha2);
Assert.AreEqual("GRC", billingAddress.CountryCodeAlpha3);
Assert.AreEqual("300", billingAddress.CountryCodeNumeric);
}
#pragma warning restore 0618
#pragma warning disable 0618
[Test]
public void ConfirmTransparentRedirectCreate_CreatesTheCreditCardObservingMakeDefaultInTRParams()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
Assert.IsTrue(creditCard.IsDefault.Value);
CreditCardRequest trParams = new CreditCardRequest
{
CustomerId = customer.Id,
Options = new CreditCardOptionsRequest
{
MakeDefault = true
}
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.CreditCard.TransparentRedirectURLForCreate(), service);
CreditCard card = gateway.CreditCard.ConfirmTransparentRedirect(queryString).Target;
Assert.IsTrue(card.IsDefault.Value);
}
#pragma warning restore 0618
#pragma warning disable 0618
[Test]
public void ConfirmTransparentRedirectCreate_CreatesTheCreditCardObservingMakeDefaultInRequest()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
MakeDefault = true
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
Assert.IsTrue(creditCard.IsDefault.Value);
CreditCardRequest trParams = new CreditCardRequest
{
CustomerId = customer.Id,
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.CreditCard.TransparentRedirectURLForCreate(), service);
CreditCard card = gateway.CreditCard.ConfirmTransparentRedirect(queryString).Target;
Assert.IsTrue(card.IsDefault.Value);
}
#pragma warning restore 0618
#pragma warning disable 0618
[Test]
public void ConfirmTransparentRedirectCreate_WithErrors()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest trParams = new CreditCardRequest { CustomerId = customer.Id };
CreditCardRequest request = new CreditCardRequest
{
CardholderName = "John Doe",
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
BillingAddress = new CreditCardAddressRequest
{
CountryName = "Greece",
CountryCodeAlpha2 = "MX"
}
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.CreditCard.TransparentRedirectURLForCreate(), service);
Result<CreditCard> result = gateway.CreditCard.ConfirmTransparentRedirect(queryString);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.ADDRESS_INCONSISTENT_COUNTRY,
result.Errors.ForObject("CreditCard").ForObject("BillingAddress").OnField("Base")[0].Code
);
}
#pragma warning restore 0618
[Test]
public void Find_FindsCreditCardByToken()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123",
CardholderName = "Michael Angelo"
};
CreditCard originalCreditCard = gateway.CreditCard.Create(creditCardRequest).Target;
CreditCard creditCard = gateway.CreditCard.Find(originalCreditCard.Token);
Assert.AreEqual("555555", creditCard.Bin);
Assert.AreEqual("4444", creditCard.LastFour);
Assert.AreEqual(EXP_MONTH, creditCard.ExpirationMonth);
Assert.AreEqual(EXP_YEAR, creditCard.ExpirationYear);
Assert.AreEqual("Michael Angelo", creditCard.CardholderName);
Assert.AreEqual(DateTime.Now.Year, creditCard.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, creditCard.UpdatedAt.Value.Year);
}
[Test]
public void Find_FindsAssociatedSubscriptions()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123"
};
CreditCard originalCreditCard = gateway.CreditCard.Create(creditCardRequest).Target;
string id = Guid.NewGuid().ToString();
var subscriptionRequest = new SubscriptionRequest
{
Id = id,
PlanId = "integration_trialless_plan",
PaymentMethodToken = originalCreditCard.Token,
Price = 1.00M
};
var resp = gateway.Subscription.Create(subscriptionRequest);
Assert.IsNotNull(resp);
if (!resp.IsSuccess())
Assert.Inconclusive(resp.Message);
else
{
CreditCard creditCard = gateway.CreditCard.Find(originalCreditCard.Token);
Assert.IsNotNull(creditCard);
Assert.IsNotEmpty(creditCard.Subscriptions);
Subscription subscription = creditCard.Subscriptions[0];
Assert.IsNotNull(subscription);
Assert.AreEqual(id, subscription.Id);
Assert.AreEqual("integration_trialless_plan", subscription.PlanId);
Assert.AreEqual(1.00M, subscription.Price);
}
}
[Test]
public void Find_FindsErrorsOutOnWhitespaceIds()
{
try {
gateway.CreditCard.Find(" ");
Assert.Fail("Should throw NotFoundException");
} catch (NotFoundException) {}
}
[Test]
public void FromNonce_ExchangesANonceForACreditCard()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
string nonce = TestHelper.GenerateUnlockedNonce(gateway, "4012888888881881", customer.Id);
CreditCard card = gateway.CreditCard.FromNonce(nonce);
Assert.AreEqual("401288******1881", card.MaskedNumber);
}
[Test]
public void FromNonce_ReturnsErrorWhenProvidedNoncePointingToUnlockedSharedCard()
{
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
try {
gateway.CreditCard.FromNonce(nonce);
Assert.Fail("Should throw NotFoundException");
} catch (NotFoundException e) {
StringAssert.Contains("not found", e.Message);
}
}
[Test]
public void FromNonce_ReturnsErrorWhenProvidedConsumedNonce()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
string nonce = TestHelper.GenerateUnlockedNonce(gateway, "4012888888881881", customer.Id);
gateway.CreditCard.FromNonce(nonce);
try {
gateway.CreditCard.FromNonce(nonce);
Assert.Fail("Should throw NotFoundException");
} catch (NotFoundException e) {
StringAssert.Contains("consumed", e.Message);
}
}
[Test]
public void Update_UpdatesCreditCardByToken()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardCreateRequest = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123",
CardholderName = "Michael Angelo"
};
CreditCard originalCreditCard = gateway.CreditCard.Create(creditCardCreateRequest).Target;
var creditCardUpdateRequest = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "4111111111111111",
ExpirationDate = "12/25",
CVV = "321",
CardholderName = "Dave Inchy"
};
CreditCard creditCard = gateway.CreditCard.Update(originalCreditCard.Token, creditCardUpdateRequest).Target;
Assert.AreEqual("411111", creditCard.Bin);
Assert.AreEqual("1111", creditCard.LastFour);
Assert.AreEqual("12", creditCard.ExpirationMonth);
Assert.AreEqual("2025", creditCard.ExpirationYear);
Assert.AreEqual("Dave Inchy", creditCard.CardholderName);
Assert.AreEqual(DateTime.Now.Year, creditCard.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, creditCard.UpdatedAt.Value.Year);
}
[Test]
public void Create_SetsDefaultIfSpecified()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var request1 = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123",
CardholderName = "Michael Angelo"
};
var request2 = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123",
CardholderName = "Michael Angelo",
Options = new CreditCardOptionsRequest
{
MakeDefault = true
},
};
CreditCard card1 = gateway.CreditCard.Create(request1).Target;
CreditCard card2 = gateway.CreditCard.Create(request2).Target;
Assert.IsFalse(gateway.CreditCard.Find(card1.Token).IsDefault.Value);
Assert.IsTrue(gateway.CreditCard.Find(card2.Token).IsDefault.Value);
}
[Test]
public void Update_UpdatesDefaultIfSpecified()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardCreateRequest = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123",
CardholderName = "Michael Angelo"
};
CreditCard card1 = gateway.CreditCard.Create(creditCardCreateRequest).Target;
CreditCard card2 = gateway.CreditCard.Create(creditCardCreateRequest).Target;
Assert.IsTrue(card1.IsDefault.Value);
Assert.IsFalse(card2.IsDefault.Value);
var creditCardUpdateRequest = new CreditCardRequest
{
Options = new CreditCardOptionsRequest
{
MakeDefault = true
}
};
gateway.CreditCard.Update(card2.Token, creditCardUpdateRequest);
Assert.IsFalse(gateway.CreditCard.Find(card1.Token).IsDefault.Value);
Assert.IsTrue(gateway.CreditCard.Find(card2.Token).IsDefault.Value);
}
[Test]
public void Update_CreatesNewBillingAddressByDefault()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
Assert.IsNotNull(customer);
var request = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123",
BillingAddress = new CreditCardAddressRequest
{
FirstName = "John",
PostalCode = "90025",
StreetAddress = "123 fake st",
}
};
var resp = gateway.CreditCard.Create(request);
Assert.IsNotNull(resp);
CreditCard creditCard = resp.Target;
Assert.IsNotNull(creditCard, resp.Message);
var updateRequest = new CreditCardRequest
{
CVV = "123",
BillingAddress = new CreditCardAddressRequest
{
LastName = "Jones",
CountryName = "El Salvador",
CountryCodeAlpha2 = "SV",
CountryCodeAlpha3 = "SLV",
CountryCodeNumeric = "222",
PostalCode = "90025",
StreetAddress = "123 fake st",
}
};
var uresp = gateway.CreditCard.Update(creditCard.Token, updateRequest);
Assert.IsNotNull(uresp);
CreditCard updatedCreditCard = uresp.Target;
Assert.IsNotNull(updatedCreditCard, uresp.Message);
Assert.IsNull(updatedCreditCard.BillingAddress.FirstName);
Assert.AreEqual("Jones", updatedCreditCard.BillingAddress.LastName);
Assert.AreNotEqual(creditCard.BillingAddress.Id, updatedCreditCard.BillingAddress.Id);
Address billingAddress = updatedCreditCard.BillingAddress;
Assert.AreEqual("El Salvador", billingAddress.CountryName);
Assert.AreEqual("SV", billingAddress.CountryCodeAlpha2);
Assert.AreEqual("SLV", billingAddress.CountryCodeAlpha3);
Assert.AreEqual("222", billingAddress.CountryCodeNumeric);
}
[Test]
public void Update_UpdatesExistingBillingAddressWhenUpdateExistingIsTrue()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var request = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123",
BillingAddress = new CreditCardAddressRequest
{
FirstName = "John",
PostalCode = "90025",
StreetAddress = "123 fake st",
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
var updateRequest = new CreditCardRequest
{
CVV = "123",
BillingAddress = new CreditCardAddressRequest
{
LastName = "Jones",
PostalCode = "90025",
StreetAddress = "123 fake st",
Options = new CreditCardAddressOptionsRequest
{
UpdateExisting = true
}
}
};
var uresp = gateway.CreditCard.Update(creditCard.Token, updateRequest);
Assert.IsNotNull(uresp);
CreditCard updatedCreditCard = uresp.Target;
Assert.IsNotNull(updatedCreditCard, uresp.Message);
Assert.AreEqual("John", updatedCreditCard.BillingAddress.FirstName);
Assert.AreEqual("Jones", updatedCreditCard.BillingAddress.LastName);
Assert.AreEqual(creditCard.BillingAddress.Id, updatedCreditCard.BillingAddress.Id);
}
#pragma warning disable 0618
[Test]
public void Update_UpdatesExistingBillingAddressWhenUpdateExistingIsTrueViaTransparentRedirect()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var request = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123",
BillingAddress = new CreditCardAddressRequest
{
FirstName = "John",
PostalCode = "90025",
StreetAddress = "123 fake st",
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
CreditCardRequest trParams = new CreditCardRequest
{
PaymentMethodToken = creditCard.Token,
BillingAddress = new CreditCardAddressRequest
{
Options = new CreditCardAddressOptionsRequest
{
UpdateExisting = true
}
}
};
CreditCardRequest updateRequest = new CreditCardRequest
{
BillingAddress = new CreditCardAddressRequest
{
LastName = "Jones",
PostalCode = "90025",
StreetAddress = "123 fake st",
}
};
string queryString = TestHelper.QueryStringForTR(trParams, updateRequest, gateway.CreditCard.TransparentRedirectURLForUpdate(), service);
var resp = gateway.CreditCard.ConfirmTransparentRedirect(queryString);
Assert.IsNotNull(resp);
CreditCard updatedCreditCard = resp.Target;
Assert.IsNotNull(updatedCreditCard, resp.Message);
Assert.AreEqual("John", updatedCreditCard.BillingAddress.FirstName);
Assert.AreEqual("Jones", updatedCreditCard.BillingAddress.LastName);
Assert.AreEqual(creditCard.BillingAddress.Id, updatedCreditCard.BillingAddress.Id);
}
#pragma warning restore 0618
#pragma warning disable 0618
[Test]
public void UpdateViaTransparentRedirect()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest createRequest = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123",
BillingAddress = new CreditCardAddressRequest
{
PostalCode = "44444"
}
};
CreditCard createdCard = gateway.CreditCard.Create(createRequest).Target;
CreditCardRequest trParams = new CreditCardRequest
{
PaymentMethodToken = createdCard.Token
};
CreditCardRequest request = new CreditCardRequest
{
CardholderName = "Joe Cool"
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.CreditCard.TransparentRedirectURLForUpdate(), service);
Result<CreditCard> result = gateway.CreditCard.ConfirmTransparentRedirect(queryString);
Assert.IsTrue(result.IsSuccess());
CreditCard card = result.Target;
Assert.AreEqual("Joe Cool", card.CardholderName);
Assert.AreEqual("44444", card.BillingAddress.PostalCode);
}
#pragma warning restore 0618
[Test]
public void Delete_DeletesTheCreditCard()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
CVV = "123",
CardholderName = "Michael Angelo"
};
CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target;
Assert.AreEqual(creditCard.Token, gateway.CreditCard.Find(creditCard.Token).Token);
gateway.CreditCard.Delete(creditCard.Token);
try
{
gateway.CreditCard.Find(creditCard.Token);
Assert.Fail("Expected NotFoundException.");
}
catch (NotFoundException)
{
// expected
}
}
[Test]
public void CheckDuplicateCreditCard()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = "4111111111111111",
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
FailOnDuplicatePaymentMethod = true
}
};
gateway.CreditCard.Create(request);
Result<CreditCard> result = gateway.CreditCard.Create(request);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.CREDIT_CARD_DUPLICATE_CARD_EXISTS,
result.Errors.ForObject("CreditCard").OnField("Number")[0].Code
);
}
[Test]
public void VerifyValidCreditCard()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = "4111111111111111",
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
Result<CreditCard> result = gateway.CreditCard.Create(request);
Assert.IsTrue(result.IsSuccess());
}
[Test]
public void VerifyValidCreditCardWithVerificationRiskData()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = "4111111111111111",
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
Result<CreditCard> result = gateway.CreditCard.Create(request);
Assert.IsTrue(result.IsSuccess());
CreditCard card = result.Target;
CreditCardVerification verification = card.Verification;
Assert.IsNotNull(verification);
Assert.IsNotNull(verification.RiskData);
}
[Test]
public void VerifyValidCreditCardWithVerificationAmount()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = "4111111111111111",
ExpirationDate = EXP_MONTH_YEAR,
BillingAddress = new CreditCardAddressRequest
{
StreetAddress = "123 fake st",
PostalCode = "90025",
},
Options = new CreditCardOptionsRequest
{
VerifyCard = true,
VerificationAmount = "1.02"
}
};
Result<CreditCard> result = gateway.CreditCard.Create(request);
Assert.IsTrue(result.IsSuccess(), result.Message);
}
[Test]
public void VerifyValidCreditCardSpecifyingMerhantAccount()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = "5555555555554444",
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true,
VerificationMerchantAccountId = MerchantAccountIDs.NON_DEFAULT_MERCHANT_ACCOUNT_ID,
}
};
Result<CreditCard> result = gateway.CreditCard.Create(request);
if (result.IsSuccess())
{
Assert.IsNotNull(result.CreditCardVerification, result.Message);
Assert.AreEqual(MerchantAccountIDs.NON_DEFAULT_MERCHANT_ACCOUNT_ID, result.CreditCardVerification.MerchantAccountId);
}
else
Assert.Inconclusive(result.Message);
}
[Test]
public void VerifyInvalidCreditCard()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = "5105105105105100",
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
Result<CreditCard> result = gateway.CreditCard.Create(request);
Assert.IsFalse(result.IsSuccess());
CreditCardVerification verification = result.CreditCardVerification;
Assert.AreEqual(VerificationStatus.PROCESSOR_DECLINED, verification.Status);
Assert.IsNull(verification.GatewayRejectionReason);
}
[Test]
public void GatewayRejectionReason_ExposedOnVerification()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "200",
Number = "4111111111111111",
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
},
};
Result<CreditCard> result = gateway.CreditCard.Create(request);
Assert.IsFalse(result.IsSuccess());
CreditCardVerification verification = result.CreditCardVerification;
Assert.AreEqual(TransactionGatewayRejectionReason.CVV, verification.GatewayRejectionReason);
}
[Test]
public void Expired()
{
ResourceCollection<CreditCard> collection = gateway.CreditCard.Expired();
Assert.IsTrue(collection.MaximumCount > 1);
List<string> cards = new List<string>();
foreach (CreditCard card in collection) {
Assert.IsTrue(card.IsExpired.Value);
cards.Add(card.Token);
}
HashSet<string> uniqueCards = new HashSet<string>(cards);
Assert.AreEqual(uniqueCards.Count, collection.MaximumCount);
}
[Test]
public void ExpiringBetween()
{
int year = DateTime.Today.Year;
DateTime beginning = new DateTime(year, 1, 1);
DateTime end = new DateTime(year, 12, 31);
ResourceCollection<CreditCard> collection = gateway.CreditCard.ExpiringBetween(beginning, end);
Assert.IsTrue(collection.MaximumCount > 1);
List<string> cards = new List<string>();
foreach (CreditCard card in collection) {
Assert.AreEqual(year.ToString(), card.ExpirationYear);
cards.Add(card.Token);
}
HashSet<string> uniqueCards = new HashSet<string>(cards);
Assert.AreEqual(uniqueCards.Count, collection.MaximumCount);
}
[Test]
public void Prepaid()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = Braintree.Tests.CreditCardNumbers.CardTypeIndicators.Prepaid,
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
Assert.AreEqual(Braintree.CreditCardPrepaid.YES, creditCard.Prepaid);
}
[Test]
public void Commercial()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = Braintree.Tests.CreditCardNumbers.CardTypeIndicators.Commercial,
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
Assert.AreEqual(Braintree.CreditCardCommercial.YES, creditCard.Commercial);
}
[Test]
public void Debit()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = Braintree.Tests.CreditCardNumbers.CardTypeIndicators.Debit,
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
Assert.AreEqual(Braintree.CreditCardDebit.YES, creditCard.Debit);
}
[Test]
public void Healthcare()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = Braintree.Tests.CreditCardNumbers.CardTypeIndicators.Healthcare,
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
Assert.AreEqual(Braintree.CreditCardHealthcare.YES, creditCard.Healthcare);
}
[Test]
public void Payroll()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = Braintree.Tests.CreditCardNumbers.CardTypeIndicators.Payroll,
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
Assert.AreEqual(Braintree.CreditCardPayroll.YES, creditCard.Payroll);
}
[Test]
public void DurbinRegulated()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = Braintree.Tests.CreditCardNumbers.CardTypeIndicators.DurbinRegulated,
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
Assert.AreEqual(Braintree.CreditCardDurbinRegulated.YES, creditCard.DurbinRegulated);
}
[Test]
public void CountryOfIssuance()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = Braintree.Tests.CreditCardNumbers.CardTypeIndicators.CountryOfIssuance,
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
Assert.AreEqual(Braintree.Tests.CreditCardDefaults.CountryOfIssuance, creditCard.CountryOfIssuance);
}
[Test]
public void IssuingBank()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = Braintree.Tests.CreditCardNumbers.CardTypeIndicators.IssuingBank,
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
Assert.AreEqual(Braintree.Tests.CreditCardDefaults.IssuingBank, creditCard.IssuingBank);
}
[Test]
public void NegativeCardTypeIndicators()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = Braintree.Tests.CreditCardNumbers.CardTypeIndicators.No,
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
Assert.AreEqual(Braintree.CreditCardPrepaid.NO, creditCard.Prepaid);
Assert.AreEqual(Braintree.CreditCardCommercial.NO, creditCard.Commercial);
Assert.AreEqual(Braintree.CreditCardHealthcare.NO, creditCard.Healthcare);
Assert.AreEqual(Braintree.CreditCardDurbinRegulated.NO, creditCard.DurbinRegulated);
Assert.AreEqual(Braintree.CreditCardPayroll.NO, creditCard.Payroll);
Assert.AreEqual(Braintree.CreditCardDebit.NO, creditCard.Debit);
}
[Test]
public void MissingCardTypeIndicators()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = Braintree.Tests.CreditCardNumbers.CardTypeIndicators.Unknown,
ExpirationDate = EXP_MONTH_YEAR,
Options = new CreditCardOptionsRequest
{
VerifyCard = true
}
};
CreditCard creditCard = gateway.CreditCard.Create(request).Target;
Assert.AreEqual(Braintree.CreditCardPrepaid.UNKNOWN, creditCard.Prepaid);
Assert.AreEqual(Braintree.CreditCardCommercial.UNKNOWN, creditCard.Commercial);
Assert.AreEqual(Braintree.CreditCardHealthcare.UNKNOWN, creditCard.Healthcare);
Assert.AreEqual(Braintree.CreditCardDurbinRegulated.UNKNOWN, creditCard.DurbinRegulated);
Assert.AreEqual(Braintree.CreditCardPayroll.UNKNOWN, creditCard.Payroll);
Assert.AreEqual(Braintree.CreditCardDebit.UNKNOWN, creditCard.Debit);
Assert.AreEqual(Braintree.CreditCard.CountryOfIssuanceUnknown, creditCard.CountryOfIssuance);
Assert.AreEqual(Braintree.CreditCard.IssuingBankUnknown, creditCard.IssuingBank);
}
[Test]
public void CreateWithPaymentMethodNonce()
{
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
PaymentMethodNonce = nonce
};
Result<CreditCard> result = gateway.CreditCard.Create(request);
Assert.IsTrue(result.IsSuccess());
}
[Test]
public void VerificationIsLatestVerification()
{
string xml = "<credit-card>"
+ "<verifications>"
+ " <verification>"
+ " <created-at type=\"datetime\">2014-11-20T17:27:15Z</created-at>"
+ " <id>123</id>"
+ " </verification>"
+ " <verification>"
+ " <created-at type=\"datetime\">2014-11-20T17:27:18Z</created-at>"
+ " <id>932</id>"
+ " </verification>"
+ " <verification>"
+ " <created-at type=\"datetime\">2014-11-20T17:27:17Z</created-at>"
+ " <id>456</id>"
+ " </verification>"
+ "</verifications>"
+ "</credit-card>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode newNode = doc.DocumentElement;
var node = new NodeWrapper(newNode);
var result = new ResultImpl<CreditCard>(node, gateway);
Assert.AreEqual("932", result.Target.Verification.Id);
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: MarginCollapsingState.cs
//
// Description: Provides paragraph level margin collapsing support.
//
// History:
// 05/05/2003 : [....] - moving from Avalon branch.
//
//---------------------------------------------------------------------------
using System;
namespace MS.Internal.PtsHost
{
// ----------------------------------------------------------------------
// MarginCollapsingState class provides paragraph level margin collapsing
// support.
//
// Adjoining vertical margins of two paragraphs collapse. The resulting
// margin width is the maximum of the adjoining margin widths. In the case
// of negative margins, the absolute maximum of the negative adjoining
// margins is deducted from the maximum of the positive adjoining margins.
// If there are no positive margins, the absolute maximum of the negative
// adjoining margins is deducted from zero.
// ----------------------------------------------------------------------
internal sealed class MarginCollapsingState : UnmanagedHandle
{
// ------------------------------------------------------------------
// Create new margin collapsing state and collapse margins if necessary.
// If no collapsing happens, retrieve margin from old collapsing state.
// This margin value should be used to advance pen.
// ------------------------------------------------------------------
internal static void CollapseTopMargin(
PtsContext ptsContext, // Current PTS Context.
MbpInfo mbp, // MBP information for element entering the scope
MarginCollapsingState mcsCurrent, // current margin collapsing state (adjacent to the new one).
out MarginCollapsingState mcsNew, // margin collapsing state for element entering the scope
out int margin) // collapsed margin value
{
margin = 0;
mcsNew = null;
// Create new margin collapsing info
mcsNew = new MarginCollapsingState(ptsContext, mbp.MarginTop);
// collapse margins, if current margin collapsing exists
if (mcsCurrent != null)
{
mcsNew.Collapse(mcsCurrent);
}
// If border or paddind is specified:
// (1) get collapsed margin value
// (2) set new mcs to null, because we don't have one anymore
if (mbp.BPTop != 0)
{
margin = mcsNew.Margin;
mcsNew.Dispose();
mcsNew = null;
}
else if (mcsCurrent == null && DoubleUtil.IsZero(mbp.Margin.Top))
{
// No need to create new margin collapsing info
mcsNew.Dispose();
mcsNew = null;
}
}
// ------------------------------------------------------------------
// Update current margin collapsing state and collapse margins if
// necessary. If no collapsing happens, retrieve margin from previous
// collapsing state. This margin value should be used to advance pen.
// ------------------------------------------------------------------
internal static void CollapseBottomMargin(
PtsContext ptsContext, // Current PTS Context.
MbpInfo mbp, // MBP information for element leaving the scope
MarginCollapsingState mcsCurrent, // current margin collapsing state (adjacent to the new one).
out MarginCollapsingState mcsNew, // margin collapsing state for element leaving the scope
out int margin) // collapsed margin value
{
margin = 0;
mcsNew = null;
// Create new margin collapsing state, if necessary
if (!DoubleUtil.IsZero(mbp.Margin.Bottom))
{
mcsNew = new MarginCollapsingState(ptsContext, mbp.MarginBottom);
}
// If the current margin collapsing state does not exist, we are done.
// Otherwise, get current border and padding and decide if to collapse margin.
if (mcsCurrent != null)
{
if (mbp.BPBottom != 0)
{
// No collapsing happens, get margin value
margin = mcsCurrent.Margin;
}
else
{
// Collapse margins
if (mcsNew == null)
{
mcsNew = new MarginCollapsingState(ptsContext, 0);
}
mcsNew.Collapse(mcsCurrent);
}
}
}
// ------------------------------------------------------------------
// Constructor.
//
// ptsContext - Current PTS context.
// margin - margin value
// ------------------------------------------------------------------
internal MarginCollapsingState(PtsContext ptsContext, int margin) : base(ptsContext)
{
_maxPositive = (margin >= 0) ? margin : 0;
_minNegative = (margin < 0) ? margin : 0;
}
// ------------------------------------------------------------------
// Constructor. Make identical copy of the margin collapsing state.
//
// mcs - margin collapsing state to copy
// ------------------------------------------------------------------
private MarginCollapsingState(MarginCollapsingState mcs) : base(mcs.PtsContext)
{
_maxPositive = mcs._maxPositive;
_minNegative = mcs._minNegative;
}
// ------------------------------------------------------------------
// Make identical copy of the margin collapsing state.
//
// Returns: identical copy of margin collapsing state.
// ------------------------------------------------------------------
internal MarginCollapsingState Clone()
{
return new MarginCollapsingState(this);
}
// ------------------------------------------------------------------
// Compare margin collapsing state with another one.
//
// mcs - another margin collapsing state
//
// Returns: 'true' if both are the same.
// ------------------------------------------------------------------
internal bool IsEqual(MarginCollapsingState mcs)
{
return (_maxPositive == mcs._maxPositive && _minNegative == mcs._minNegative);
}
// ------------------------------------------------------------------
// The resulting margin width is the maximum of the adjoining margin
// widths. In the case of negative margins, the absolute maximum of
// the negative adjoining margins is deducted from the maximum of
// the positive adjoining margins. If there are no positive margins,
// the absolute maximum of the negative adjoining margins is deducted
// from zero.
//
// mcs - margin collapsing state to collapse with
// ------------------------------------------------------------------
internal void Collapse(MarginCollapsingState mcs)
{
_maxPositive = Math.Max(_maxPositive, mcs._maxPositive);
_minNegative = Math.Min(_minNegative, mcs._minNegative);
}
// ------------------------------------------------------------------
// The resulting margin width is the maximum of the adjoining margin
// widths. In the case of negative margins, the absolute maximum of
// the negative adjoining margins is deducted from the maximum of
// the positive adjoining margins. If there are no positive margins,
// the absolute maximum of the negative adjoining margins is deducted
// from zero.
//
// margin - margin value to collapse with
// ------------------------------------------------------------------
//internal void Collapse(int margin)
//{
// _maxPositive = Math.Max(_maxPositive, margin);
// _minNegative = Math.Min(_minNegative, margin);
//}
// ------------------------------------------------------------------
// Actual margin value.
// ------------------------------------------------------------------
internal int Margin { get { return _maxPositive + _minNegative; } }
// ------------------------------------------------------------------
// Maximum positive and minimum negative value for margin.
// ------------------------------------------------------------------
private int _maxPositive;
private int _minNegative;
}
}
| |
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 RegPetServer.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>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//-----------------------------------------------------------------------------
// PageFlipTracker.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework;
using System.Diagnostics;
namespace GameStateManagement
{
/// <remarks>
/// PageFlipTracker watches the touchpanel for drag and flick gestures, and computes the appropriate
/// offsets for flipping horizontally through a multi-page display. It is used by PageFlipControl
/// to handle the scroll logic. PageFlipTracker is broken out into a separate class so that XNA apps
/// with their own scheme for UI controls can still use it to handle the scroll logic.
///
/// Handling TouchPanel.EnabledGestures
/// --------------------------
/// This class watches for HorizontalDrag, DragComplete, and Flick gestures. However, it cannot just
/// set TouchPanel.EnabledGestures, because that would most likely interfere with gestures needed
/// elsewhere in the application. So it just exposes a const 'HandledGestures' field and relies on
/// the client code to set TouchPanel.EnabledGestures appropriately.
///
/// Handling screen rotation
/// ------------------------
/// This class uses TouchPanel.DisplayWidth to determine the width of the screen. DisplayWidth
/// is automatically updated by the system when the orientation changes.
/// </remarks>
public class PageFlipTracker
{
public const GestureType GesturesNeeded = GestureType.Flick | GestureType.HorizontalDrag | GestureType.DragComplete;
#region Tuning options
public static TimeSpan FlipDuration = TimeSpan.FromSeconds(0.3);
/// <summary>
/// Exponent on curve to make page flips and springbacks start quickly and slow to a stop.
///
/// Interpolation formula is (1-TransitionAlpha)^TransitionExponent, where
/// TransitionAlpha animates uniformly from 0 to 1 over timespan FlipDuration.
/// </summary>
public static double FlipExponent = 3.0;
/// <summary>
/// By default, this many pixels of the next page will be visible
/// on the right-hand edge of the screen, unless the current page's
/// contentWidth is too large.
/// </summary>
public static int PreviewMargin = 20;
/// <summary>
/// How far (as a fraction of the total screen width) you have
/// to drag a screen past its edge to trigger a flip by dragging.
/// </summary>
public static float DragToFlipTheshold = 1.0f / 3.0f;
#endregion
#region Private fields
// Time stamp when transition started
private DateTime flipStartTime;
// Horizontal offset at start of current transition. Target offset is always 0.
private float flipStartOffset;
#endregion
#region Properties
// Current active page. If we're in a transition, this is the page we're transitioning TO.
public int CurrentPage { get; private set; }
// Offset in pixels to render currentPage at. If this is positive, other
// pages may be visible to the left.
//
// This is always relative to the current page.
public float CurrentPageOffset { get; private set; }
public bool IsLeftPageVisible
{
get
{
return PageWidthList.Count >= 2 && CurrentPageOffset > 0;
}
}
public bool IsRightPageVisible
{
get
{
return PageWidthList.Count >= 2 && CurrentPageOffset + EffectivePageWidth(CurrentPage) <= TouchPanel.DisplayWidth;
}
}
// True if we're currently in a transition
public bool InFlip { get; private set; }
// Alpha value that animates from 0 to 1 during a spring. Will be 1 when not springing.
public float FlipAlpha { get; private set; }
// PageWidthList contains the width in pixels of each page. Pages can be added or removed at any time by
// changing this list.
public List<int> PageWidthList = new List<int>();
#endregion
public PageFlipTracker()
{
}
public int EffectivePageWidth(int page)
{
int displayWidth = TouchPanel.DisplayWidth - PreviewMargin;
return Math.Max(displayWidth, PageWidthList[page]);
}
// Update is called once per frame.
public void Update()
{
if (InFlip)
{
TimeSpan transitionClock = DateTime.Now - flipStartTime;
if (transitionClock >= FlipDuration)
{
EndFlip();
}
else
{
double f = transitionClock.TotalSeconds / FlipDuration.TotalSeconds;
f = Math.Max(f, 0.0); // this shouldn't happen, but just in case time goes crazy
FlipAlpha = (float)(1 - Math.Pow(1 - f, FlipExponent));
CurrentPageOffset = flipStartOffset * (1 - FlipAlpha);
}
}
}
public void HandleInput(InputState input)
{
foreach (GestureSample sample in input.Gestures)
{
switch (sample.GestureType)
{
case GestureType.HorizontalDrag:
CurrentPageOffset += sample.Delta.X;
flipStartOffset = CurrentPageOffset;
break;
case GestureType.DragComplete:
if (!InFlip)
{
if (CurrentPageOffset < -TouchPanel.DisplayWidth * DragToFlipTheshold)
{
// flip to next page
BeginFlip(1);
}
else if (CurrentPageOffset + TouchPanel.DisplayWidth * (1 - DragToFlipTheshold) > EffectivePageWidth(CurrentPage))
{
// flip to previous page
BeginFlip(-1);
}
else
{
// "snap back" effect when you drag a little and let go
BeginFlip(0);
}
}
break;
case GestureType.Flick:
// Only respond to mostly-horizontal flicks
if (Math.Abs(sample.Delta.X) > Math.Abs(sample.Delta.Y))
{
if (sample.Delta.X > 0)
{
BeginFlip(-1);
}
else
{
BeginFlip(1);
}
}
break;
}
}
}
void BeginFlip(int pageDelta)
{
if(PageWidthList.Count == 0)
return;
int pageFrom = CurrentPage;
CurrentPage = (CurrentPage + pageDelta + PageWidthList.Count) % PageWidthList.Count;
if (pageDelta > 0)
{
// going to next page; offset starts out large
CurrentPageOffset += EffectivePageWidth(pageFrom);
}
else if(pageDelta < 0)
{
// going to previous page; offset starts out negative
CurrentPageOffset -= EffectivePageWidth(CurrentPage);
}
InFlip = true;
FlipAlpha = 0;
flipStartOffset = CurrentPageOffset;
flipStartTime = DateTime.Now;
}
// FIXME: private
void EndFlip()
{
InFlip = false;
FlipAlpha = 1;
CurrentPageOffset = 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.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
namespace System
{
public partial class String
{
//
//Native Static Methods
//
private unsafe static int CompareOrdinalIgnoreCaseHelper(String strA, String strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
int length = Math.Min(strA.Length, strB.Length);
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
int charA = 0, charB = 0;
while (length != 0)
{
charA = *a;
charB = *b;
Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20;
//Return the (case-insensitive) difference between them.
if (charA != charB)
return charA - charB;
// Next char
a++; b++;
length--;
}
return strA.Length - strB.Length;
}
}
// native call to COMString::CompareOrdinalEx
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int CompareOrdinalHelper(String strA, int indexA, int countA, String strB, int indexB, int countB);
//This will not work in case-insensitive mode for any character greater than 0x80.
//We'll throw an ArgumentException.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern int nativeCompareOrdinalIgnoreCaseWC(String strA, sbyte* strBBytes);
//
//
// NATIVE INSTANCE METHODS
//
//
//
// Search/Query methods
//
private unsafe static bool EqualsHelper(String strA, String strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
Debug.Assert(strA.Length == strB.Length);
int length = strA.Length;
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
#if BIT64
// Single int read aligns pointers for the following long reads
// PERF: No length check needed as there is always an int32 worth of string allocated
// This read can also include the null terminator which both strings will have
if (*(int*)a != *(int*)b) return false;
length -= 2; a += 2; b += 2;
// for AMD64 bit platform we unroll by 12 and
// check 3 qword at a time. This is less code
// than the 32 bit case and is a shorter path length.
while (length >= 12)
{
if (*(long*)a != *(long*)b) return false;
if (*(long*)(a + 4) != *(long*)(b + 4)) return false;
if (*(long*)(a + 8) != *(long*)(b + 8)) return false;
length -= 12; a += 12; b += 12;
}
#else
while (length >= 10)
{
if (*(int*)a != *(int*)b) return false;
if (*(int*)(a + 2) != *(int*)(b + 2)) return false;
if (*(int*)(a + 4) != *(int*)(b + 4)) return false;
if (*(int*)(a + 6) != *(int*)(b + 6)) return false;
if (*(int*)(a + 8) != *(int*)(b + 8)) return false;
length -= 10; a += 10; b += 10;
}
#endif
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) return false;
length -= 2; a += 2; b += 2;
}
return true;
}
}
private unsafe static bool EqualsIgnoreCaseAsciiHelper(String strA, String strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
Debug.Assert(strA.Length == strB.Length);
int length = strA.Length;
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
while (length != 0)
{
int charA = *a;
int charB = *b;
Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
// Ordinal equals or lowercase equals if the result ends up in the a-z range
if (charA == charB ||
((charA | 0x20) == (charB | 0x20) &&
(uint)((charA | 0x20) - 'a') <= (uint)('z' - 'a')))
{
a++;
b++;
length--;
}
else
{
return false;
}
}
return true;
}
}
private unsafe static bool StartsWithOrdinalHelper(String str, String startsWith)
{
Debug.Assert(str != null);
Debug.Assert(startsWith != null);
Debug.Assert(str.Length >= startsWith.Length);
int length = startsWith.Length;
fixed (char* ap = &str._firstChar) fixed (char* bp = &startsWith._firstChar)
{
char* a = ap;
char* b = bp;
#if BIT64
// Single int read aligns pointers for the following long reads
// No length check needed as this method is called when length >= 2
Debug.Assert(length >= 2);
if (*(int*)a != *(int*)b) return false;
length -= 2; a += 2; b += 2;
while (length >= 12)
{
if (*(long*)a != *(long*)b) return false;
if (*(long*)(a + 4) != *(long*)(b + 4)) return false;
if (*(long*)(a + 8) != *(long*)(b + 8)) return false;
length -= 12; a += 12; b += 12;
}
#else
while (length >= 10)
{
if (*(int*)a != *(int*)b) return false;
if (*(int*)(a+2) != *(int*)(b+2)) return false;
if (*(int*)(a+4) != *(int*)(b+4)) return false;
if (*(int*)(a+6) != *(int*)(b+6)) return false;
if (*(int*)(a+8) != *(int*)(b+8)) return false;
length -= 10; a += 10; b += 10;
}
#endif
while (length >= 2)
{
if (*(int*)a != *(int*)b) return false;
length -= 2; a += 2; b += 2;
}
// PERF: This depends on the fact that the String objects are always zero terminated
// and that the terminating zero is not included in the length. For even string sizes
// this compare can include the zero terminator. Bitwise OR avoids a branch.
return length == 0 | *a == *b;
}
}
private static unsafe int CompareOrdinalHelper(String strA, String strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
// NOTE: This may be subject to change if eliminating the check
// in the callers makes them small enough to be inlined
Debug.Assert(strA._firstChar == strB._firstChar,
"For performance reasons, callers of this method should " +
"check/short-circuit beforehand if the first char is the same.");
int length = Math.Min(strA.Length, strB.Length);
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
// Check if the second chars are different here
// The reason we check if _firstChar is different is because
// it's the most common case and allows us to avoid a method call
// to here.
// The reason we check if the second char is different is because
// if the first two chars the same we can increment by 4 bytes,
// leaving us word-aligned on both 32-bit (12 bytes into the string)
// and 64-bit (16 bytes) platforms.
// For empty strings, the second char will be null due to padding.
// The start of the string (not including sync block pointer)
// is the method table pointer + string length, which takes up
// 8 bytes on 32-bit, 12 on x64. For empty strings the null
// terminator immediately follows, leaving us with an object
// 10/14 bytes in size. Since everything needs to be a multiple
// of 4/8, this will get padded and zeroed out.
// For one-char strings the second char will be the null terminator.
// NOTE: If in the future there is a way to read the second char
// without pinning the string (e.g. System.Runtime.CompilerServices.Unsafe
// is exposed to mscorlib, or a future version of C# allows inline IL),
// then do that and short-circuit before the fixed.
if (*(a + 1) != *(b + 1)) goto DiffOffset1;
// Since we know that the first two chars are the same,
// we can increment by 2 here and skip 4 bytes.
// This leaves us 8-byte aligned, which results
// on better perf for 64-bit platforms.
length -= 2; a += 2; b += 2;
// unroll the loop
#if BIT64
while (length >= 12)
{
if (*(long*)a != *(long*)b) goto DiffOffset0;
if (*(long*)(a + 4) != *(long*)(b + 4)) goto DiffOffset4;
if (*(long*)(a + 8) != *(long*)(b + 8)) goto DiffOffset8;
length -= 12; a += 12; b += 12;
}
#else // BIT64
while (length >= 10)
{
if (*(int*)a != *(int*)b) goto DiffOffset0;
if (*(int*)(a + 2) != *(int*)(b + 2)) goto DiffOffset2;
if (*(int*)(a + 4) != *(int*)(b + 4)) goto DiffOffset4;
if (*(int*)(a + 6) != *(int*)(b + 6)) goto DiffOffset6;
if (*(int*)(a + 8) != *(int*)(b + 8)) goto DiffOffset8;
length -= 10; a += 10; b += 10;
}
#endif // BIT64
// Fallback loop:
// go back to slower code path and do comparison on 4 bytes at a time.
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) goto DiffNextInt;
length -= 2;
a += 2;
b += 2;
}
// At this point, we have compared all the characters in at least one string.
// The longer string will be larger.
return strA.Length - strB.Length;
#if BIT64
DiffOffset8: a += 4; b += 4;
DiffOffset4: a += 4; b += 4;
#else // BIT64
// Use jumps instead of falling through, since
// otherwise going to DiffOffset8 will involve
// 8 add instructions before getting to DiffNextInt
DiffOffset8: a += 8; b += 8; goto DiffOffset0;
DiffOffset6: a += 6; b += 6; goto DiffOffset0;
DiffOffset4: a += 2; b += 2;
DiffOffset2: a += 2; b += 2;
#endif // BIT64
DiffOffset0:
// If we reached here, we already see a difference in the unrolled loop above
#if BIT64
if (*(int*)a == *(int*)b)
{
a += 2; b += 2;
}
#endif // BIT64
DiffNextInt:
if (*a != *b) return *a - *b;
DiffOffset1:
Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
return *(a + 1) - *(b + 1);
}
}
// Provides a culture-correct string comparison. StrA is compared to StrB
// to determine whether it is lexicographically less, equal, or greater, and then returns
// either a negative integer, 0, or a positive integer; respectively.
//
public static int Compare(String strA, String strB)
{
return Compare(strA, strB, StringComparison.CurrentCulture);
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
// The case-sensitive option is set by ignoreCase
//
public static int Compare(String strA, String strB, bool ignoreCase)
{
var comparisonType = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
return Compare(strA, strB, comparisonType);
}
// Provides a more flexible function for string comparision. See StringComparison
// for meaning of different comparisonType.
public static int Compare(String strA, String strB, StringComparison comparisonType)
{
// Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase]
if ((uint)(comparisonType - StringComparison.CurrentCulture) > (uint)(StringComparison.OrdinalIgnoreCase - StringComparison.CurrentCulture))
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
if (object.ReferenceEquals(strA, strB))
{
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
return -1;
}
if (strB == null)
{
return 1;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
// Most common case: first character is different.
// Returns false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
case StringComparison.OrdinalIgnoreCase:
// If both strings are ASCII strings, we can take the fast path.
if (strA.IsAscii() && strB.IsAscii())
{
return (CompareOrdinalIgnoreCaseHelper(strA, strB));
}
return CompareInfo.CompareOrdinalIgnoreCase(strA, 0, strA.Length, strB, 0, strB.Length);
default:
throw new NotSupportedException(SR.NotSupported_StringComparison);
}
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
//
public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
return culture.CompareInfo.Compare(strA, strB, options);
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
// The case-sensitive option is set by ignoreCase, and the culture is set
// by culture
//
public static int Compare(String strA, String strB, bool ignoreCase, CultureInfo culture)
{
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return Compare(strA, strB, culture, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length count is compared with the substring of strB
// beginning at indexB of the same length.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length)
{
// NOTE: It's important we call the boolean overload, and not the StringComparison
// one. The two have some subtly different behavior (see notes in the former).
return Compare(strA, indexA, strB, indexB, length, ignoreCase: false);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length count is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase)
{
// Ideally we would just forward to the string.Compare overload that takes
// a StringComparison parameter, and just pass in CurrentCulture/CurrentCultureIgnoreCase.
// That function will return early if an optimization can be applied, e.g. if
// (object)strA == strB && indexA == indexB then it will return 0 straightaway.
// There are a couple of subtle behavior differences that prevent us from doing so
// however:
// - string.Compare(null, -1, null, -1, -1, StringComparison.CurrentCulture) works
// since that method also returns early for nulls before validation. It shouldn't
// for this overload.
// - Since we originally forwarded to CompareInfo.Compare for all of the argument
// validation logic, the ArgumentOutOfRangeExceptions thrown will contain different
// parameter names.
// Therefore, we have to duplicate some of the logic here.
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean,
// and the culture is set by culture.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, CultureInfo culture)
{
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return Compare(strA, indexA, strB, indexB, length, culture, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length, CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
return culture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
}
public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (strA.Length - indexA < 0 || strB.Length - indexB < 0)
{
string paramName = strA.Length - indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
case StringComparison.OrdinalIgnoreCase:
return (CompareInfo.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB));
default:
throw new ArgumentException(SR.NotSupported_StringComparison);
}
}
// Compares strA and strB using an ordinal (code-point) comparison.
//
public static int CompareOrdinal(String strA, String strB)
{
if (object.ReferenceEquals(strA, strB))
{
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
return -1;
}
if (strB == null)
{
return 1;
}
// Most common case, first character is different.
// This will return false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
}
// TODO https://github.com/dotnet/corefx/issues/21395: Expose this publicly?
internal static int CompareOrdinal(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB)
{
// TODO: This needs to be optimized / unrolled. It can't just use CompareOrdinalHelper(str, str)
// (changed to accept spans) because its implementation is based on a string layout,
// in a way that doesn't work when there isn't guaranteed to be a null terminator.
int minLength = Math.Min(strA.Length, strB.Length);
for (int i = 0; i < minLength; i++)
{
if (strA[i] != strB[i])
{
return strA[i] - strB[i];
}
}
return strA.Length - strB.Length;
}
// Compares strA and strB using an ordinal (code-point) comparison.
//
public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length)
{
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
// COMPAT: Checking for nulls should become before the arguments are validated,
// but other optimizations which allow us to return early should come after.
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeCount);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
if (lengthA < 0 || lengthB < 0)
{
string paramName = lengthA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
}
// Compares this String to another String (cast as object), returning an integer that
// indicates the relationship. This method returns a value less than 0 if this is less than value, 0
// if this is equal to value, or a value greater than 0 if this is greater than value.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
string other = value as string;
if (other == null)
{
throw new ArgumentException(SR.Arg_MustBeString);
}
return CompareTo(other); // will call the string-based overload
}
// Determines the sorting relation of StrB to the current instance.
//
public int CompareTo(String strB)
{
return string.Compare(this, strB, StringComparison.CurrentCulture);
}
// Determines whether a specified string is a suffix of the current instance.
//
// The case-sensitive and culture-sensitive option is set by options,
// and the default culture is used.
//
public Boolean EndsWith(String value)
{
return EndsWith(value, StringComparison.CurrentCulture);
}
public Boolean EndsWith(String value, StringComparison comparisonType)
{
if ((Object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
if ((Object)this == (Object)value)
{
return true;
}
if (value.Length == 0)
{
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.IsSuffix(this, value, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.IsSuffix(this, value, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return this.Length < value.Length ? false : (CompareOrdinalHelper(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
case StringComparison.OrdinalIgnoreCase:
return this.Length < value.Length ? false : (CompareInfo.CompareOrdinalIgnoreCase(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public Boolean EndsWith(String value, Boolean ignoreCase, CultureInfo culture)
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
return true;
}
CultureInfo referenceCulture;
if (culture == null)
referenceCulture = CultureInfo.CurrentCulture;
else
referenceCulture = culture;
return referenceCulture.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
public bool EndsWith(char value)
{
int thisLen = Length;
return thisLen != 0 && this[thisLen - 1] == value;
}
// Determines whether two strings match.
public override bool Equals(Object obj)
{
if (object.ReferenceEquals(this, obj))
return true;
string str = obj as string;
if (str == null)
return false;
if (this.Length != str.Length)
return false;
return EqualsHelper(this, str);
}
// Determines whether two strings match.
public bool Equals(String value)
{
if (object.ReferenceEquals(this, value))
return true;
// NOTE: No need to worry about casting to object here.
// If either side of an == comparison between strings
// is null, Roslyn generates a simple ceq instruction
// instead of calling string.op_Equality.
if (value == null)
return false;
if (this.Length != value.Length)
return false;
return EqualsHelper(this, value);
}
public bool Equals(String value, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
if ((Object)this == (Object)value)
{
return true;
}
if ((Object)value == null)
{
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.None) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.IgnoreCase) == 0);
case StringComparison.InvariantCulture:
return (CultureInfo.InvariantCulture.CompareInfo.Compare(this, value, CompareOptions.None) == 0);
case StringComparison.InvariantCultureIgnoreCase:
return (CultureInfo.InvariantCulture.CompareInfo.Compare(this, value, CompareOptions.IgnoreCase) == 0);
case StringComparison.Ordinal:
if (this.Length != value.Length)
return false;
return EqualsHelper(this, value);
case StringComparison.OrdinalIgnoreCase:
if (this.Length != value.Length)
return false;
// If both strings are ASCII strings, we can take the fast path.
if (this.IsAscii() && value.IsAscii())
{
return EqualsIgnoreCaseAsciiHelper(this, value);
}
return (CompareInfo.CompareOrdinalIgnoreCase(this, 0, this.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Determines whether two Strings match.
public static bool Equals(String a, String b)
{
if ((Object)a == (Object)b)
{
return true;
}
if ((Object)a == null || (Object)b == null || a.Length != b.Length)
{
return false;
}
return EqualsHelper(a, b);
}
public static bool Equals(String a, String b, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
if ((Object)a == (Object)b)
{
return true;
}
if ((Object)a == null || (Object)b == null)
{
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0);
case StringComparison.InvariantCulture:
return (CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0);
case StringComparison.InvariantCultureIgnoreCase:
return (CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0);
case StringComparison.Ordinal:
if (a.Length != b.Length)
return false;
return EqualsHelper(a, b);
case StringComparison.OrdinalIgnoreCase:
if (a.Length != b.Length)
return false;
else
{
// If both strings are ASCII strings, we can take the fast path.
if (a.IsAscii() && b.IsAscii())
{
return EqualsIgnoreCaseAsciiHelper(a, b);
}
// Take the slow path.
return (CompareInfo.CompareOrdinalIgnoreCase(a, 0, a.Length, b, 0, b.Length) == 0);
}
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public static bool operator ==(String a, String b)
{
return String.Equals(a, b);
}
public static bool operator !=(String a, String b)
{
return !String.Equals(a, b);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int InternalMarvin32HashString(string s);
// Gets a hash code for this string. If strings A and B are such that A.Equals(B), then
// they will return the same hash code.
public override int GetHashCode()
{
return InternalMarvin32HashString(this);
}
// Gets a hash code for this string and this comparison. If strings A and B and comparition C are such
// that String.Equals(A, B, C), then they will return the same hash code with this comparison C.
public int GetHashCode(StringComparison comparisonType) => StringComparer.FromComparison(comparisonType).GetHashCode(this);
// Use this if and only if you need the hashcode to not change across app domains (e.g. you have an app domain agile
// hash table).
internal int GetLegacyNonRandomizedHashCode()
{
unsafe
{
fixed (char* src = &_firstChar)
{
Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary");
#if BIT64
int hash1 = 5381;
#else // !BIT64 (32)
int hash1 = (5381<<16) + 5381;
#endif
int hash2 = hash1;
#if BIT64
int c;
char* s = src;
while ((c = s[0]) != 0)
{
hash1 = ((hash1 << 5) + hash1) ^ c;
c = s[1];
if (c == 0)
break;
hash2 = ((hash2 << 5) + hash2) ^ c;
s += 2;
}
#else // !BIT64 (32)
// 32 bit machines.
int* pint = (int *)src;
int len = this.Length;
while (len > 2)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ pint[1];
pint += 2;
len -= 4;
}
if (len > 0)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
}
#endif
#if DEBUG
// We want to ensure we can change our hash function daily.
// This is perfectly fine as long as you don't persist the
// value from GetHashCode to disk or count on String A
// hashing before string B. Those are bugs in your code.
hash1 ^= ThisAssembly.DailyBuildNumber;
#endif
return hash1 + (hash2 * 1566083941);
}
}
}
// Determines whether a specified string is a prefix of the current instance
//
public Boolean StartsWith(String value)
{
if ((Object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
return StartsWith(value, StringComparison.CurrentCulture);
}
public Boolean StartsWith(String value, StringComparison comparisonType)
{
if ((Object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
if ((Object)this == (Object)value)
{
return true;
}
if (value.Length == 0)
{
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
if (this.Length < value.Length || _firstChar != value._firstChar)
{
return false;
}
return (value.Length == 1) ?
true : // First char is the same and thats all there is to compare
StartsWithOrdinalHelper(this, value);
case StringComparison.OrdinalIgnoreCase:
if (this.Length < value.Length)
{
return false;
}
return (CompareInfo.CompareOrdinalIgnoreCase(this, 0, value.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public Boolean StartsWith(String value, Boolean ignoreCase, CultureInfo culture)
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
return true;
}
CultureInfo referenceCulture;
if (culture == null)
referenceCulture = CultureInfo.CurrentCulture;
else
referenceCulture = culture;
return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
public bool StartsWith(char value) => Length != 0 && _firstChar == 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.
namespace System.Xml.Serialization
{
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Schema;
using System.Xml;
using System.Text;
using System.ComponentModel;
using System.Globalization;
using System.Security.Cryptography;
using System.Diagnostics;
using System.Linq;
using System.Xml.Extensions;
using System.Xml.Serialization;
// These classes provide a higher level view on reflection specific to
// Xml serialization, for example:
// - allowing one to talk about types w/o having them compiled yet
// - abstracting collections & arrays
// - abstracting classes, structs, interfaces
// - knowing about XSD primitives
// - dealing with Serializable and xmlelement
// and lots of other little details
internal enum TypeKind
{
Root,
Primitive,
Enum,
Struct,
Class,
Array,
Collection,
Enumerable,
Void,
Node,
Attribute,
Serializable
}
internal enum TypeFlags
{
None = 0x0,
Abstract = 0x1,
Reference = 0x2,
Special = 0x4,
CanBeAttributeValue = 0x8,
CanBeTextValue = 0x10,
CanBeElementValue = 0x20,
HasCustomFormatter = 0x40,
AmbiguousDataType = 0x80,
IgnoreDefault = 0x200,
HasIsEmpty = 0x400,
HasDefaultConstructor = 0x800,
XmlEncodingNotRequired = 0x1000,
UseReflection = 0x4000,
CollapseWhitespace = 0x8000,
OptionalValue = 0x10000,
CtorInaccessible = 0x20000,
UsePrivateImplementation = 0x40000,
GenericInterface = 0x80000,
Unsupported = 0x100000,
}
internal class TypeDesc
{
private string _name;
private string _fullName;
private string _cSharpName;
private TypeDesc _arrayElementTypeDesc;
private TypeDesc _arrayTypeDesc;
private TypeDesc _nullableTypeDesc;
private TypeKind _kind;
private XmlSchemaType _dataType;
private Type _type;
private TypeDesc _baseTypeDesc;
private TypeFlags _flags;
private string _formatterName;
private bool _isXsdType;
private bool _isMixed;
private int _weight;
private Exception _exception;
internal TypeDesc(string name, string fullName, XmlSchemaType dataType, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, string formatterName)
{
_name = name.Replace('+', '.');
_fullName = fullName.Replace('+', '.');
_kind = kind;
_baseTypeDesc = baseTypeDesc;
_flags = flags;
_isXsdType = kind == TypeKind.Primitive;
if (_isXsdType)
_weight = 1;
else if (kind == TypeKind.Enum)
_weight = 2;
else if (_kind == TypeKind.Root)
_weight = -1;
else
_weight = baseTypeDesc == null ? 0 : baseTypeDesc.Weight + 1;
_dataType = dataType;
_formatterName = formatterName;
}
internal TypeDesc(string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags)
: this(name, fullName, (XmlSchemaType)null, kind, baseTypeDesc, flags, null)
{ }
internal TypeDesc(Type type, bool isXsdType, XmlSchemaType dataType, string formatterName, TypeFlags flags)
: this(type.Name, type.FullName, dataType, TypeKind.Primitive, (TypeDesc)null, flags, formatterName)
{
_isXsdType = isXsdType;
_type = type;
}
internal TypeDesc(Type type, string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, TypeDesc arrayElementTypeDesc)
: this(name, fullName, null, kind, baseTypeDesc, flags, null)
{
_arrayElementTypeDesc = arrayElementTypeDesc;
_type = type;
}
public override string ToString()
{
return _fullName;
}
internal TypeFlags Flags
{
get { return _flags; }
}
internal bool IsXsdType
{
get { return _isXsdType; }
}
internal bool IsMappedType
{
get { return false; }
}
internal string Name
{
get { return _name; }
}
internal string FullName
{
get { return _fullName; }
}
internal string CSharpName
{
get
{
if (_cSharpName == null)
{
_cSharpName = _type == null ? CodeIdentifier.GetCSharpName(_fullName) : CodeIdentifier.GetCSharpName(_type);
}
return _cSharpName;
}
}
internal XmlSchemaType DataType
{
get { return _dataType; }
}
internal Type Type
{
get { return _type; }
}
internal string FormatterName
{
get { return _formatterName; }
}
internal TypeKind Kind
{
get { return _kind; }
}
internal bool IsValueType
{
get { return (_flags & TypeFlags.Reference) == 0; }
}
internal bool CanBeAttributeValue
{
get { return (_flags & TypeFlags.CanBeAttributeValue) != 0; }
}
internal bool XmlEncodingNotRequired
{
get { return (_flags & TypeFlags.XmlEncodingNotRequired) != 0; }
}
internal bool CanBeElementValue
{
get { return (_flags & TypeFlags.CanBeElementValue) != 0; }
}
internal bool CanBeTextValue
{
get { return (_flags & TypeFlags.CanBeTextValue) != 0; }
}
internal bool IsMixed
{
get { return _isMixed || CanBeTextValue; }
set { _isMixed = value; }
}
internal bool IsSpecial
{
get { return (_flags & TypeFlags.Special) != 0; }
}
internal bool IsAmbiguousDataType
{
get { return (_flags & TypeFlags.AmbiguousDataType) != 0; }
}
internal bool HasCustomFormatter
{
get { return (_flags & TypeFlags.HasCustomFormatter) != 0; }
}
internal bool HasDefaultSupport
{
get { return (_flags & TypeFlags.IgnoreDefault) == 0; }
}
internal bool HasIsEmpty
{
get { return (_flags & TypeFlags.HasIsEmpty) != 0; }
}
internal bool CollapseWhitespace
{
get { return (_flags & TypeFlags.CollapseWhitespace) != 0; }
}
internal bool HasDefaultConstructor
{
get { return (_flags & TypeFlags.HasDefaultConstructor) != 0; }
}
internal bool IsUnsupported
{
get { return (_flags & TypeFlags.Unsupported) != 0; }
}
internal bool IsGenericInterface
{
get { return (_flags & TypeFlags.GenericInterface) != 0; }
}
internal bool IsPrivateImplementation
{
get { return (_flags & TypeFlags.UsePrivateImplementation) != 0; }
}
internal bool CannotNew
{
get { return !HasDefaultConstructor || ConstructorInaccessible; }
}
internal bool IsAbstract
{
get { return (_flags & TypeFlags.Abstract) != 0; }
}
internal bool IsOptionalValue
{
get { return (_flags & TypeFlags.OptionalValue) != 0; }
}
internal bool UseReflection
{
get { return (_flags & TypeFlags.UseReflection) != 0; }
}
internal bool IsVoid
{
get { return _kind == TypeKind.Void; }
}
internal bool IsClass
{
get { return _kind == TypeKind.Class; }
}
internal bool IsStructLike
{
get { return _kind == TypeKind.Struct || _kind == TypeKind.Class; }
}
internal bool IsArrayLike
{
get { return _kind == TypeKind.Array || _kind == TypeKind.Collection || _kind == TypeKind.Enumerable; }
}
internal bool IsCollection
{
get { return _kind == TypeKind.Collection; }
}
internal bool IsEnumerable
{
get { return _kind == TypeKind.Enumerable; }
}
internal bool IsArray
{
get { return _kind == TypeKind.Array; }
}
internal bool IsPrimitive
{
get { return _kind == TypeKind.Primitive; }
}
internal bool IsEnum
{
get { return _kind == TypeKind.Enum; }
}
internal bool IsNullable
{
get { return !IsValueType; }
}
internal bool IsRoot
{
get { return _kind == TypeKind.Root; }
}
internal bool ConstructorInaccessible
{
get { return (_flags & TypeFlags.CtorInaccessible) != 0; }
}
internal Exception Exception
{
get { return _exception; }
set { _exception = value; }
}
internal TypeDesc GetNullableTypeDesc(Type type)
{
if (IsOptionalValue)
return this;
if (_nullableTypeDesc == null)
{
_nullableTypeDesc = new TypeDesc("NullableOf" + _name, "System.Nullable`1[" + _fullName + "]", null, TypeKind.Struct, this, _flags | TypeFlags.OptionalValue, _formatterName);
_nullableTypeDesc._type = type;
}
return _nullableTypeDesc;
}
internal void CheckSupported()
{
if (IsUnsupported)
{
if (Exception != null)
{
throw Exception;
}
else
{
throw new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, FullName));
}
}
if (_baseTypeDesc != null)
_baseTypeDesc.CheckSupported();
if (_arrayElementTypeDesc != null)
_arrayElementTypeDesc.CheckSupported();
}
internal void CheckNeedConstructor()
{
if (!IsValueType && !IsAbstract && !HasDefaultConstructor)
{
_flags |= TypeFlags.Unsupported;
_exception = new InvalidOperationException(SR.Format(SR.XmlConstructorInaccessible, FullName));
}
}
internal TypeDesc ArrayElementTypeDesc
{
get { return _arrayElementTypeDesc; }
set { _arrayElementTypeDesc = value; }
}
internal int Weight
{
get { return _weight; }
}
internal TypeDesc CreateArrayTypeDesc()
{
if (_arrayTypeDesc == null)
_arrayTypeDesc = new TypeDesc(null, _name + "[]", _fullName + "[]", TypeKind.Array, null, TypeFlags.Reference | (_flags & TypeFlags.UseReflection), this);
return _arrayTypeDesc;
}
internal TypeDesc BaseTypeDesc
{
get { return _baseTypeDesc; }
set
{
_baseTypeDesc = value;
_weight = _baseTypeDesc == null ? 0 : _baseTypeDesc.Weight + 1;
}
}
internal bool IsDerivedFrom(TypeDesc baseTypeDesc)
{
TypeDesc typeDesc = this;
while (typeDesc != null)
{
if (typeDesc == baseTypeDesc) return true;
typeDesc = typeDesc.BaseTypeDesc;
}
return baseTypeDesc.IsRoot;
}
internal static TypeDesc FindCommonBaseTypeDesc(TypeDesc[] typeDescs)
{
if (typeDescs.Length == 0) return null;
TypeDesc leastDerivedTypeDesc = null;
int leastDerivedLevel = int.MaxValue;
for (int i = 0; i < typeDescs.Length; i++)
{
int derivationLevel = typeDescs[i].Weight;
if (derivationLevel < leastDerivedLevel)
{
leastDerivedLevel = derivationLevel;
leastDerivedTypeDesc = typeDescs[i];
}
}
while (leastDerivedTypeDesc != null)
{
int i;
for (i = 0; i < typeDescs.Length; i++)
{
if (!typeDescs[i].IsDerivedFrom(leastDerivedTypeDesc)) break;
}
if (i == typeDescs.Length) break;
leastDerivedTypeDesc = leastDerivedTypeDesc.BaseTypeDesc;
}
return leastDerivedTypeDesc;
}
}
internal class TypeScope
{
private Hashtable _typeDescs = new Hashtable();
private Hashtable _arrayTypeDescs = new Hashtable();
private ArrayList _typeMappings = new ArrayList();
private static Hashtable s_primitiveTypes = new Hashtable();
private static Hashtable s_primitiveDataTypes = new Hashtable();
private static NameTable s_primitiveNames = new NameTable();
private static string[] s_unsupportedTypes = new string[] {
"anyURI",
"duration",
"ENTITY",
"ENTITIES",
"gDay",
"gMonth",
"gMonthDay",
"gYear",
"gYearMonth",
"ID",
"IDREF",
"IDREFS",
"integer",
"language",
"negativeInteger",
"nonNegativeInteger",
"nonPositiveInteger",
//"normalizedString",
"NOTATION",
"positiveInteger",
"token"
};
static TypeScope()
{
AddPrimitive(typeof(string), "string", "String", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor);
AddPrimitive(typeof(int), "int", "Int32", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(bool), "boolean", "Boolean", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(short), "short", "Int16", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(long), "long", "Int64", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(float), "float", "Single", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(double), "double", "Double", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(decimal), "decimal", "Decimal", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(DateTime), "dateTime", "DateTime", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(XmlQualifiedName), "QName", "XmlQualifiedName", TypeFlags.CanBeAttributeValue | TypeFlags.HasCustomFormatter | TypeFlags.HasIsEmpty | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.Reference);
AddPrimitive(typeof(byte), "unsignedByte", "Byte", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(SByte), "byte", "SByte", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(UInt16), "unsignedShort", "UInt16", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(UInt32), "unsignedInt", "UInt32", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(UInt64), "unsignedLong", "UInt64", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
// Types without direct mapping (ambiguous)
AddPrimitive(typeof(DateTime), "date", "Date", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(DateTime), "time", "Time", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(string), "Name", "XmlName", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(string), "NCName", "XmlNCName", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(string), "NMTOKEN", "XmlNmToken", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(string), "NMTOKENS", "XmlNmTokens", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(byte[]), "base64Binary", "ByteArrayBase64", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired | TypeFlags.HasDefaultConstructor);
AddPrimitive(typeof(byte[]), "hexBinary", "ByteArrayHex", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired | TypeFlags.HasDefaultConstructor);
// NOTE, Micorosft: byte[] can also be used to mean array of bytes. That datatype is not a primitive, so we
// can't use the AmbiguousDataType mechanism. To get an array of bytes in literal XML, apply [XmlArray] or
// [XmlArrayItem].
XmlSchemaPatternFacet guidPattern = new XmlSchemaPatternFacet();
guidPattern.Value = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
AddNonXsdPrimitive(typeof(Guid), "guid", UrtTypes.Namespace, "Guid", new XmlQualifiedName("string", XmlSchema.Namespace), new XmlSchemaFacet[] { guidPattern }, TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.IgnoreDefault);
AddNonXsdPrimitive(typeof(char), "char", UrtTypes.Namespace, "Char", new XmlQualifiedName("unsignedShort", XmlSchema.Namespace), new XmlSchemaFacet[0], TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.IgnoreDefault);
AddNonXsdPrimitive(typeof(TimeSpan), "TimeSpan", UrtTypes.Namespace, "TimeSpan", new XmlQualifiedName("duration", XmlSchema.Namespace), new XmlSchemaFacet[0], TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedTypes(Soap.Encoding);
// Unsuppoted types that we map to string, if in the future we decide
// to add support for them we would need to create custom formatters for them
// normalizedString is the only one unsupported type that suppose to preserve whitesapce
AddPrimitive(typeof(string), "normalizedString", "String", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor);
for (int i = 0; i < s_unsupportedTypes.Length; i++)
{
AddPrimitive(typeof(string), s_unsupportedTypes[i], "String", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.CollapseWhitespace);
}
}
internal static bool IsKnownType(Type type)
{
if (type == typeof(object))
return true;
if (type.IsEnum)
return false;
switch (type.GetTypeCode())
{
case TypeCode.String: return true;
case TypeCode.Int32: return true;
case TypeCode.Boolean: return true;
case TypeCode.Int16: return true;
case TypeCode.Int64: return true;
case TypeCode.Single: return true;
case TypeCode.Double: return true;
case TypeCode.Decimal: return true;
case TypeCode.DateTime: return true;
case TypeCode.Byte: return true;
case TypeCode.SByte: return true;
case TypeCode.UInt16: return true;
case TypeCode.UInt32: return true;
case TypeCode.UInt64: return true;
case TypeCode.Char: return true;
default:
if (type == typeof(XmlQualifiedName))
return true;
else if (type == typeof(byte[]))
return true;
else if (type == typeof(Guid))
return true;
else if (type == typeof(TimeSpan))
return true;
else if (type == typeof(XmlNode[]))
return true;
break;
}
return false;
}
private static void AddSoapEncodedTypes(string ns)
{
AddSoapEncodedPrimitive(typeof(string), "normalizedString", ns, "String", new XmlQualifiedName("normalizedString", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor);
for (int i = 0; i < s_unsupportedTypes.Length; i++)
{
AddSoapEncodedPrimitive(typeof(string), s_unsupportedTypes[i], ns, "String", new XmlQualifiedName(s_unsupportedTypes[i], XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.Reference | TypeFlags.CollapseWhitespace);
}
AddSoapEncodedPrimitive(typeof(string), "string", ns, "String", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(int), "int", ns, "Int32", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(bool), "boolean", ns, "Boolean", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(short), "short", ns, "Int16", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(long), "long", ns, "Int64", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(float), "float", ns, "Single", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(double), "double", ns, "Double", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(decimal), "decimal", ns, "Decimal", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(DateTime), "dateTime", ns, "DateTime", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(XmlQualifiedName), "QName", ns, "XmlQualifiedName", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.HasCustomFormatter | TypeFlags.HasIsEmpty | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(byte), "unsignedByte", ns, "Byte", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(SByte), "byte", ns, "SByte", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(UInt16), "unsignedShort", ns, "UInt16", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(UInt32), "unsignedInt", ns, "UInt32", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(UInt64), "unsignedLong", ns, "UInt64", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
// Types without direct mapping (ambigous)
AddSoapEncodedPrimitive(typeof(DateTime), "date", ns, "Date", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(DateTime), "time", ns, "Time", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(string), "Name", ns, "XmlName", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(string), "NCName", ns, "XmlNCName", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(string), "NMTOKEN", ns, "XmlNmToken", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(string), "NMTOKENS", ns, "XmlNmTokens", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddSoapEncodedPrimitive(typeof(byte[]), "base64Binary", ns, "ByteArrayBase64", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(byte[]), "hexBinary", ns, "ByteArrayHex", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired);
AddSoapEncodedPrimitive(typeof(string), "arrayCoordinate", ns, "String", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue);
AddSoapEncodedPrimitive(typeof(byte[]), "base64", ns, "ByteArrayBase64", new XmlQualifiedName("base64Binary", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.IgnoreDefault | TypeFlags.Reference);
}
private static void AddPrimitive(Type type, string dataTypeName, string formatterName, TypeFlags flags)
{
XmlSchemaSimpleType dataType = new XmlSchemaSimpleType();
dataType.Name = dataTypeName;
TypeDesc typeDesc = new TypeDesc(type, true, dataType, formatterName, flags);
if (s_primitiveTypes[type] == null)
s_primitiveTypes.Add(type, typeDesc);
s_primitiveDataTypes.Add(dataType, typeDesc);
s_primitiveNames.Add(dataTypeName, XmlSchema.Namespace, typeDesc);
}
private static void AddNonXsdPrimitive(Type type, string dataTypeName, string ns, string formatterName, XmlQualifiedName baseTypeName, XmlSchemaFacet[] facets, TypeFlags flags)
{
XmlSchemaSimpleType dataType = new XmlSchemaSimpleType();
dataType.Name = dataTypeName;
XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
restriction.BaseTypeName = baseTypeName;
foreach (XmlSchemaFacet facet in facets)
{
restriction.Facets.Add(facet);
}
dataType.Content = restriction;
TypeDesc typeDesc = new TypeDesc(type, false, dataType, formatterName, flags);
if (s_primitiveTypes[type] == null)
s_primitiveTypes.Add(type, typeDesc);
s_primitiveDataTypes.Add(dataType, typeDesc);
s_primitiveNames.Add(dataTypeName, ns, typeDesc);
}
private static void AddSoapEncodedPrimitive(Type type, string dataTypeName, string ns, string formatterName, XmlQualifiedName baseTypeName, TypeFlags flags)
{
AddNonXsdPrimitive(type, dataTypeName, ns, formatterName, baseTypeName, new XmlSchemaFacet[0], flags);
}
internal TypeDesc GetTypeDesc(string name, string ns)
{
return GetTypeDesc(name, ns, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue);
}
internal TypeDesc GetTypeDesc(string name, string ns, TypeFlags flags)
{
TypeDesc typeDesc = (TypeDesc)s_primitiveNames[name, ns];
if (typeDesc != null)
{
if ((typeDesc.Flags & flags) != 0)
{
return typeDesc;
}
}
return null;
}
internal TypeDesc GetTypeDesc(XmlSchemaSimpleType dataType)
{
return (TypeDesc)s_primitiveDataTypes[dataType];
}
internal TypeDesc GetTypeDesc(Type type)
{
return GetTypeDesc(type, null, true, true);
}
internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference)
{
return GetTypeDesc(type, source, directReference, true);
}
internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference, bool throwOnError)
{
if (type.ContainsGenericParameters)
{
throw new InvalidOperationException(SR.Format(SR.XmlUnsupportedOpenGenericType, type.ToString()));
}
TypeDesc typeDesc = (TypeDesc)s_primitiveTypes[type];
if (typeDesc == null)
{
typeDesc = (TypeDesc)_typeDescs[type];
if (typeDesc == null)
{
typeDesc = ImportTypeDesc(type, source, directReference);
}
}
if (throwOnError)
typeDesc.CheckSupported();
return typeDesc;
}
internal TypeDesc GetArrayTypeDesc(Type type)
{
TypeDesc typeDesc = (TypeDesc)_arrayTypeDescs[type];
if (typeDesc == null)
{
typeDesc = GetTypeDesc(type);
if (!typeDesc.IsArrayLike)
typeDesc = ImportTypeDesc(type, null, false);
typeDesc.CheckSupported();
_arrayTypeDescs.Add(type, typeDesc);
}
return typeDesc;
}
#if !FEATURE_SERIALIZATION_UAPAOT
internal TypeMapping GetTypeMappingFromTypeDesc(TypeDesc typeDesc)
{
foreach (TypeMapping typeMapping in TypeMappings)
{
if (typeMapping.TypeDesc == typeDesc)
return typeMapping;
}
return null;
}
internal Type GetTypeFromTypeDesc(TypeDesc typeDesc)
{
if (typeDesc.Type != null)
return typeDesc.Type;
foreach (DictionaryEntry de in _typeDescs)
{
if (de.Value == typeDesc)
return de.Key as Type;
}
return null;
}
#endif
private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directReference)
{
TypeDesc typeDesc = null;
TypeKind kind;
Type arrayElementType = null;
Type baseType = null;
TypeFlags flags = 0;
Exception exception = null;
if (!type.IsVisible)
{
flags |= TypeFlags.Unsupported;
exception = new InvalidOperationException(SR.Format(SR.XmlTypeInaccessible, type.FullName));
}
else if (directReference && (type.IsAbstract && type.IsSealed))
{
flags |= TypeFlags.Unsupported;
exception = new InvalidOperationException(SR.Format(SR.XmlTypeStatic, type.FullName));
}
if (DynamicAssemblies.IsTypeDynamic(type))
{
flags |= TypeFlags.UseReflection;
}
if (!type.IsValueType)
flags |= TypeFlags.Reference;
if (type == typeof(object))
{
kind = TypeKind.Root;
flags |= TypeFlags.HasDefaultConstructor;
}
else if (type == typeof(ValueType))
{
kind = TypeKind.Enum;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
}
else if (type == typeof(void))
{
kind = TypeKind.Void;
}
else if (typeof(IXmlSerializable).IsAssignableFrom(type))
{
kind = TypeKind.Serializable;
flags |= TypeFlags.Special | TypeFlags.CanBeElementValue;
flags |= GetConstructorFlags(type, ref exception);
}
else if (type.IsArray)
{
kind = TypeKind.Array;
if (type.GetArrayRank() > 1)
{
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedRank, type.FullName));
}
}
arrayElementType = type.GetElementType();
flags |= TypeFlags.HasDefaultConstructor;
}
else if (typeof(ICollection).IsAssignableFrom(type) && !IsArraySegment(type))
{
kind = TypeKind.Collection;
arrayElementType = GetCollectionElementType(type, memberInfo == null ? null : memberInfo.DeclaringType.FullName + "." + memberInfo.Name);
flags |= GetConstructorFlags(type, ref exception);
}
else if (type == typeof(XmlQualifiedName))
{
kind = TypeKind.Primitive;
}
else if (type.IsPrimitive)
{
kind = TypeKind.Primitive;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
}
else if (type.IsEnum)
{
kind = TypeKind.Enum;
}
else if (type.IsValueType)
{
kind = TypeKind.Struct;
if (IsOptionalValue(type))
{
baseType = type.GetGenericArguments()[0];
flags |= TypeFlags.OptionalValue;
}
else
{
baseType = type.BaseType;
}
if (type.IsAbstract) flags |= TypeFlags.Abstract;
}
else if (type.IsClass)
{
if (type == typeof(XmlAttribute))
{
kind = TypeKind.Attribute;
flags |= TypeFlags.Special | TypeFlags.CanBeAttributeValue;
}
else if (typeof(XmlNode).IsAssignableFrom(type))
{
kind = TypeKind.Node;
baseType = type.BaseType;
flags |= TypeFlags.Special | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue;
if (typeof(XmlText).IsAssignableFrom(type))
flags &= ~TypeFlags.CanBeElementValue;
else if (typeof(XmlElement).IsAssignableFrom(type))
flags &= ~TypeFlags.CanBeTextValue;
else if (type.IsAssignableFrom(typeof(XmlAttribute)))
flags |= TypeFlags.CanBeAttributeValue;
}
else
{
kind = TypeKind.Class;
baseType = type.BaseType;
if (type.IsAbstract)
flags |= TypeFlags.Abstract;
}
}
else if (type.IsInterface)
{
kind = TypeKind.Void;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
if (memberInfo == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterface, type.FullName));
}
else
{
exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterfaceDetails, memberInfo.DeclaringType.FullName + "." + memberInfo.Name, type.FullName));
}
}
}
else
{
kind = TypeKind.Void;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
}
// check to see if the type has public default constructor for classes
if (kind == TypeKind.Class && !type.IsAbstract)
{
flags |= GetConstructorFlags(type, ref exception);
}
// check if a struct-like type is enumerable
if (kind == TypeKind.Struct || kind == TypeKind.Class)
{
if (typeof(IEnumerable).IsAssignableFrom(type) && !IsArraySegment(type))
{
arrayElementType = GetEnumeratorElementType(type, ref flags);
kind = TypeKind.Enumerable;
// GetEnumeratorElementType checks for the security attributes on the GetEnumerator(), Add() methods and Current property,
// we need to check the MoveNext() and ctor methods for the security attribues
flags |= GetConstructorFlags(type, ref exception);
}
}
typeDesc = new TypeDesc(type, CodeIdentifier.MakeValid(TypeName(type)), type.ToString(), kind, null, flags, null);
typeDesc.Exception = exception;
if (directReference && (typeDesc.IsClass || kind == TypeKind.Serializable))
typeDesc.CheckNeedConstructor();
if (typeDesc.IsUnsupported)
{
// return right away, do not check anything else
return typeDesc;
}
_typeDescs.Add(type, typeDesc);
if (arrayElementType != null)
{
TypeDesc td = GetTypeDesc(arrayElementType, memberInfo, true, false);
// explicitly disallow read-only elements, even if they are collections
if (directReference && (td.IsCollection || td.IsEnumerable) && !td.IsPrimitive)
{
td.CheckNeedConstructor();
}
typeDesc.ArrayElementTypeDesc = td;
}
if (baseType != null && baseType != typeof(object) && baseType != typeof(ValueType))
{
typeDesc.BaseTypeDesc = GetTypeDesc(baseType, memberInfo, false, false);
}
if (type.IsNestedPublic)
{
for (Type t = type.DeclaringType; t != null && !t.ContainsGenericParameters && !(t.IsAbstract && t.IsSealed); t = t.DeclaringType)
GetTypeDesc(t, null, false);
}
return typeDesc;
}
private static bool IsArraySegment(Type t)
{
return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
}
internal static bool IsOptionalValue(Type type)
{
if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition())
return true;
}
return false;
}
/*
static string GetHash(string str) {
MD5 md5 = MD5.Create();
string hash = Convert.ToBase64String(md5.ComputeHash(Encoding.UTF8.GetBytes(str)), 0, 6).Replace("+", "_P").Replace("/", "_S");
return hash;
}
*/
internal static string TypeName(Type t)
{
if (t.IsArray)
{
return "ArrayOf" + TypeName(t.GetElementType());
}
else if (t.IsGenericType)
{
StringBuilder typeName = new StringBuilder();
StringBuilder ns = new StringBuilder();
string name = t.Name;
int arity = name.IndexOf("`", StringComparison.Ordinal);
if (arity >= 0)
{
name = name.Substring(0, arity);
}
typeName.Append(name);
typeName.Append("Of");
Type[] arguments = t.GetGenericArguments();
for (int i = 0; i < arguments.Length; i++)
{
typeName.Append(TypeName(arguments[i]));
ns.Append(arguments[i].Namespace);
}
/*
if (ns.Length > 0) {
typeName.Append("_");
typeName.Append(GetHash(ns.ToString()));
}
*/
return typeName.ToString();
}
return t.Name;
}
internal static Type GetArrayElementType(Type type, string memberInfo)
{
if (type.IsArray)
return type.GetElementType();
else if (IsArraySegment(type))
return null;
else if (typeof(ICollection).IsAssignableFrom(type))
return GetCollectionElementType(type, memberInfo);
else if (typeof(IEnumerable).IsAssignableFrom(type))
{
TypeFlags flags = TypeFlags.None;
return GetEnumeratorElementType(type, ref flags);
}
else
return null;
}
internal static MemberMapping[] GetAllMembers(StructMapping mapping)
{
if (mapping.BaseMapping == null)
return mapping.Members;
ArrayList list = new ArrayList();
GetAllMembers(mapping, list);
return (MemberMapping[])list.ToArray(typeof(MemberMapping));
}
internal static void GetAllMembers(StructMapping mapping, ArrayList list)
{
if (mapping.BaseMapping != null)
{
GetAllMembers(mapping.BaseMapping, list);
}
for (int i = 0; i < mapping.Members.Length; i++)
{
list.Add(mapping.Members[i]);
}
}
internal static MemberMapping[] GetAllMembers(StructMapping mapping, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos)
{
MemberMapping[] mappings = GetAllMembers(mapping);
PopulateMemberInfos(mapping, mappings, memberInfos);
return mappings;
}
internal static MemberMapping[] GetSettableMembers(StructMapping structMapping)
{
ArrayList list = new ArrayList();
GetSettableMembers(structMapping, list);
return (MemberMapping[])list.ToArray(typeof(MemberMapping));
}
private static void GetSettableMembers(StructMapping mapping, ArrayList list)
{
if (mapping.BaseMapping != null)
{
GetSettableMembers(mapping.BaseMapping, list);
}
if (mapping.Members != null)
{
foreach (MemberMapping memberMapping in mapping.Members)
{
MemberInfo memberInfo = memberMapping.MemberInfo;
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null && !CanWriteProperty(propertyInfo, memberMapping.TypeDesc))
{
throw new InvalidOperationException(SR.Format(SR.XmlReadOnlyPropertyError, propertyInfo.DeclaringType, propertyInfo.Name));
}
list.Add(memberMapping);
}
}
}
private static bool CanWriteProperty(PropertyInfo propertyInfo, TypeDesc typeDesc)
{
Debug.Assert(propertyInfo != null);
Debug.Assert(typeDesc != null);
// If the property is a collection, we don't need a setter.
if (typeDesc.Kind == TypeKind.Collection || typeDesc.Kind == TypeKind.Enumerable)
{
return true;
}
// Else the property needs a public setter.
return propertyInfo.SetMethod != null && propertyInfo.SetMethod.IsPublic;
}
internal static MemberMapping[] GetSettableMembers(StructMapping mapping, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos)
{
MemberMapping[] mappings = GetSettableMembers(mapping);
PopulateMemberInfos(mapping, mappings, memberInfos);
return mappings;
}
private static void PopulateMemberInfos(StructMapping structMapping, MemberMapping[] mappings, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos)
{
memberInfos.Clear();
for (int i = 0; i < mappings.Length; ++i)
{
memberInfos[mappings[i].Name] = mappings[i].MemberInfo;
if (mappings[i].ChoiceIdentifier != null)
memberInfos[mappings[i].ChoiceIdentifier.MemberName] = mappings[i].ChoiceIdentifier.MemberInfo;
if (mappings[i].CheckSpecifiedMemberInfo != null)
memberInfos[mappings[i].Name + "Specified"] = mappings[i].CheckSpecifiedMemberInfo;
}
// The scenario here is that user has one base class A and one derived class B and wants to serialize/deserialize an object of B.
// There's one virtual property defined in A and overridden by B. Without the replacing logic below, the code generated will always
// try to access the property defined in A, rather than B.
// The logic here is to:
// 1) Check current members inside memberInfos dictionary and figure out whether there's any override or new properties defined in the derived class.
// If so, replace the one on the base class with the one on the derived class.
// 2) Do the same thing for the memberMapping array. Note that we need to create a new copy of MemberMapping object since the old one could still be referenced
// by the StructMapping of the baseclass, so updating it directly could lead to other issues.
Dictionary<string, MemberInfo> replaceList = null;
MemberInfo replacedInfo = null;
foreach (KeyValuePair<string, MemberInfo> pair in memberInfos)
{
if (ShouldBeReplaced(pair.Value, structMapping.TypeDesc.Type, out replacedInfo))
{
if (replaceList == null)
{
replaceList = new Dictionary<string, MemberInfo>();
}
replaceList.Add(pair.Key, replacedInfo);
}
}
if (replaceList != null)
{
foreach (KeyValuePair<string, MemberInfo> pair in replaceList)
{
memberInfos[pair.Key] = pair.Value;
}
for (int i = 0; i < mappings.Length; i++)
{
MemberInfo mi;
if (replaceList.TryGetValue(mappings[i].Name, out mi))
{
MemberMapping newMapping = mappings[i].Clone();
newMapping.MemberInfo = mi;
mappings[i] = newMapping;
}
}
}
}
private static bool ShouldBeReplaced(MemberInfo memberInfoToBeReplaced, Type derivedType, out MemberInfo replacedInfo)
{
replacedInfo = memberInfoToBeReplaced;
Type currentType = derivedType;
Type typeToBeReplaced = memberInfoToBeReplaced.DeclaringType;
if (typeToBeReplaced.IsAssignableFrom(currentType))
{
while (currentType != typeToBeReplaced)
{
TypeInfo currentInfo = currentType.GetTypeInfo();
foreach (PropertyInfo info in currentInfo.DeclaredProperties)
{
if (info.Name == memberInfoToBeReplaced.Name)
{
// we have a new modifier situation: property names are the same but the declaring types are different
replacedInfo = info;
if (replacedInfo != memberInfoToBeReplaced)
{
if (!info.GetMethod.IsPublic
&& memberInfoToBeReplaced is PropertyInfo
&& ((PropertyInfo)memberInfoToBeReplaced).GetMethod.IsPublic
)
{
break;
}
return true;
}
}
}
foreach (FieldInfo info in currentInfo.DeclaredFields)
{
if (info.Name == memberInfoToBeReplaced.Name)
{
// we have a new modifier situation: field names are the same but the declaring types are different
replacedInfo = info;
if (replacedInfo != memberInfoToBeReplaced)
{
return true;
}
}
}
// we go one level down and try again
currentType = currentType.BaseType;
}
}
return false;
}
private static TypeFlags GetConstructorFlags(Type type, ref Exception exception)
{
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty<Type>());
if (ctor != null)
{
TypeFlags flags = TypeFlags.HasDefaultConstructor;
if (!ctor.IsPublic)
flags |= TypeFlags.CtorInaccessible;
else
{
object[] attrs = ctor.GetCustomAttributes(typeof(ObsoleteAttribute), false);
if (attrs != null && attrs.Length > 0)
{
ObsoleteAttribute obsolete = (ObsoleteAttribute)attrs[0];
if (obsolete.IsError)
{
flags |= TypeFlags.CtorInaccessible;
}
}
}
return flags;
}
return 0;
}
private static Type GetEnumeratorElementType(Type type, ref TypeFlags flags)
{
if (typeof(IEnumerable).IsAssignableFrom(type))
{
MethodInfo enumerator = type.GetMethod("GetEnumerator", Array.Empty<Type>());
if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
{
// try generic implementation
enumerator = null;
foreach (MemberInfo member in type.GetMember("System.Collections.Generic.IEnumerable<*", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
{
enumerator = member as MethodInfo;
if (enumerator != null && typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
{
// use the first one we find
flags |= TypeFlags.GenericInterface;
break;
}
else
{
enumerator = null;
}
}
if (enumerator == null)
{
// and finally private interface implementation
flags |= TypeFlags.UsePrivateImplementation;
enumerator = type.GetMethod("System.Collections.IEnumerable.GetEnumerator", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty<Type>());
}
}
if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
{
return null;
}
XmlAttributes methodAttrs = new XmlAttributes(enumerator);
if (methodAttrs.XmlIgnore) return null;
PropertyInfo p = enumerator.ReturnType.GetProperty("Current");
Type currentType = (p == null ? typeof(object) : p.PropertyType);
MethodInfo addMethod = type.GetMethod("Add", new Type[] { currentType });
if (addMethod == null && currentType != typeof(object))
{
currentType = typeof(object);
addMethod = type.GetMethod("Add", new Type[] { currentType });
}
if (addMethod == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, currentType, "IEnumerable"));
}
return currentType;
}
else
{
return null;
}
}
internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo)
{
if (typeof(IDictionary).IsAssignableFrom(type))
{
if (memberInfo == null)
{
throw new NotSupportedException(SR.Format(SR.XmlUnsupportedIDictionary, type.FullName));
}
else
{
throw new NotSupportedException(SR.Format(SR.XmlUnsupportedIDictionaryDetails, memberInfo, type.FullName));
}
}
MemberInfo[] defaultMembers = type.GetDefaultMembers();
PropertyInfo indexer = null;
if (defaultMembers != null && defaultMembers.Length > 0)
{
for (Type t = type; t != null; t = t.BaseType)
{
for (int i = 0; i < defaultMembers.Length; i++)
{
if (defaultMembers[i] is PropertyInfo)
{
PropertyInfo defaultProp = (PropertyInfo)defaultMembers[i];
if (defaultProp.DeclaringType != t) continue;
if (!defaultProp.CanRead) continue;
MethodInfo getMethod = defaultProp.GetMethod;
ParameterInfo[] parameters = getMethod.GetParameters();
if (parameters.Length == 1 && parameters[0].ParameterType == typeof(int))
{
indexer = defaultProp;
break;
}
}
}
if (indexer != null) break;
}
}
if (indexer == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlNoDefaultAccessors, type.FullName));
}
MethodInfo addMethod = type.GetMethod("Add", new Type[] { indexer.PropertyType });
if (addMethod == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, indexer.PropertyType, "ICollection"));
}
return indexer;
}
private static Type GetCollectionElementType(Type type, string memberInfo)
{
return GetDefaultIndexer(type, memberInfo).PropertyType;
}
internal static XmlQualifiedName ParseWsdlArrayType(string type, out string dims, XmlSchemaObject parent)
{
string ns;
string name;
int nsLen = type.LastIndexOf(':');
if (nsLen <= 0)
{
ns = "";
}
else
{
ns = type.Substring(0, nsLen);
}
int nameLen = type.IndexOf('[', nsLen + 1);
if (nameLen <= nsLen)
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidArrayTypeSyntax, type));
}
name = type.Substring(nsLen + 1, nameLen - nsLen - 1);
dims = type.Substring(nameLen);
// parent is not null only in the case when we used XmlSchema.Read(),
// in which case we need to fixup the wsdl:arayType attribute value
while (parent != null)
{
if (parent.Namespaces != null)
{
string wsdlNs;
if (parent.Namespaces.Namespaces.TryGetValue(ns, out wsdlNs) && wsdlNs != null)
{
ns = wsdlNs;
break;
}
}
parent = parent.Parent;
}
return new XmlQualifiedName(name, ns);
}
internal ICollection Types
{
get { return _typeDescs.Keys; }
}
internal void AddTypeMapping(TypeMapping typeMapping)
{
_typeMappings.Add(typeMapping);
}
internal ICollection TypeMappings
{
get { return _typeMappings; }
}
internal static Hashtable PrimtiveTypes { get { return s_primitiveTypes; } }
}
internal class Soap
{
private Soap() { }
internal const string Encoding = "http://schemas.xmlsoap.org/soap/encoding/";
internal const string UrType = "anyType";
internal const string Array = "Array";
internal const string ArrayType = "arrayType";
}
internal class Soap12
{
private Soap12() { }
internal const string Encoding = "http://www.w3.org/2003/05/soap-encoding";
internal const string RpcNamespace = "http://www.w3.org/2003/05/soap-rpc";
internal const string RpcResult = "result";
}
internal class Wsdl
{
private Wsdl() { }
internal const string Namespace = "http://schemas.xmlsoap.org/wsdl/";
internal const string ArrayType = "arrayType";
}
internal class UrtTypes
{
private UrtTypes() { }
internal const string Namespace = "http://microsoft.com/wsdl/types/";
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine.Events;
using UnityEngine.Serialization;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine.EventSystems;
namespace UnityEngine.UI
{
// Simple selectable object - derived from to create a control.
[AddComponentMenu("UI/Selectable", 70)]
[ExecuteInEditMode]
[SelectionBase]
[DisallowMultipleComponent]
public class Selectable
:
UIBehaviour,
IMoveHandler,
IPointerDownHandler, IPointerUpHandler,
IPointerEnterHandler, IPointerExitHandler,
ISelectHandler, IDeselectHandler
{
// Selection state
// List of all the selectable objects currently active in the scene
private static List<Selectable> s_List = new List<Selectable>();
public static List<Selectable> allSelectables { get { return s_List; } }
// Navigation information.
[FormerlySerializedAs("navigation")]
[SerializeField]
private Navigation m_Navigation = Navigation.defaultNavigation;
// Highlighting state
public enum Transition
{
None,
ColorTint,
SpriteSwap,
Animation
}
// Type of the transition that occurs when the button state changes.
[FormerlySerializedAs("transition")]
[SerializeField]
private Transition m_Transition = Transition.ColorTint;
// Colors used for a color tint-based transition.
[FormerlySerializedAs("colors")]
[SerializeField]
private ColorBlock m_Colors = ColorBlock.defaultColorBlock;
// Sprites used for a Image swap-based transition.
[FormerlySerializedAs("spriteState")]
[SerializeField]
private SpriteState m_SpriteState;
[FormerlySerializedAs("animationTriggers")]
[SerializeField]
private AnimationTriggers m_AnimationTriggers = new AnimationTriggers();
[Tooltip("Can the Selectable be interacted with?")]
[SerializeField]
private bool m_Interactable = true;
// Graphic that will be colored.
[FormerlySerializedAs("highlightGraphic")]
[FormerlySerializedAs("m_HighlightGraphic")]
[SerializeField]
private Graphic m_TargetGraphic;
private bool m_GroupsAllowInteraction = true;
private SelectionState m_CurrentSelectionState;
#if UNITY_EDITOR
// Whether the OnEnable of this Instace has been run already.
[NonSerialized]
private bool m_HasEnableRun = false;
#endif
public Navigation navigation { get { return m_Navigation; } set { if (SetPropertyUtility.SetStruct(ref m_Navigation, value)) OnSetProperty(); } }
public Transition transition { get { return m_Transition; } set { if (SetPropertyUtility.SetStruct(ref m_Transition, value)) OnSetProperty(); } }
public ColorBlock colors { get { return m_Colors; } set { if (SetPropertyUtility.SetStruct(ref m_Colors, value)) OnSetProperty(); } }
public SpriteState spriteState { get { return m_SpriteState; } set { if (SetPropertyUtility.SetStruct(ref m_SpriteState, value)) OnSetProperty(); } }
public AnimationTriggers animationTriggers { get { return m_AnimationTriggers; } set { if (SetPropertyUtility.SetClass(ref m_AnimationTriggers, value)) OnSetProperty(); } }
public Graphic targetGraphic { get { return m_TargetGraphic; } set { if (SetPropertyUtility.SetClass(ref m_TargetGraphic, value)) OnSetProperty(); } }
public bool interactable { get { return m_Interactable; } set { if (SetPropertyUtility.SetStruct(ref m_Interactable, value)) OnSetProperty(); } }
private bool isPointerInside { get; set; }
private bool isPointerDown { get; set; }
private bool hasSelection { get; set; }
protected Selectable()
{ }
// Convenience function that converts the Graphic to a Image, if possible
public Image image
{
get { return m_TargetGraphic as Image; }
set { m_TargetGraphic = value; }
}
// Get the animator
public Animator animator
{
get { return GetComponent<Animator>(); }
}
protected override void Awake()
{
if (m_TargetGraphic == null)
m_TargetGraphic = GetComponent<Graphic>();
}
private readonly List<CanvasGroup> m_CanvasGroupCache = new List<CanvasGroup>();
protected override void OnCanvasGroupChanged()
{
// Figure out if parent groups allow interaction
// If no interaction is alowed... then we need
// to not do that :)
var groupAllowInteraction = true;
Transform t = transform;
while (t != null)
{
t.GetComponents(m_CanvasGroupCache);
for (var i = 0; i < m_CanvasGroupCache.Count; i++)
{
if (!m_CanvasGroupCache[i].interactable)
{
groupAllowInteraction = false;
break;
}
if (m_CanvasGroupCache[i].ignoreParentGroups)
break;
}
t = t.parent;
}
if (groupAllowInteraction != m_GroupsAllowInteraction)
{
m_GroupsAllowInteraction = groupAllowInteraction;
OnSetProperty();
}
}
public virtual bool IsInteractable()
{
return m_GroupsAllowInteraction && m_Interactable;
}
// Call from unity if animation properties have changed
protected override void OnDidApplyAnimationProperties()
{
OnSetProperty();
}
// Select on enable and add to the list.
protected override void OnEnable()
{
base.OnEnable();
s_List.Add(this);
var state = SelectionState.Normal;
// The button will be highlighted even in some cases where it shouldn't.
// For example: We only want to set the State as Highlighted if the StandaloneInputModule.m_CurrentInputMode == InputMode.Buttons
// But we dont have access to this, and it might not apply to other InputModules.
// TODO: figure out how to solve this. Case 617348.
if (hasSelection)
state = SelectionState.Highlighted;
m_CurrentSelectionState = state;
InternalEvaluateAndTransitionToSelectionState(true);
#if UNITY_EDITOR
m_HasEnableRun = true;
#endif
}
private void OnSetProperty()
{
#if UNITY_EDITOR
if (Application.isPlaying)
InternalEvaluateAndTransitionToSelectionState(true);
else
#endif
InternalEvaluateAndTransitionToSelectionState(false);
}
// Remove from the list.
protected override void OnDisable()
{
s_List.Remove(this);
InstantClearState();
base.OnDisable();
}
#if UNITY_EDITOR
protected override void OnValidate()
{
base.OnValidate();
m_Colors.fadeDuration = Mathf.Max(m_Colors.fadeDuration, 0.0f);
// OnValidate can be called before OnEnable, this makes it unsafe to access other components
// since they might not have been initialized yet.
// OnSetProperty potentially access Animator or Graphics. (case 618186)
if (m_HasEnableRun)
{
// Need to clear out the override image on the target...
DoSpriteSwap(null);
OnSetProperty();
}
}
protected override void Reset()
{
m_TargetGraphic = GetComponent<Graphic>();
}
#endif // if UNITY_EDITOR
protected SelectionState currentSelectionState
{
get { return m_CurrentSelectionState; }
}
protected virtual void InstantClearState()
{
string triggerName = m_AnimationTriggers.normalTrigger;
isPointerInside = false;
isPointerDown = false;
hasSelection = false;
switch (m_Transition)
{
case Transition.ColorTint:
StartColorTween(Color.white, true);
break;
case Transition.SpriteSwap:
DoSpriteSwap(null);
break;
case Transition.Animation:
TriggerAnimation(triggerName);
break;
}
}
protected virtual void DoStateTransition(SelectionState state, bool instant)
{
Color tintColor;
Sprite transitionSprite;
string triggerName;
switch (state)
{
case SelectionState.Normal:
tintColor = m_Colors.normalColor;
transitionSprite = null;
triggerName = m_AnimationTriggers.normalTrigger;
break;
case SelectionState.Highlighted:
tintColor = m_Colors.highlightedColor;
transitionSprite = m_SpriteState.highlightedSprite;
triggerName = m_AnimationTriggers.highlightedTrigger;
break;
case SelectionState.Pressed:
tintColor = m_Colors.pressedColor;
transitionSprite = m_SpriteState.pressedSprite;
triggerName = m_AnimationTriggers.pressedTrigger;
break;
case SelectionState.Disabled:
tintColor = m_Colors.disabledColor;
transitionSprite = m_SpriteState.disabledSprite;;
triggerName = m_AnimationTriggers.disabledTrigger;
break;
default:
tintColor = Color.black;
transitionSprite = null;
triggerName = string.Empty;
break;
}
if (gameObject.activeInHierarchy)
{
switch (m_Transition)
{
case Transition.ColorTint:
StartColorTween(tintColor * m_Colors.colorMultiplier, instant);
break;
case Transition.SpriteSwap:
DoSpriteSwap(transitionSprite);
break;
case Transition.Animation:
TriggerAnimation(triggerName);
break;
}
}
}
protected enum SelectionState
{
Normal,
Highlighted,
Pressed,
Disabled
}
// Selection logic
// Find the next selectable object in the specified world-space direction.
public Selectable FindSelectable(Vector3 dir)
{
dir = dir.normalized;
Vector3 pos = transform.TransformPoint(GetPointOnRectEdge(transform as RectTransform, dir));
float maxScore = Mathf.NegativeInfinity;
Selectable bestPick = null;
for (int i = 0; i < s_List.Count; ++i)
{
Selectable sel = s_List[i];
if (sel == this || sel == null)
continue;
if (!sel.IsInteractable() || sel.navigation.mode == Navigation.Mode.None)
continue;
var selRect = sel.transform as RectTransform;
Vector3 selCenter = selRect != null ? (Vector3)selRect.rect.center : Vector3.zero;
Vector3 myVector = sel.transform.TransformPoint(selCenter) - pos;
// Value that is the distance out along the direction.
float dot = Vector3.Dot(dir, myVector);
// Skip elements that are in the wrong direction or which have zero distance.
// This also ensures that the scoring formula below will not have a division by zero error.
if (dot <= 0)
continue;
// This scoring function has two priorities:
// - Score higher for positions that are closer.
// - Score higher for positions that are located in the right direction.
// This scoring function combines both of these criteria.
// It can be seen as this:
// Dot (dir, myVector.normalized) / myVector.magnitude
// The first part equals 1 if the direction of myVector is the same as dir, and 0 if it's orthogonal.
// The second part scores lower the greater the distance is by dividing by the distance.
// The formula below is equivalent but more optimized.
//
// If a given score is chosen, the positions that evaluate to that score will form a circle
// that touches pos and whose center is located along dir. A way to visualize the resulting functionality is this:
// From the position pos, blow up a circular balloon so it grows in the direction of dir.
// The first Selectable whose center the circular balloon touches is the one that's chosen.
float score = dot / myVector.sqrMagnitude;
if (score > maxScore)
{
maxScore = score;
bestPick = sel;
}
}
return bestPick;
}
private static Vector3 GetPointOnRectEdge(RectTransform rect, Vector2 dir)
{
if (rect == null)
return Vector3.zero;
if (dir != Vector2.zero)
dir /= Mathf.Max(Mathf.Abs(dir.x), Mathf.Abs(dir.y));
dir = rect.rect.center + Vector2.Scale(rect.rect.size, dir * 0.5f);
return dir;
}
// Convenience function -- change the selection to the specified object if it's not null and happens to be active.
void Navigate(AxisEventData eventData, Selectable sel)
{
if (sel != null && sel.enabled && sel.gameObject.activeInHierarchy)
eventData.selectedObject = sel.gameObject;
}
// Find the selectable object to the left of this one.
public virtual Selectable FindSelectableOnLeft()
{
if (m_Navigation.mode == Navigation.Mode.Explicit)
{
return m_Navigation.selectOnLeft;
}
if ((m_Navigation.mode & Navigation.Mode.Horizontal) != 0)
{
return FindSelectable(transform.rotation * Vector3.left);
}
return null;
}
// Find the selectable object to the right of this one.
public virtual Selectable FindSelectableOnRight()
{
if (m_Navigation.mode == Navigation.Mode.Explicit)
{
return m_Navigation.selectOnRight;
}
if ((m_Navigation.mode & Navigation.Mode.Horizontal) != 0)
{
return FindSelectable(transform.rotation * Vector3.right);
}
return null;
}
// Find the selectable object above this one
public virtual Selectable FindSelectableOnUp()
{
if (m_Navigation.mode == Navigation.Mode.Explicit)
{
return m_Navigation.selectOnUp;
}
if ((m_Navigation.mode & Navigation.Mode.Vertical) != 0)
{
return FindSelectable(transform.rotation * Vector3.up);
}
return null;
}
// Find the selectable object below this one.
public virtual Selectable FindSelectableOnDown()
{
if (m_Navigation.mode == Navigation.Mode.Explicit)
{
return m_Navigation.selectOnDown;
}
if ((m_Navigation.mode & Navigation.Mode.Vertical) != 0)
{
return FindSelectable(transform.rotation * Vector3.down);
}
return null;
}
public virtual void OnMove(AxisEventData eventData)
{
switch (eventData.moveDir)
{
case MoveDirection.Right:
Navigate(eventData, FindSelectableOnRight());
break;
case MoveDirection.Up:
Navigate(eventData, FindSelectableOnUp());
break;
case MoveDirection.Left:
Navigate(eventData, FindSelectableOnLeft());
break;
case MoveDirection.Down:
Navigate(eventData, FindSelectableOnDown());
break;
}
}
void StartColorTween(Color targetColor, bool instant)
{
if (m_TargetGraphic == null)
return;
m_TargetGraphic.CrossFadeColor(targetColor, instant ? 0f : m_Colors.fadeDuration, true, true);
}
void DoSpriteSwap(Sprite newSprite)
{
if (image == null)
return;
image.overrideSprite = newSprite;
}
void TriggerAnimation(string triggername)
{
if (animator == null || animator.runtimeAnimatorController == null || string.IsNullOrEmpty(triggername))
return;
animator.ResetTrigger(m_AnimationTriggers.normalTrigger);
animator.ResetTrigger(m_AnimationTriggers.pressedTrigger);
animator.ResetTrigger(m_AnimationTriggers.highlightedTrigger);
animator.ResetTrigger(m_AnimationTriggers.disabledTrigger);
animator.SetTrigger(triggername);
}
// Whether the control should be 'selected'.
protected bool IsHighlighted(BaseEventData eventData)
{
if (!IsActive())
return false;
if (IsPressed(eventData))
return false;
bool selected = false;
if (eventData as PointerEventData == null)
selected = hasSelection;
if (eventData is PointerEventData)
{
var pointerData = eventData as PointerEventData;
selected =
(isPointerDown && !isPointerInside && pointerData.pointerPress == gameObject) // This object pressed, but pointer moved off
|| (!isPointerDown && isPointerInside && pointerData.pointerPress == gameObject) // This object pressed, but pointer released over (PointerUp event)
|| (!isPointerDown && isPointerInside && pointerData.pointerPress == null); // Nothing pressed, but pointer is over
}
return selected;
}
// Whether the control should be pressed.
protected bool IsPressed(BaseEventData eventData)
{
if (!IsActive())
return false;
bool pressed = ((hasSelection && (eventData as PointerEventData == null)) || isPointerInside) && isPointerDown;
return pressed;
}
// The current visual state of the control.
protected void UpdateSelectionState(BaseEventData eventData)
{
if (IsPressed(eventData))
{
m_CurrentSelectionState = SelectionState.Pressed;
return;
}
if (IsHighlighted(eventData))
{
m_CurrentSelectionState = SelectionState.Highlighted;
return;
}
m_CurrentSelectionState = SelectionState.Normal;
}
// Change the button to the correct state
private void EvaluateAndTransitionToSelectionState(BaseEventData eventData)
{
if (!IsActive())
return;
UpdateSelectionState(eventData);
InternalEvaluateAndTransitionToSelectionState(false);
}
private void InternalEvaluateAndTransitionToSelectionState(bool instant)
{
var transitionState = m_CurrentSelectionState;
if (IsActive() && !IsInteractable())
transitionState = SelectionState.Disabled;
DoStateTransition(transitionState, instant);
}
public virtual void OnPointerDown(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;
// Selection tracking
if (IsInteractable() && navigation.mode != Navigation.Mode.None)
EventSystem.current.SetSelectedGameObject(gameObject, eventData);
isPointerDown = true;
EvaluateAndTransitionToSelectionState(eventData);
}
public virtual void OnPointerUp(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;
isPointerDown = false;
EvaluateAndTransitionToSelectionState(eventData);
}
public virtual void OnPointerEnter(PointerEventData eventData)
{
isPointerInside = true;
EvaluateAndTransitionToSelectionState(eventData);
}
public virtual void OnPointerExit(PointerEventData eventData)
{
isPointerInside = false;
EvaluateAndTransitionToSelectionState(eventData);
}
public virtual void OnSelect(BaseEventData eventData)
{
hasSelection = true;
EvaluateAndTransitionToSelectionState(eventData);
}
public virtual void OnDeselect(BaseEventData eventData)
{
hasSelection = false;
EvaluateAndTransitionToSelectionState(eventData);
}
public virtual void Select()
{
if (EventSystem.current.alreadySelecting)
return;
EventSystem.current.SetSelectedGameObject(gameObject);
}
}
}
| |
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;
// <auto-generated />
namespace NorthwindRepository{
/// <summary>
/// Strongly-typed collection for the QuarterlyOrder class.
/// </summary>
[Serializable]
public partial class QuarterlyOrderCollection : ReadOnlyList<QuarterlyOrder, QuarterlyOrderCollection>
{
public QuarterlyOrderCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the Quarterly Orders view.
/// </summary>
[Serializable]
public partial class QuarterlyOrder : ReadOnlyRecord<QuarterlyOrder>, 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("Quarterly Orders", TableType.View, DataService.GetInstance("NorthwindRepository"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema);
colvarCustomerID.ColumnName = "CustomerID";
colvarCustomerID.DataType = DbType.String;
colvarCustomerID.MaxLength = 5;
colvarCustomerID.AutoIncrement = false;
colvarCustomerID.IsNullable = true;
colvarCustomerID.IsPrimaryKey = false;
colvarCustomerID.IsForeignKey = false;
colvarCustomerID.IsReadOnly = false;
schema.Columns.Add(colvarCustomerID);
TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema);
colvarCompanyName.ColumnName = "CompanyName";
colvarCompanyName.DataType = DbType.String;
colvarCompanyName.MaxLength = 40;
colvarCompanyName.AutoIncrement = false;
colvarCompanyName.IsNullable = true;
colvarCompanyName.IsPrimaryKey = false;
colvarCompanyName.IsForeignKey = false;
colvarCompanyName.IsReadOnly = false;
schema.Columns.Add(colvarCompanyName);
TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema);
colvarCity.ColumnName = "City";
colvarCity.DataType = DbType.String;
colvarCity.MaxLength = 15;
colvarCity.AutoIncrement = false;
colvarCity.IsNullable = true;
colvarCity.IsPrimaryKey = false;
colvarCity.IsForeignKey = false;
colvarCity.IsReadOnly = false;
schema.Columns.Add(colvarCity);
TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema);
colvarCountry.ColumnName = "Country";
colvarCountry.DataType = DbType.String;
colvarCountry.MaxLength = 15;
colvarCountry.AutoIncrement = false;
colvarCountry.IsNullable = true;
colvarCountry.IsPrimaryKey = false;
colvarCountry.IsForeignKey = false;
colvarCountry.IsReadOnly = false;
schema.Columns.Add(colvarCountry);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["NorthwindRepository"].AddSchema("Quarterly Orders",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public QuarterlyOrder()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public QuarterlyOrder(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public QuarterlyOrder(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public QuarterlyOrder(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("CustomerID")]
[Bindable(true)]
public string CustomerID
{
get
{
return GetColumnValue<string>("CustomerID");
}
set
{
SetColumnValue("CustomerID", value);
}
}
[XmlAttribute("CompanyName")]
[Bindable(true)]
public string CompanyName
{
get
{
return GetColumnValue<string>("CompanyName");
}
set
{
SetColumnValue("CompanyName", value);
}
}
[XmlAttribute("City")]
[Bindable(true)]
public string City
{
get
{
return GetColumnValue<string>("City");
}
set
{
SetColumnValue("City", value);
}
}
[XmlAttribute("Country")]
[Bindable(true)]
public string Country
{
get
{
return GetColumnValue<string>("Country");
}
set
{
SetColumnValue("Country", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string CustomerID = @"CustomerID";
public static string CompanyName = @"CompanyName";
public static string City = @"City";
public static string Country = @"Country";
}
#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
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace System.Data.SqlClient
{
public sealed class SqlConnectionStringBuilder : DbConnectionStringBuilder
{
private enum Keywords
{ // specific ordering for ConnectionString output construction
// NamedConnection,
DataSource,
FailoverPartner,
AttachDBFilename,
InitialCatalog,
IntegratedSecurity,
PersistSecurityInfo,
UserID,
Password,
Pooling,
MinPoolSize,
MaxPoolSize,
MultipleActiveResultSets,
Replication,
ConnectTimeout,
Encrypt,
TrustServerCertificate,
LoadBalanceTimeout,
PacketSize,
TypeSystemVersion,
ApplicationName,
CurrentLanguage,
WorkstationID,
UserInstance,
ApplicationIntent,
MultiSubnetFailover,
ConnectRetryCount,
ConnectRetryInterval,
// keep the count value last
KeywordsCount
}
internal const int KeywordsCount = (int)Keywords.KeywordsCount;
internal const int DeprecatedKeywordsCount = 6;
private static readonly string[] s_validKeywords = CreateValidKeywords();
private static readonly Dictionary<string, Keywords> s_keywords = CreateKeywordsDictionary();
private ApplicationIntent _applicationIntent = DbConnectionStringDefaults.ApplicationIntent;
private string _applicationName = DbConnectionStringDefaults.ApplicationName;
private string _attachDBFilename = DbConnectionStringDefaults.AttachDBFilename;
private string _currentLanguage = DbConnectionStringDefaults.CurrentLanguage;
private string _dataSource = DbConnectionStringDefaults.DataSource;
private string _failoverPartner = DbConnectionStringDefaults.FailoverPartner;
private string _initialCatalog = DbConnectionStringDefaults.InitialCatalog;
// private string _namedConnection = DbConnectionStringDefaults.NamedConnection;
private string _password = DbConnectionStringDefaults.Password;
private string _typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion;
private string _userID = DbConnectionStringDefaults.UserID;
private string _workstationID = DbConnectionStringDefaults.WorkstationID;
private int _connectTimeout = DbConnectionStringDefaults.ConnectTimeout;
private int _loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout;
private int _maxPoolSize = DbConnectionStringDefaults.MaxPoolSize;
private int _minPoolSize = DbConnectionStringDefaults.MinPoolSize;
private int _packetSize = DbConnectionStringDefaults.PacketSize;
private int _connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount;
private int _connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval;
private bool _encrypt = DbConnectionStringDefaults.Encrypt;
private bool _trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate;
private bool _integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity;
private bool _multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets;
private bool _multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover;
private bool _persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo;
private bool _pooling = DbConnectionStringDefaults.Pooling;
private bool _replication = DbConnectionStringDefaults.Replication;
private bool _userInstance = DbConnectionStringDefaults.UserInstance;
private static string[] CreateValidKeywords()
{
string[] validKeywords = new string[KeywordsCount];
validKeywords[(int)Keywords.ApplicationIntent] = DbConnectionStringKeywords.ApplicationIntent;
validKeywords[(int)Keywords.ApplicationName] = DbConnectionStringKeywords.ApplicationName;
validKeywords[(int)Keywords.AttachDBFilename] = DbConnectionStringKeywords.AttachDBFilename;
validKeywords[(int)Keywords.ConnectTimeout] = DbConnectionStringKeywords.ConnectTimeout;
validKeywords[(int)Keywords.CurrentLanguage] = DbConnectionStringKeywords.CurrentLanguage;
validKeywords[(int)Keywords.DataSource] = DbConnectionStringKeywords.DataSource;
validKeywords[(int)Keywords.Encrypt] = DbConnectionStringKeywords.Encrypt;
validKeywords[(int)Keywords.FailoverPartner] = DbConnectionStringKeywords.FailoverPartner;
validKeywords[(int)Keywords.InitialCatalog] = DbConnectionStringKeywords.InitialCatalog;
validKeywords[(int)Keywords.IntegratedSecurity] = DbConnectionStringKeywords.IntegratedSecurity;
validKeywords[(int)Keywords.LoadBalanceTimeout] = DbConnectionStringKeywords.LoadBalanceTimeout;
validKeywords[(int)Keywords.MaxPoolSize] = DbConnectionStringKeywords.MaxPoolSize;
validKeywords[(int)Keywords.MinPoolSize] = DbConnectionStringKeywords.MinPoolSize;
validKeywords[(int)Keywords.MultipleActiveResultSets] = DbConnectionStringKeywords.MultipleActiveResultSets;
validKeywords[(int)Keywords.MultiSubnetFailover] = DbConnectionStringKeywords.MultiSubnetFailover;
// validKeywords[(int)Keywords.NamedConnection] = DbConnectionStringKeywords.NamedConnection;
validKeywords[(int)Keywords.PacketSize] = DbConnectionStringKeywords.PacketSize;
validKeywords[(int)Keywords.Password] = DbConnectionStringKeywords.Password;
validKeywords[(int)Keywords.PersistSecurityInfo] = DbConnectionStringKeywords.PersistSecurityInfo;
validKeywords[(int)Keywords.Pooling] = DbConnectionStringKeywords.Pooling;
validKeywords[(int)Keywords.Replication] = DbConnectionStringKeywords.Replication;
validKeywords[(int)Keywords.TrustServerCertificate] = DbConnectionStringKeywords.TrustServerCertificate;
validKeywords[(int)Keywords.TypeSystemVersion] = DbConnectionStringKeywords.TypeSystemVersion;
validKeywords[(int)Keywords.UserID] = DbConnectionStringKeywords.UserID;
validKeywords[(int)Keywords.UserInstance] = DbConnectionStringKeywords.UserInstance;
validKeywords[(int)Keywords.WorkstationID] = DbConnectionStringKeywords.WorkstationID;
validKeywords[(int)Keywords.ConnectRetryCount] = DbConnectionStringKeywords.ConnectRetryCount;
validKeywords[(int)Keywords.ConnectRetryInterval] = DbConnectionStringKeywords.ConnectRetryInterval;
return validKeywords;
}
private static Dictionary<string, Keywords> CreateKeywordsDictionary()
{
Dictionary<string, Keywords> hash = new Dictionary<string, Keywords>(KeywordsCount + SqlConnectionString.SynonymCount, StringComparer.OrdinalIgnoreCase);
hash.Add(DbConnectionStringKeywords.ApplicationIntent, Keywords.ApplicationIntent);
hash.Add(DbConnectionStringKeywords.ApplicationName, Keywords.ApplicationName);
hash.Add(DbConnectionStringKeywords.AttachDBFilename, Keywords.AttachDBFilename);
hash.Add(DbConnectionStringKeywords.ConnectTimeout, Keywords.ConnectTimeout);
hash.Add(DbConnectionStringKeywords.CurrentLanguage, Keywords.CurrentLanguage);
hash.Add(DbConnectionStringKeywords.DataSource, Keywords.DataSource);
hash.Add(DbConnectionStringKeywords.Encrypt, Keywords.Encrypt);
hash.Add(DbConnectionStringKeywords.FailoverPartner, Keywords.FailoverPartner);
hash.Add(DbConnectionStringKeywords.InitialCatalog, Keywords.InitialCatalog);
hash.Add(DbConnectionStringKeywords.IntegratedSecurity, Keywords.IntegratedSecurity);
hash.Add(DbConnectionStringKeywords.LoadBalanceTimeout, Keywords.LoadBalanceTimeout);
hash.Add(DbConnectionStringKeywords.MultipleActiveResultSets, Keywords.MultipleActiveResultSets);
hash.Add(DbConnectionStringKeywords.MaxPoolSize, Keywords.MaxPoolSize);
hash.Add(DbConnectionStringKeywords.MinPoolSize, Keywords.MinPoolSize);
hash.Add(DbConnectionStringKeywords.MultiSubnetFailover, Keywords.MultiSubnetFailover);
// hash.Add(DbConnectionStringKeywords.NamedConnection, Keywords.NamedConnection);
hash.Add(DbConnectionStringKeywords.PacketSize, Keywords.PacketSize);
hash.Add(DbConnectionStringKeywords.Password, Keywords.Password);
hash.Add(DbConnectionStringKeywords.PersistSecurityInfo, Keywords.PersistSecurityInfo);
hash.Add(DbConnectionStringKeywords.Pooling, Keywords.Pooling);
hash.Add(DbConnectionStringKeywords.Replication, Keywords.Replication);
hash.Add(DbConnectionStringKeywords.TrustServerCertificate, Keywords.TrustServerCertificate);
hash.Add(DbConnectionStringKeywords.TypeSystemVersion, Keywords.TypeSystemVersion);
hash.Add(DbConnectionStringKeywords.UserID, Keywords.UserID);
hash.Add(DbConnectionStringKeywords.UserInstance, Keywords.UserInstance);
hash.Add(DbConnectionStringKeywords.WorkstationID, Keywords.WorkstationID);
hash.Add(DbConnectionStringKeywords.ConnectRetryCount, Keywords.ConnectRetryCount);
hash.Add(DbConnectionStringKeywords.ConnectRetryInterval, Keywords.ConnectRetryInterval);
hash.Add(DbConnectionStringSynonyms.APP, Keywords.ApplicationName);
hash.Add(DbConnectionStringSynonyms.EXTENDEDPROPERTIES, Keywords.AttachDBFilename);
hash.Add(DbConnectionStringSynonyms.INITIALFILENAME, Keywords.AttachDBFilename);
hash.Add(DbConnectionStringSynonyms.CONNECTIONTIMEOUT, Keywords.ConnectTimeout);
hash.Add(DbConnectionStringSynonyms.TIMEOUT, Keywords.ConnectTimeout);
hash.Add(DbConnectionStringSynonyms.LANGUAGE, Keywords.CurrentLanguage);
hash.Add(DbConnectionStringSynonyms.ADDR, Keywords.DataSource);
hash.Add(DbConnectionStringSynonyms.ADDRESS, Keywords.DataSource);
hash.Add(DbConnectionStringSynonyms.NETWORKADDRESS, Keywords.DataSource);
hash.Add(DbConnectionStringSynonyms.SERVER, Keywords.DataSource);
hash.Add(DbConnectionStringSynonyms.DATABASE, Keywords.InitialCatalog);
hash.Add(DbConnectionStringSynonyms.TRUSTEDCONNECTION, Keywords.IntegratedSecurity);
hash.Add(DbConnectionStringSynonyms.ConnectionLifetime, Keywords.LoadBalanceTimeout);
hash.Add(DbConnectionStringSynonyms.Pwd, Keywords.Password);
hash.Add(DbConnectionStringSynonyms.PERSISTSECURITYINFO, Keywords.PersistSecurityInfo);
hash.Add(DbConnectionStringSynonyms.UID, Keywords.UserID);
hash.Add(DbConnectionStringSynonyms.User, Keywords.UserID);
hash.Add(DbConnectionStringSynonyms.WSID, Keywords.WorkstationID);
Debug.Assert((KeywordsCount + SqlConnectionString.SynonymCount) == hash.Count, "initial expected size is incorrect");
return hash;
}
public SqlConnectionStringBuilder() : this((string)null)
{
}
public SqlConnectionStringBuilder(string connectionString) : base()
{
if (!string.IsNullOrEmpty(connectionString))
{
ConnectionString = connectionString;
}
}
public override object this[string keyword]
{
get
{
Keywords index = GetIndex(keyword);
return GetAt(index);
}
set
{
if (null != value)
{
Keywords index = GetIndex(keyword);
switch (index)
{
case Keywords.ApplicationIntent: this.ApplicationIntent = ConvertToApplicationIntent(keyword, value); break;
case Keywords.ApplicationName: ApplicationName = ConvertToString(value); break;
case Keywords.AttachDBFilename: AttachDBFilename = ConvertToString(value); break;
case Keywords.CurrentLanguage: CurrentLanguage = ConvertToString(value); break;
case Keywords.DataSource: DataSource = ConvertToString(value); break;
case Keywords.FailoverPartner: FailoverPartner = ConvertToString(value); break;
case Keywords.InitialCatalog: InitialCatalog = ConvertToString(value); break;
// case Keywords.NamedConnection: NamedConnection = ConvertToString(value); break;
case Keywords.Password: Password = ConvertToString(value); break;
case Keywords.UserID: UserID = ConvertToString(value); break;
case Keywords.TypeSystemVersion: TypeSystemVersion = ConvertToString(value); break;
case Keywords.WorkstationID: WorkstationID = ConvertToString(value); break;
case Keywords.ConnectTimeout: ConnectTimeout = ConvertToInt32(value); break;
case Keywords.LoadBalanceTimeout: LoadBalanceTimeout = ConvertToInt32(value); break;
case Keywords.MaxPoolSize: MaxPoolSize = ConvertToInt32(value); break;
case Keywords.MinPoolSize: MinPoolSize = ConvertToInt32(value); break;
case Keywords.PacketSize: PacketSize = ConvertToInt32(value); break;
case Keywords.IntegratedSecurity: IntegratedSecurity = ConvertToIntegratedSecurity(value); break;
case Keywords.Encrypt: Encrypt = ConvertToBoolean(value); break;
case Keywords.TrustServerCertificate: TrustServerCertificate = ConvertToBoolean(value); break;
case Keywords.MultipleActiveResultSets: MultipleActiveResultSets = ConvertToBoolean(value); break;
case Keywords.MultiSubnetFailover: MultiSubnetFailover = ConvertToBoolean(value); break;
case Keywords.PersistSecurityInfo: PersistSecurityInfo = ConvertToBoolean(value); break;
case Keywords.Pooling: Pooling = ConvertToBoolean(value); break;
case Keywords.Replication: Replication = ConvertToBoolean(value); break;
case Keywords.UserInstance: UserInstance = ConvertToBoolean(value); break;
case Keywords.ConnectRetryCount: ConnectRetryCount = ConvertToInt32(value); break;
case Keywords.ConnectRetryInterval: ConnectRetryInterval = ConvertToInt32(value); break;
default:
Debug.Assert(false, "unexpected keyword");
throw UnsupportedKeyword(keyword);
}
}
else
{
Remove(keyword);
}
}
}
public ApplicationIntent ApplicationIntent
{
get { return _applicationIntent; }
set
{
if (!DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value))
{
throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)value);
}
SetApplicationIntentValue(value);
_applicationIntent = value;
}
}
public string ApplicationName
{
get { return _applicationName; }
set
{
SetValue(DbConnectionStringKeywords.ApplicationName, value);
_applicationName = value;
}
}
public string AttachDBFilename
{
get { return _attachDBFilename; }
set
{
SetValue(DbConnectionStringKeywords.AttachDBFilename, value);
_attachDBFilename = value;
}
}
public int ConnectTimeout
{
get { return _connectTimeout; }
set
{
if (value < 0)
{
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectTimeout);
}
SetValue(DbConnectionStringKeywords.ConnectTimeout, value);
_connectTimeout = value;
}
}
public string CurrentLanguage
{
get { return _currentLanguage; }
set
{
SetValue(DbConnectionStringKeywords.CurrentLanguage, value);
_currentLanguage = value;
}
}
public string DataSource
{
get { return _dataSource; }
set
{
SetValue(DbConnectionStringKeywords.DataSource, value);
_dataSource = value;
}
}
public bool Encrypt
{
get { return _encrypt; }
set
{
SetValue(DbConnectionStringKeywords.Encrypt, value);
_encrypt = value;
}
}
public bool TrustServerCertificate
{
get { return _trustServerCertificate; }
set
{
SetValue(DbConnectionStringKeywords.TrustServerCertificate, value);
_trustServerCertificate = value;
}
}
public string FailoverPartner
{
get { return _failoverPartner; }
set
{
SetValue(DbConnectionStringKeywords.FailoverPartner, value);
_failoverPartner = value;
}
}
public string InitialCatalog
{
get { return _initialCatalog; }
set
{
SetValue(DbConnectionStringKeywords.InitialCatalog, value);
_initialCatalog = value;
}
}
public bool IntegratedSecurity
{
get { return _integratedSecurity; }
set
{
SetValue(DbConnectionStringKeywords.IntegratedSecurity, value);
_integratedSecurity = value;
}
}
public int LoadBalanceTimeout
{
get { return _loadBalanceTimeout; }
set
{
if (value < 0)
{
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.LoadBalanceTimeout);
}
SetValue(DbConnectionStringKeywords.LoadBalanceTimeout, value);
_loadBalanceTimeout = value;
}
}
public int MaxPoolSize
{
get { return _maxPoolSize; }
set
{
if (value < 1)
{
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.MaxPoolSize);
}
SetValue(DbConnectionStringKeywords.MaxPoolSize, value);
_maxPoolSize = value;
}
}
public int ConnectRetryCount
{
get { return _connectRetryCount; }
set
{
if ((value < 0) || (value > 255))
{
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectRetryCount);
}
SetValue(DbConnectionStringKeywords.ConnectRetryCount, value);
_connectRetryCount = value;
}
}
public int ConnectRetryInterval
{
get { return _connectRetryInterval; }
set
{
if ((value < 1) || (value > 60))
{
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectRetryInterval);
}
SetValue(DbConnectionStringKeywords.ConnectRetryInterval, value);
_connectRetryInterval = value;
}
}
public int MinPoolSize
{
get { return _minPoolSize; }
set
{
if (value < 0)
{
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.MinPoolSize);
}
SetValue(DbConnectionStringKeywords.MinPoolSize, value);
_minPoolSize = value;
}
}
public bool MultipleActiveResultSets
{
get { return _multipleActiveResultSets; }
set
{
SetValue(DbConnectionStringKeywords.MultipleActiveResultSets, value);
_multipleActiveResultSets = value;
}
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Reviewed and Approved by UE")]
public bool MultiSubnetFailover
{
get { return _multiSubnetFailover; }
set
{
SetValue(DbConnectionStringKeywords.MultiSubnetFailover, value);
_multiSubnetFailover = value;
}
}
/*
[DisplayName(DbConnectionStringKeywords.NamedConnection)]
[ResCategoryAttribute(Res.DataCategory_NamedConnectionString)]
[ResDescriptionAttribute(Res.DbConnectionString_NamedConnection)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[TypeConverter(typeof(NamedConnectionStringConverter))]
public string NamedConnection {
get { return _namedConnection; }
set {
SetValue(DbConnectionStringKeywords.NamedConnection, value);
_namedConnection = value;
}
}
*/
public int PacketSize
{
get { return _packetSize; }
set
{
if ((value < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < value))
{
throw SQL.InvalidPacketSizeValue();
}
SetValue(DbConnectionStringKeywords.PacketSize, value);
_packetSize = value;
}
}
public string Password
{
get { return _password; }
set
{
SetValue(DbConnectionStringKeywords.Password, value);
_password = value;
}
}
public bool PersistSecurityInfo
{
get { return _persistSecurityInfo; }
set
{
SetValue(DbConnectionStringKeywords.PersistSecurityInfo, value);
_persistSecurityInfo = value;
}
}
public bool Pooling
{
get { return _pooling; }
set
{
SetValue(DbConnectionStringKeywords.Pooling, value);
_pooling = value;
}
}
public bool Replication
{
get { return _replication; }
set
{
SetValue(DbConnectionStringKeywords.Replication, value);
_replication = value;
}
}
public string TypeSystemVersion
{
get { return _typeSystemVersion; }
set
{
SetValue(DbConnectionStringKeywords.TypeSystemVersion, value);
_typeSystemVersion = value;
}
}
public string UserID
{
get { return _userID; }
set
{
SetValue(DbConnectionStringKeywords.UserID, value);
_userID = value;
}
}
public bool UserInstance
{
get { return _userInstance; }
set
{
SetValue(DbConnectionStringKeywords.UserInstance, value);
_userInstance = value;
}
}
public string WorkstationID
{
get { return _workstationID; }
set
{
SetValue(DbConnectionStringKeywords.WorkstationID, value);
_workstationID = value;
}
}
public override ICollection Keys
{
get
{
return new System.Collections.ObjectModel.ReadOnlyCollection<string>(s_validKeywords);
}
}
public override ICollection Values
{
get
{
// written this way so if the ordering of Keywords & _validKeywords changes
// this is one less place to maintain
object[] values = new object[s_validKeywords.Length];
for (int i = 0; i < values.Length; ++i)
{
values[i] = GetAt((Keywords)i);
}
return new System.Collections.ObjectModel.ReadOnlyCollection<object>(values);
}
}
public override void Clear()
{
base.Clear();
for (int i = 0; i < s_validKeywords.Length; ++i)
{
Reset((Keywords)i);
}
}
public override bool ContainsKey(string keyword)
{
ADP.CheckArgumentNull(keyword, nameof(keyword));
return s_keywords.ContainsKey(keyword);
}
private static bool ConvertToBoolean(object value)
{
return DbConnectionStringBuilderUtil.ConvertToBoolean(value);
}
private static int ConvertToInt32(object value)
{
return DbConnectionStringBuilderUtil.ConvertToInt32(value);
}
private static bool ConvertToIntegratedSecurity(object value)
{
return DbConnectionStringBuilderUtil.ConvertToIntegratedSecurity(value);
}
private static string ConvertToString(object value)
{
return DbConnectionStringBuilderUtil.ConvertToString(value);
}
private static ApplicationIntent ConvertToApplicationIntent(string keyword, object value)
{
return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(keyword, value);
}
private object GetAt(Keywords index)
{
switch (index)
{
case Keywords.ApplicationIntent: return this.ApplicationIntent;
case Keywords.ApplicationName: return ApplicationName;
case Keywords.AttachDBFilename: return AttachDBFilename;
case Keywords.ConnectTimeout: return ConnectTimeout;
case Keywords.CurrentLanguage: return CurrentLanguage;
case Keywords.DataSource: return DataSource;
case Keywords.Encrypt: return Encrypt;
case Keywords.FailoverPartner: return FailoverPartner;
case Keywords.InitialCatalog: return InitialCatalog;
case Keywords.IntegratedSecurity: return IntegratedSecurity;
case Keywords.LoadBalanceTimeout: return LoadBalanceTimeout;
case Keywords.MultipleActiveResultSets: return MultipleActiveResultSets;
case Keywords.MaxPoolSize: return MaxPoolSize;
case Keywords.MinPoolSize: return MinPoolSize;
case Keywords.MultiSubnetFailover: return MultiSubnetFailover;
// case Keywords.NamedConnection: return NamedConnection;
case Keywords.PacketSize: return PacketSize;
case Keywords.Password: return Password;
case Keywords.PersistSecurityInfo: return PersistSecurityInfo;
case Keywords.Pooling: return Pooling;
case Keywords.Replication: return Replication;
case Keywords.TrustServerCertificate: return TrustServerCertificate;
case Keywords.TypeSystemVersion: return TypeSystemVersion;
case Keywords.UserID: return UserID;
case Keywords.UserInstance: return UserInstance;
case Keywords.WorkstationID: return WorkstationID;
case Keywords.ConnectRetryCount: return ConnectRetryCount;
case Keywords.ConnectRetryInterval: return ConnectRetryInterval;
default:
Debug.Assert(false, "unexpected keyword");
throw UnsupportedKeyword(s_validKeywords[(int)index]);
}
}
private Keywords GetIndex(string keyword)
{
ADP.CheckArgumentNull(keyword, nameof(keyword));
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
return index;
}
throw UnsupportedKeyword(keyword);
}
public override bool Remove(string keyword)
{
ADP.CheckArgumentNull(keyword, nameof(keyword));
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
if (base.Remove(s_validKeywords[(int)index]))
{
Reset(index);
return true;
}
}
return false;
}
private void Reset(Keywords index)
{
switch (index)
{
case Keywords.ApplicationIntent:
_applicationIntent = DbConnectionStringDefaults.ApplicationIntent;
break;
case Keywords.ApplicationName:
_applicationName = DbConnectionStringDefaults.ApplicationName;
break;
case Keywords.AttachDBFilename:
_attachDBFilename = DbConnectionStringDefaults.AttachDBFilename;
break;
case Keywords.ConnectTimeout:
_connectTimeout = DbConnectionStringDefaults.ConnectTimeout;
break;
case Keywords.CurrentLanguage:
_currentLanguage = DbConnectionStringDefaults.CurrentLanguage;
break;
case Keywords.DataSource:
_dataSource = DbConnectionStringDefaults.DataSource;
break;
case Keywords.Encrypt:
_encrypt = DbConnectionStringDefaults.Encrypt;
break;
case Keywords.FailoverPartner:
_failoverPartner = DbConnectionStringDefaults.FailoverPartner;
break;
case Keywords.InitialCatalog:
_initialCatalog = DbConnectionStringDefaults.InitialCatalog;
break;
case Keywords.IntegratedSecurity:
_integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity;
break;
case Keywords.LoadBalanceTimeout:
_loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout;
break;
case Keywords.MultipleActiveResultSets:
_multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets;
break;
case Keywords.MaxPoolSize:
_maxPoolSize = DbConnectionStringDefaults.MaxPoolSize;
break;
case Keywords.MinPoolSize:
_minPoolSize = DbConnectionStringDefaults.MinPoolSize;
break;
case Keywords.MultiSubnetFailover:
_multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover;
break;
// case Keywords.NamedConnection:
// _namedConnection = DbConnectionStringDefaults.NamedConnection;
// break;
case Keywords.PacketSize:
_packetSize = DbConnectionStringDefaults.PacketSize;
break;
case Keywords.Password:
_password = DbConnectionStringDefaults.Password;
break;
case Keywords.PersistSecurityInfo:
_persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo;
break;
case Keywords.Pooling:
_pooling = DbConnectionStringDefaults.Pooling;
break;
case Keywords.ConnectRetryCount:
_connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount;
break;
case Keywords.ConnectRetryInterval:
_connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval;
break;
case Keywords.Replication:
_replication = DbConnectionStringDefaults.Replication;
break;
case Keywords.TrustServerCertificate:
_trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate;
break;
case Keywords.TypeSystemVersion:
_typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion;
break;
case Keywords.UserID:
_userID = DbConnectionStringDefaults.UserID;
break;
case Keywords.UserInstance:
_userInstance = DbConnectionStringDefaults.UserInstance;
break;
case Keywords.WorkstationID:
_workstationID = DbConnectionStringDefaults.WorkstationID;
break;
default:
Debug.Assert(false, "unexpected keyword");
throw UnsupportedKeyword(s_validKeywords[(int)index]);
}
}
private void SetValue(string keyword, bool value)
{
base[keyword] = value.ToString();
}
private void SetValue(string keyword, int value)
{
base[keyword] = value.ToString((System.IFormatProvider)null);
}
private void SetValue(string keyword, string value)
{
ADP.CheckArgumentNull(value, keyword);
base[keyword] = value;
}
private void SetApplicationIntentValue(ApplicationIntent value)
{
Debug.Assert(DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value), "invalid value");
base[DbConnectionStringKeywords.ApplicationIntent] = DbConnectionStringBuilderUtil.ApplicationIntentToString(value);
}
public override bool ShouldSerialize(string keyword)
{
ADP.CheckArgumentNull(keyword, nameof(keyword));
Keywords index;
return s_keywords.TryGetValue(keyword, out index) && base.ShouldSerialize(s_validKeywords[(int)index]);
}
public override bool TryGetValue(string keyword, out object value)
{
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
value = GetAt(index);
return true;
}
value = null;
return false;
}
private static readonly string[] s_notSupportedKeywords = new string[] {
DbConnectionStringKeywords.AsynchronousProcessing,
DbConnectionStringKeywords.ConnectionReset,
DbConnectionStringKeywords.ContextConnection,
DbConnectionStringKeywords.Enlist,
DbConnectionStringKeywords.TransactionBinding,
DbConnectionStringSynonyms.Async
};
private static readonly string[] s_notSupportedNetworkLibraryKeywords = new string[] {
DbConnectionStringKeywords.NetworkLibrary,
DbConnectionStringSynonyms.NET,
DbConnectionStringSynonyms.NETWORK
};
private Exception UnsupportedKeyword(string keyword)
{
if (s_notSupportedKeywords.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
return SQL.UnsupportedKeyword(keyword);
}
else if (s_notSupportedNetworkLibraryKeywords.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
return SQL.NetworkLibraryKeywordNotSupported();
}
else
{
return ADP.KeywordNotSupported(keyword);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
internal class TestApp
{
private static unsafe long test_4()
{
AA loc_x = new AA(0, 100);
return (&loc_x.m_b)->m_bval;
}
private static unsafe long test_11(B[][] ab, long i, long j)
{
fixed (B* pb = &ab[i][j])
{
return pb->m_bval;
}
}
private static unsafe long test_18(B* pb1, long i)
{
B* pb;
return (pb = (B*)(((byte*)pb1) + i * sizeof(B)))->m_bval;
}
private static unsafe long test_25(B* pb, long[,,] i, long ii, byte jj)
{
return (&pb[i[ii - jj, 0, ii - jj] = ii - 1])->m_bval;
}
private static unsafe long test_32(ulong ub, byte lb)
{
return ((B*)(ub | lb))->m_bval;
}
private static unsafe long test_39(long p, long s)
{
return ((B*)((p >> 4) | s))->m_bval;
}
private static unsafe long test_46(B[] ab)
{
fixed (B* pb = &ab[0])
{
return pb[0].m_bval;
}
}
private static unsafe long test_53(B* pb)
{
return (++pb)[0].m_bval;
}
private static unsafe long test_60(B* pb, long[] i, long ii)
{
return (&pb[i[ii]])[0].m_bval;
}
private static unsafe long test_67(AA* px)
{
return (AA.get_pb_1(px) + 1)[0].m_bval;
}
private static unsafe long test_74(long pb)
{
return ((B*)checked(((long)pb) + 1))[0].m_bval;
}
private static unsafe long test_81(B* pb)
{
return AA.get_bv1((pb--));
}
private static unsafe long test_88(AA[,] ab, long i)
{
long j = 0;
fixed (B* pb = &ab[--i, ++j].m_b)
{
return AA.get_bv1(pb);
}
}
private static unsafe long test_95(B* pb1, long i)
{
B* pb;
return AA.get_bv1((pb = pb1 + i));
}
private static unsafe long test_102(B* pb1, B* pb2)
{
return AA.get_bv1((pb1 > pb2 ? pb2 : null));
}
private static unsafe long test_109(long pb)
{
return AA.get_bv1(((B*)pb));
}
private static unsafe long test_116(double* pb, long i)
{
return AA.get_bv1(((B*)(pb + i)));
}
private static unsafe long test_123(ref B b)
{
fixed (B* pb = &b)
{
return AA.get_bv2(*pb);
}
}
private static unsafe long test_130(B* pb)
{
return AA.get_bv2(*(--pb));
}
private static unsafe long test_137(B* pb, long i)
{
return AA.get_bv2(*(&pb[-(i << (int)i)]));
}
private static unsafe long test_144(AA* px)
{
return AA.get_bv2(*AA.get_pb(px));
}
private static unsafe long test_151(long pb)
{
return AA.get_bv2(*((B*)checked((long)pb)));
}
private static unsafe long test_158(B* pb)
{
return AA.get_bv3(ref *(pb++));
}
private static unsafe long test_165(B[,] ab, long i, long j)
{
fixed (B* pb = &ab[i, j])
{
return AA.get_bv3(ref *pb);
}
}
private static unsafe long test_172(B* pb1)
{
B* pb;
return AA.get_bv3(ref *(pb = pb1 - 8));
}
private static unsafe long test_179(B* pb, B* pb1, B* pb2)
{
return AA.get_bv3(ref *(pb = pb + (pb2 - pb1)));
}
private static unsafe long test_186(B* pb1, bool trig)
{
fixed (B* pb = &AA.s_x.m_b)
{
return AA.get_bv3(ref *(trig ? pb : pb1));
}
}
private static unsafe long test_193(byte* pb)
{
return AA.get_bv3(ref *((B*)(pb + 7)));
}
private static unsafe long test_200(B b)
{
return (&b)->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_207()
{
fixed (B* pb = &AA.s_x.m_b)
{
return pb->m_bval == 100 ? 100 : 101;
}
}
private static unsafe long test_214(B* pb, long i)
{
return (&pb[i * 2])->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_221(B* pb1, B* pb2)
{
return (pb1 >= pb2 ? pb1 : null)->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_228(long pb)
{
return ((B*)pb)->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_235(B* pb)
{
return AA.get_i1(&pb->m_bval);
}
private static unsafe long test_242(B[] ab, long i)
{
fixed (B* pb = &ab[i])
{
return AA.get_i1(&pb->m_bval);
}
}
private static unsafe long test_249(B* pb)
{
return AA.get_i1(&(pb += 6)->m_bval);
}
private static unsafe long test_256(B* pb, long[,,] i, long ii)
{
return AA.get_i1(&(&pb[++i[--ii, 0, 0]])->m_bval);
}
private static unsafe long test_263(AA* px)
{
return AA.get_i1(&((B*)AA.get_pb_i(px))->m_bval);
}
private static unsafe long test_270(byte diff, A* pa)
{
return AA.get_i1(&((B*)(((byte*)pa) + diff))->m_bval);
}
private static unsafe long test_277()
{
AA loc_x = new AA(0, 100);
return AA.get_i2((&loc_x.m_b)->m_bval);
}
private static unsafe long test_284(B[][] ab, long i, long j)
{
fixed (B* pb = &ab[i][j])
{
return AA.get_i2(pb->m_bval);
}
}
private static unsafe long test_291(B* pb1, long i)
{
B* pb;
return AA.get_i2((pb = (B*)(((byte*)pb1) + i * sizeof(B)))->m_bval);
}
private static unsafe long test_298(B* pb, long[,,] i, long ii, byte jj)
{
return AA.get_i2((&pb[i[ii - jj, 0, ii - jj] = ii - 1])->m_bval);
}
private static unsafe long test_305(ulong ub, byte lb)
{
return AA.get_i2(((B*)(ub | lb))->m_bval);
}
private static unsafe long test_312(long p, long s)
{
return AA.get_i2(((B*)((p >> 4) | s))->m_bval);
}
private static unsafe long test_319(B[] ab)
{
fixed (B* pb = &ab[0])
{
return AA.get_i3(ref pb->m_bval);
}
}
private static unsafe long test_326(B* pb)
{
return AA.get_i3(ref (++pb)->m_bval);
}
private static unsafe long test_333(B* pb, long[] i, long ii)
{
return AA.get_i3(ref (&pb[i[ii]])->m_bval);
}
private static unsafe long test_340(AA* px)
{
return AA.get_i3(ref (AA.get_pb_1(px) + 1)->m_bval);
}
private static unsafe long test_347(long pb)
{
return AA.get_i3(ref ((B*)checked(((long)pb) + 1))->m_bval);
}
private static unsafe long test_354(B* pb)
{
return AA.get_bv1((pb--)) != 100 ? 99 : 100;
}
private static unsafe long test_361(AA[,] ab, long i)
{
long j = 0;
fixed (B* pb = &ab[--i, ++j].m_b)
{
return AA.get_bv1(pb) != 100 ? 99 : 100;
}
}
private static unsafe long test_368(B* pb1, long i)
{
B* pb;
return AA.get_bv1((pb = pb1 + i)) != 100 ? 99 : 100;
}
private static unsafe long test_375(B* pb1, B* pb2)
{
return AA.get_bv1((pb1 > pb2 ? pb2 : null)) != 100 ? 99 : 100;
}
private static unsafe long test_382(long pb)
{
return AA.get_bv1(((B*)pb)) != 100 ? 99 : 100;
}
private static unsafe long test_389(double* pb, long i)
{
return AA.get_bv1(((B*)(pb + i))) != 100 ? 99 : 100;
}
private static unsafe long test_396(B* pb1, B* pb2)
{
if (pb1 >= pb2) return 100;
throw new Exception();
}
private static unsafe int Main()
{
AA loc_x = new AA(0, 100);
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_4() != 100)
{
Console.WriteLine("test_4() failed.");
return 104;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_11(new B[][] { new B[] { new B(), new B() }, new B[] { new B(), loc_x.m_b } }, 1, 1) != 100)
{
Console.WriteLine("test_11() failed.");
return 111;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_18(&loc_x.m_b - 8, 8) != 100)
{
Console.WriteLine("test_18() failed.");
return 118;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_25(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2, 2) != 100)
{
Console.WriteLine("test_25() failed.");
return 125;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_32(((ulong)&loc_x.m_b) & (~(ulong)0xff), unchecked((byte)&loc_x.m_b)) != 100)
{
Console.WriteLine("test_32() failed.");
return 132;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_39(((long)(&loc_x.m_b)) << 4, ((long)(&loc_x.m_b)) & 0xff000000) != 100)
{
Console.WriteLine("test_39() failed.");
return 139;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_46(new B[] { loc_x.m_b }) != 100)
{
Console.WriteLine("test_46() failed.");
return 146;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_53(&loc_x.m_b - 1) != 100)
{
Console.WriteLine("test_53() failed.");
return 153;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_60(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100)
{
Console.WriteLine("test_60() failed.");
return 160;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_67(&loc_x) != 100)
{
Console.WriteLine("test_67() failed.");
return 167;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_74((long)(((long)&loc_x.m_b) - 1)) != 100)
{
Console.WriteLine("test_74() failed.");
return 174;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_81(&loc_x.m_b) != 100)
{
Console.WriteLine("test_81() failed.");
return 181;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_88(new AA[,] { { new AA(), new AA() }, { new AA(), loc_x } }, 2) != 100)
{
Console.WriteLine("test_88() failed.");
return 188;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_95(&loc_x.m_b - 8, 8) != 100)
{
Console.WriteLine("test_95() failed.");
return 195;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_102(&loc_x.m_b + 1, &loc_x.m_b) != 100)
{
Console.WriteLine("test_102() failed.");
return 202;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_109((long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_109() failed.");
return 209;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_116(((double*)(&loc_x.m_b)) - 4, 4) != 100)
{
Console.WriteLine("test_116() failed.");
return 216;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_123(ref loc_x.m_b) != 100)
{
Console.WriteLine("test_123() failed.");
return 223;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_130(&loc_x.m_b + 1) != 100)
{
Console.WriteLine("test_130() failed.");
return 230;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_137(&loc_x.m_b + 2, 1) != 100)
{
Console.WriteLine("test_137() failed.");
return 237;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_144(&loc_x) != 100)
{
Console.WriteLine("test_144() failed.");
return 244;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_151((long)(long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_151() failed.");
return 251;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_158(&loc_x.m_b) != 100)
{
Console.WriteLine("test_158() failed.");
return 258;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_165(new B[,] { { new B(), new B() }, { new B(), loc_x.m_b } }, 1, 1) != 100)
{
Console.WriteLine("test_165() failed.");
return 265;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_172(&loc_x.m_b + 8) != 100)
{
Console.WriteLine("test_172() failed.");
return 272;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_179(&loc_x.m_b - 2, &loc_x.m_b - 1, &loc_x.m_b + 1) != 100)
{
Console.WriteLine("test_179() failed.");
return 279;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_186(&loc_x.m_b, true) != 100)
{
Console.WriteLine("test_186() failed.");
return 286;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_193(((byte*)(&loc_x.m_b)) - 7) != 100)
{
Console.WriteLine("test_193() failed.");
return 293;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_200(loc_x.m_b) != 100)
{
Console.WriteLine("test_200() failed.");
return 300;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_207() != 100)
{
Console.WriteLine("test_207() failed.");
return 307;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_214(&loc_x.m_b - 2, 1) != 100)
{
Console.WriteLine("test_214() failed.");
return 314;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_221(&loc_x.m_b, &loc_x.m_b) != 100)
{
Console.WriteLine("test_221() failed.");
return 321;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_228((long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_228() failed.");
return 328;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_235(&loc_x.m_b) != 100)
{
Console.WriteLine("test_235() failed.");
return 335;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_242(new B[] { new B(), new B(), loc_x.m_b }, 2) != 100)
{
Console.WriteLine("test_242() failed.");
return 342;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_249(&loc_x.m_b - 6) != 100)
{
Console.WriteLine("test_249() failed.");
return 349;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_256(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2) != 100)
{
Console.WriteLine("test_256() failed.");
return 356;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_263(&loc_x) != 100)
{
Console.WriteLine("test_263() failed.");
return 363;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_270((byte)(((long)&loc_x.m_b) - ((long)&loc_x.m_a)), &loc_x.m_a) != 100)
{
Console.WriteLine("test_270() failed.");
return 370;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_277() != 100)
{
Console.WriteLine("test_277() failed.");
return 377;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_284(new B[][] { new B[] { new B(), new B() }, new B[] { new B(), loc_x.m_b } }, 1, 1) != 100)
{
Console.WriteLine("test_284() failed.");
return 384;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_291(&loc_x.m_b - 8, 8) != 100)
{
Console.WriteLine("test_291() failed.");
return 391;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_298(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2, 2) != 100)
{
Console.WriteLine("test_298() failed.");
return 398;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_305(((ulong)&loc_x.m_b) & (~(ulong)0xff), unchecked((byte)&loc_x.m_b)) != 100)
{
Console.WriteLine("test_305() failed.");
return 405;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_312(((long)(&loc_x.m_b)) << 4, ((long)(&loc_x.m_b)) & 0xff000000) != 100)
{
Console.WriteLine("test_312() failed.");
return 412;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_319(new B[] { loc_x.m_b }) != 100)
{
Console.WriteLine("test_319() failed.");
return 419;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_326(&loc_x.m_b - 1) != 100)
{
Console.WriteLine("test_326() failed.");
return 426;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_333(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100)
{
Console.WriteLine("test_333() failed.");
return 433;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_340(&loc_x) != 100)
{
Console.WriteLine("test_340() failed.");
return 440;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_347((long)(((long)&loc_x.m_b) - 1)) != 100)
{
Console.WriteLine("test_347() failed.");
return 447;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_354(&loc_x.m_b) != 100)
{
Console.WriteLine("test_354() failed.");
return 454;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_361(new AA[,] { { new AA(), new AA() }, { new AA(), loc_x } }, 2) != 100)
{
Console.WriteLine("test_361() failed.");
return 461;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_368(&loc_x.m_b - 8, 8) != 100)
{
Console.WriteLine("test_368() failed.");
return 468;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_375(&loc_x.m_b + 1, &loc_x.m_b) != 100)
{
Console.WriteLine("test_375() failed.");
return 475;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_382((long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_382() failed.");
return 482;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_389(((double*)(&loc_x.m_b)) - 4, 4) != 100)
{
Console.WriteLine("test_389() failed.");
return 489;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_396(&loc_x.m_b, &loc_x.m_b) != 100)
{
Console.WriteLine("test_396() failed.");
return 496;
}
Console.WriteLine("All tests passed.");
return 100;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;
using log4net.Config;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.ClientStack.Linden;
using OpenSim.Region.CoreModules.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.OptionalModules.World.NPC;
using OpenSim.Tests.Common;
namespace OpenSim.Region.ClientStack.Linden.Tests
{
[TestFixture]
public class EventQueueTests : OpenSimTestCase
{
private TestScene m_scene;
private EventQueueGetModule m_eqgMod;
private NPCModule m_npcMod;
[SetUp]
public override void SetUp()
{
base.SetUp();
uint port = 9999;
// This is an unfortunate bit of clean up we have to do because MainServer manages things through static
// variables and the VM is not restarted between tests.
MainServer.RemoveHttpServer(port);
BaseHttpServer server = new BaseHttpServer(port, false, "","","");
MainServer.AddHttpServer(server);
MainServer.Instance = server;
IConfigSource config = new IniConfigSource();
config.AddConfig("Startup");
CapabilitiesModule capsModule = new CapabilitiesModule();
m_eqgMod = new EventQueueGetModule();
// For NPC test support
config.AddConfig("NPC");
config.Configs["NPC"].Set("Enabled", "true");
m_npcMod = new NPCModule();
m_scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(m_scene, config, capsModule, m_eqgMod, m_npcMod);
}
[Test]
public void TestAddForClient()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
SceneHelpers.AddScenePresence(m_scene, TestHelpers.ParseTail(0x1));
// TODO: Add more assertions for the other aspects of event queues
Assert.That(MainServer.Instance.GetPollServiceHandlerKeys().Count, Is.EqualTo(1));
}
[Test]
public void TestRemoveForClient()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID spId = TestHelpers.ParseTail(0x1);
SceneHelpers.AddScenePresence(m_scene, spId);
m_scene.CloseAgent(spId, false);
// TODO: Add more assertions for the other aspects of event queues
Assert.That(MainServer.Instance.GetPollServiceHandlerKeys().Count, Is.EqualTo(0));
}
[Test]
public void TestEnqueueMessage()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, TestHelpers.ParseTail(0x1));
string messageName = "TestMessage";
m_eqgMod.Enqueue(m_eqgMod.BuildEvent(messageName, new OSDMap()), sp.UUID);
Hashtable eventsResponse = m_eqgMod.GetEvents(UUID.Zero, sp.UUID);
// initial queue as null events
// eventsResponse = m_eqgMod.GetEvents(UUID.Zero, sp.UUID);
if((int)eventsResponse["int_response_code"] != (int)HttpStatusCode.OK)
{
eventsResponse = m_eqgMod.GetEvents(UUID.Zero, sp.UUID);
if((int)eventsResponse["int_response_code"] != (int)HttpStatusCode.OK)
eventsResponse = m_eqgMod.GetEvents(UUID.Zero, sp.UUID);
}
Assert.That((int)eventsResponse["int_response_code"], Is.EqualTo((int)HttpStatusCode.OK));
// Console.WriteLine("Response [{0}]", (string)eventsResponse["str_response_string"]);
string data = String.Empty;
if(eventsResponse["bin_response_data"] != null)
data = Encoding.UTF8.GetString((byte[])eventsResponse["bin_response_data"]);
OSDMap rawOsd = (OSDMap)OSDParser.DeserializeLLSDXml(data);
OSDArray eventsOsd = (OSDArray)rawOsd["events"];
bool foundUpdate = false;
foreach (OSD osd in eventsOsd)
{
OSDMap eventOsd = (OSDMap)osd;
if (eventOsd["message"] == messageName)
foundUpdate = true;
}
Assert.That(foundUpdate, Is.True, string.Format("Did not find {0} in response", messageName));
}
/// <summary>
/// Test an attempt to put a message on the queue of a user that is not in the region.
/// </summary>
[Test]
public void TestEnqueueMessageNoUser()
{
TestHelpers.InMethod();
TestHelpers.EnableLogging();
string messageName = "TestMessage";
m_eqgMod.Enqueue(m_eqgMod.BuildEvent(messageName, new OSDMap()), TestHelpers.ParseTail(0x1));
Hashtable eventsResponse = m_eqgMod.GetEvents(UUID.Zero, TestHelpers.ParseTail(0x1));
Assert.That((int)eventsResponse["int_response_code"], Is.EqualTo((int)HttpStatusCode.BadGateway));
}
/// <summary>
/// NPCs do not currently have an event queue but a caller may try to send a message anyway, so check behaviour.
/// </summary>
[Test]
public void TestEnqueueMessageToNpc()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID npcId
= m_npcMod.CreateNPC(
"John", "Smith", new Vector3(128, 128, 30), UUID.Zero, true, m_scene, new AvatarAppearance());
ScenePresence npc = m_scene.GetScenePresence(npcId);
string messageName = "TestMessage";
m_eqgMod.Enqueue(m_eqgMod.BuildEvent(messageName, new OSDMap()), npc.UUID);
Hashtable eventsResponse = m_eqgMod.GetEvents(UUID.Zero, npc.UUID);
Assert.That((int)eventsResponse["int_response_code"], Is.EqualTo((int)HttpStatusCode.BadGateway));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using gov.va.medora.mdo.dao;
using gov.va.medora.mdo.dao.sql.cdw;
namespace gov.va.medora.mdo.api
{
public class EncounterApi
{
string DAO_NAME = "IEncounterDao";
public EncounterApi() { }
public IndexedHashtable getAppointments(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getAppointments", new object[] { });
}
public IndexedHashtable getMentalHealthAppointments(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getMentalHealthAppointments", new object[] { });
}
public IndexedHashtable getMentalHealthVisits(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getMentalHealthVisits", new object[] { });
}
public Dictionary<string, HashSet<string>> getUpdatedFutureAppointments(AbstractConnection cxn, DateTime updatedSince)
{
CdwEncounterDao dao = new CdwEncounterDao(cxn);
return dao.getUpdatedFutureAppointments(updatedSince);
}
public Appointment[] getAppointments(AbstractConnection cxn)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getAppointments();
}
public IndexedHashtable getAppointments(ConnectionSet cxns, int pastDays, int futureDays)
{
return cxns.query(DAO_NAME, "getAppointments", new object[] { pastDays, futureDays });
}
public Appointment[] getAppointments(AbstractConnection cxn, int pastDays, int futureDays)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getAppointments(pastDays,futureDays);
}
public IndexedHashtable getFutureAppointments(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getFutureAppointments", new object[] { });
}
public Appointment[] getFutureAppointments(AbstractConnection cxn)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getFutureAppointments();
}
public string getAppointmentText(AbstractConnection cxn, string apptId)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getAppointmentText(apptId);
}
public IndexedHashtable getInpatientMoves(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getInpatientMoves", new object[] { });
}
public Adt[] getInpatientMoves(AbstractConnection cxn)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getInpatientMoves();
}
public IndexedHashtable getInpatientMoves(ConnectionSet cxns, string fromDate, string toDate)
{
return cxns.query(DAO_NAME, "getInpatientMoves", new object[] { fromDate,toDate });
}
public IndexedHashtable getInpatientMoves(ConnectionSet cxns, string fromDate, string toDate, string iterLength)
{
return cxns.query(DAO_NAME, "getInpatientMoves", new object[] { fromDate, toDate, iterLength });
}
public Adt[] getInpatientMoves(AbstractConnection cxn, string fromDate, string toDate)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getInpatientMoves(fromDate, toDate);
}
public Adt[] getInpatientMovesByCheckinId(AbstractConnection cxn, string checkinId)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getInpatientMovesByCheckinId(checkinId);
}
public IndexedHashtable getInpatientMovesByCheckinId(ConnectionSet cxns, string checkinId)
{
return cxns.query(DAO_NAME, "getInpatientMovesByCheckinId", new object[] { checkinId });
}
public IndexedHashtable getLocations(ConnectionSet cxns, string target, string direction)
{
return cxns.query(DAO_NAME, "lookupLocations", new object[] { target, direction });
}
public HospitalLocation[] getLocations(AbstractConnection cxn, string target, string direction)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.lookupLocations(target, direction);
}
public IndexedHashtable getWards(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getWards", new object[] { });
}
public HospitalLocation[] getWards(AbstractConnection cxn)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getWards();
}
public DictionaryHashList getSpecialties(AbstractConnection cxn)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getSpecialties();
}
public DictionaryHashList getTeams(AbstractConnection cxn)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getTeams();
}
public HospitalLocation[] getClinics(AbstractConnection cxn, string target, string direction)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getClinics(target, direction);
}
public InpatientStay[] getStaysForWard(AbstractConnection cxn, string wardId)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getStaysForWard(wardId);
}
public IndexedHashtable getDRGRecords(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getDRGRecords", new object[] { });
}
public Drg[] getDRGRecords(AbstractConnection cxn)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getDRGRecords();
}
public IndexedHashtable getOutpatientEncounterReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getOutpatientEncounterReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getAdmissionsReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getAdmissionsReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getExpandedAdtReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getExpandedAdtReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getDischargesReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getDischargesReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getTransfersReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getTransfersReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getFutureClinicVisitsReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME,"getFutureClinicVisitsReport", new object[]{fromDate,toDate,nrpts});
}
public IndexedHashtable getPastClinicVisitsReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getPastClinicVisitsReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getTreatingSpecialtyReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getTreatingSpecialtyReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getCareTeamReports(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getCareTeamReport", new object[] { });
}
public IndexedHashtable getDischargeDiagnosisReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getDischargeDiagnosisReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getCompAndPenReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getCompAndPenReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getIcdProceduresReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getIcdProceduresReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getIcdSurgeryReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getIcdSurgeryReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getAdmissions(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getAdmissions", new object[] { });
}
public InpatientStay[] getAdmissions(AbstractConnection cxn)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getAdmissions();
}
public IndexedHashtable getVisits(ConnectionSet cxns, string fromDate, string toDate)
{
return cxns.query(DAO_NAME,"getVisits",new object[]{fromDate, toDate});
}
public Visit[] getVisits(AbstractConnection cxn, string fromDate, string toDate)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getVisits(fromDate, toDate);
}
public Adt[] getInpatientDischarges(AbstractConnection cxn, string pid)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getInpatientDischarges(pid);
}
public IndexedHashtable getStayMovementsByDateRange(ConnectionSet cxns, string fromDate, string toDate)
{
return cxns.query(DAO_NAME, "getStayMovementsByDateRange", new object[] { fromDate, toDate });
}
public InpatientStay[] getStayMovementsByDateRange(AbstractConnection cxn, string fromDate, string toDate)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getStayMovementsByDateRange(fromDate, toDate);
}
public IndexedHashtable getStayMovementsByPatient(ConnectionSet cxns, string dfn)
{
return cxns.query(DAO_NAME, "getStayMovementsByPatient", new object[] { dfn });
}
public InpatientStay getStayMovements(AbstractConnection cxn, string checkinId)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getStayMovements(checkinId);
}
public Site[] getSiteDivisions(AbstractConnection cxn, string siteId)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getSiteDivisions(siteId);
}
public IList<Appointment> getPendingAppointments(AbstractConnection cxn, string startDate)
{
return ((ISchedulingDao)cxn.getDao("ISchedulingDao")).getPendingAppointments(startDate);
}
public IList<AppointmentType> getAppointmentTypes(AbstractConnection cxn, string target)
{
return ((ISchedulingDao)cxn.getDao("ISchedulingDao")).getAppointmentTypes(target);
}
//public string getClinicAvailability(AbstractConnection cxn, string clinicId)
//{
// return ((ISchedulingDao)cxn.getDao("ISchedulingDao")).getClinicAvailability(clinicId);
//}
public Appointment makeAppointment(AbstractConnection cxn, Appointment appointment)
{
return ((ISchedulingDao)cxn.getDao("ISchedulingDao")).makeAppointment(appointment);
}
public Appointment cancelAppointment(AbstractConnection cxn, Appointment appointment, string cancellationReason, string remarks)
{
return ((ISchedulingDao)cxn.getDao("ISchedulingDao")).cancelAppointment(appointment, cancellationReason, remarks);
}
public Appointment checkInAppointment(AbstractConnection cxn, Appointment appointment)
{
return ((ISchedulingDao)cxn.getDao("ISchedulingDao")).checkInAppointment(appointment);
}
public HospitalLocation getClinicSchedulingDetails(AbstractConnection cxn, string clinicId)
{
return ((ISchedulingDao)cxn.getDao("ISchedulingDao")).getClinicSchedulingDetails(clinicId);
}
public bool hasClinicAccess(AbstractConnection cxn, string clinicId)
{
return ((ISchedulingDao)cxn.getDao("ISchedulingDao")).hasClinicAccess(clinicId);
}
public bool hasValidStopCode(AbstractConnection cxn, string clinicId)
{
return ((ISchedulingDao)cxn.getDao("ISchedulingDao")).hasValidStopCode(clinicId);
}
public bool isValidStopCode(AbstractConnection cxn, string stopCodeId)
{
return ((ISchedulingDao)cxn.getDao("ISchedulingDao")).isValidStopCode(stopCodeId);
}
public Dictionary<string, string> getCancellationReasons(AbstractConnection cxn)
{
return ((ISchedulingDao)cxn.getDao("ISchedulingDao")).getCancellationReasons();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
// Make sure the interop data are present even without reflection
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.All)]
internal class __BlockAllReflectionAttribute : Attribute { }
}
// Name of namespace matches the name of the assembly on purpose to
// ensure that we can handle this (mostly an issue for C++ code generation).
namespace PInvokeTests
{
internal class Program
{
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
private static extern int Square(int intValue);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
private static extern int IsTrue(bool boolValue);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
private static extern int CheckIncremental(int[] array, int sz);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
private static extern int CheckIncremental_Foo(Foo[] array, int sz);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
private static extern int Inc(ref int value);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
private static extern int VerifyByRefFoo(ref Foo value);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
private static extern bool GetNextChar(ref char c);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
private static extern int VerifyAnsiString(string str);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
private static extern int VerifyAnsiStringOut(out string str);
[DllImport("*", EntryPoint = "VerifyAnsiString", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
private static extern int VerifyUTF8String([MarshalAs(UnmanagedType.LPUTF8Str)] string str);
[DllImport("*", EntryPoint = "VerifyAnsiStringOut", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
private static extern int VerifyUTF8StringOut([Out, MarshalAs(UnmanagedType.LPUTF8Str)] out string str);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
private static extern int VerifyAnsiStringRef(ref string str);
[DllImport("*", EntryPoint = "VerifyAnsiStringRef", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
private static extern int VerifyAnsiStringInRef([In]ref string str);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
private static extern int VerifyUnicodeString(string str);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
private static extern int VerifyUnicodeStringOut(out string str);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
private static extern int VerifyUnicodeStringRef(ref string str);
[DllImport("*", EntryPoint = "VerifyUnicodeStringRef", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
private static extern int VerifyUnicodeStringInRef([In]ref string str);
[DllImport("*", CharSet = CharSet.Ansi)]
private static extern int VerifyAnsiStringArray([In, MarshalAs(UnmanagedType.LPArray)]string[] str);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
private static extern bool VerifyAnsiCharArrayIn(char[] a);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
private static extern bool VerifyAnsiCharArrayOut([Out]char[] a);
[DllImport("*", CharSet = CharSet.Ansi)]
private static extern void ToUpper([In, Out, MarshalAs(UnmanagedType.LPArray)]string[] str);
[DllImport("*", CharSet = CharSet.Ansi)]
private static extern bool VerifySizeParamIndex(
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out byte[] arrByte, out byte arrSize);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, EntryPoint = "VerifyUnicodeStringBuilder")]
private static extern int VerifyUnicodeStringBuilder(StringBuilder sb);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, EntryPoint = "VerifyUnicodeStringBuilder")]
private static extern int VerifyUnicodeStringBuilderIn([In]StringBuilder sb);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
private static extern int VerifyUnicodeStringBuilderOut([Out]StringBuilder sb);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, EntryPoint = "VerifyAnsiStringBuilder")]
private static extern int VerifyAnsiStringBuilder(StringBuilder sb);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, EntryPoint = "VerifyAnsiStringBuilder")]
private static extern int VerifyAnsiStringBuilderIn([In]StringBuilder sb);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
private static extern int VerifyAnsiStringBuilderOut([Out]StringBuilder sb);
[DllImport("*", CallingConvention = CallingConvention.StdCall, EntryPoint = "SafeHandleTest")]
public static extern bool HandleRefTest(HandleRef hr, Int64 hrValue);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
public static extern bool SafeHandleTest(SafeMemoryHandle sh1, Int64 sh1Value);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
public static extern int SafeHandleOutTest(out SafeMemoryHandle sh1);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
public static extern int SafeHandleRefTest(ref SafeMemoryHandle sh1, bool change);
[DllImport("*", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern bool LastErrorTest();
delegate int Delegate_Int(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool ReversePInvoke_Int(Delegate_Int del);
delegate int Delegate_Int_AggressiveInlining(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j);
[DllImport("*", CallingConvention = CallingConvention.StdCall, EntryPoint = "ReversePInvoke_Int")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static extern bool ReversePInvoke_Int_AggressiveInlining(Delegate_Int_AggressiveInlining del);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet=CharSet.Ansi)]
delegate bool Delegate_String(string s);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool ReversePInvoke_String(Delegate_String del);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)]
delegate bool Delegate_Array([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] array, IntPtr sz);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool ReversePInvoke_Array(Delegate_Array del);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern Delegate_String GetDelegate();
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool Callback(ref Delegate_String d);
delegate void Delegate_Unused();
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern unsafe int* ReversePInvoke_Unused(Delegate_Unused del);
[DllImport("*", CallingConvention = CallingConvention.StdCall, EntryPoint = "StructTest")]
static extern bool StructTest_Auto(AutoStruct ss);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool StructTest_Sequential2(NesterOfSequentialStruct.SequentialStruct ss);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool StructTest(SequentialStruct ss);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern void StructTest_ByRef(ref SequentialStruct ss);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern void StructTest_ByOut(out SequentialStruct ss);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool StructTest_Explicit(ExplicitStruct es);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool StructTest_Nested(NestedStruct ns);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool StructTest_Array(SequentialStruct []ns, int length);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
static extern bool IsNULL(char[] a);
[DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
static extern bool IsNULL(String sb);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool IsNULL(Foo[] foo);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool IsNULL(SequentialStruct[] foo);
[StructLayout(LayoutKind.Sequential, CharSet= CharSet.Ansi, Pack = 4)]
public unsafe struct InlineArrayStruct
{
public int f0;
public int f1;
public int f2;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public short[] inlineArray;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)]
public string inlineString;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 4)]
public unsafe struct InlineUnicodeStruct
{
public int f0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)]
public string inlineString;
}
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool InlineArrayTest(ref InlineArrayStruct ias, ref InlineUnicodeStruct ius);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, SetLastError = true)]
public unsafe delegate void SetLastErrorFuncDelegate(int errorCode);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
internal static extern IntPtr GetFunctionPointer();
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal unsafe struct InlineString
{
internal uint size;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
internal string name;
}
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
static extern bool InlineStringTest(ref InlineString ias);
internal delegate int Callback0();
internal delegate int Callback1();
internal delegate int Callback2();
[DllImport("*")]
internal static extern bool RegisterCallbacks(ref Callbacks callbacks);
[StructLayout(LayoutKind.Sequential)]
internal struct Callbacks
{
public Callback0 callback0;
public Callback1 callback1;
public Callback2 callback2;
}
public static int callbackFunc0() { return 0; }
public static int callbackFunc1() { return 1; }
public static int callbackFunc2() { return 2; }
public static int Main(string[] args)
{
TestBlittableType();
TestBoolean();
TestUnichar();
TestArrays();
TestByRef();
TestString();
TestStringBuilder();
TestLastError();
TestHandleRef();
TestSafeHandle();
TestStringArray();
TestSizeParamIndex();
#if !CODEGEN_CPP
TestDelegate();
TestStruct();
TestMarshalStructAPIs();
#endif
return 100;
}
public static void ThrowIfNotEquals<T>(T expected, T actual, string message)
{
if (!expected.Equals(actual))
{
message += "\nExpected: " + expected.ToString() + "\n";
message += "Actual: " + actual.ToString() + "\n";
throw new Exception(message);
}
}
public static void ThrowIfNotEquals(bool expected, bool actual, string message)
{
ThrowIfNotEquals(expected ? 1 : 0, actual ? 1 : 0, message);
}
private static void TestBlittableType()
{
Console.WriteLine("Testing marshalling blittable types");
ThrowIfNotEquals(100, Square(10), "Int marshalling failed");
}
private static void TestBoolean()
{
Console.WriteLine("Testing marshalling boolean");
ThrowIfNotEquals(1, IsTrue(true), "Bool marshalling failed");
ThrowIfNotEquals(0, IsTrue(false), "Bool marshalling failed");
}
private static void TestUnichar()
{
Console.WriteLine("Testing Unichar");
char c = 'a';
ThrowIfNotEquals(true, GetNextChar(ref c), "Unichar marshalling failed.");
ThrowIfNotEquals('b', c, "Unichar marshalling failed.");
}
struct Foo
{
public int a;
public float b;
}
private static void TestArrays()
{
Console.WriteLine("Testing marshalling int arrays");
const int ArraySize = 100;
int[] arr = new int[ArraySize];
for (int i = 0; i < ArraySize; i++)
arr[i] = i;
ThrowIfNotEquals(0, CheckIncremental(arr, ArraySize), "Array marshalling failed");
Console.WriteLine("Testing marshalling blittable struct arrays");
Foo[] arr_foo = null;
ThrowIfNotEquals(true, IsNULL(arr_foo), "Blittable array null check failed");
arr_foo = new Foo[ArraySize];
for (int i = 0; i < ArraySize; i++)
{
arr_foo[i].a = i;
arr_foo[i].b = i;
}
ThrowIfNotEquals(0, CheckIncremental_Foo(arr_foo, ArraySize), "Array marshalling failed");
char[] a = "Hello World".ToCharArray();
ThrowIfNotEquals(true, VerifyAnsiCharArrayIn(a), "Ansi Char Array In failed");
char[] b = new char[12];
ThrowIfNotEquals(true, VerifyAnsiCharArrayOut(b), "Ansi Char Array Out failed");
ThrowIfNotEquals("Hello World!", new String(b), "Ansi Char Array Out failed2");
char[] c = null;
ThrowIfNotEquals(true, IsNULL(c), "AnsiChar Array null check failed");
}
private static void TestByRef()
{
Console.WriteLine("Testing marshalling by ref");
int value = 100;
ThrowIfNotEquals(0, Inc(ref value), "By ref marshalling failed");
ThrowIfNotEquals(101, value, "By ref marshalling failed");
Foo foo = new Foo();
foo.a = 10;
foo.b = 20;
int ret = VerifyByRefFoo(ref foo);
ThrowIfNotEquals(0, ret, "By ref struct marshalling failed");
ThrowIfNotEquals(foo.a, 11, "By ref struct unmarshalling failed");
ThrowIfNotEquals(foo.b, 21.0f, "By ref struct unmarshalling failed");
}
private static void TestString()
{
Console.WriteLine("Testing marshalling string");
ThrowIfNotEquals(1, VerifyAnsiString("Hello World"), "Ansi String marshalling failed.");
ThrowIfNotEquals(1, VerifyUnicodeString("Hello World"), "Unicode String marshalling failed.");
string s;
ThrowIfNotEquals(1, VerifyAnsiStringOut(out s), "Out Ansi String marshalling failed");
ThrowIfNotEquals("Hello World", s, "Out Ansi String marshalling failed");
VerifyAnsiStringInRef(ref s);
ThrowIfNotEquals("Hello World", s, "In Ref ansi String marshalling failed");
VerifyAnsiStringRef(ref s);
ThrowIfNotEquals("Hello World!", s, "Ref ansi String marshalling failed");
ThrowIfNotEquals(1, VerifyUnicodeStringOut(out s), "Out Unicode String marshalling failed");
ThrowIfNotEquals("Hello World", s, "Out Unicode String marshalling failed");
VerifyUnicodeStringInRef(ref s);
ThrowIfNotEquals("Hello World", s, "In Ref Unicode String marshalling failed");
VerifyUnicodeStringRef(ref s);
ThrowIfNotEquals("Hello World!", s, "Ref Unicode String marshalling failed");
string ss = null;
ThrowIfNotEquals(true, IsNULL(ss), "Ansi String null check failed");
ThrowIfNotEquals(1, VerifyUTF8String("Hello World"), "UTF8 String marshalling failed.");
ThrowIfNotEquals(1, VerifyUTF8StringOut(out s), "Out UTF8 String marshalling failed");
ThrowIfNotEquals("Hello World", s, "Out UTF8 String marshalling failed");
}
private static void TestStringBuilder()
{
Console.WriteLine("Testing marshalling string builder");
StringBuilder sb = new StringBuilder("Hello World");
ThrowIfNotEquals(1, VerifyUnicodeStringBuilder(sb), "Unicode StringBuilder marshalling failed");
ThrowIfNotEquals("HELLO WORLD", sb.ToString(), "Unicode StringBuilder marshalling failed.");
StringBuilder sb1 = null;
// for null stringbuilder it should return -1
ThrowIfNotEquals(-1, VerifyUnicodeStringBuilder(sb1), "Null unicode StringBuilder marshalling failed");
StringBuilder sb2 = new StringBuilder("Hello World");
ThrowIfNotEquals(1, VerifyUnicodeStringBuilderIn(sb2), "In unicode StringBuilder marshalling failed");
// Only [In] should change stringbuilder value
ThrowIfNotEquals("Hello World", sb2.ToString(), "In unicode StringBuilder marshalling failed");
StringBuilder sb3 = new StringBuilder();
ThrowIfNotEquals(1, VerifyUnicodeStringBuilderOut(sb3), "Out Unicode string marshalling failed");
ThrowIfNotEquals("Hello World", sb3.ToString(), "Out Unicode StringBuilder marshalling failed");
StringBuilder sb4 = new StringBuilder("Hello World");
ThrowIfNotEquals(1, VerifyAnsiStringBuilder(sb4), "Ansi StringBuilder marshalling failed");
ThrowIfNotEquals("HELLO WORLD", sb4.ToString(), "Ansi StringBuilder marshalling failed.");
StringBuilder sb5 = null;
// for null stringbuilder it should return -1
ThrowIfNotEquals(-1, VerifyAnsiStringBuilder(sb5), "Null Ansi StringBuilder marshalling failed");
StringBuilder sb6 = new StringBuilder("Hello World");
ThrowIfNotEquals(1, VerifyAnsiStringBuilderIn(sb6), "In unicode StringBuilder marshalling failed");
// Only [In] should change stringbuilder value
ThrowIfNotEquals("Hello World", sb6.ToString(), "In unicode StringBuilder marshalling failed");
StringBuilder sb7 = new StringBuilder();
ThrowIfNotEquals(1, VerifyAnsiStringBuilderOut(sb7), "Out Ansi string marshalling failed");
ThrowIfNotEquals("Hello World!", sb7.ToString(), "Out Ansi StringBuilder marshalling failed");
}
private static void TestStringArray()
{
Console.WriteLine("Testing marshalling string array");
string[] strArray = new string[] { "Hello", "World" };
ThrowIfNotEquals(1, VerifyAnsiStringArray(strArray), "Ansi string array in marshalling failed.");
ToUpper(strArray);
ThrowIfNotEquals(true, "HELLO" == strArray[0] && "WORLD" == strArray[1], "Ansi string array out marshalling failed.");
}
private static void TestLastError()
{
Console.WriteLine("Testing last error");
ThrowIfNotEquals(true, LastErrorTest(), "GetLastWin32Error is not zero");
ThrowIfNotEquals(12345, Marshal.GetLastWin32Error(), "Last Error test failed");
}
private static void TestHandleRef()
{
Console.WriteLine("Testing marshalling HandleRef");
ThrowIfNotEquals(true, HandleRefTest(new HandleRef(new object(), (IntPtr)2018), 2018), "HandleRef marshalling failed");
}
private static void TestSafeHandle()
{
Console.WriteLine("Testing marshalling SafeHandle");
SafeMemoryHandle hnd = SafeMemoryHandle.AllocateMemory(1000);
IntPtr hndIntPtr = hnd.DangerousGetHandle(); //get the IntPtr associated with hnd
long val = hndIntPtr.ToInt64(); //return the 64-bit value associated with hnd
ThrowIfNotEquals(true, SafeHandleTest(hnd, val), "SafeHandle marshalling failed.");
Console.WriteLine("Testing marshalling out SafeHandle");
SafeMemoryHandle hnd2;
int actual = SafeHandleOutTest(out hnd2);
int expected = unchecked((int)hnd2.DangerousGetHandle().ToInt64());
ThrowIfNotEquals(actual, expected, "SafeHandle out marshalling failed");
Console.WriteLine("Testing marshalling ref SafeHandle");
SafeMemoryHandle hndOriginal = hnd2;
SafeHandleRefTest(ref hnd2, false);
ThrowIfNotEquals(hndOriginal, hnd2, "SafeHandle no-op ref marshalling failed");
int actual3 = SafeHandleRefTest(ref hnd2, true);
int expected3 = unchecked((int)hnd2.DangerousGetHandle().ToInt64());
ThrowIfNotEquals(actual3, expected3, "SafeHandle ref marshalling failed");
hndOriginal.Dispose();
hnd2.Dispose();
}
private static void TestSizeParamIndex()
{
Console.WriteLine("Testing SizeParamIndex");
byte byte_Array_Size;
byte[] arrByte;
VerifySizeParamIndex(out arrByte, out byte_Array_Size);
ThrowIfNotEquals(10, byte_Array_Size, "out size failed.");
bool pass = true;
for (int i = 0; i < byte_Array_Size; i++)
{
if (arrByte[i] != i)
{
pass = false;
break;
}
}
ThrowIfNotEquals(true, pass, "SizeParamIndex failed.");
}
private class ClosedDelegateCLass
{
public int Sum(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j)
{
return a + b + c + d + e + f + g + h + i + j;
}
public bool GetString(String s)
{
return s == "Hello World";
}
public bool CheckArray(int[] a, IntPtr sz)
{
if (sz != new IntPtr(42))
return false;
for (int i = 0; i < (int)sz; i++)
{
if (a[i] != i)
return false;
}
return true;
}
}
private static void TestDelegate()
{
Console.WriteLine("Testing Delegate");
Delegate_Int del = new Delegate_Int(Sum);
ThrowIfNotEquals(true, ReversePInvoke_Int(del), "Delegate marshalling failed.");
Delegate_Int_AggressiveInlining del_aggressive = new Delegate_Int_AggressiveInlining(Sum);
ThrowIfNotEquals(true, ReversePInvoke_Int_AggressiveInlining(del_aggressive), "Delegate marshalling with aggressive inlining failed.");
unsafe
{
//
// We haven't instantiated Delegate_Unused and nobody
// allocates it. If a EEType is not constructed for Delegate_Unused
// it will fail during linking.
//
ReversePInvoke_Unused(null);
}
Delegate_Int closed = new Delegate_Int((new ClosedDelegateCLass()).Sum);
ThrowIfNotEquals(true, ReversePInvoke_Int(closed), "Closed Delegate marshalling failed.");
Delegate_String ret = GetDelegate();
ThrowIfNotEquals(true, ret("Hello World!"), "Delegate as P/Invoke return failed");
Delegate_String d = new Delegate_String(new ClosedDelegateCLass().GetString);
ThrowIfNotEquals(true, Callback(ref d), "Delegate IN marshalling failed");
ThrowIfNotEquals(true, d("Hello World!"), "Delegate OUT marshalling failed");
Delegate_String ds = new Delegate_String((new ClosedDelegateCLass()).GetString);
ThrowIfNotEquals(true, ReversePInvoke_String(ds), "Delegate marshalling failed.");
Delegate_Array da = new Delegate_Array((new ClosedDelegateCLass()).CheckArray);
ThrowIfNotEquals(true, ReversePInvoke_Array(da), "Delegate array marshalling failed.");
IntPtr procAddress = GetFunctionPointer();
SetLastErrorFuncDelegate funcDelegate =
Marshal.GetDelegateForFunctionPointer<SetLastErrorFuncDelegate>(procAddress);
funcDelegate(0x204);
ThrowIfNotEquals(0x204, Marshal.GetLastWin32Error(), "Not match");
}
static int Sum(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j)
{
return a + b + c + d + e + f + g + h + i + j;
}
[StructLayout(LayoutKind.Auto)]
public struct AutoStruct
{
public short f0;
public int f1;
public float f2;
[MarshalAs(UnmanagedType.LPStr)]
public String f3;
}
[StructLayout(LayoutKind.Sequential)]
public struct SequentialStruct
{
public short f0;
public int f1;
public float f2;
[MarshalAs(UnmanagedType.LPStr)]
public String f3;
}
// A second struct with the same name but nested. Regression test against native types being mangled into
// the compiler-generated type and losing fully qualified type name information.
class NesterOfSequentialStruct
{
[StructLayout(LayoutKind.Sequential)]
public struct SequentialStruct
{
public float f1;
public int f2;
}
}
[StructLayout(LayoutKind.Explicit)]
public struct ExplicitStruct
{
[FieldOffset(0)]
public int f1;
[FieldOffset(12)]
public float f2;
[FieldOffset(24)]
[MarshalAs(UnmanagedType.LPStr)]
public String f3;
}
[StructLayout(LayoutKind.Sequential)]
public struct NestedStruct
{
public int f1;
public ExplicitStruct f2;
}
[StructLayout(LayoutKind.Sequential)]
public struct NonBlittableStruct
{
public int f1;
public bool f2;
public bool f3;
public bool f4;
}
[StructLayout(LayoutKind.Sequential)]
public class BlittableClass
{
public long f1;
public int f2;
public int f3;
public long f4;
}
[StructLayout(LayoutKind.Sequential)]
public class NonBlittableClass
{
public bool f1;
public bool f2;
public int f3;
}
private static void TestStruct()
{
Console.WriteLine("Testing Structs");
SequentialStruct ss = new SequentialStruct();
ss.f0 = 100;
ss.f1 = 1;
ss.f2 = 10.0f;
ss.f3 = "Hello";
ThrowIfNotEquals(true, StructTest(ss), "Struct marshalling scenario1 failed.");
StructTest_ByRef(ref ss);
ThrowIfNotEquals(true, ss.f1 == 2 && ss.f2 == 11.0 && ss.f3.Equals("Ifmmp"), "Struct marshalling scenario2 failed.");
SequentialStruct ss2 = new SequentialStruct();
StructTest_ByOut(out ss2);
ThrowIfNotEquals(true, ss2.f0 == 1 && ss2.f1 == 1.0 && ss2.f2 == 1.0 && ss2.f3.Equals("0123456"), "Struct marshalling scenario3 failed.");
NesterOfSequentialStruct.SequentialStruct ss3 = new NesterOfSequentialStruct.SequentialStruct();
ss3.f1 = 10.0f;
ss3.f2 = 123;
ThrowIfNotEquals(true, StructTest_Sequential2(ss3), "Struct marshalling scenario1 failed.");
ExplicitStruct es = new ExplicitStruct();
es.f1 = 100;
es.f2 = 100.0f;
es.f3 = "Hello";
ThrowIfNotEquals(true, StructTest_Explicit(es), "Struct marshalling scenario4 failed.");
NestedStruct ns = new NestedStruct();
ns.f1 = 100;
ns.f2 = es;
ThrowIfNotEquals(true, StructTest_Nested(ns), "Struct marshalling scenario5 failed.");
SequentialStruct[] ssa = null;
ThrowIfNotEquals(true, IsNULL(ssa), "Non-blittable array null check failed");
ssa = new SequentialStruct[3];
for (int i = 0; i < 3; i++)
{
ssa[i].f1 = 0;
ssa[i].f1 = i;
ssa[i].f2 = i*i;
ssa[i].f3 = i.LowLevelToString();
}
ThrowIfNotEquals(true, StructTest_Array(ssa, ssa.Length), "Array of struct marshalling failed");
InlineString ils = new InlineString();
InlineStringTest(ref ils);
ThrowIfNotEquals("Hello World!", ils.name, "Inline string marshalling failed");
InlineArrayStruct ias = new InlineArrayStruct();
ias.inlineArray = new short[128];
for (short i = 0; i < 128; i++)
{
ias.inlineArray[i] = i;
}
ias.inlineString = "Hello";
InlineUnicodeStruct ius = new InlineUnicodeStruct();
ius.inlineString = "Hello World";
ThrowIfNotEquals(true, InlineArrayTest(ref ias, ref ius), "inline array marshalling failed");
bool pass = true;
for (short i = 0; i < 128; i++)
{
if (ias.inlineArray[i] != i + 1)
{
pass = false;
}
}
ThrowIfNotEquals(true, pass, "inline array marshalling failed");
ThrowIfNotEquals("Hello World", ias.inlineString, "Inline ByValTStr Ansi marshalling failed");
ThrowIfNotEquals("Hello World", ius.inlineString, "Inline ByValTStr Unicode marshalling failed");
pass = false;
AutoStruct autoStruct = new AutoStruct();
try
{
// passing struct with Auto layout should throw exception.
StructTest_Auto(autoStruct);
}
catch (Exception)
{
pass = true;
}
ThrowIfNotEquals(true, pass, "Struct marshalling scenario6 failed.");
Callbacks callbacks = new Callbacks();
callbacks.callback0 = new Callback0(callbackFunc0);
callbacks.callback1 = new Callback1(callbackFunc1);
callbacks.callback2 = new Callback2(callbackFunc2);
ThrowIfNotEquals(true, RegisterCallbacks(ref callbacks), "Scenario 7: Struct with delegate marshalling failed");
}
private static void TestMarshalStructAPIs()
{
Console.WriteLine("Testing Marshal APIs for structs");
NonBlittableStruct ts = new NonBlittableStruct() { f1 = 100, f2 = true, f3 = false, f4 = true };
int size = Marshal.SizeOf<NonBlittableStruct>(ts);
ThrowIfNotEquals(16, size, "Marshal.SizeOf<NonBlittableStruct> failed");
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr<NonBlittableStruct>(ts, memory, false);
NonBlittableStruct ts2 = Marshal.PtrToStructure<NonBlittableStruct>(memory);
ThrowIfNotEquals(true, ts2.f1 == 100 && ts2.f2 == true && ts2.f3 == false && ts2.f4 == true, "NonBlittableStruct marshalling Marshal API failed");
IntPtr offset = Marshal.OffsetOf<NonBlittableStruct>("f2");
ThrowIfNotEquals(new IntPtr(4), offset, "Struct marshalling OffsetOf failed.");
}
finally
{
Marshal.FreeHGlobal(memory);
}
BlittableClass bc = new BlittableClass() { f1 = 100, f2 = 12345678, f3 = 999, f4 = -4 };
int bc_size = Marshal.SizeOf<BlittableClass>(bc);
ThrowIfNotEquals(24, bc_size, "Marshal.SizeOf<BlittableClass> failed");
IntPtr bc_memory = Marshal.AllocHGlobal(bc_size);
try
{
Marshal.StructureToPtr<BlittableClass>(bc, bc_memory, false);
BlittableClass bc2 = Marshal.PtrToStructure<BlittableClass>(bc_memory);
ThrowIfNotEquals(true, bc2.f1 == 100 && bc2.f2 == 12345678 && bc2.f3 == 999 && bc2.f4 == -4, "BlittableClass marshalling Marshal API failed");
}
finally
{
Marshal.FreeHGlobal(bc_memory);
}
NonBlittableClass nbc = new NonBlittableClass() { f1 = false, f2 = true, f3 = 42 };
int nbc_size = Marshal.SizeOf<NonBlittableClass>(nbc);
ThrowIfNotEquals(12, nbc_size, "Marshal.SizeOf<NonBlittableClass> failed");
IntPtr nbc_memory = Marshal.AllocHGlobal(nbc_size);
try
{
Marshal.StructureToPtr<NonBlittableClass>(nbc, nbc_memory, false);
NonBlittableClass nbc2 = Marshal.PtrToStructure<NonBlittableClass>(nbc_memory);
ThrowIfNotEquals(true, nbc2.f1 == false && nbc2.f2 == true && nbc2.f3 == 42, "NonBlittableClass marshalling Marshal API failed");
}
finally
{
Marshal.FreeHGlobal(nbc_memory);
}
}
}
public class SafeMemoryHandle : SafeHandle //SafeHandle subclass
{
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
public static extern SafeMemoryHandle AllocateMemory(int size);
[DllImport("*", CallingConvention = CallingConvention.StdCall)]
public static extern bool ReleaseMemory(IntPtr handle);
public SafeMemoryHandle()
: base(IntPtr.Zero, true)
{
}
private static readonly IntPtr _invalidHandleValue = new IntPtr(-1);
public override bool IsInvalid
{
get { return handle == IntPtr.Zero || handle == _invalidHandleValue; }
}
override protected bool ReleaseHandle()
{
return ReleaseMemory(handle);
}
} //end of SafeMemoryHandle class
public static class LowLevelExtensions
{
// Int32.ToString() calls into glob/loc garbage that hits CppCodegen limitations
public static string LowLevelToString(this int i)
{
char[] digits = new char[11];
int numDigits = 0;
if (i == int.MinValue)
return "-2147483648";
bool negative = i < 0;
if (negative)
i = -i;
do
{
digits[numDigits] = (char)('0' + (i % 10));
numDigits++;
i /= 10;
}
while (i != 0);
if (negative)
{
digits[numDigits] = '-';
numDigits++;
}
Array.Reverse(digits);
return new string(digits, digits.Length - numDigits, numDigits);
}
}
}
| |
// QuickGraph Library
//
// Copyright (c) 2004 Jonathan de Halleux
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// QuickGraph Library HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
using System;
namespace QuickGraph.Tests.Algorithms.Search
{
using MbUnit.Framework;
using MbUnit.Core.Framework;
using QuickGraph.Tests.Generators;
using QuickGraph.Concepts;
using QuickGraph.Concepts.Traversals;
using QuickGraph.Concepts.Modifications;
using QuickGraph.Algorithms;
using QuickGraph.Algorithms.Search;
using QuickGraph.Collections;
using QuickGraph.Representations;
[TestFixture]
public class DepthFirstAlgorithmSearchTest
{
private VertexVertexDictionary parents;
private VertexIntDictionary discoverTimes;
private VertexIntDictionary finishTimes;
private int time;
private AdjacencyGraph g;
private DepthFirstSearchAlgorithm dfs;
public VertexVertexDictionary Parents
{
get
{
return parents;
}
}
public VertexIntDictionary DiscoverTimes
{
get
{
return discoverTimes;
}
}
public VertexIntDictionary FinishTimes
{
get
{
return finishTimes;
}
}
public void StartVertex(Object sender, VertexEventArgs args)
{
Assert.IsTrue( sender is DepthFirstSearchAlgorithm );
DepthFirstSearchAlgorithm algo = (DepthFirstSearchAlgorithm)sender;
Assert.AreEqual(algo.Colors[args.Vertex], GraphColor.White);
}
public void DiscoverVertex(Object sender, VertexEventArgs args)
{
Assert.IsTrue( sender is DepthFirstSearchAlgorithm );
DepthFirstSearchAlgorithm algo = (DepthFirstSearchAlgorithm)sender;
Assert.AreEqual(algo.Colors[args.Vertex], GraphColor.Gray);
Assert.AreEqual(algo.Colors[Parents[args.Vertex]], GraphColor.Gray);
DiscoverTimes[args.Vertex]=time++;
}
public void ExamineEdge(Object sender, EdgeEventArgs args)
{
Assert.IsTrue( sender is DepthFirstSearchAlgorithm );
DepthFirstSearchAlgorithm algo = (DepthFirstSearchAlgorithm)sender;
Assert.AreEqual(algo.Colors[args.Edge.Source], GraphColor.Gray);
}
public void TreeEdge(Object sender, EdgeEventArgs args)
{
Assert.IsTrue( sender is DepthFirstSearchAlgorithm );
DepthFirstSearchAlgorithm algo = (DepthFirstSearchAlgorithm)sender;
Assert.AreEqual(algo.Colors[args.Edge.Target], GraphColor.White);
Parents[args.Edge.Target] = args.Edge.Source;
}
public void BackEdge(Object sender, EdgeEventArgs args)
{
Assert.IsTrue( sender is DepthFirstSearchAlgorithm );
DepthFirstSearchAlgorithm algo = (DepthFirstSearchAlgorithm)sender;
Assert.AreEqual(algo.Colors[args.Edge.Target], GraphColor.Gray);
}
public void FowardOrCrossEdge(Object sender, EdgeEventArgs args)
{
Assert.IsTrue( sender is DepthFirstSearchAlgorithm );
DepthFirstSearchAlgorithm algo = (DepthFirstSearchAlgorithm)sender;
Assert.AreEqual(algo.Colors[args.Edge.Target], GraphColor.Black);
}
public void FinishVertex(Object sender, VertexEventArgs args)
{
Assert.IsTrue( sender is DepthFirstSearchAlgorithm );
DepthFirstSearchAlgorithm algo = (DepthFirstSearchAlgorithm)sender;
Assert.AreEqual(algo.Colors[args.Vertex], GraphColor.Black);
FinishTimes[args.Vertex]=time++;
}
public bool IsDescendant(IVertex u, IVertex v)
{
IVertex t=null;
IVertex p=u;
do
{
t=p;
p=Parents[t];
if (p==v)
return true;
}
while (t!=p);
return false;
}
[SetUp]
public void Init()
{
parents = new VertexVertexDictionary();
discoverTimes = new VertexIntDictionary();
finishTimes = new VertexIntDictionary();
time = 0;
g = new AdjacencyGraph(true);
dfs = new DepthFirstSearchAlgorithm(g);
dfs.StartVertex += new VertexEventHandler(this.StartVertex);
dfs.DiscoverVertex += new VertexEventHandler(this.DiscoverVertex);
dfs.ExamineEdge += new EdgeEventHandler(this.ExamineEdge);
dfs.TreeEdge += new EdgeEventHandler(this.TreeEdge);
dfs.BackEdge += new EdgeEventHandler(this.BackEdge);
dfs.ForwardOrCrossEdge += new EdgeEventHandler(this.FowardOrCrossEdge);
dfs.FinishVertex += new VertexEventHandler(this.FinishVertex);
}
[Test]
public void GraphWithSelfEdges()
{
RandomGraph.Graph(g,20,100,new Random(),true);
foreach(IVertex v in g.Vertices)
Parents[v] = v;
// compute
dfs.Compute();
CheckDfs();
}
[Test]
public void GraphWithoutSelfEdges()
{
RandomGraph.Graph(g,20,100,new Random(),false);
foreach(IVertex v in g.Vertices)
Parents[v] = v;
// compute
dfs.Compute();
CheckDfs();
}
protected void CheckDfs()
{
// check
// all vertices should be black
foreach(IVertex v in g.Vertices)
{
Assert.IsTrue( dfs.Colors.Contains(v));
Assert.AreEqual(dfs.Colors[v],GraphColor.Black);
}
// check parenthesis structure of discover/finish times
// See CLR p.480
foreach(IVertex u in g.Vertices)
{
foreach(IVertex v in g.Vertices)
{
if (u != v)
{
Assert.IsTrue(
FinishTimes[u] < DiscoverTimes[v]
|| FinishTimes[v] < DiscoverTimes[u]
|| (
DiscoverTimes[v] < DiscoverTimes[u]
&& FinishTimes[u] < FinishTimes[v]
&& IsDescendant(u, v)
)
|| (
DiscoverTimes[u] < DiscoverTimes[v]
&& FinishTimes[v] < FinishTimes[u]
&& IsDescendant(v, u)
)
);
}
}
}
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System
{
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Runtime;
using System.ServiceModel;
using System.Text;
// Thin wrapper around formatted string; use type system to help ensure we
// are doing canonicalization right/consistently - the literal sections are held in an
// un-escaped format
// We are assuming that the string will be always built as Lit{Var}Lit[{Var}Lit[{Var}Lit[...]]],
// when the first and last literals may be empty
class UriTemplateCompoundPathSegment : UriTemplatePathSegment, IComparable<UriTemplateCompoundPathSegment>
{
readonly string firstLiteral;
readonly List<VarAndLitPair> varLitPairs;
CompoundSegmentClass csClass;
UriTemplateCompoundPathSegment(string originalSegment, bool endsWithSlash, string firstLiteral)
: base(originalSegment, UriTemplatePartType.Compound, endsWithSlash)
{
this.firstLiteral = firstLiteral;
this.varLitPairs = new List<VarAndLitPair>();
}
public static new UriTemplateCompoundPathSegment CreateFromUriTemplate(string segment, UriTemplate template)
{
string origSegment = segment;
bool endsWithSlash = segment.EndsWith("/", StringComparison.Ordinal);
if (endsWithSlash)
{
segment = segment.Remove(segment.Length - 1);
}
int nextVarStart = segment.IndexOf("{", StringComparison.Ordinal);
Fx.Assert(nextVarStart >= 0, "The method is only called after identifying a '{' character in the segment");
string firstLiteral = ((nextVarStart > 0) ? segment.Substring(0, nextVarStart) : string.Empty);
if (firstLiteral.IndexOf(UriTemplate.WildcardPath, StringComparison.Ordinal) != -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(
SR.GetString(SR.UTInvalidWildcardInVariableOrLiteral, template.originalTemplate, UriTemplate.WildcardPath)));
}
UriTemplateCompoundPathSegment result = new UriTemplateCompoundPathSegment(origSegment, endsWithSlash,
((firstLiteral != string.Empty) ? Uri.UnescapeDataString(firstLiteral) : string.Empty));
do
{
int nextVarEnd = segment.IndexOf("}", nextVarStart + 1, StringComparison.Ordinal);
if (nextVarEnd < nextVarStart + 2)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(
SR.GetString(SR.UTInvalidFormatSegmentOrQueryPart, segment)));
}
bool hasDefault;
string varName = template.AddPathVariable(UriTemplatePartType.Compound,
segment.Substring(nextVarStart + 1, nextVarEnd - nextVarStart - 1), out hasDefault);
if (hasDefault)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTDefaultValueToCompoundSegmentVar, template, origSegment, varName)));
}
nextVarStart = segment.IndexOf("{", nextVarEnd + 1, StringComparison.Ordinal);
string literal;
if (nextVarStart > 0)
{
if (nextVarStart == nextVarEnd + 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("template",
SR.GetString(SR.UTDoesNotSupportAdjacentVarsInCompoundSegment, template, segment));
}
literal = segment.Substring(nextVarEnd + 1, nextVarStart - nextVarEnd - 1);
}
else if (nextVarEnd + 1 < segment.Length)
{
literal = segment.Substring(nextVarEnd + 1);
}
else
{
literal = string.Empty;
}
if (literal.IndexOf(UriTemplate.WildcardPath, StringComparison.Ordinal) != -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(
SR.GetString(SR.UTInvalidWildcardInVariableOrLiteral, template.originalTemplate, UriTemplate.WildcardPath)));
}
if (literal.IndexOf('}') != -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(
SR.GetString(SR.UTInvalidFormatSegmentOrQueryPart, segment)));
}
result.varLitPairs.Add(new VarAndLitPair(varName, ((literal == string.Empty) ? string.Empty : Uri.UnescapeDataString(literal))));
} while (nextVarStart > 0);
if (string.IsNullOrEmpty(result.firstLiteral))
{
if (string.IsNullOrEmpty(result.varLitPairs[result.varLitPairs.Count - 1].Literal))
{
result.csClass = CompoundSegmentClass.HasNoPrefixNorSuffix;
}
else
{
result.csClass = CompoundSegmentClass.HasOnlySuffix;
}
}
else
{
if (string.IsNullOrEmpty(result.varLitPairs[result.varLitPairs.Count - 1].Literal))
{
result.csClass = CompoundSegmentClass.HasOnlyPrefix;
}
else
{
result.csClass = CompoundSegmentClass.HasPrefixAndSuffix;
}
}
return result;
}
public override void Bind(string[] values, ref int valueIndex, StringBuilder path)
{
Fx.Assert(valueIndex + this.varLitPairs.Count <= values.Length, "Not enough values to bind");
path.Append(this.firstLiteral);
for (int pairIndex = 0; pairIndex < this.varLitPairs.Count; pairIndex++)
{
path.Append(values[valueIndex++]);
path.Append(this.varLitPairs[pairIndex].Literal);
}
if (this.EndsWithSlash)
{
path.Append("/");
}
}
public override bool IsEquivalentTo(UriTemplatePathSegment other, bool ignoreTrailingSlash)
{
if (other == null)
{
Fx.Assert("why would we ever call this?");
return false;
}
if (!ignoreTrailingSlash && (this.EndsWithSlash != other.EndsWithSlash))
{
return false;
}
UriTemplateCompoundPathSegment otherAsCompound = other as UriTemplateCompoundPathSegment;
if (otherAsCompound == null)
{
// if other can't be cast as a compound then it can't be equivalent
return false;
}
if (this.varLitPairs.Count != otherAsCompound.varLitPairs.Count)
{
return false;
}
if (StringComparer.OrdinalIgnoreCase.Compare(this.firstLiteral, otherAsCompound.firstLiteral) != 0)
{
return false;
}
for (int pairIndex = 0; pairIndex < this.varLitPairs.Count; pairIndex++)
{
if (StringComparer.OrdinalIgnoreCase.Compare(this.varLitPairs[pairIndex].Literal,
otherAsCompound.varLitPairs[pairIndex].Literal) != 0)
{
return false;
}
}
return true;
}
public override bool IsMatch(UriTemplateLiteralPathSegment segment, bool ignoreTrailingSlash)
{
if (!ignoreTrailingSlash && (this.EndsWithSlash != segment.EndsWithSlash))
{
return false;
}
return TryLookup(segment.AsUnescapedString(), null);
}
public override void Lookup(string segment, NameValueCollection boundParameters)
{
if (!TryLookup(segment, boundParameters))
{
Fx.Assert("How can that be? Lookup is expected to be called after IsMatch");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTCSRLookupBeforeMatch)));
}
}
bool TryLookup(string segment, NameValueCollection boundParameters)
{
int segmentPosition = 0;
if (!string.IsNullOrEmpty(this.firstLiteral))
{
if (segment.StartsWith(this.firstLiteral, StringComparison.Ordinal))
{
segmentPosition = this.firstLiteral.Length;
}
else
{
return false;
}
}
for (int pairIndex = 0; pairIndex < this.varLitPairs.Count - 1; pairIndex++)
{
int nextLiteralPosition = segment.IndexOf(this.varLitPairs[pairIndex].Literal, segmentPosition, StringComparison.Ordinal);
if (nextLiteralPosition < segmentPosition + 1)
{
return false;
}
if (boundParameters != null)
{
string varValue = segment.Substring(segmentPosition, nextLiteralPosition - segmentPosition);
boundParameters.Add(this.varLitPairs[pairIndex].VarName, varValue);
}
segmentPosition = nextLiteralPosition + this.varLitPairs[pairIndex].Literal.Length;
}
if (segmentPosition < segment.Length)
{
if (string.IsNullOrEmpty(this.varLitPairs[varLitPairs.Count - 1].Literal))
{
if (boundParameters != null)
{
boundParameters.Add(this.varLitPairs[varLitPairs.Count - 1].VarName,
segment.Substring(segmentPosition));
}
return true;
}
else if ((segmentPosition + this.varLitPairs[varLitPairs.Count - 1].Literal.Length < segment.Length) &&
segment.EndsWith(this.varLitPairs[varLitPairs.Count - 1].Literal, StringComparison.Ordinal))
{
if (boundParameters != null)
{
boundParameters.Add(this.varLitPairs[varLitPairs.Count - 1].VarName,
segment.Substring(segmentPosition, segment.Length - segmentPosition - this.varLitPairs[varLitPairs.Count - 1].Literal.Length));
}
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
// A note about comparing compound segments:
// We are using this for generating the sorted collections at the nodes of the UriTemplateTrieNode.
// The idea is that we are sorting the segments based on preferred matching, when we have two
// compound segments matching the same wire segment, we will give preference to the preceding one.
// The order is based on the following concepts:
// - We are defining four classes of compound segments: prefix+suffix, prefix-only, suffix-only
// and none
// - Whenever we are comparing segments from different class the preferred one is the segment with
// the prefared class, based on the order we defined them (p+s \ p \ s \ n).
// - Within each class the preference is based on the prefix\suffix, while prefix has precedence
// over suffix if both exists.
// - If after comparing the class, as well as the prefix\suffix, we didn't reach to a conclusion,
// the preference is given to the segment with more variables parts.
// This order mostly follows the intuitive common sense; the major issue comes from preferring the
// prefix over the suffix in the case where both exist. This is derived from the problematic of any
// other type of solution that don't prefere the prefix over the suffix or vice versa. To better
// understanding lets considered the following example:
// In comparing 'foo{x}bar' and 'food{x}ar', unless we are preferring prefix or suffix, we have
// to state that they have the same order. So is the case with 'foo{x}babar' and 'food{x}ar', which
// will lead us to claiming the 'foo{x}bar' and 'foo{x}babar' are from the same order, which they
// clearly are not.
// Taking other approaches to this problem results in similar cases. The only solution is preferring
// either the prefix or the suffix over the other; since we already preferred prefix over suffix
// implicitly (we preferred the prefix only class over the suffix only, we also prefared literal
// over variable, if in the same path segment) that still maintain consistency.
// Therefore:
// - 'food{var}' should be before 'foo{var}'; '{x}.{y}.{z}' should be before '{x}.{y}'.
// - the order between '{var}bar' and '{var}qux' is not important
// - '{x}.{y}' and '{x}_{y}' should have the same order
// - 'foo{x}bar' is less preferred than 'food{x}ar'
// In the above third case - if we are opening the table with allowDuplicate=false, we will throw;
// if we are opening it with allowDuplicate=true we will let it go and might match both templates
// for certain wire candidates.
int IComparable<UriTemplateCompoundPathSegment>.CompareTo(UriTemplateCompoundPathSegment other)
{
Fx.Assert(other != null, "We are only expected to get here for comparing real compound segments");
switch (this.csClass)
{
case CompoundSegmentClass.HasPrefixAndSuffix:
switch (other.csClass)
{
case CompoundSegmentClass.HasPrefixAndSuffix:
return CompareToOtherThatHasPrefixAndSuffix(other);
case CompoundSegmentClass.HasOnlyPrefix:
case CompoundSegmentClass.HasOnlySuffix:
case CompoundSegmentClass.HasNoPrefixNorSuffix:
return -1;
default:
Fx.Assert("Invalid other.CompoundSegmentClass");
return 0;
}
case CompoundSegmentClass.HasOnlyPrefix:
switch (other.csClass)
{
case CompoundSegmentClass.HasPrefixAndSuffix:
return 1;
case CompoundSegmentClass.HasOnlyPrefix:
return CompareToOtherThatHasOnlyPrefix(other);
case CompoundSegmentClass.HasOnlySuffix:
case CompoundSegmentClass.HasNoPrefixNorSuffix:
return -1;
default:
Fx.Assert("Invalid other.CompoundSegmentClass");
return 0;
}
case CompoundSegmentClass.HasOnlySuffix:
switch (other.csClass)
{
case CompoundSegmentClass.HasPrefixAndSuffix:
case CompoundSegmentClass.HasOnlyPrefix:
return 1;
case CompoundSegmentClass.HasOnlySuffix:
return CompareToOtherThatHasOnlySuffix(other);
case CompoundSegmentClass.HasNoPrefixNorSuffix:
return -1;
default:
Fx.Assert("Invalid other.CompoundSegmentClass");
return 0;
}
case CompoundSegmentClass.HasNoPrefixNorSuffix:
switch (other.csClass)
{
case CompoundSegmentClass.HasPrefixAndSuffix:
case CompoundSegmentClass.HasOnlyPrefix:
case CompoundSegmentClass.HasOnlySuffix:
return 1;
case CompoundSegmentClass.HasNoPrefixNorSuffix:
return CompareToOtherThatHasNoPrefixNorSuffix(other);
default:
Fx.Assert("Invalid other.CompoundSegmentClass");
return 0;
}
default:
Fx.Assert("Invalid this.CompoundSegmentClass");
return 0;
}
}
int CompareToOtherThatHasPrefixAndSuffix(UriTemplateCompoundPathSegment other)
{
Fx.Assert(this.csClass == CompoundSegmentClass.HasPrefixAndSuffix, "Otherwise, how did we got here?");
Fx.Assert(other.csClass == CompoundSegmentClass.HasPrefixAndSuffix, "Otherwise, how did we got here?");
// In this case we are determining the order based on the prefix of the two segments,
// then by their suffix and then based on the number of variables
int prefixOrder = ComparePrefixToOtherPrefix(other);
if (prefixOrder == 0)
{
int suffixOrder = CompareSuffixToOtherSuffix(other);
if (suffixOrder == 0)
{
return (other.varLitPairs.Count - this.varLitPairs.Count);
}
else
{
return suffixOrder;
}
}
else
{
return prefixOrder;
}
}
int CompareToOtherThatHasOnlyPrefix(UriTemplateCompoundPathSegment other)
{
Fx.Assert(this.csClass == CompoundSegmentClass.HasOnlyPrefix, "Otherwise, how did we got here?");
Fx.Assert(other.csClass == CompoundSegmentClass.HasOnlyPrefix, "Otherwise, how did we got here?");
// In this case we are determining the order based on the prefix of the two segments,
// then based on the number of variables
int prefixOrder = ComparePrefixToOtherPrefix(other);
if (prefixOrder == 0)
{
return (other.varLitPairs.Count - this.varLitPairs.Count);
}
else
{
return prefixOrder;
}
}
int CompareToOtherThatHasOnlySuffix(UriTemplateCompoundPathSegment other)
{
Fx.Assert(this.csClass == CompoundSegmentClass.HasOnlySuffix, "Otherwise, how did we got here?");
Fx.Assert(other.csClass == CompoundSegmentClass.HasOnlySuffix, "Otherwise, how did we got here?");
// In this case we are determining the order based on the suffix of the two segments,
// then based on the number of variables
int suffixOrder = CompareSuffixToOtherSuffix(other);
if (suffixOrder == 0)
{
return (other.varLitPairs.Count - this.varLitPairs.Count);
}
else
{
return suffixOrder;
}
}
int CompareToOtherThatHasNoPrefixNorSuffix(UriTemplateCompoundPathSegment other)
{
Fx.Assert(this.csClass == CompoundSegmentClass.HasNoPrefixNorSuffix, "Otherwise, how did we got here?");
Fx.Assert(other.csClass == CompoundSegmentClass.HasNoPrefixNorSuffix, "Otherwise, how did we got here?");
// In this case the order is determined by the number of variables
return (other.varLitPairs.Count - this.varLitPairs.Count);
}
int ComparePrefixToOtherPrefix(UriTemplateCompoundPathSegment other)
{
return string.Compare(other.firstLiteral, this.firstLiteral, StringComparison.OrdinalIgnoreCase);
}
int CompareSuffixToOtherSuffix(UriTemplateCompoundPathSegment other)
{
string reversedSuffix = ReverseString(this.varLitPairs[this.varLitPairs.Count - 1].Literal);
string reversedOtherSuffix = ReverseString(other.varLitPairs[other.varLitPairs.Count - 1].Literal);
return string.Compare(reversedOtherSuffix, reversedSuffix, StringComparison.OrdinalIgnoreCase);
}
static string ReverseString(string stringToReverse)
{
char[] reversedString = new char[stringToReverse.Length];
for (int i = 0; i < stringToReverse.Length; i++)
{
reversedString[i] = stringToReverse[stringToReverse.Length - i - 1];
}
return new string(reversedString);
}
enum CompoundSegmentClass
{
Undefined,
HasPrefixAndSuffix,
HasOnlyPrefix,
HasOnlySuffix,
HasNoPrefixNorSuffix
}
struct VarAndLitPair
{
readonly string literal;
readonly string varName;
public VarAndLitPair(string varName, string literal)
{
this.varName = varName;
this.literal = literal;
}
public string Literal
{
get
{
return this.literal;
}
}
public string VarName
{
get
{
return this.varName;
}
}
}
}
}
| |
#if NET45 || NET40
namespace AutoMapper.Execution
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
public static class ProxyGenerator
{
private static readonly byte[] privateKey =
StringToByteArray(
"002400000480000094000000060200000024000052534131000400000100010079dfef85ed6ba841717e154f13182c0a6029a40794a6ecd2886c7dc38825f6a4c05b0622723a01cd080f9879126708eef58f134accdc99627947425960ac2397162067507e3c627992aa6b92656ad3380999b30b5d5645ba46cc3fcc6a1de5de7afebcf896c65fb4f9547a6c0c6433045fceccb1fa15e960d519d0cd694b29a4");
private static readonly byte[] privateKeyToken = StringToByteArray("be96cd2c38ef1005");
private static readonly MethodInfo delegate_Combine = typeof(Delegate).GetDeclaredMethod("Combine", new[] { typeof(Delegate), typeof(Delegate) });
private static readonly MethodInfo delegate_Remove = typeof(Delegate).GetDeclaredMethod("Remove", new[] { typeof(Delegate), typeof(Delegate) });
private static readonly EventInfo iNotifyPropertyChanged_PropertyChanged =
typeof(INotifyPropertyChanged).GetRuntimeEvent("PropertyChanged");
private static readonly ConstructorInfo proxyBase_ctor =
typeof(ProxyBase).GetDeclaredConstructor(new Type[0]);
private static readonly ModuleBuilder proxyModule = CreateProxyModule();
private static readonly LockingConcurrentDictionary<TypeDescription, Type> proxyTypes = new LockingConcurrentDictionary<TypeDescription, Type>(EmitProxy);
private static ModuleBuilder CreateProxyModule()
{
AssemblyName name = new AssemblyName("AutoMapper.Proxies");
name.SetPublicKey(privateKey);
name.SetPublicKeyToken(privateKeyToken);
#if NET45
AssemblyBuilder builder = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
#else
AssemblyBuilder builder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
#endif
return builder.DefineDynamicModule("AutoMapper.Proxies.emit");
}
private static Type EmitProxy(TypeDescription typeDescription)
{
var interfaceType = typeDescription.Type;
var additionalProperties = typeDescription.AdditionalProperties;
var propertyNames = string.Join("_", additionalProperties.Select(p => p.Name));
string name =
$"Proxy{propertyNames}<{Regex.Replace(interfaceType.AssemblyQualifiedName ?? interfaceType.FullName ?? interfaceType.Name, @"[\s,]+", "_")}>";
var allInterfaces = new List<Type> { interfaceType };
allInterfaces.AddRange(interfaceType.GetTypeInfo().ImplementedInterfaces);
Debug.WriteLine(name, "Emitting proxy type");
TypeBuilder typeBuilder = proxyModule.DefineType(name,
TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Public, typeof(ProxyBase),
interfaceType.IsInterface ? new[] { interfaceType } : Type.EmptyTypes);
ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public,
CallingConventions.Standard, new Type[0]);
ILGenerator ctorIl = constructorBuilder.GetILGenerator();
ctorIl.Emit(OpCodes.Ldarg_0);
ctorIl.Emit(OpCodes.Call, proxyBase_ctor);
ctorIl.Emit(OpCodes.Ret);
FieldBuilder propertyChangedField = null;
if(typeof(INotifyPropertyChanged).IsAssignableFrom(interfaceType))
{
propertyChangedField = typeBuilder.DefineField("PropertyChanged", typeof(PropertyChangedEventHandler),
FieldAttributes.Private);
MethodBuilder addPropertyChangedMethod = typeBuilder.DefineMethod("add_PropertyChanged",
MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName |
MethodAttributes.NewSlot | MethodAttributes.Virtual, typeof(void),
new[] { typeof(PropertyChangedEventHandler) });
ILGenerator addIl = addPropertyChangedMethod.GetILGenerator();
addIl.Emit(OpCodes.Ldarg_0);
addIl.Emit(OpCodes.Dup);
addIl.Emit(OpCodes.Ldfld, propertyChangedField);
addIl.Emit(OpCodes.Ldarg_1);
addIl.Emit(OpCodes.Call, delegate_Combine);
addIl.Emit(OpCodes.Castclass, typeof(PropertyChangedEventHandler));
addIl.Emit(OpCodes.Stfld, propertyChangedField);
addIl.Emit(OpCodes.Ret);
MethodBuilder removePropertyChangedMethod = typeBuilder.DefineMethod("remove_PropertyChanged",
MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName |
MethodAttributes.NewSlot | MethodAttributes.Virtual, typeof(void),
new[] { typeof(PropertyChangedEventHandler) });
ILGenerator removeIl = removePropertyChangedMethod.GetILGenerator();
removeIl.Emit(OpCodes.Ldarg_0);
removeIl.Emit(OpCodes.Dup);
removeIl.Emit(OpCodes.Ldfld, propertyChangedField);
removeIl.Emit(OpCodes.Ldarg_1);
removeIl.Emit(OpCodes.Call, delegate_Remove);
removeIl.Emit(OpCodes.Castclass, typeof(PropertyChangedEventHandler));
removeIl.Emit(OpCodes.Stfld, propertyChangedField);
removeIl.Emit(OpCodes.Ret);
typeBuilder.DefineMethodOverride(addPropertyChangedMethod,
iNotifyPropertyChanged_PropertyChanged.GetAddMethod());
typeBuilder.DefineMethodOverride(removePropertyChangedMethod,
iNotifyPropertyChanged_PropertyChanged.GetRemoveMethod());
}
var propertiesToImplement = new List<PropertyDescription>();
// first we collect all properties, those with setters before getters in order to enable less specific redundant getters
foreach(var property in
allInterfaces.Where(intf => intf != typeof(INotifyPropertyChanged))
.SelectMany(intf => intf.GetProperties())
.Select(p => new PropertyDescription(p))
.Concat(additionalProperties))
{
if(property.CanWrite)
{
propertiesToImplement.Insert(0, property);
}
else
{
propertiesToImplement.Add(property);
}
}
var fieldBuilders = new Dictionary<string, PropertyEmitter>();
foreach(var property in propertiesToImplement)
{
PropertyEmitter propertyEmitter;
if(fieldBuilders.TryGetValue(property.Name, out propertyEmitter))
{
if((propertyEmitter.PropertyType != property.Type) &&
((property.CanWrite) || (!property.Type.IsAssignableFrom(propertyEmitter.PropertyType))))
{
throw new ArgumentException(
$"The interface has a conflicting property {property.Name}",
nameof(interfaceType));
}
}
else
{
fieldBuilders.Add(property.Name,
propertyEmitter =
new PropertyEmitter(typeBuilder, property, propertyChangedField));
}
}
return typeBuilder.CreateType();
}
public static Type GetProxyType(Type interfaceType)
{
var key = new TypeDescription(interfaceType);
if(!interfaceType.IsInterface())
{
throw new ArgumentException("Only interfaces can be proxied", nameof(interfaceType));
}
return proxyTypes.GetOrAdd(key);
}
public static Type GetSimilarType(Type sourceType, IEnumerable<PropertyDescription> additionalProperties)
{
return proxyTypes.GetOrAdd(new TypeDescription(sourceType, additionalProperties));
}
private static byte[] StringToByteArray(string hex)
{
int numberChars = hex.Length;
byte[] bytes = new byte[numberChars / 2];
for(int i = 0; i < numberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
}
public struct TypeDescription : IEquatable<TypeDescription>
{
public TypeDescription(Type type) : this(type, PropertyDescription.Empty)
{
}
public TypeDescription(Type type, IEnumerable<PropertyDescription> additionalProperties)
{
Type = type ?? throw new ArgumentNullException(nameof(type));
AdditionalProperties = additionalProperties?.ToArray() ?? throw new ArgumentNullException(nameof(additionalProperties));
}
public Type Type { get; }
public PropertyDescription[] AdditionalProperties { get; }
public override int GetHashCode()
{
var hashCode = Type.GetHashCode();
foreach(var property in AdditionalProperties)
{
hashCode = HashCodeCombiner.CombineCodes(hashCode, property.GetHashCode());
}
return hashCode;
}
public override bool Equals(object other) => other is TypeDescription && Equals((TypeDescription)other);
public bool Equals(TypeDescription other) => Type == other.Type && AdditionalProperties.SequenceEqual(other.AdditionalProperties);
public static bool operator ==(TypeDescription left, TypeDescription right) => left.Equals(right);
public static bool operator !=(TypeDescription left, TypeDescription right) => !left.Equals(right);
}
[DebuggerDisplay("{Name}-{Type.Name}")]
public struct PropertyDescription : IEquatable<PropertyDescription>
{
internal static PropertyDescription[] Empty = new PropertyDescription[0];
public PropertyDescription(string name, Type type, bool canWrite = true)
{
Name = name;
Type = type;
CanWrite = canWrite;
}
public PropertyDescription(PropertyInfo property)
{
Name = property.Name;
Type = property.PropertyType;
CanWrite = property.CanWrite;
}
public string Name { get; }
public Type Type { get; }
public bool CanWrite { get; }
public override int GetHashCode()
{
var code = HashCodeCombiner.Combine(Name, Type);
return HashCodeCombiner.CombineCodes(code, CanWrite.GetHashCode());
}
public override bool Equals(object other) => other is PropertyDescription && Equals((PropertyDescription)other);
public bool Equals(PropertyDescription other) => Name == other.Name && Type == other.Type && CanWrite == other.CanWrite;
public static bool operator ==(PropertyDescription left, PropertyDescription right) => left.Equals(right);
public static bool operator !=(PropertyDescription left, PropertyDescription right) => !left.Equals(right);
}
}
#endif
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ReadonlypropertyOperations operations.
/// </summary>
internal partial class ReadonlypropertyOperations : IServiceOperations<AzureCompositeModel>, IReadonlypropertyOperations
{
/// <summary>
/// Initializes a new instance of the ReadonlypropertyOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ReadonlypropertyOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that have readonly properties
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ReadonlyObj>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/readonlyproperty/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ReadonlyObj>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ReadonlyObj>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that have readonly properties
/// </summary>
/// <param name='complexBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(ReadonlyObj complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/readonlyproperty/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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.IO;
using System.Text;
using Xunit;
namespace System.IO.Tests
{
public class BinaryWriterTests
{
protected virtual Stream CreateStream()
{
return new MemoryStream();
}
[Fact]
public void BinaryWriter_CtorAndWriteTests1()
{
// [] Smoke test to ensure that we can write with the constructed writer
using (Stream mstr = CreateStream())
using (BinaryWriter dw2 = new BinaryWriter(mstr))
using (BinaryReader dr2 = new BinaryReader(mstr))
{
dw2.Write(true);
dw2.Flush();
mstr.Position = 0;
Assert.True(dr2.ReadBoolean());
}
}
[Fact]
public void BinaryWriter_CtorAndWriteTests1_Negative()
{
// [] Should throw ArgumentNullException for null argument
Assert.Throws<ArgumentNullException>(() => new BinaryWriter(null));
// [] Can't construct a BinaryWriter on a readonly stream
using (Stream memStream = new MemoryStream(new byte[10], false))
{
Assert.Throws<ArgumentException>(() => new BinaryWriter(memStream));
}
// [] Can't construct a BinaryWriter with a closed stream
{
Stream memStream = CreateStream();
memStream.Dispose();
Assert.Throws<ArgumentException>(() => new BinaryWriter(memStream));
}
}
[Theory]
[MemberData(nameof(EncodingAndEncodingStrings))]
public void BinaryWriter_EncodingCtorAndWriteTests(Encoding encoding, string testString)
{
using (Stream memStream = CreateStream())
using (BinaryWriter writer = new BinaryWriter(memStream, encoding))
using (BinaryReader reader = new BinaryReader(memStream, encoding))
{
writer.Write(testString);
writer.Flush();
memStream.Position = 0;
Assert.Equal(testString, reader.ReadString());
}
}
public static IEnumerable<object[]> EncodingAndEncodingStrings
{
get
{
yield return new object[] { Encoding.UTF8, "This is UTF8\u00FF" };
yield return new object[] { Encoding.BigEndianUnicode, "This is BigEndianUnicode\u00FF" };
yield return new object[] { Encoding.Unicode, "This is Unicode\u00FF" };
}
}
[Fact]
public void BinaryWriter_EncodingCtorAndWriteTests_Negative()
{
// [] Check for ArgumentNullException on null stream
Assert.Throws<ArgumentNullException>(() => new BinaryReader((Stream)null, Encoding.UTF8));
// [] Check for ArgumentNullException on null encoding
Assert.Throws<ArgumentNullException>(() => new BinaryReader(CreateStream(), null));
}
[Fact]
public void BinaryWriter_SeekTests()
{
int[] iArrLargeValues = new int[] { 10000, 100000, int.MaxValue / 200, int.MaxValue / 1000, short.MaxValue, int.MaxValue, int.MaxValue - 1, int.MaxValue / 2, int.MaxValue / 10, int.MaxValue / 100 };
BinaryWriter dw2 = null;
MemoryStream mstr = null;
byte[] bArr = null;
StringBuilder sb = new StringBuilder();
Int64 lReturn = 0;
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("Hello, this is my string".ToCharArray());
for (int iLoop = 0; iLoop < iArrLargeValues.Length; iLoop++)
{
lReturn = dw2.Seek(iArrLargeValues[iLoop], SeekOrigin.Begin);
Assert.Equal(iArrLargeValues[iLoop], lReturn);
}
dw2.Dispose();
mstr.Dispose();
// [] Seek from start of stream
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(0, SeekOrigin.Begin);
Assert.Equal(0, lReturn);
dw2.Write("lki".ToCharArray());
dw2.Flush();
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("lki3456789", sb.ToString());
dw2.Dispose();
mstr.Dispose();
// [] Seek into stream from start
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(3, SeekOrigin.Begin);
Assert.Equal(3, lReturn);
dw2.Write("lk".ToCharArray());
dw2.Flush();
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("012lk56789", sb.ToString());
dw2.Dispose();
mstr.Dispose();
// [] Seek from end of stream
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(-3, SeekOrigin.End);
Assert.Equal(7, lReturn);
dw2.Write("ll".ToCharArray());
dw2.Flush();
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("0123456ll9", sb.ToString());
dw2.Dispose();
mstr.Dispose();
// [] Seeking from current position
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
mstr.Position = 2;
lReturn = dw2.Seek(2, SeekOrigin.Current);
Assert.Equal(4, lReturn);
dw2.Write("ll".ToCharArray());
dw2.Flush();
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("0123ll6789", sb.ToString());
dw2.Dispose();
mstr.Dispose();
// [] Seeking past the end from middle
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(4, SeekOrigin.End); //This won't throw any exception now.
Assert.Equal(14, mstr.Position);
dw2.Dispose();
mstr.Dispose();
// [] Seek past the end from beginning
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(11, SeekOrigin.Begin); //This won't throw any exception now.
Assert.Equal(11, mstr.Position);
dw2.Dispose();
mstr.Dispose();
// [] Seek to the end
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(10, SeekOrigin.Begin);
Assert.Equal(10, lReturn);
dw2.Write("ll".ToCharArray());
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("0123456789ll", sb.ToString());
dw2.Dispose();
mstr.Dispose();
}
[Theory]
[InlineData(-1)]
[InlineData(-2)]
[InlineData(-10000)]
[InlineData(int.MinValue)]
public void BinaryWriter_SeekTests_NegativeOffset(int invalidValue)
{
// [] IOException if offset is negative
using (Stream memStream = CreateStream())
using (BinaryWriter writer = new BinaryWriter(memStream))
{
writer.Write("Hello, this is my string".ToCharArray());
Assert.Throws<IOException>(() => writer.Seek(invalidValue, SeekOrigin.Begin));
}
}
[Fact]
public void BinaryWriter_SeekTests_InvalidSeekOrigin()
{
// [] ArgumentException for invalid seekOrigin
using (Stream memStream = CreateStream())
using (BinaryWriter writer = new BinaryWriter(memStream))
{
writer.Write("012345789".ToCharArray());
Assert.Throws<ArgumentException>(() =>
{
writer.Seek(3, ~SeekOrigin.Begin);
});
}
}
[Fact]
public void BinaryWriter_BaseStreamTests()
{
// [] Get the base stream for MemoryStream
using (Stream ms2 = CreateStream())
using (BinaryWriter sr2 = new BinaryWriter(ms2))
{
Assert.Same(ms2, sr2.BaseStream);
}
}
[Fact]
public virtual void BinaryWriter_FlushTests()
{
// [] Check that flush updates the underlying stream
using (Stream memstr2 = CreateStream())
using (BinaryWriter bw2 = new BinaryWriter(memstr2))
{
string str = "HelloWorld";
int expectedLength = str.Length + 1; // 1 for 7-bit encoded length
bw2.Write(str);
Assert.Equal(expectedLength, memstr2.Length);
bw2.Flush();
Assert.Equal(expectedLength, memstr2.Length);
}
// [] Flushing a closed writer may throw an exception depending on the underlying stream
using (Stream memstr2 = CreateStream())
{
BinaryWriter bw2 = new BinaryWriter(memstr2);
bw2.Dispose();
bw2.Flush();
}
}
[Fact]
public void BinaryWriter_DisposeTests()
{
// Disposing multiple times should not throw an exception
using (Stream memStream = CreateStream())
using (BinaryWriter binaryWriter = new BinaryWriter(memStream))
{
binaryWriter.Dispose();
binaryWriter.Dispose();
binaryWriter.Dispose();
}
}
[Fact]
public void BinaryWriter_CloseTests()
{
// Closing multiple times should not throw an exception
using (Stream memStream = CreateStream())
using (BinaryWriter binaryWriter = new BinaryWriter(memStream))
{
binaryWriter.Close();
binaryWriter.Close();
binaryWriter.Close();
}
}
[Fact]
public void BinaryWriter_DisposeTests_Negative()
{
using (Stream memStream = CreateStream())
{
BinaryWriter binaryWriter = new BinaryWriter(memStream);
binaryWriter.Dispose();
ValidateDisposedExceptions(binaryWriter);
}
}
[Fact]
public void BinaryWriter_CloseTests_Negative()
{
using (Stream memStream = CreateStream())
{
BinaryWriter binaryWriter = new BinaryWriter(memStream);
binaryWriter.Close();
ValidateDisposedExceptions(binaryWriter);
}
}
private void ValidateDisposedExceptions(BinaryWriter binaryWriter)
{
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Seek(1, SeekOrigin.Begin));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new byte[2], 0, 2));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new char[2], 0, 2));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(true));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((byte)4));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new byte[] { 1, 2 }));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write('a'));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new char[] { 'a', 'b' }));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(5.3));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((short)3));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(33));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((Int64)42));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((sbyte)4));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write("Hello There"));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((float)4.3));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((UInt16)3));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((uint)4));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((ulong)5));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write("Bah"));
}
}
}
| |
// 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 System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Graphics.Containers;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Overlays;
using osu.Game.Screens;
using osu.Game.Screens.Menu;
using osu.Game.Screens.Play;
using osu.Game.Tests.Beatmaps.IO;
using osuTK.Input;
using static osu.Game.Tests.Visual.Navigation.TestSceneScreenNavigation;
namespace osu.Game.Tests.Visual.Navigation
{
public class TestScenePerformFromScreen : OsuGameTestScene
{
private bool actionPerformed;
public override void SetUpSteps()
{
AddStep("reset status", () => actionPerformed = false);
base.SetUpSteps();
}
[Test]
public void TestPerformAtMenu()
{
AddStep("perform immediately", () => Game.PerformFromScreen(_ => actionPerformed = true));
AddAssert("did perform", () => actionPerformed);
}
[Test]
public void TestPerformAtSongSelect()
{
PushAndConfirm(() => new TestPlaySongSelect());
AddStep("perform immediately", () => Game.PerformFromScreen(_ => actionPerformed = true, new[] { typeof(TestPlaySongSelect) }));
AddAssert("did perform", () => actionPerformed);
AddAssert("screen didn't change", () => Game.ScreenStack.CurrentScreen is TestPlaySongSelect);
}
[Test]
public void TestPerformAtMenuFromSongSelect()
{
PushAndConfirm(() => new TestPlaySongSelect());
AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true));
AddUntilStep("returned to menu", () => Game.ScreenStack.CurrentScreen is MainMenu);
AddAssert("did perform", () => actionPerformed);
}
[Test]
public void TestPerformAtSongSelectFromPlayerLoader()
{
importAndWaitForSongSelect();
AddStep("Press enter", () => InputManager.Key(Key.Enter));
AddUntilStep("Wait for new screen", () => Game.ScreenStack.CurrentScreen is PlayerLoader);
AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true, new[] { typeof(TestPlaySongSelect) }));
AddUntilStep("returned to song select", () => Game.ScreenStack.CurrentScreen is TestPlaySongSelect);
AddAssert("did perform", () => actionPerformed);
}
[Test]
public void TestPerformAtMenuFromPlayerLoader()
{
importAndWaitForSongSelect();
AddStep("Press enter", () => InputManager.Key(Key.Enter));
AddUntilStep("Wait for new screen", () => Game.ScreenStack.CurrentScreen is PlayerLoader);
AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true));
AddUntilStep("returned to song select", () => Game.ScreenStack.CurrentScreen is MainMenu);
AddAssert("did perform", () => actionPerformed);
}
[Test]
public void TestOverlaysAlwaysClosed()
{
ChatOverlay chat = null;
AddUntilStep("is at menu", () => Game.ScreenStack.CurrentScreen is MainMenu);
AddUntilStep("wait for chat load", () => (chat = Game.ChildrenOfType<ChatOverlay>().SingleOrDefault()) != null);
AddStep("show chat", () => InputManager.Key(Key.F8));
AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true));
AddUntilStep("still at menu", () => Game.ScreenStack.CurrentScreen is MainMenu);
AddAssert("did perform", () => actionPerformed);
AddAssert("chat closed", () => chat.State.Value == Visibility.Hidden);
}
[TestCase(true)]
[TestCase(false)]
public void TestPerformBlockedByDialog(bool confirmed)
{
DialogBlockingScreen blocker = null;
PushAndConfirm(() => blocker = new DialogBlockingScreen());
AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true));
AddWaitStep("wait a bit", 10);
AddAssert("screen didn't change", () => Game.ScreenStack.CurrentScreen is DialogBlockingScreen);
AddAssert("did not perform", () => !actionPerformed);
AddAssert("only one exit attempt", () => blocker.ExitAttempts == 1);
AddUntilStep("wait for dialog display", () => Game.Dependencies.Get<DialogOverlay>().IsLoaded);
if (confirmed)
{
AddStep("accept dialog", () => InputManager.Key(Key.Number1));
AddUntilStep("wait for dialog dismissed", () => Game.Dependencies.Get<DialogOverlay>().CurrentDialog == null);
AddUntilStep("did perform", () => actionPerformed);
}
else
{
AddStep("cancel dialog", () => InputManager.Key(Key.Number2));
AddAssert("screen didn't change", () => Game.ScreenStack.CurrentScreen is DialogBlockingScreen);
AddAssert("did not perform", () => !actionPerformed);
}
}
[TestCase(true)]
[TestCase(false)]
public void TestPerformBlockedByDialogNested(bool confirmSecond)
{
DialogBlockingScreen blocker = null;
DialogBlockingScreen blocker2 = null;
PushAndConfirm(() => blocker = new DialogBlockingScreen());
PushAndConfirm(() => blocker2 = new DialogBlockingScreen());
AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true));
AddUntilStep("wait for dialog", () => blocker2.ExitAttempts == 1);
AddWaitStep("wait a bit", 10);
AddUntilStep("wait for dialog display", () => Game.Dependencies.Get<DialogOverlay>().IsLoaded);
AddAssert("screen didn't change", () => Game.ScreenStack.CurrentScreen == blocker2);
AddAssert("did not perform", () => !actionPerformed);
AddAssert("only one exit attempt", () => blocker2.ExitAttempts == 1);
AddStep("accept dialog", () => InputManager.Key(Key.Number1));
AddUntilStep("screen changed", () => Game.ScreenStack.CurrentScreen == blocker);
AddUntilStep("wait for second dialog", () => blocker.ExitAttempts == 1);
AddAssert("did not perform", () => !actionPerformed);
AddAssert("only one exit attempt", () => blocker.ExitAttempts == 1);
if (confirmSecond)
{
AddStep("accept dialog", () => InputManager.Key(Key.Number1));
AddUntilStep("did perform", () => actionPerformed);
}
else
{
AddStep("cancel dialog", () => InputManager.Key(Key.Number2));
AddAssert("screen didn't change", () => Game.ScreenStack.CurrentScreen == blocker);
AddAssert("did not perform", () => !actionPerformed);
}
}
private void importAndWaitForSongSelect()
{
AddStep("import beatmap", () => BeatmapImportHelper.LoadQuickOszIntoOsu(Game).WaitSafely());
PushAndConfirm(() => new TestPlaySongSelect());
AddUntilStep("beatmap updated", () => Game.Beatmap.Value.BeatmapSetInfo.OnlineID == 241526);
}
public class DialogBlockingScreen : OsuScreen
{
[Resolved]
private DialogOverlay dialogOverlay { get; set; }
private int dialogDisplayCount;
public int ExitAttempts { get; private set; }
public override bool OnExiting(IScreen next)
{
ExitAttempts++;
if (dialogDisplayCount++ < 1)
{
dialogOverlay.Push(new ConfirmExitDialog(this.Exit, () => { }));
return true;
}
return base.OnExiting(next);
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Runtime
{
using System;
using System.Threading;
using System.Runtime.CompilerServices;
public sealed class KernelCircularBuffer< T >
{
//
// State
//
private readonly int m_size;
private readonly T[] m_array;
private readonly ManualResetEvent m_writerEvent;
private readonly ManualResetEvent m_readerEvent;
private int m_count;
private int m_writerPos;
private int m_readerPos;
//
// Constructor Methods
//
public KernelCircularBuffer( int size )
{
m_size = size;
m_array = new T[size];
m_writerEvent = new ManualResetEvent( true );
m_readerEvent = new ManualResetEvent( false );
m_count = 0;
m_writerPos = 0;
m_readerPos = 0;
}
//
// Helper Methods
//
public void Clear()
{
BugCheck.AssertInterruptsOff();
m_writerEvent.Set ();
m_readerEvent.Reset();
m_count = 0;
m_writerPos = 0;
m_readerPos = 0;
}
public bool Peek( out T val )
{
BugCheck.AssertInterruptsOff();
if(this.IsEmpty)
{
val = default(T);
return false;
}
else
{
val = m_array[m_readerPos];
return true;
}
}
//--//
public bool EnqueueNonblocking( T val )
{
BugCheck.AssertInterruptsOff();
if(this.IsFull)
{
return false;
}
if(this.IsEmpty)
{
m_readerEvent.Set();
}
int pos = m_writerPos;
m_array[pos] = val;
m_writerPos = NextPosition( pos );
m_count++;
if(this.IsFull)
{
m_writerEvent.Reset();
}
return true;
}
public bool DequeueNonblocking( out T val )
{
BugCheck.AssertInterruptsOff();
if(this.IsEmpty)
{
val = default(T);
return false;
}
if(this.IsFull)
{
m_writerEvent.Set();
}
int pos = m_readerPos;
val = m_array[pos];
m_readerPos = NextPosition( pos );
m_count--;
if(this.IsEmpty)
{
m_readerEvent.Reset();
}
return true;
}
//--//
public void EnqueueBlocking( T val )
{
BugCheck.AssertInterruptsOn();
while(true)
{
bool fSent;
using(SmartHandles.InterruptState.Disable())
{
fSent = EnqueueNonblocking( val );
}
if(fSent)
{
return;
}
m_writerEvent.WaitOne();
}
}
public T DequeueBlocking()
{
BugCheck.AssertInterruptsOn();
while(true)
{
bool fReceived;
T val;
using(SmartHandles.InterruptState.Disable())
{
fReceived = DequeueNonblocking( out val );
}
if(fReceived)
{
return val;
}
m_readerEvent.WaitOne();
}
}
//--//
public bool EnqueueBlocking( int timeout ,
T val )
{
BugCheck.AssertInterruptsOn();
while(true)
{
bool fSent;
using(SmartHandles.InterruptState.Disable())
{
fSent = EnqueueNonblocking( val );
}
if(fSent)
{
return true;
}
if(m_writerEvent.WaitOne( timeout, false ) == false)
{
return false;
}
}
}
public bool DequeueBlocking( int timeout ,
out T val )
{
BugCheck.AssertInterruptsOn();
while(true)
{
bool fReceived;
using(SmartHandles.InterruptState.Disable())
{
fReceived = DequeueNonblocking( out val );
}
if(fReceived)
{
return true;
}
if(m_readerEvent.WaitOne( timeout, false ) == false)
{
return false;
}
}
}
[Inline]
private int DequeueMultipleNonblocking(ref T[] val, int offset, int maxCount)
{
int totalRead = 0;
if (maxCount == 0 || this.IsEmpty)
{
return 0;
}
if (this.IsFull)
{
m_writerEvent.Set();
}
//
// Potentially read twice since the data could loop around the circular
// buffer.
//
for (int i = 0; i < 2; i++)
{
int countToRead = maxCount;
int availableLinear = m_size - m_writerPos;
if (m_count < availableLinear)
{
availableLinear = m_count;
}
if (availableLinear < countToRead)
{
countToRead = availableLinear;
}
Array.Copy(m_array, m_readerPos, val, offset, countToRead);
m_readerPos = NextPosition(m_readerPos + countToRead - 1);
m_count -= countToRead;
maxCount -= countToRead;
offset += countToRead;
totalRead += countToRead;
if (m_count == 0 || maxCount == 0)
{
break;
}
}
if (this.IsEmpty)
{
m_readerEvent.Reset();
}
return totalRead;
}
public int DequeueMultipleBlocking(ref T[] val, int offset, int maxCount, int timeout)
{
int countRead = 0;
BugCheck.AssertInterruptsOn();
if (val.Length < offset + maxCount)
{
throw new ArgumentException();
}
using (SmartHandles.InterruptState.Disable())
{
countRead = DequeueMultipleNonblocking(ref val, offset, maxCount);
}
if (countRead == 0)
{
if (!m_readerEvent.WaitOne(timeout, false))
{
throw new TimeoutException();
}
using (SmartHandles.InterruptState.Disable())
{
countRead += DequeueMultipleNonblocking(ref val, offset, maxCount);
}
}
return countRead;
}
//--//
[Inline]
private int NextPosition( int val )
{
val = val + 1;
if(val == m_size)
{
return 0;
}
return val;
}
[Inline]
private int PreviousPosition( int val )
{
if(val == 0)
{
val = m_size;
}
return val - 1;
}
//
// Access Methods
//
public int Count
{
get
{
return m_count;
}
}
public int RemainingCapacity
{
get
{
return m_size - m_count;
}
}
public bool IsEmpty
{
[Inline]
get
{
return m_count == 0;
}
}
public bool IsFull
{
[Inline]
get
{
return m_count == m_size;
}
}
}
}
| |
// Copyright 2022 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 gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>CustomerConversionGoal</c> resource.</summary>
public sealed partial class CustomerConversionGoalName : gax::IResourceName, sys::IEquatable<CustomerConversionGoalName>
{
/// <summary>The possible contents of <see cref="CustomerConversionGoalName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>.
/// </summary>
CustomerCategorySource = 1,
}
private static gax::PathTemplate s_customerCategorySource = new gax::PathTemplate("customers/{customer_id}/customerConversionGoals/{category_source}");
/// <summary>Creates a <see cref="CustomerConversionGoalName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CustomerConversionGoalName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CustomerConversionGoalName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CustomerConversionGoalName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CustomerConversionGoalName"/> with the pattern
/// <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="categoryId">The <c>Category</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="CustomerConversionGoalName"/> constructed from the provided ids.
/// </returns>
public static CustomerConversionGoalName FromCustomerCategorySource(string customerId, string categoryId, string sourceId) =>
new CustomerConversionGoalName(ResourceNameType.CustomerCategorySource, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), categoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(categoryId, nameof(categoryId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerConversionGoalName"/> with pattern
/// <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="categoryId">The <c>Category</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerConversionGoalName"/> with pattern
/// <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>.
/// </returns>
public static string Format(string customerId, string categoryId, string sourceId) =>
FormatCustomerCategorySource(customerId, categoryId, sourceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerConversionGoalName"/> with pattern
/// <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="categoryId">The <c>Category</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerConversionGoalName"/> with pattern
/// <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>.
/// </returns>
public static string FormatCustomerCategorySource(string customerId, string categoryId, string sourceId) =>
s_customerCategorySource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(categoryId, nameof(categoryId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerConversionGoalName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customerConversionGoalName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CustomerConversionGoalName"/> if successful.</returns>
public static CustomerConversionGoalName Parse(string customerConversionGoalName) =>
Parse(customerConversionGoalName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerConversionGoalName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerConversionGoalName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CustomerConversionGoalName"/> if successful.</returns>
public static CustomerConversionGoalName Parse(string customerConversionGoalName, bool allowUnparsed) =>
TryParse(customerConversionGoalName, allowUnparsed, out CustomerConversionGoalName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerConversionGoalName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customerConversionGoalName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerConversionGoalName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customerConversionGoalName, out CustomerConversionGoalName result) =>
TryParse(customerConversionGoalName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerConversionGoalName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerConversionGoalName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerConversionGoalName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customerConversionGoalName, bool allowUnparsed, out CustomerConversionGoalName result)
{
gax::GaxPreconditions.CheckNotNull(customerConversionGoalName, nameof(customerConversionGoalName));
gax::TemplatedResourceName resourceName;
if (s_customerCategorySource.TryParseName(customerConversionGoalName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerCategorySource(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(customerConversionGoalName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private CustomerConversionGoalName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string categoryId = null, string customerId = null, string sourceId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CategoryId = categoryId;
CustomerId = customerId;
SourceId = sourceId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CustomerConversionGoalName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/customerConversionGoals/{category}~{source}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="categoryId">The <c>Category</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
public CustomerConversionGoalName(string customerId, string categoryId, string sourceId) : this(ResourceNameType.CustomerCategorySource, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), categoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(categoryId, nameof(categoryId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Category</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CategoryId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>Source</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string SourceId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerCategorySource: return s_customerCategorySource.Expand(CustomerId, $"{CategoryId}~{SourceId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CustomerConversionGoalName);
/// <inheritdoc/>
public bool Equals(CustomerConversionGoalName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CustomerConversionGoalName a, CustomerConversionGoalName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CustomerConversionGoalName a, CustomerConversionGoalName b) => !(a == b);
}
public partial class CustomerConversionGoal
{
/// <summary>
/// <see cref="CustomerConversionGoalName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal CustomerConversionGoalName ResourceNameAsCustomerConversionGoalName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CustomerConversionGoalName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Text;
namespace TwitterClient
{
public struct TwitterConfig
{
public readonly string OAuthToken;
public readonly string OAuthTokenSecret;
public readonly string OAuthConsumerKey;
public readonly string OAuthConsumerSecret;
public readonly string Keywords;
public TwitterConfig(string oauthToken, string oauthTokenSecret, string oauthConsumerKey, string oauthConsumerSecret, string keywords)
{
OAuthToken = oauthToken;
OAuthTokenSecret = oauthTokenSecret;
OAuthConsumerKey = oauthConsumerKey;
OAuthConsumerSecret = oauthConsumerSecret;
Keywords = keywords;
}
}
[DataContract]
public class TwitterUser
{
[DataMember(Name = "time_zone")] public string TimeZone;
[DataMember(Name = "name")] public string Name;
[DataMember(Name = "profile_image_url")] public string ProfileImageUrl;
}
[DataContract]
public class Tweet
{
[DataMember(Name = "id")] public Int64 Id;
[DataMember(Name = "in_reply_to_status_id")] public Int64? ReplyToStatusId;
[DataMember(Name = "in_reply_to_user_id")] public Int64? ReplyToUserId;
[DataMember(Name = "in_reply_to_screen_name")] public string ReplyToScreenName;
[DataMember(Name = "retweeted")] public bool Retweeted;
[DataMember(Name = "text")] public string Text;
[DataMember(Name = "lang")] public string Language;
[DataMember(Name = "source")] public string Source;
[DataMember(Name = "retweet_count")] public string RetweetCount;
[DataMember(Name = "user")] public TwitterUser User;
[DataMember(Name = "created_at")] public string CreatedAt;
[IgnoreDataMember] public string RawJson;
public static IEnumerable<Tweet> StreamStatuses(TwitterConfig config)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Tweet));
var streamReader = ReadTweets(config);
while (true)
{
string line = null;
try { line = streamReader.ReadLine(); }
catch (Exception) { }
if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("{\"delete\""))
{
var result = (Tweet)jsonSerializer.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(line)));
result.RawJson = line;
yield return result;
}
// Oops the Twitter has ended... or more likely some error have occurred.
// Reconnect to the twitter feed.
if (line == null)
{
streamReader = ReadTweets(config);
}
}
}
static TextReader ReadTweets(TwitterConfig config)
{
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// unique request details
var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var oauth_timestamp = Convert.ToInt64(
(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc))
.TotalSeconds).ToString();
var resource_url = "https://stream.twitter.com/1.1/statuses/filter.json";
// create oauth signature
var baseString = string.Format(
"oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}&" +
"oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&track={6}",
config.OAuthConsumerKey,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
config.OAuthToken,
oauth_version,
Uri.EscapeDataString(config.Keywords));
baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(config.OAuthConsumerSecret),
"&", Uri.EscapeDataString(config.OAuthTokenSecret));
string oauth_signature;
using (var hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var authHeader = string.Format(
"OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\"",
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(config.OAuthConsumerKey),
Uri.EscapeDataString(config.OAuthToken),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
// make the request
ServicePointManager.Expect100Continue = false;
var postBody = "track=" + config.Keywords;
resource_url += "?" + postBody;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
// bail out and retry after 5 seconds
var tresponse = request.GetResponseAsync();
if (tresponse.Wait(5000))
return new StreamReader(tresponse.Result.GetResponseStream());
else
{
request.Abort();
return StreamReader.Null;
}
}
}
public class TwitterPayload
{
public Int64 ID;
public DateTime CreatedAt;
public string UserName;
public string TimeZone;
public string ProfileImageUrl;
public string Text;
public string Language;
public string Topic;
public string RawJson;
public override string ToString()
{
return new { ID, CreatedAt, UserName, TimeZone, ProfileImageUrl, Language, Topic }.ToString();
}
}
public class Payload
{
public DateTime CreatedAt;
public string Topic;
public string Text;
public override string ToString()
{
return new { CreatedAt, Topic }.ToString();
}
}
public class TwitterMin
{
public Int64 ID;
public DateTime CreatedAt;
public string UserName;
// public string TimeZone;
// public string ProfileImageUrl;
public string Text;
// public string Language;
public string Topic;
// public string RawJson;
public override string ToString()
{
return new { ID, CreatedAt, UserName, Text, Topic }.ToString();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
using Timer=OpenSim.Region.ScriptEngine.Shared.Api.Plugins.Timer;
namespace OpenSim.Region.ScriptEngine.Shared.Api
{
/// <summary>
/// Handles LSL commands that takes long time and returns an event, for example timers, HTTP requests, etc.
/// </summary>
public class AsyncCommandManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Thread cmdHandlerThread;
private static int cmdHandlerThreadCycleSleepms;
/// <summary>
/// Lock for reading/writing static components of AsyncCommandManager.
/// </summary>
/// <remarks>
/// This lock exists so that multiple threads from different engines and/or different copies of the same engine
/// are prevented from running non-thread safe code (e.g. read/write of lists) concurrently.
/// </remarks>
private static object staticLock = new object();
private static List<IScriptEngine> m_ScriptEngines =
new List<IScriptEngine>();
public IScriptEngine m_ScriptEngine;
private static Dictionary<IScriptEngine, Dataserver> m_Dataserver =
new Dictionary<IScriptEngine, Dataserver>();
private static Dictionary<IScriptEngine, Timer> m_Timer =
new Dictionary<IScriptEngine, Timer>();
private static Dictionary<IScriptEngine, Listener> m_Listener =
new Dictionary<IScriptEngine, Listener>();
private static Dictionary<IScriptEngine, HttpRequest> m_HttpRequest =
new Dictionary<IScriptEngine, HttpRequest>();
private static Dictionary<IScriptEngine, SensorRepeat> m_SensorRepeat =
new Dictionary<IScriptEngine, SensorRepeat>();
private static Dictionary<IScriptEngine, XmlRequest> m_XmlRequest =
new Dictionary<IScriptEngine, XmlRequest>();
public Dataserver DataserverPlugin
{
get
{
lock (staticLock)
return m_Dataserver[m_ScriptEngine];
}
}
public Timer TimerPlugin
{
get
{
lock (staticLock)
return m_Timer[m_ScriptEngine];
}
}
public HttpRequest HttpRequestPlugin
{
get
{
lock (staticLock)
return m_HttpRequest[m_ScriptEngine];
}
}
public Listener ListenerPlugin
{
get
{
lock (staticLock)
return m_Listener[m_ScriptEngine];
}
}
public SensorRepeat SensorRepeatPlugin
{
get
{
lock (staticLock)
return m_SensorRepeat[m_ScriptEngine];
}
}
public XmlRequest XmlRequestPlugin
{
get
{
lock (staticLock)
return m_XmlRequest[m_ScriptEngine];
}
}
public IScriptEngine[] ScriptEngines
{
get
{
lock (staticLock)
return m_ScriptEngines.ToArray();
}
}
public AsyncCommandManager(IScriptEngine _ScriptEngine)
{
m_ScriptEngine = _ScriptEngine;
// If there is more than one scene in the simulator or multiple script engines are used on the same region
// then more than one thread could arrive at this block of code simultaneously. However, it cannot be
// executed concurrently both because concurrent list operations are not thread-safe and because of other
// race conditions such as the later check of cmdHandlerThread == null.
lock (staticLock)
{
if (m_ScriptEngines.Count == 0)
ReadConfig();
if (!m_ScriptEngines.Contains(m_ScriptEngine))
m_ScriptEngines.Add(m_ScriptEngine);
// Create instances of all plugins
if (!m_Dataserver.ContainsKey(m_ScriptEngine))
m_Dataserver[m_ScriptEngine] = new Dataserver(this);
if (!m_Timer.ContainsKey(m_ScriptEngine))
m_Timer[m_ScriptEngine] = new Timer(this);
if (!m_HttpRequest.ContainsKey(m_ScriptEngine))
m_HttpRequest[m_ScriptEngine] = new HttpRequest(this);
if (!m_Listener.ContainsKey(m_ScriptEngine))
m_Listener[m_ScriptEngine] = new Listener(this);
if (!m_SensorRepeat.ContainsKey(m_ScriptEngine))
m_SensorRepeat[m_ScriptEngine] = new SensorRepeat(this);
if (!m_XmlRequest.ContainsKey(m_ScriptEngine))
m_XmlRequest[m_ScriptEngine] = new XmlRequest(this);
StartThread();
}
}
private static void StartThread()
{
if (cmdHandlerThread == null)
{
// Start the thread that will be doing the work
cmdHandlerThread
= Watchdog.StartThread(
CmdHandlerThreadLoop, "AsyncLSLCmdHandlerThread", ThreadPriority.Normal, true, true);
}
}
private void ReadConfig()
{
// cmdHandlerThreadCycleSleepms = m_ScriptEngine.Config.GetInt("AsyncLLCommandLoopms", 100);
// TODO: Make this sane again
cmdHandlerThreadCycleSleepms = 100;
}
~AsyncCommandManager()
{
// Shut down thread
// try
// {
// if (cmdHandlerThread != null)
// {
// if (cmdHandlerThread.IsAlive == true)
// {
// cmdHandlerThread.Abort();
// //cmdHandlerThread.Join();
// }
// }
// }
// catch
// {
// }
}
/// <summary>
/// Main loop for the manager thread
/// </summary>
private static void CmdHandlerThreadLoop()
{
while (true)
{
try
{
Thread.Sleep(cmdHandlerThreadCycleSleepms);
DoOneCmdHandlerPass();
Watchdog.UpdateThread();
}
catch (Exception e)
{
m_log.Error("[ASYNC COMMAND MANAGER]: Exception in command handler pass: ", e);
}
}
}
private static void DoOneCmdHandlerPass()
{
lock (staticLock)
{
// Check HttpRequests
m_HttpRequest[m_ScriptEngines[0]].CheckHttpRequests();
// Check XMLRPCRequests
m_XmlRequest[m_ScriptEngines[0]].CheckXMLRPCRequests();
foreach (IScriptEngine s in m_ScriptEngines)
{
// Check Listeners
m_Listener[s].CheckListeners();
// Check timers
m_Timer[s].CheckTimerEvents();
// Check Sensors
m_SensorRepeat[s].CheckSenseRepeaterEvents();
// Check dataserver
m_Dataserver[s].ExpireRequests();
}
}
}
/// <summary>
/// Remove a specific script (and all its pending commands)
/// </summary>
/// <param name="localID"></param>
/// <param name="itemID"></param>
public static void RemoveScript(IScriptEngine engine, uint localID, UUID itemID)
{
// m_log.DebugFormat("[ASYNC COMMAND MANAGER]: Removing facilities for script {0}", itemID);
lock (staticLock)
{
// Remove dataserver events
m_Dataserver[engine].RemoveEvents(localID, itemID);
// Remove from: Timers
m_Timer[engine].UnSetTimerEvents(localID, itemID);
// Remove from: HttpRequest
IHttpRequestModule iHttpReq = engine.World.RequestModuleInterface<IHttpRequestModule>();
if (iHttpReq != null)
iHttpReq.StopHttpRequestsForScript(itemID);
IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>();
if (comms != null)
comms.DeleteListener(itemID);
IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>();
if (xmlrpc != null)
{
xmlrpc.DeleteChannels(itemID);
xmlrpc.CancelSRDRequests(itemID);
}
// Remove Sensors
m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID);
}
}
/// <summary>
/// Get the sensor repeat plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static SensorRepeat GetSensorRepeatPlugin(IScriptEngine engine)
{
lock (staticLock)
{
if (m_SensorRepeat.ContainsKey(engine))
return m_SensorRepeat[engine];
else
return null;
}
}
/// <summary>
/// Get the dataserver plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Dataserver GetDataserverPlugin(IScriptEngine engine)
{
lock (staticLock)
{
if (m_Dataserver.ContainsKey(engine))
return m_Dataserver[engine];
else
return null;
}
}
/// <summary>
/// Get the timer plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Timer GetTimerPlugin(IScriptEngine engine)
{
lock (staticLock)
{
if (m_Timer.ContainsKey(engine))
return m_Timer[engine];
else
return null;
}
}
/// <summary>
/// Get the listener plugin for this script engine.
/// </summary>
/// <param name="engine"></param>
/// <returns></returns>
public static Listener GetListenerPlugin(IScriptEngine engine)
{
lock (staticLock)
{
if (m_Listener.ContainsKey(engine))
return m_Listener[engine];
else
return null;
}
}
public static Object[] GetSerializationData(IScriptEngine engine, UUID itemID)
{
List<Object> data = new List<Object>();
lock (staticLock)
{
Object[] listeners = m_Listener[engine].GetSerializationData(itemID);
if (listeners.Length > 0)
{
data.Add("listener");
data.Add(listeners.Length);
data.AddRange(listeners);
}
Object[] timers=m_Timer[engine].GetSerializationData(itemID);
if (timers.Length > 0)
{
data.Add("timer");
data.Add(timers.Length);
data.AddRange(timers);
}
Object[] sensors = m_SensorRepeat[engine].GetSerializationData(itemID);
if (sensors.Length > 0)
{
data.Add("sensor");
data.Add(sensors.Length);
data.AddRange(sensors);
}
}
return data.ToArray();
}
public static void CreateFromData(IScriptEngine engine, uint localID,
UUID itemID, UUID hostID, Object[] data)
{
int idx = 0;
int len;
while (idx < data.Length)
{
string type = data[idx].ToString();
len = (int)data[idx+1];
idx+=2;
if (len > 0)
{
Object[] item = new Object[len];
Array.Copy(data, idx, item, 0, len);
idx+=len;
lock (staticLock)
{
switch (type)
{
case "listener":
m_Listener[engine].CreateFromData(localID, itemID,
hostID, item);
break;
case "timer":
m_Timer[engine].CreateFromData(localID, itemID,
hostID, item);
break;
case "sensor":
m_SensorRepeat[engine].CreateFromData(localID,
itemID, hostID, item);
break;
}
}
}
}
}
}
}
| |
using System;
using System.Data;
using System.Linq;
namespace NetGore.Db
{
public class DataReaderContainer : IDataReader
{
IDataReader _dataReader;
/// <summary>
/// Initializes a new instance of the <see cref="DataReaderContainer"/> class.
/// </summary>
/// <param name="dataReader">The <see cref="IDataReader"/> to use.</param>
/// <exception cref="ArgumentNullException"><paramref name="dataReader" /> is <c>null</c>.</exception>
public DataReaderContainer(IDataReader dataReader)
{
if (dataReader == null)
throw new ArgumentNullException("dataReader");
_dataReader = dataReader;
}
/// <summary>
/// Initializes a new instance of the <see cref="DataReaderContainer"/> class.
/// </summary>
protected DataReaderContainer()
{
}
/// <summary>
/// Gets or sets the <see cref="IDataReader"/> to use.
/// </summary>
protected IDataReader DataReader
{
get { return _dataReader; }
set { _dataReader = value; }
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposeManaged"><c>true</c> to release both managed and unmanaged resources;
/// <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposeManaged)
{
if (disposeManaged)
{
if (DataReader != null)
DataReader.Dispose();
}
}
#region IDataReader Members
/// <summary>
/// Gets the column located at the specified index.
/// </summary>
/// <returns>
/// The column located at the specified index as an <see cref="T:System.Object"/>.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public object this[int i]
{
get { return _dataReader[i]; }
}
/// <summary>
/// Gets the column with the specified name.
/// </summary>
/// <returns>
/// The column with the specified name as an <see cref="T:System.Object"/>.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// No column with the specified name was found.
/// </exception>
public object this[string name]
{
get { return _dataReader[name]; }
}
/// <summary>
/// Gets a value indicating the depth of nesting for the current row.
/// </summary>
/// <returns>
/// The level of nesting.
/// </returns>
public int Depth
{
get { return _dataReader.Depth; }
}
/// <summary>
/// Gets the number of columns in the current row.
/// </summary>
/// <returns>
/// When not positioned in a valid recordset, 0; otherwise, the number of columns in the current record. The default is -1.
/// </returns>
public int FieldCount
{
get { return _dataReader.FieldCount; }
}
/// <summary>
/// Gets a value indicating whether the data reader is closed.
/// </summary>
/// <returns>
/// true if the data reader is closed; otherwise, false.
/// </returns>
public bool IsClosed
{
get { return _dataReader.IsClosed; }
}
/// <summary>
/// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement.
/// </summary>
/// <returns>
/// The number of rows changed, inserted, or deleted; 0 if no rows were affected or the statement failed; and -1 for SELECT statements.
/// </returns>
public int RecordsAffected
{
get { return _dataReader.RecordsAffected; }
}
/// <summary>
/// Closes the <see cref="T:System.Data.IDataReader"/> Object.
/// </summary>
public void Close()
{
_dataReader.Close();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public virtual void Dispose()
{
Dispose(true);
}
/// <summary>
/// Gets the value of the specified column as a Boolean.
/// </summary>
/// <param name="i">The zero-based column ordinal.</param>
/// <returns>The value of the column.</returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public bool GetBoolean(int i)
{
return _dataReader.GetBoolean(i);
}
/// <summary>
/// Gets the 8-bit unsigned integer value of the specified column.
/// </summary>
/// <param name="i">The zero-based column ordinal.</param>
/// <returns>
/// The 8-bit unsigned integer value of the specified column.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public byte GetByte(int i)
{
return _dataReader.GetByte(i);
}
/// <summary>
/// Reads a stream of bytes from the specified column offset into the buffer as an array, starting at the given buffer offset.
/// </summary>
/// <param name="i">The zero-based column ordinal.</param>
/// <param name="fieldOffset">The index within the field from which to start the read operation.</param>
/// <param name="buffer">The buffer into which to read the stream of bytes.</param>
/// <param name="bufferoffset">The index for <paramref name="buffer"/> to start the read operation.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>The actual number of bytes read.</returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
return _dataReader.GetBytes(i, fieldOffset, buffer, bufferoffset, length);
}
/// <summary>
/// Gets the character value of the specified column.
/// </summary>
/// <param name="i">The zero-based column ordinal.</param>
/// <returns>
/// The character value of the specified column.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public char GetChar(int i)
{
return _dataReader.GetChar(i);
}
/// <summary>
/// Reads a stream of characters from the specified column offset into the buffer as an array, starting at the given buffer offset.
/// </summary>
/// <param name="i">The zero-based column ordinal.</param>
/// <param name="fieldoffset">The index within the row from which to start the read operation.</param>
/// <param name="buffer">The buffer into which to read the stream of bytes.</param>
/// <param name="bufferoffset">The index for <paramref name="buffer"/> to start the read operation.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>The actual number of characters read.</returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
return _dataReader.GetChars(i, fieldoffset, buffer, bufferoffset, length);
}
/// <summary>
/// Returns an <see cref="T:System.Data.IDataReader"/> for the specified column ordinal.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// An <see cref="T:System.Data.IDataReader"/>.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public IDataReader GetData(int i)
{
return _dataReader.GetData(i);
}
/// <summary>
/// Gets the data type information for the specified field.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// The data type information for the specified field.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public string GetDataTypeName(int i)
{
return _dataReader.GetDataTypeName(i);
}
/// <summary>
/// Gets the date and time data value of the specified field.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// The date and time data value of the specified field.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public DateTime GetDateTime(int i)
{
return _dataReader.GetDateTime(i);
}
/// <summary>
/// Gets the fixed-position numeric value of the specified field.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// The fixed-position numeric value of the specified field.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public decimal GetDecimal(int i)
{
return _dataReader.GetDecimal(i);
}
/// <summary>
/// Gets the double-precision floating point number of the specified field.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// The double-precision floating point number of the specified field.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public double GetDouble(int i)
{
return _dataReader.GetDouble(i);
}
/// <summary>
/// Gets the <see cref="T:System.Type"/> information corresponding to the type of <see cref="T:System.Object"/> that would be returned from <see cref="M:System.Data.IDataRecord.GetValue(System.Int32)"/>.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// The <see cref="T:System.Type"/> information corresponding to the type of <see cref="T:System.Object"/> that would be returned from <see cref="M:System.Data.IDataRecord.GetValue(System.Int32)"/>.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public Type GetFieldType(int i)
{
return _dataReader.GetFieldType(i);
}
/// <summary>
/// Gets the single-precision floating point number of the specified field.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// The single-precision floating point number of the specified field.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public float GetFloat(int i)
{
return _dataReader.GetFloat(i);
}
/// <summary>
/// Returns the GUID value of the specified field.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>The GUID value of the specified field.</returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public Guid GetGuid(int i)
{
return _dataReader.GetGuid(i);
}
/// <summary>
/// Gets the 16-bit signed integer value of the specified field.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// The 16-bit signed integer value of the specified field.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public short GetInt16(int i)
{
return _dataReader.GetInt16(i);
}
/// <summary>
/// Gets the 32-bit signed integer value of the specified field.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// The 32-bit signed integer value of the specified field.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public int GetInt32(int i)
{
return _dataReader.GetInt32(i);
}
/// <summary>
/// Gets the 64-bit signed integer value of the specified field.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// The 64-bit signed integer value of the specified field.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public long GetInt64(int i)
{
return _dataReader.GetInt64(i);
}
/// <summary>
/// Gets the name for the field to find.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// The name of the field or the empty string (""), if there is no value to return.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public string GetName(int i)
{
return _dataReader.GetName(i);
}
/// <summary>
/// Return the index of the named field.
/// </summary>
/// <param name="name">The name of the field to find.</param>
/// <returns>The index of the named field.</returns>
public int GetOrdinal(string name)
{
return _dataReader.GetOrdinal(name);
}
/// <summary>
/// Returns a <see cref="T:System.Data.DataTable"/> that describes the column metadata of the <see cref="T:System.Data.IDataReader"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.Data.DataTable"/> that describes the column metadata.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The <see cref="T:System.Data.IDataReader"/> is closed.
/// </exception>
public DataTable GetSchemaTable()
{
return _dataReader.GetSchemaTable();
}
/// <summary>
/// Gets the string value of the specified field.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>The string value of the specified field.</returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public string GetString(int i)
{
return _dataReader.GetString(i);
}
/// <summary>
/// Return the value of the specified field.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// The <see cref="T:System.Object"/> which will contain the field value upon return.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public object GetValue(int i)
{
return _dataReader.GetValue(i);
}
/// <summary>
/// Gets all the attribute fields in the collection for the current record.
/// </summary>
/// <param name="values">An array of <see cref="T:System.Object"/> to copy the attribute fields into.</param>
/// <returns>
/// The number of instances of <see cref="T:System.Object"/> in the array.
/// </returns>
public int GetValues(object[] values)
{
return _dataReader.GetValues(values);
}
/// <summary>
/// Return whether the specified field is set to null.
/// </summary>
/// <param name="i">The index of the field to find.</param>
/// <returns>
/// true if the specified field is set to null; otherwise, false.
/// </returns>
/// <exception cref="T:System.IndexOutOfRangeException">
/// The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
/// </exception>
public bool IsDBNull(int i)
{
return _dataReader.IsDBNull(i);
}
/// <summary>
/// Advances the data reader to the next result, when reading the results of batch SQL statements.
/// </summary>
/// <returns>
/// true if there are more rows; otherwise, false.
/// </returns>
public bool NextResult()
{
return _dataReader.NextResult();
}
/// <summary>
/// Advances the <see cref="T:System.Data.IDataReader"/> to the next record.
/// </summary>
/// <returns>
/// true if there are more rows; otherwise, false.
/// </returns>
public bool Read()
{
return _dataReader.Read();
}
#endregion
}
}
| |
// SharpZipLibrary samples
//
// $Id$
// $URL$
//
// Copyright (c) 2007, AlphaSierraPapa
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// - Neither the name of the SharpDevelop team 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.
// Define test to add more detailed Console.WriteLine style information
// #define TEST
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Reflection;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
namespace ICSharpCode.SharpZipLib.Samples.SZ
{
/// <summary>
/// A command line archiver using the SharpZipLib compression library
/// </summary>
public class SharpZipArchiver {
/// <summary>
/// Options for handling overwriting of files.
/// </summary>
enum Overwrite {
Prompt,
Never,
Always
}
/// <summary>
/// The operations that can be performed.
/// </summary>
enum Operation
{
Create, // add files to new archive
Extract, // extract files from existing archive
List, // show contents of existing archive
Delete, // Delete from archive
Add, // Add to archive.
Test, // Test the archive for validity.
}
/// <summary>
/// Interpret attributes based on the operating system they are from.
/// </summary>
/// <param name="operatingSystem">The operating system to base interpretation of attributes on.</param>
/// <param name="attributes">The external attributes.</param>
/// <returns>A string representation of the attributres passed.</returns>
static string InterpretExternalAttributes(int operatingSystem, int attributes)
{
string result = string.Empty;
if ((operatingSystem == 0) || (operatingSystem == 10)) {
// Directory
if ((attributes & 0x10) != 0)
result = result + "D";
else
result = result + "-";
// Volume
if ((attributes & 0x08) != 0)
result = result + "V";
else
result = result + "-";
// Read-only
if ((attributes & 0x01) != 0)
result = result + "r";
else
result = result + "-";
// Archive
if ((attributes & 0x20) != 0)
result = result + "a";
else
result = result + "-";
// System
if ((attributes & 0x04) != 0)
result = result + "s";
else
result = result + "-";
// Hidden
if ((attributes & 0x02) != 0)
result = result + "h";
else
result = result + "-";
// Device
if ((attributes & 0x4) != 0)
result = result + "d";
else
result = result + "-";
// OS is NTFS
if ( operatingSystem == 10 )
{
// Encrypted
if ( (attributes & 0x4000) != 0 ) {
result += "E";
}
else {
result += "-";
}
// Not content indexed
if ( (attributes & 0x2000) != 0 ) {
result += "n";
}
else {
result += "-";
}
// Offline
if ( (attributes & 0x1000) != 0 ) {
result += "O";
}
else {
result += "-";
}
// Compressed
if ( (attributes & 0x0800) != 0 ) {
result += "C";
}
else {
result += "-";
}
// Reparse point
if ( (attributes & 0x0400) != 0 ) {
result += "R";
}
else {
result += "-";
}
// Sparse
if ( (attributes & 0x0200) != 0 ) {
result += "S";
}
else {
result += "-";
}
// Temporary
if ( (attributes & 0x0100) != 0 ) {
result += "T";
}
else {
result += "-";
}
}
}
return result;
}
/// <summary>
/// Determine if string is numeric [0-9]+
/// </summary>
/// <param name="rhs">string to test</param>
/// <returns>true iff rhs is numeric</returns>
static bool IsNumeric(string rhs)
{
bool result;
if ((rhs != null) && (rhs.Length > 0)) {
result = true;
for (int i = 0; result && (i < rhs.Length); ++i) {
if (!char.IsDigit(rhs[i])) {
result = false;
}
}
} else {
result = false;
}
return result;
}
/// <summary>
/// Parse command line arguments.
/// This is fairly flexible without using any custom classes. Arguments and options can appear
/// in any order and are case insensitive. Arguments for options are indicated with an '='
/// as in -demo=argument, sometimes the '=' can be omitted as well secretly.
/// Grouping of single character options is supported.
///
/// The actual arguments and their handling is however a grab bag of ad-hoc things and its a bit messy. Could be a
/// bit more rigorous about how things are done. Up side is almost anything is/can be allowed
/// </summary>
/// <returns>
/// <c>true</c> if arguments are valid such that processing should continue
/// </returns>
bool SetArgs(string[] args) {
bool result = true;
int argIndex = 0;
while (argIndex < args.Length) {
if (args[argIndex][0] == '-' || args[argIndex][0] == '/') {
string option = args[argIndex].Substring(1).ToLower();
string optArg = "";
int parameterIndex = option.IndexOf('=');
if (parameterIndex >= 0) {
if (parameterIndex < option.Length - 1) {
optArg = option.Substring(parameterIndex + 1);
}
option = option.Substring(0, parameterIndex);
}
if (option.Length == 0) {
Console.WriteLine("Invalid argument {0}", args[argIndex]);
result = false;
}
else {
int optionIndex = 0;
while (optionIndex < option.Length) {
switch(option[optionIndex]) {
case '-': // long option
optionIndex = option.Length;
switch (option) {
case "-abs":
relativePathInfo = false;
break;
case "-add":
operation = Operation.Add;
break;
case "-create":
operation = Operation.Create;
break;
case "-list":
operation = Operation.List;
useZipFileWhenListing = true;
break;
case "-extract":
operation = Operation.Extract;
if (optArg.Length > 0) {
targetOutputDirectory = optArg;
}
break;
case "-delete":
operation = Operation.Delete;
break;
case "-test":
operation = Operation.Test;
break;
case "-info":
ShowEnvironment();
break;
case "-emptydirs":
addEmptyDirectoryEntries = true;
break;
case "-data":
testData = true;
break;
case "-extractdir":
if (optArg.Length > 0) {
targetOutputDirectory = optArg;
} else {
result = false;
Console.WriteLine("Invalid extractdir " + args[argIndex]);
}
break;
case "-zip64":
if ( optArg.Length > 0 ) {
switch ( optArg ) {
case "on":
useZip64_ = UseZip64.On;
break;
case "off":
useZip64_ = UseZip64.Off;
break;
case "auto":
useZip64_ = UseZip64.Dynamic;
break;
}
}
break;
case "-encoding":
if (optArg.Length > 0) {
if (IsNumeric(optArg)) {
try {
int enc = int.Parse(optArg);
if (Encoding.GetEncoding(enc) != null) {
ZipConstants.DefaultCodePage = enc;
} else {
result = false;
Console.WriteLine("Invalid encoding " + args[argIndex]);
}
}
catch (Exception) {
result = false;
Console.WriteLine("Invalid encoding " + args[argIndex]);
}
} else {
try {
ZipConstants.DefaultCodePage = Encoding.GetEncoding(optArg).CodePage;
}
catch (Exception) {
result = false;
Console.WriteLine("Invalid encoding " + args[argIndex]);
}
}
} else {
result = false;
Console.WriteLine("Missing encoding parameter");
}
break;
case "-store":
useZipStored = true;
break;
case "-deflate":
useZipStored = false;
break;
case "-version":
ShowVersion();
break;
case "-help":
ShowHelp();
break;
#if !NETCF
case "-restore-dates":
restoreDateTime = true;
break;
#endif
default:
Console.WriteLine("Invalid long argument " + args[argIndex]);
result = false;
break;
}
break;
case '?':
ShowHelp();
break;
case 's':
if (optionIndex != 0) {
result = false;
Console.WriteLine("-s cannot be in a group");
} else {
if (optArg.Length > 0) {
password = optArg;
} else if (option.Length > 1) {
password = option.Substring(1);
} else {
Console.WriteLine("Missing argument to " + args[argIndex]);
}
}
optionIndex = option.Length;
break;
case 'c':
operation = Operation.Create;
break;
case 'l':
if (optionIndex != 0) {
result = false;
Console.WriteLine("-l cannot be in a group");
} else {
if (optArg.Length > 0) {
try {
compressionLevel = int.Parse(optArg);
}
catch (Exception) {
Console.WriteLine("Level invalid");
}
}
}
optionIndex = option.Length;
break;
case 'o':
optionIndex += 1;
overwriteFiles = (optionIndex < option.Length) ? (option[optionIndex] == '+') ? Overwrite.Always : Overwrite.Never : Overwrite.Never;
break;
case 'p':
relativePathInfo = true;
break;
case 'q':
silent = true;
if (overwriteFiles == Overwrite.Prompt) {
overwriteFiles = Overwrite.Never;
}
break;
case 'r':
recursive = true;
break;
case 'v':
operation = Operation.List;
break;
case 'x':
if (optionIndex != 0) {
result = false;
Console.WriteLine("-x cannot be in a group");
} else {
operation = Operation.Extract;
if (optArg.Length > 0) {
targetOutputDirectory = optArg;
}
}
optionIndex = option.Length;
break;
default:
Console.WriteLine("Invalid argument: " + args[argIndex]);
result = false;
break;
}
++optionIndex;
}
}
}
else {
fileSpecs.Add(args[argIndex]);
}
++argIndex;
}
if (fileSpecs.Count > 0 && operation == Operation.Create) {
string checkPath = (string)fileSpecs[0];
int deviceCheck = checkPath.IndexOf(':');
#if NETCF_1_0
if (checkPath.IndexOfAny(Path.InvalidPathChars) >= 0
#else
if (checkPath.IndexOfAny(Path.GetInvalidPathChars()) >= 0
#endif
|| checkPath.IndexOf('*') >= 0 || checkPath.IndexOf('?') >= 0
|| (deviceCheck >= 0 && deviceCheck != 1)) {
Console.WriteLine("There are invalid characters in the specified zip file name");
result = false;
}
}
return result && (fileSpecs.Count > 0);
}
/// <summary>
/// Show encoding/locale information
/// </summary>
void ShowEnvironment()
{
seenHelp = true;
#if !NETCF_1_0
Console.WriteLine(
"Current encoding is {0}, code page {1}, windows code page {2}",
Console.Out.Encoding.EncodingName,
Console.Out.Encoding.CodePage,
Console.Out.Encoding.WindowsCodePage);
Console.WriteLine("Default code page is {0}",
Encoding.Default.CodePage);
Console.WriteLine( "Current culture LCID 0x{0:X}, {1}", CultureInfo.CurrentCulture.LCID, CultureInfo.CurrentCulture.EnglishName);
Console.WriteLine( "Current thread OEM codepage {0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage);
Console.WriteLine( "Current thread Mac codepage {0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.MacCodePage);
Console.WriteLine( "Current thread Ansi codepage {0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage);
#endif
}
/// <summary>
/// Display version information
/// </summary>
void ShowVersion() {
seenHelp = true;
Console.WriteLine("SharpZip Archiver v0.37 Copyright 2004 John Reilly");
#if !NETCF
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies) {
if (assembly.GetName().Name == "ICSharpCode.SharpZipLib") {
Console.WriteLine("#ZipLib v{0} {1}", assembly.GetName().Version,
assembly.GlobalAssemblyCache ? "Running from GAC" : "Running from DLL"
);
}
}
#endif
}
/// <summary>
/// Show help on possible options and arguments
/// </summary>
void ShowHelp()
{
if (seenHelp) {
return;
}
seenHelp = true;
ShowVersion();
Console.WriteLine("usage sz {options} archive files");
Console.WriteLine("");
Console.WriteLine("Options:");
Console.WriteLine("-abs Store absolute path info");
Console.WriteLine("-?, --help Show this help");
Console.WriteLine("-c --create Create new archive");
Console.WriteLine("-v List archive contents (default)");
Console.WriteLine("--list List archive contents extended format");
Console.WriteLine("-x{=dir}, --extract{=dir} Extract archive contents to dir(default .)");
Console.WriteLine("--extractdir=path Set extract directory (default .)");
Console.WriteLine("--info Show current environment information" );
Console.WriteLine("--store Store entries (default=deflate)");
Console.WriteLine("--version Show version information");
Console.WriteLine("--emptydirs Create entries for empty directories");
Console.WriteLine("--encoding=codepage|name Set code page for encoding by name or number");
Console.WriteLine("--zip64=on|off|auto Set use zip64 flag (default is auto)");
#if !NETCF
Console.WriteLine("--restore-dates Restore dates on extraction");
#endif
Console.WriteLine("--delete Delete files from archive");
Console.WriteLine("--test Test archive for validity");
Console.WriteLine("--data Test archive data");
Console.WriteLine("--add Add files to archive");
Console.WriteLine("-o+ Overwrite files without prompting");
Console.WriteLine("-o- Never overwrite files");
Console.WriteLine("-p Store relative path info (default)");
Console.WriteLine("-r Recurse sub-folders");
Console.WriteLine("-q Quiet mode");
Console.WriteLine("-s=password Set archive password");
Console.WriteLine("-l=level Use compression level (0-9) when compressing");
Console.WriteLine("");
}
///<summary>
/// Calculate compression ratio as a percentage
/// Doesnt allow for expansion (ratio > 100) as the resulting strings can get huge easily
/// </summary>
static int GetCompressionRatio(long packedSize, long unpackedSize)
{
int result = 0;
if (unpackedSize > 0 && unpackedSize >= packedSize) {
result = (int) Math.Round((1.0 - ((double)packedSize / (double)unpackedSize)) * 100.0);
}
return result;
}
/// <summary>
/// List zip file contents using stream
/// </summary>
/// <param name="fileName">File to list contents of</param>
void ListZip(string fileName) {
try {
// TODO for asian/non-latin/non-proportional fonts string lengths dont work so output may not line up
const string headerTitles = "Name Length Ratio Size Date & time CRC-32";
const string headerUnderline = "--------------- ---------- ----- ---------- ------------------- --------";
FileInfo fileInfo = new FileInfo(fileName);
if (fileInfo.Exists == false) {
Console.WriteLine("No such file exists {0}", fileName);
return;
}
Console.WriteLine(fileName);
using (FileStream fileStream = File.OpenRead(fileName)) {
using (ZipInputStream stream = new ZipInputStream(fileStream)) {
if ((password != null) && (password.Length > 0)) {
stream.Password = password;
}
int entryCount = 0;
long totalSize = 0;
ZipEntry theEntry;
while ((theEntry = stream.GetNextEntry()) != null) {
if ( theEntry.IsDirectory ) {
Console.WriteLine("Directory {0}", theEntry.Name);
continue;
}
if ( !theEntry.IsFile ) {
Console.WriteLine("Non file entry {0}", theEntry.Name);
continue;
}
if (entryCount == 0) {
Console.WriteLine(headerTitles);
Console.WriteLine(headerUnderline);
}
++entryCount;
int ratio = GetCompressionRatio(theEntry.CompressedSize, theEntry.Size);
totalSize += theEntry.Size;
if (theEntry.Name.Length > 15) {
Console.WriteLine(theEntry.Name);
Console.WriteLine(
"{0,-15} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss} {5,8:x}",
"", theEntry.Size, ratio, theEntry.CompressedSize, theEntry.DateTime, theEntry.Crc);
} else {
Console.WriteLine(
"{0,-15} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss} {5,8:x}",
theEntry.Name, theEntry.Size, ratio, theEntry.CompressedSize, theEntry.DateTime, theEntry.Crc);
}
}
if (entryCount == 0) {
Console.WriteLine("Archive is empty!");
} else {
Console.WriteLine(headerUnderline);
Console.WriteLine(
"{0,-15} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss}",
entryCount + " entries", totalSize, GetCompressionRatio(fileInfo.Length, totalSize), fileInfo.Length, fileInfo.LastWriteTime);
}
}
}
}
catch(Exception exception)
{
Console.WriteLine("Exception during list operation: {0}", exception.Message);
}
}
/// <summary>
/// List zip file contents using <see cref="ZipFile"/> class
/// </summary>
/// <param name="fileName">File to list contents of</param>
void ListZipViaZipFile(string fileName) {
try {
const string headerTitles = "Name Length Ratio Size Date & time CRC-32 Attr";
const string headerUnderline = "------------ ---------- ----- ---------- ------------------- -------- ------";
FileInfo fileInfo = new FileInfo(fileName);
if (fileInfo.Exists == false) {
Console.WriteLine("No such file exists {0}", fileName);
return;
}
Console.WriteLine(fileName);
int entryCount = 0;
long totalSize = 0;
using (ZipFile zipFile = new ZipFile(fileName)) {
foreach (ZipEntry theEntry in zipFile) {
if ( theEntry.IsDirectory ) {
Console.WriteLine("Directory {0}", theEntry.Name);
}
else if ( !theEntry.IsFile ) {
Console.WriteLine("Non file entry {0}", theEntry.Name);
continue;
}
else {
if (entryCount == 0) {
Console.WriteLine(headerTitles);
Console.WriteLine(headerUnderline);
}
++entryCount;
int ratio = GetCompressionRatio(theEntry.CompressedSize, theEntry.Size);
totalSize += theEntry.Size;
if (theEntry.Name.Length > 12) {
Console.WriteLine(theEntry.Name);
Console.WriteLine(
"{0,-12} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss} {5,8:x} {6,4}",
"", theEntry.Size, ratio, theEntry.CompressedSize, theEntry.DateTime, theEntry.Crc,
InterpretExternalAttributes(theEntry.HostSystem, theEntry.ExternalFileAttributes));
}
else {
Console.WriteLine(
"{0,-12} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss} {5,8:x} {6,4}",
theEntry.Name, theEntry.Size, ratio, theEntry.CompressedSize, theEntry.DateTime, theEntry.Crc,
InterpretExternalAttributes(theEntry.HostSystem, theEntry.ExternalFileAttributes));
}
}
}
}
if (entryCount == 0) {
Console.WriteLine("Archive is empty!");
} else {
Console.WriteLine(headerUnderline);
Console.WriteLine(
"{0,-12} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss}",
entryCount + " entries", totalSize, GetCompressionRatio(fileInfo.Length, totalSize), fileInfo.Length, fileInfo.LastWriteTime);
}
}
catch(Exception exception) {
Console.WriteLine("Exception during list operation: {0}", exception.Message);
}
}
/// <summary>
/// Execute List operation
/// Currently only Zip files are supported
/// </summary>
/// <param name="fileSpecifications">Files to list</param>
void List(ArrayList fileSpecifications)
{
foreach (string spec in fileSpecifications) {
string [] names;
string pathName = Path.GetDirectoryName(spec);
if ( (pathName == null) || (pathName.Length == 0) ) {
pathName = @".\";
}
names = Directory.GetFiles(pathName, Path.GetFileName(spec));
if (names.Length == 0) {
Console.WriteLine("No files found matching {0}", spec);
}
else {
foreach (string file in names) {
if (useZipFileWhenListing) {
ListZipViaZipFile(file);
} else {
ListZip(file);
}
Console.WriteLine("");
}
}
}
}
/// <summary>
/// 'Cook' a name making it acceptable as a zip entry name.
/// </summary>
/// <param name="name">name to cook</param>
/// <param name="stripPrefix">String to remove from front of name if present</param>
/// <param name="relativePath">Make names relative if <c>true</c> or absolute if <c>false</c></param>
static public string CookZipEntryName(string name, string stripPrefix, bool relativePath)
{
#if TEST
Console.WriteLine("Cooking '{0}' prefix is '{1}'", name, stripPrefix);
#endif
if (name == null) {
return "";
}
if (stripPrefix != null && stripPrefix.Length > 0 && name.IndexOf(stripPrefix, 0) == 0) {
name = name.Substring(stripPrefix.Length);
}
if (Path.IsPathRooted(name)) {
// NOTE:
// for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt
name = name.Substring(Path.GetPathRoot(name).Length);
#if TEST
Console.WriteLine("Removing root info {0}", name);
#endif
}
name = name.Replace(@"\", "/");
if (relativePath) {
if (name.Length > 0 && (name[0] == Path.AltDirectorySeparatorChar || name[0] == Path.DirectorySeparatorChar)) {
name = name.Remove(0, 1);
}
} else {
if (name.Length > 0 && name[0] != Path.AltDirectorySeparatorChar && name[0] != Path.DirectorySeparatorChar) {
name = name.Insert(0, "/");
}
}
#if TEST
Console.WriteLine("Cooked value '{0}'", name);
#endif
return name;
}
/// <summary>
/// Make string into something acceptable as an entry name
/// </summary>
/// <param name="name">Name to 'cook'</param>
string CookZipEntryName(string name)
{
return CookZipEntryName(name, removablePathPrefix, relativePathInfo);
}
// TODO: Add equivalent for non-seekable output
/// <summary>
/// Add a file were the output is seekable
/// </summary>
void AddFileSeekableOutput(string file, string entryPath)
{
ZipEntry entry = new ZipEntry(entryPath);
FileInfo fileInfo = new FileInfo(file);
entry.DateTime = fileInfo.LastWriteTime; // or DateTime.Now or whatever, for now use the file
entry.ExternalFileAttributes = (int)fileInfo.Attributes;
entry.Size = fileInfo.Length;
if (useZipStored) {
entry.CompressionMethod = CompressionMethod.Stored;
} else {
entry.CompressionMethod = CompressionMethod.Deflated;
}
using (FileStream fileStream = File.OpenRead(file)) {
outputStream.PutNextEntry(entry);
StreamUtils.Copy(fileStream, outputStream, GetBuffer());
}
}
byte[] GetBuffer()
{
if ( buffer == null ) {
buffer = new byte[bufferSize_];
}
return buffer;
}
/// <summary>
/// Add file to archive
/// </summary>
/// <param name="fileName">file to add</param>
void AddFile(string fileName) {
#if TEST
Console.WriteLine("AddFile {0}", fileName);
#endif
if (File.Exists(fileName)) {
string entryName = CookZipEntryName(fileName);
if (silent == false) {
Console.Write(" " + entryName);
}
AddFileSeekableOutput(fileName, entryName);
if (silent == false) {
Console.WriteLine("");
}
} else {
Console.WriteLine("No such file exists {0}", fileName);
}
}
/// <summary>
/// Add an entry for a folder or directory
/// </summary>
/// <param name="folderName">The name of the folder to add</param>
void AddFolder(string folderName)
{
#if TEST
Console.WriteLine("AddFolder {0}", folderName);
#endif
folderName = CookZipEntryName(folderName);
if (folderName.Length == 0 || folderName[folderName.Length - 1] != '/') {
folderName = folderName + '/';
}
ZipEntry zipEntry = new ZipEntry(folderName);
outputStream.PutNextEntry(zipEntry);
}
/// <summary>
/// Compress contents of folder
/// </summary>
/// <param name="basePath">The folder to compress</param>
/// <param name="recursiveSearch">If true process recursively</param>
/// <param name="searchPattern">Pattern to match for files</param>
/// <returns>Number of entries added</returns>
int CompressFolder(string basePath, bool recursiveSearch, string searchPattern)
{
int result = 0;
#if TEST
Console.WriteLine("CompressFolder basepath {0} pattern {1}", basePath, searchPattern);
#endif
string [] names = Directory.GetFiles(basePath, searchPattern);
foreach (string fileName in names) {
AddFile(fileName);
++result;
}
if (names.Length == 0 && addEmptyDirectoryEntries) {
AddFolder(basePath);
++result;
}
if (recursiveSearch) {
names = Directory.GetDirectories(basePath);
foreach (string folderName in names) {
result += CompressFolder(folderName, true, searchPattern);
}
}
return result;
}
/// <summary>
/// Create archives based on specifications passed and internal state
/// </summary>
void Create(ArrayList fileSpecifications)
{
string zipFileName = fileSpecifications[0] as string;
if (Path.GetExtension(zipFileName).Length == 0) {
zipFileName = Path.ChangeExtension(zipFileName, ".zip");
}
fileSpecifications.RemoveAt(0);
if (overwriteFiles == Overwrite.Never && File.Exists(zipFileName)) {
Console.WriteLine("File {0} already exists", zipFileName);
return;
}
int totalEntries = 0;
using (FileStream stream = File.Create(zipFileName)) {
using (outputStream = new ZipOutputStream(stream)) {
if ((password != null) && (password.Length > 0)) {
outputStream.Password = password;
}
outputStream.UseZip64 = useZip64_;
outputStream.SetLevel(compressionLevel);
foreach(string spec in fileSpecifications) {
string fileName = Path.GetFileName(spec);
string pathName = Path.GetDirectoryName(spec);
if (pathName == null || pathName.Length == 0) {
pathName = Path.GetFullPath(".");
if (relativePathInfo == true) {
removablePathPrefix = pathName;
}
} else {
pathName = Path.GetFullPath(pathName);
// TODO: for paths like ./txt/*.txt the prefix should be fullpath for .
// for z:txt/*.txt should be fullpath for z:.
if (relativePathInfo == true) {
removablePathPrefix = pathName;
}
}
// TODO wildcards arent full supported by this
if (recursive || fileName.IndexOf('*') >= 0 || fileName.IndexOf('?') >= 0) {
// TODO this allows possible conflicts in filenames that are added to Zip file
// as part of different file specs.
totalEntries += CompressFolder(pathName, recursive, fileName);
} else {
AddFile(pathName + @"\" + fileName);
++totalEntries;
}
}
if (totalEntries == 0) {
Console.WriteLine("File created has no entries!");
}
}
}
}
bool ExtractFile(ZipInputStream inputStream, ZipEntry theEntry, string targetDir)
{
// try and sort out the correct place to save this entry
string entryFileName;
if (Path.IsPathRooted(theEntry.Name)) {
string workName = Path.GetPathRoot(theEntry.Name);
workName = theEntry.Name.Substring(workName.Length);
entryFileName = Path.Combine(Path.GetDirectoryName(workName), Path.GetFileName(theEntry.Name));
}
else {
entryFileName = theEntry.Name;
}
string targetName = Path.Combine(targetDir, entryFileName);
string fullPath = Path.GetDirectoryName(Path.GetFullPath(targetName));
#if TEST
Console.WriteLine("Decompress targetfile name " + entryFileName);
Console.WriteLine("Decompress targetpath " + fullPath);
#endif
// Could be an option or parameter to allow failure or try creation
if (Directory.Exists(fullPath) == false) {
try {
Directory.CreateDirectory(fullPath);
}
catch {
return false;
}
}
else if (overwriteFiles == Overwrite.Prompt) {
if (File.Exists(targetName) == true) {
Console.Write("File " + targetName + " already exists. Overwrite? ");
// TODO sort out the complexities of Read so single key presses can be used
string readValue;
try {
readValue = Console.ReadLine();
}
catch {
readValue = null;
}
if (readValue == null || readValue.ToLower() != "y") {
#if TEST
Console.WriteLine("Skipped!");
#endif
return true;
}
}
}
if (entryFileName.Length > 0) {
#if TEST
Console.WriteLine("Extracting...");
#endif
using (FileStream streamWriter = File.Create(targetName)) {
byte[] data = new byte[4096];
int size;
do {
size = inputStream.Read(data, 0, data.Length);
streamWriter.Write(data, 0, size);
} while (size > 0);
}
#if !NETCF
if (restoreDateTime) {
File.SetLastWriteTime(targetName, theEntry.DateTime);
}
#endif
}
return true;
}
void ExtractDirectory(ZipInputStream inputStream, ZipEntry theEntry, string targetDir)
{
// For now do nothing.
}
/// <summary>
/// Decompress a file
/// </summary>
/// <param name="fileName">File to decompress</param>
/// <param name="targetDir">Directory to create output in</param>
/// <returns>true iff all has been done successfully</returns>
bool DecompressFile(string fileName, string targetDir)
{
bool result = true;
try {
using (ZipInputStream inputStream = new ZipInputStream(File.OpenRead(fileName))) {
if (password != null) {
inputStream.Password = password;
}
ZipEntry theEntry;
while ((theEntry = inputStream.GetNextEntry()) != null) {
if ( theEntry.IsFile ) {
ExtractFile(inputStream, theEntry, targetDir);
}
else if ( theEntry.IsDirectory )
{
ExtractDirectory(inputStream, theEntry, targetDir);
}
}
}
}
catch (Exception except) {
result = false;
Console.WriteLine(except.Message + " Failed to unzip file");
}
return result;
}
/// <summary>
/// Extract archives based on user input
/// Allows simple wildcards to specify multiple archives
/// </summary>
void Extract(ArrayList fileSpecifications)
{
if (targetOutputDirectory == null || targetOutputDirectory.Length == 0) {
targetOutputDirectory = @".\";
}
foreach(string spec in fileSpecifications) {
string [] names;
if (spec.IndexOf('*') >= 0 || spec.IndexOf('?') >= 0) {
string pathName = Path.GetDirectoryName(spec);
if (pathName == null || pathName.Length == 0) {
pathName = @".\";
}
names = Directory.GetFiles(pathName, Path.GetFileName(spec));
} else {
names = new string[] { spec };
}
foreach (string fileName in names) {
if (File.Exists(fileName) == false) {
Console.WriteLine("No such file exists {0}", spec);
} else {
DecompressFile(fileName, targetOutputDirectory);
}
}
}
}
void Test(ArrayList fileSpecs)
{
string zipFileName = fileSpecs[0] as string;
if (Path.GetExtension(zipFileName).Length == 0) {
zipFileName = Path.ChangeExtension(zipFileName, ".zip");
}
using (ZipFile zipFile = new ZipFile(zipFileName)) {
if ( zipFile.TestArchive(testData) ) {
Console.WriteLine("Archive test passed");
} else {
Console.WriteLine("Archive test failure");
}
}
}
/// <summary>
/// Delete entries from an archive
/// </summary>
/// <param name="fileSpecs">The file specs to operate on.</param>
void Delete(ArrayList fileSpecs)
{
string zipFileName = fileSpecs[0] as string;
if (Path.GetExtension(zipFileName).Length == 0) {
zipFileName = Path.ChangeExtension(zipFileName, ".zip");
}
using (ZipFile zipFile = new ZipFile(zipFileName)) {
zipFile.BeginUpdate();
for ( int i = 1; i < fileSpecs.Count; ++i ) {
zipFile.Delete((string)fileSpecs[i]);
}
zipFile.CommitUpdate();
}
}
void Add(ArrayList fileSpecs)
{
string zipFileName = fileSpecs[0] as string;
if (Path.GetExtension(zipFileName).Length == 0) {
zipFileName = Path.ChangeExtension(zipFileName, ".zip");
}
using (ZipFile zipFile = new ZipFile(zipFileName)) {
zipFile.BeginUpdate();
for ( int i = 1; i < fileSpecs.Count; ++i ) {
zipFile.Add((string)fileSpecs[i]);
}
zipFile.CommitUpdate();
}
}
/// <summary>
/// Parse command line arguments and 'execute' them.
/// </summary>
void Execute(string[] args) {
if (SetArgs(args)) {
if (fileSpecs.Count == 0) {
if (!silent) {
Console.WriteLine("Nothing to do");
}
}
else {
switch (operation) {
case Operation.List:
List(fileSpecs);
break;
case Operation.Create:
Create(fileSpecs);
break;
case Operation.Extract:
Extract(fileSpecs);
break;
case Operation.Delete:
Delete(fileSpecs);
break;
case Operation.Add:
Add(fileSpecs);
break;
case Operation.Test:
Test(fileSpecs);
break;
}
}
} else {
if (!silent) {
ShowHelp();
}
}
}
/// <summary>
/// Entry point for program, creates archiver and runs it
/// </summary>
/// <param name="args">
/// Command line argument to process
/// </param>
public static void Main(string[] args) {
SharpZipArchiver sza = new SharpZipArchiver();
sza.Execute(args);
}
#region Instance Fields
/// <summary>
/// The Zip64 extension use to apply.
/// </summary>
UseZip64 useZip64_ = UseZip64.Off;
/// <summary>
/// Has user already seen help output?
/// </summary>
bool seenHelp;
/// <summary>
/// The size of the buffer to use when copying.
/// </summary>
int bufferSize_ = 8192;
/// <summary>
/// Buffer for use when copying between streams.
/// </summary>
byte[] buffer;
/// <summary>
/// File specification possibly with wildcards from command line
/// </summary>
ArrayList fileSpecs = new ArrayList();
/// <summary>
/// Deflate compression level
/// </summary>
int compressionLevel = Deflater.DEFAULT_COMPRESSION;
/// <summary>
/// Create entries for directories with no files
/// </summary>
bool addEmptyDirectoryEntries;
/// <summary>
/// Apply operations recursively
/// </summary>
bool recursive;
/// <summary>
/// Use ZipFile class for listing entries
/// </summary>
bool useZipFileWhenListing;
/// <summary>
/// Use relative path information
/// </summary>
bool relativePathInfo = true;
/// <summary>
/// Operate silently
/// </summary>
bool silent;
/// <summary>
/// Use store rather than deflate when adding files, not likely to be used much
/// but it does exercise the option as the library supports it
/// </summary>
bool useZipStored;
#if !NETCF
/// <summary>
/// Restore file date and time to that stored in zip file on extraction
/// </summary>
bool restoreDateTime;
#endif
/// <summary>
/// Overwrite files handling
/// </summary>
Overwrite overwriteFiles = Overwrite.Prompt;
/// <summary>
/// Optional password for archive
/// </summary>
string password;
/// <summary>
/// prefix to remove when creating relative path names
/// </summary>
string removablePathPrefix;
/// <summary>
/// Where things will go
/// </summary>
string targetOutputDirectory;
/// <summary>
/// What to do based on parsed command line arguments
/// </summary>
Operation operation = Operation.List;
/// <summary>
/// Flag indicating wether entry data should be included when testing.
/// </summary>
bool testData;
/// <summary>
/// stream used when creating archives.
/// </summary>
ZipOutputStream outputStream;
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
class AndMessageFilterTable<FilterData> : IMessageFilterTable<FilterData>
{
Dictionary<MessageFilter, FilterData> filters;
Dictionary<MessageFilter, FilterDataPair> filterData;
MessageFilterTable<FilterDataPair> table;
public AndMessageFilterTable()
{
this.filters = new Dictionary<MessageFilter, FilterData>();
this.filterData = new Dictionary<MessageFilter, FilterDataPair>();
this.table = new MessageFilterTable<FilterDataPair>();
}
public FilterData this[MessageFilter filter]
{
get
{
return this.filters[filter];
}
set
{
if (this.filters.ContainsKey(filter))
{
this.filters[filter] = value;
this.filterData[filter].data = value;
}
else
{
Add(filter, value);
}
}
}
public int Count
{
get
{
return this.filters.Count;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public ICollection<MessageFilter> Keys
{
get
{
return this.filters.Keys;
}
}
public ICollection<FilterData> Values
{
get
{
return this.filters.Values;
}
}
public void Add(MessageFilter filter, FilterData data)
{
if (filter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("filter");
}
this.Add((AndMessageFilter)filter, data);
}
public void Add(KeyValuePair<MessageFilter, FilterData> item)
{
this.Add(item.Key, item.Value);
}
public void Add(AndMessageFilter filter, FilterData data)
{
if (filter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("filter");
}
this.filters.Add(filter, data);
FilterDataPair pair = new FilterDataPair(filter, data);
this.filterData.Add(filter, pair);
this.table.Add(filter.Filter1, pair);
}
public void Clear()
{
this.filters.Clear();
this.filterData.Clear();
this.table.Clear();
}
public bool Contains(KeyValuePair<MessageFilter, FilterData> item)
{
return ((ICollection<KeyValuePair<MessageFilter, FilterData>>)this.filters).Contains(item);
}
public bool ContainsKey(MessageFilter filter)
{
if (filter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("filter");
}
return this.filters.ContainsKey(filter);
}
public void CopyTo(KeyValuePair<MessageFilter, FilterData>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<MessageFilter, FilterData>>)this.filters).CopyTo(array, arrayIndex);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<KeyValuePair<MessageFilter, FilterData>> GetEnumerator()
{
return this.filters.GetEnumerator();
}
FilterDataPair InnerMatch(Message message)
{
List<FilterDataPair> pairs = new List<FilterDataPair>();
this.table.GetMatchingValues(message, pairs);
FilterDataPair pair = null;
for (int i = 0; i < pairs.Count; ++i)
{
if (pairs[i].filter.Filter2.Match(message))
{
if (pair != null)
{
Collection<MessageFilter> matches = new Collection<MessageFilter>();
matches.Add(pair.filter);
matches.Add(pairs[i].filter);
throw TraceUtility.ThrowHelperError(new MultipleFilterMatchesException(SR.GetString(SR.FilterMultipleMatches), null, matches), message);
}
pair = pairs[i];
}
}
return pair;
}
FilterDataPair InnerMatch(MessageBuffer messageBuffer)
{
List<FilterDataPair> pairs = new List<FilterDataPair>();
this.table.GetMatchingValues(messageBuffer, pairs);
FilterDataPair pair = null;
for (int i = 0; i < pairs.Count; ++i)
{
if (pairs[i].filter.Filter2.Match(messageBuffer))
{
if (pair != null)
{
Collection<MessageFilter> matches = new Collection<MessageFilter>();
matches.Add(pair.filter);
matches.Add(pairs[i].filter);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MultipleFilterMatchesException(SR.GetString(SR.FilterMultipleMatches), null, matches));
}
pair = pairs[i];
}
}
return pair;
}
void InnerMatch(Message message, ICollection<MessageFilter> results)
{
List<FilterDataPair> pairs = new List<FilterDataPair>();
this.table.GetMatchingValues(message, pairs);
for (int i = 0; i < pairs.Count; ++i)
{
if (pairs[i].filter.Filter2.Match(message))
{
results.Add(pairs[i].filter);
}
}
}
void InnerMatchData(Message message, ICollection<FilterData> results)
{
List<FilterDataPair> pairs = new List<FilterDataPair>();
this.table.GetMatchingValues(message, pairs);
for (int i = 0; i < pairs.Count; ++i)
{
if (pairs[i].filter.Filter2.Match(message))
{
results.Add(pairs[i].data);
}
}
}
void InnerMatch(MessageBuffer messageBuffer, ICollection<MessageFilter> results)
{
List<FilterDataPair> pairs = new List<FilterDataPair>();
this.table.GetMatchingValues(messageBuffer, pairs);
for (int i = 0; i < pairs.Count; ++i)
{
if (pairs[i].filter.Filter2.Match(messageBuffer))
{
results.Add(pairs[i].filter);
}
}
}
void InnerMatchData(MessageBuffer messageBuffer, ICollection<FilterData> results)
{
List<FilterDataPair> pairs = new List<FilterDataPair>();
this.table.GetMatchingValues(messageBuffer, pairs);
for (int i = 0; i < pairs.Count; ++i)
{
if (pairs[i].filter.Filter2.Match(messageBuffer))
{
results.Add(pairs[i].data);
}
}
}
internal bool GetMatchingValue(Message message, out FilterData data, out bool addressMatched)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
List<FilterDataPair> pairs = new List<FilterDataPair>();
addressMatched = this.table.GetMatchingValues(message, pairs);
FilterDataPair pair = null;
for (int i = 0; i < pairs.Count; ++i)
{
if (pairs[i].filter.Filter2.Match(message))
{
if (pair != null)
{
Collection<MessageFilter> matches = new Collection<MessageFilter>();
matches.Add(pair.filter);
matches.Add(pairs[i].filter);
throw TraceUtility.ThrowHelperError(new MultipleFilterMatchesException(SR.GetString(SR.FilterMultipleMatches), null, matches), message);
}
pair = pairs[i];
}
}
if (pair == null)
{
data = default(FilterData);
return false;
}
data = pair.data;
return true;
}
public bool GetMatchingValue(Message message, out FilterData data)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
FilterDataPair pair = InnerMatch(message);
if (pair == null)
{
data = default(FilterData);
return false;
}
data = pair.data;
return true;
}
public bool GetMatchingValue(MessageBuffer messageBuffer, out FilterData data)
{
if (messageBuffer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageBuffer");
}
FilterDataPair pair = InnerMatch(messageBuffer);
if (pair == null)
{
data = default(FilterData);
return false;
}
data = pair.data;
return true;
}
public bool GetMatchingFilter(Message message, out MessageFilter filter)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
FilterDataPair pair = InnerMatch(message);
if (pair == null)
{
filter = null;
return false;
}
filter = pair.filter;
return true;
}
public bool GetMatchingFilter(MessageBuffer messageBuffer, out MessageFilter filter)
{
if (messageBuffer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageBuffer");
}
FilterDataPair pair = InnerMatch(messageBuffer);
if (pair == null)
{
filter = null;
return false;
}
filter = pair.filter;
return true;
}
public bool GetMatchingFilters(Message message, ICollection<MessageFilter> results)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
if (results == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("results");
}
int count = results.Count;
InnerMatch(message, results);
return count != results.Count;
}
public bool GetMatchingFilters(MessageBuffer messageBuffer, ICollection<MessageFilter> results)
{
if (messageBuffer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageBuffer");
}
if (results == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("results");
}
int count = results.Count;
InnerMatch(messageBuffer, results);
return count != results.Count;
}
public bool GetMatchingValues(Message message, ICollection<FilterData> results)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
if (results == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("results");
}
int count = results.Count;
InnerMatchData(message, results);
return count != results.Count;
}
public bool GetMatchingValues(MessageBuffer messageBuffer, ICollection<FilterData> results)
{
if (messageBuffer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageBuffer");
}
if (results == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("results");
}
int count = results.Count;
InnerMatchData(messageBuffer, results);
return count != results.Count;
}
public bool Remove(MessageFilter filter)
{
if (filter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("filter");
}
AndMessageFilter sbFilter = filter as AndMessageFilter;
if (sbFilter != null)
{
return Remove(sbFilter);
}
return false;
}
public bool Remove(KeyValuePair<MessageFilter, FilterData> item)
{
if (((ICollection<KeyValuePair<MessageFilter, FilterData>>)this.filters).Contains(item))
{
return Remove(item.Key);
}
return false;
}
public bool Remove(AndMessageFilter filter)
{
if (filter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("filter");
}
if (this.filters.Remove(filter))
{
this.filterData.Remove(filter);
this.table.Remove(filter.Filter1);
return true;
}
return false;
}
internal class FilterDataPair
{
internal AndMessageFilter filter;
internal FilterData data;
internal FilterDataPair(AndMessageFilter filter, FilterData data)
{
this.filter = filter;
this.data = data;
}
}
public bool TryGetValue(MessageFilter filter, out FilterData data)
{
return this.filters.TryGetValue(filter, out data);
}
}
}
| |
using System;
using System.IO;
namespace ICSharpCode.SharpZipLib.Tar
{
/// <summary>
/// The TarOutputStream writes a UNIX tar archive as an OutputStream.
/// Methods are provided to put entries, and then write their contents
/// by writing to this stream using write().
/// </summary>
/// public
public class TarOutputStream : Stream
{
#region Constructors
/// <summary>
/// Construct TarOutputStream using default block factor
/// </summary>
/// <param name="outputStream">stream to write to</param>
public TarOutputStream(Stream outputStream)
: this(outputStream, TarBuffer.DefaultBlockFactor)
{
}
/// <summary>
/// Construct TarOutputStream with user specified block factor
/// </summary>
/// <param name="outputStream">stream to write to</param>
/// <param name="blockFactor">blocking factor</param>
public TarOutputStream(Stream outputStream, int blockFactor)
{
if (outputStream == null) {
throw new ArgumentNullException(nameof(outputStream));
}
this.outputStream = outputStream;
buffer = TarBuffer.CreateOutputTarBuffer(outputStream, blockFactor);
assemblyBuffer = new byte[TarBuffer.BlockSize];
blockBuffer = new byte[TarBuffer.BlockSize];
}
#endregion
/// <summary>
/// Get/set flag indicating ownership of the underlying stream.
/// When the flag is true <see cref="Close"></see> will close the underlying stream also.
/// </summary>
public bool IsStreamOwner {
get { return buffer.IsStreamOwner; }
set { buffer.IsStreamOwner = value; }
}
/// <summary>
/// true if the stream supports reading; otherwise, false.
/// </summary>
public override bool CanRead {
get {
return outputStream.CanRead;
}
}
/// <summary>
/// true if the stream supports seeking; otherwise, false.
/// </summary>
public override bool CanSeek {
get {
return outputStream.CanSeek;
}
}
/// <summary>
/// true if stream supports writing; otherwise, false.
/// </summary>
public override bool CanWrite {
get {
return outputStream.CanWrite;
}
}
/// <summary>
/// length of stream in bytes
/// </summary>
public override long Length {
get {
return outputStream.Length;
}
}
/// <summary>
/// gets or sets the position within the current stream.
/// </summary>
public override long Position {
get {
return outputStream.Position;
}
set {
outputStream.Position = value;
}
}
/// <summary>
/// set the position within the current stream
/// </summary>
/// <param name="offset">The offset relative to the <paramref name="origin"/> to seek to</param>
/// <param name="origin">The <see cref="SeekOrigin"/> to seek from.</param>
/// <returns>The new position in the stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
return outputStream.Seek(offset, origin);
}
/// <summary>
/// Set the length of the current stream
/// </summary>
/// <param name="value">The new stream length.</param>
public override void SetLength(long value)
{
outputStream.SetLength(value);
}
/// <summary>
/// Read a byte from the stream and advance the position within the stream
/// by one byte or returns -1 if at the end of the stream.
/// </summary>
/// <returns>The byte value or -1 if at end of stream</returns>
public override int ReadByte()
{
return outputStream.ReadByte();
}
/// <summary>
/// read bytes from the current stream and advance the position within the
/// stream by the number of bytes read.
/// </summary>
/// <param name="buffer">The buffer to store read bytes in.</param>
/// <param name="offset">The index into the buffer to being storing bytes at.</param>
/// <param name="count">The desired number of bytes to read.</param>
/// <returns>The total number of bytes read, or zero if at the end of the stream.
/// The number of bytes may be less than the <paramref name="count">count</paramref>
/// requested if data is not avialable.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
return outputStream.Read(buffer, offset, count);
}
/// <summary>
/// All buffered data is written to destination
/// </summary>
public override void Flush()
{
outputStream.Flush();
}
/// <summary>
/// Ends the TAR archive without closing the underlying OutputStream.
/// The result is that the EOF block of nulls is written.
/// </summary>
public void Finish()
{
if (IsEntryOpen) {
CloseEntry();
}
WriteEofBlock();
}
/// <summary>
/// Ends the TAR archive and closes the underlying OutputStream.
/// </summary>
/// <remarks>This means that Finish() is called followed by calling the
/// TarBuffer's Close().</remarks>
public override void Close()
{
if (!isClosed) {
isClosed = true;
Finish();
buffer.Close();
}
}
/// <summary>
/// Get the record size being used by this stream's TarBuffer.
/// </summary>
public int RecordSize {
get { return buffer.RecordSize; }
}
/// <summary>
/// Get the record size being used by this stream's TarBuffer.
/// </summary>
/// <returns>
/// The TarBuffer record size.
/// </returns>
[Obsolete("Use RecordSize property instead")]
public int GetRecordSize()
{
return buffer.RecordSize;
}
/// <summary>
/// Get a value indicating wether an entry is open, requiring more data to be written.
/// </summary>
bool IsEntryOpen {
get { return (currBytes < currSize); }
}
/// <summary>
/// Put an entry on the output stream. This writes the entry's
/// header and positions the output stream for writing
/// the contents of the entry. Once this method is called, the
/// stream is ready for calls to write() to write the entry's
/// contents. Once the contents are written, closeEntry()
/// <B>MUST</B> be called to ensure that all buffered data
/// is completely written to the output stream.
/// </summary>
/// <param name="entry">
/// The TarEntry to be written to the archive.
/// </param>
public void PutNextEntry(TarEntry entry)
{
if (entry == null) {
throw new ArgumentNullException(nameof(entry));
}
if (entry.TarHeader.Name.Length > TarHeader.NAMELEN) {
var longHeader = new TarHeader();
longHeader.TypeFlag = TarHeader.LF_GNU_LONGNAME;
longHeader.Name = longHeader.Name + "././@LongLink";
longHeader.Mode = 420;//644 by default
longHeader.UserId = entry.UserId;
longHeader.GroupId = entry.GroupId;
longHeader.GroupName = entry.GroupName;
longHeader.UserName = entry.UserName;
longHeader.LinkName = "";
longHeader.Size = entry.TarHeader.Name.Length + 1; // Plus one to avoid dropping last char
longHeader.WriteHeader(blockBuffer);
buffer.WriteBlock(blockBuffer); // Add special long filename header block
int nameCharIndex = 0;
while (nameCharIndex < entry.TarHeader.Name.Length) {
Array.Clear(blockBuffer, 0, blockBuffer.Length);
TarHeader.GetAsciiBytes(entry.TarHeader.Name, nameCharIndex, this.blockBuffer, 0, TarBuffer.BlockSize);
nameCharIndex += TarBuffer.BlockSize;
buffer.WriteBlock(blockBuffer);
}
}
entry.WriteEntryHeader(blockBuffer);
buffer.WriteBlock(blockBuffer);
currBytes = 0;
currSize = entry.IsDirectory ? 0 : entry.Size;
}
/// <summary>
/// Close an entry. This method MUST be called for all file
/// entries that contain data. The reason is that we must
/// buffer data written to the stream in order to satisfy
/// the buffer's block based writes. Thus, there may be
/// data fragments still being assembled that must be written
/// to the output stream before this entry is closed and the
/// next entry written.
/// </summary>
public void CloseEntry()
{
if (assemblyBufferLength > 0) {
Array.Clear(assemblyBuffer, assemblyBufferLength, assemblyBuffer.Length - assemblyBufferLength);
buffer.WriteBlock(assemblyBuffer);
currBytes += assemblyBufferLength;
assemblyBufferLength = 0;
}
if (currBytes < currSize) {
string errorText = string.Format(
"Entry closed at '{0}' before the '{1}' bytes specified in the header were written",
currBytes, currSize);
throw new TarException(errorText);
}
}
/// <summary>
/// Writes a byte to the current tar archive entry.
/// This method simply calls Write(byte[], int, int).
/// </summary>
/// <param name="value">
/// The byte to be written.
/// </param>
public override void WriteByte(byte value)
{
Write(new byte[] { value }, 0, 1);
}
/// <summary>
/// Writes bytes to the current tar archive entry. This method
/// is aware of the current entry and will throw an exception if
/// you attempt to write bytes past the length specified for the
/// current entry. The method is also (painfully) aware of the
/// record buffering required by TarBuffer, and manages buffers
/// that are not a multiple of recordsize in length, including
/// assembling records from small buffers.
/// </summary>
/// <param name = "buffer">
/// The buffer to write to the archive.
/// </param>
/// <param name = "offset">
/// The offset in the buffer from which to get bytes.
/// </param>
/// <param name = "count">
/// The number of bytes to write.
/// </param>
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null) {
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0) {
throw new ArgumentOutOfRangeException(nameof(offset), "Cannot be negative");
}
if (buffer.Length - offset < count) {
throw new ArgumentException("offset and count combination is invalid");
}
if (count < 0) {
throw new ArgumentOutOfRangeException(nameof(count), "Cannot be negative");
}
if ((currBytes + count) > currSize) {
string errorText = string.Format("request to write '{0}' bytes exceeds size in header of '{1}' bytes",
count, this.currSize);
throw new ArgumentOutOfRangeException(nameof(count), errorText);
}
//
// We have to deal with assembly!!!
// The programmer can be writing little 32 byte chunks for all
// we know, and we must assemble complete blocks for writing.
// TODO REVIEW Maybe this should be in TarBuffer? Could that help to
// eliminate some of the buffer copying.
//
if (assemblyBufferLength > 0) {
if ((assemblyBufferLength + count) >= blockBuffer.Length) {
int aLen = blockBuffer.Length - assemblyBufferLength;
Array.Copy(assemblyBuffer, 0, blockBuffer, 0, assemblyBufferLength);
Array.Copy(buffer, offset, blockBuffer, assemblyBufferLength, aLen);
this.buffer.WriteBlock(blockBuffer);
currBytes += blockBuffer.Length;
offset += aLen;
count -= aLen;
assemblyBufferLength = 0;
} else {
Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count);
offset += count;
assemblyBufferLength += count;
count -= count;
}
}
//
// When we get here we have EITHER:
// o An empty "assembly" buffer.
// o No bytes to write (count == 0)
//
while (count > 0) {
if (count < blockBuffer.Length) {
Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count);
assemblyBufferLength += count;
break;
}
this.buffer.WriteBlock(buffer, offset);
int bufferLength = blockBuffer.Length;
currBytes += bufferLength;
count -= bufferLength;
offset += bufferLength;
}
}
/// <summary>
/// Write an EOF (end of archive) block to the tar archive.
/// An EOF block consists of all zeros.
/// </summary>
void WriteEofBlock()
{
Array.Clear(blockBuffer, 0, blockBuffer.Length);
buffer.WriteBlock(blockBuffer);
}
#region Instance Fields
/// <summary>
/// bytes written for this entry so far
/// </summary>
long currBytes;
/// <summary>
/// current 'Assembly' buffer length
/// </summary>
int assemblyBufferLength;
/// <summary>
/// Flag indicating wether this instance has been closed or not.
/// </summary>
bool isClosed;
/// <summary>
/// Size for the current entry
/// </summary>
protected long currSize;
/// <summary>
/// single block working buffer
/// </summary>
protected byte[] blockBuffer;
/// <summary>
/// 'Assembly' buffer used to assemble data before writing
/// </summary>
protected byte[] assemblyBuffer;
/// <summary>
/// TarBuffer used to provide correct blocking factor
/// </summary>
protected TarBuffer buffer;
/// <summary>
/// the destination stream for the archive contents
/// </summary>
protected Stream outputStream;
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.