context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Toggl.Phoebe.Data;
using Toggl.Phoebe.Data.DataObjects;
using Toggl.Phoebe.Logging;
using Toggl.Phoebe.Net;
using XPlatUtils;
namespace Toggl.Phoebe.Data.Models
{
public class TimeEntryModel : Model<TimeEntryData>, ITimeEntryModel
{
private const string Tag = "TimeEntryModel";
private static string GetPropertyName<T> (Expression<Func<TimeEntryModel, T>> expr)
{
return expr.ToPropertyName ();
}
private static bool ShouldAddDefaultTag
{
get { return ServiceContainer.Resolve<ISettingsStore> ().UseDefaultTag; }
}
internal static readonly string DefaultTag = "mobile";
public static new readonly string PropertyId = Model<TimeEntryData>.PropertyId;
public static readonly string PropertyState = GetPropertyName (m => m.State);
public static readonly string PropertyDescription = GetPropertyName (m => m.Description);
public static readonly string PropertyStartTime = GetPropertyName (m => m.StartTime);
public static readonly string PropertyStopTime = GetPropertyName (m => m.StopTime);
public static readonly string PropertyDurationOnly = GetPropertyName (m => m.DurationOnly);
public static readonly string PropertyIsBillable = GetPropertyName (m => m.IsBillable);
public static readonly string PropertyUser = GetPropertyName (m => m.User);
public static readonly string PropertyWorkspace = GetPropertyName (m => m.Workspace);
public static readonly string PropertyProject = GetPropertyName (m => m.Project);
public static readonly string PropertyTask = GetPropertyName (m => m.Task);
public TimeEntryModel ()
{
}
public TimeEntryModel (TimeEntryData data) : base (data)
{
}
public TimeEntryModel (Guid id) : base (id)
{
}
public TimeEntryModel (string id) : base (new Guid (id))
{
}
protected override TimeEntryData Duplicate (TimeEntryData data)
{
return new TimeEntryData (data);
}
protected override void OnBeforeSave ()
{
if (Data.UserId == Guid.Empty) {
throw new ValidationException ("User must be set for TimeEntry model.");
}
if (Data.WorkspaceId == Guid.Empty) {
throw new ValidationException ("Workspace must be set for TimeEntry model.");
}
}
protected override void DetectChangedProperties (TimeEntryData oldData, TimeEntryData newData)
{
base.DetectChangedProperties (oldData, newData);
if (oldData.State != newData.State) {
OnPropertyChanged (PropertyState);
}
if (ReturnEmptyIfNull (oldData.Description) != ReturnEmptyIfNull (newData.Description)) {
OnPropertyChanged (PropertyDescription);
}
if (oldData.StartTime != newData.StartTime) {
OnPropertyChanged (PropertyStartTime);
}
if (oldData.StopTime != newData.StopTime) {
OnPropertyChanged (PropertyStopTime);
}
if (oldData.DurationOnly != newData.DurationOnly) {
OnPropertyChanged (PropertyDurationOnly);
}
if (oldData.IsBillable != newData.IsBillable) {
OnPropertyChanged (PropertyIsBillable);
}
if (oldData.UserId != newData.UserId || user.IsNewInstance) {
OnPropertyChanged (PropertyUser);
}
if (oldData.WorkspaceId != newData.WorkspaceId || workspace.IsNewInstance) {
OnPropertyChanged (PropertyWorkspace);
}
if (oldData.ProjectId != newData.ProjectId || project.IsNewInstance) {
OnPropertyChanged (PropertyProject);
}
if (oldData.TaskId != newData.TaskId || task.IsNewInstance) {
OnPropertyChanged (PropertyTask);
}
}
private string ReturnEmptyIfNull (String s)
{
return String.IsNullOrEmpty (s) ? String.Empty : s;
}
public TimeEntryState State
{
get {
EnsureLoaded ();
return Data.State;
} set {
if (State == value) {
return;
}
MutateData (data => {
// Adjust start-time to keep duration same when switching to running state
if (value == TimeEntryState.Running && data.StopTime.HasValue) {
var duration = GetDuration (data);
var now = Time.UtcNow;
data.StopTime = null;
data.StartTime = (now - duration).Truncate (TimeSpan.TicksPerSecond);
}
data.State = value;
});
}
}
public string Description
{
get {
EnsureLoaded ();
return ReturnEmptyIfNull (Data.Description);
} set {
value = ReturnEmptyIfNull (value);
if (Description == value) {
return;
}
MutateData (data => data.Description = value);
}
}
public DateTime StartTime
{
get {
EnsureLoaded ();
return Data.StartTime;
} set {
value = value.ToUtc ().Truncate (TimeSpan.TicksPerSecond);
if (StartTime == value) {
return;
}
MutateData (data => {
var duration = GetDuration (data);
data.StartTime = value;
if (State != TimeEntryState.Running) {
if (data.StopTime.HasValue) {
data.StopTime = data.StartTime + duration;
} else {
var now = Time.UtcNow;
data.StopTime = data.StartTime.Date
.AddHours (now.Hour)
.AddMinutes (now.Minute)
.AddSeconds (data.StartTime.Second);
if (data.StopTime < data.StartTime) {
data.StopTime = data.StartTime + duration;
}
}
data.StartTime = data.StartTime.Truncate (TimeSpan.TicksPerSecond);
data.StopTime = data.StopTime.Truncate (TimeSpan.TicksPerSecond);
}
});
}
}
public DateTime? StopTime
{
get {
EnsureLoaded ();
return Data.StopTime;
} set {
value = value.ToUtc ().Truncate (TimeSpan.TicksPerSecond);
if (StopTime == value) {
return;
}
MutateData (data => data.StopTime = value);
}
}
public bool DurationOnly
{
get {
EnsureLoaded ();
return Data.DurationOnly;
} set {
if (DurationOnly == value) {
return;
}
MutateData (data => data.DurationOnly = value);
}
}
public bool IsBillable
{
get {
EnsureLoaded ();
return Data.IsBillable;
} set {
if (IsBillable == value) {
return;
}
MutateData (data => data.IsBillable = value);
}
}
public TimeSpan GetDuration ()
{
return GetDuration (Data, Time.UtcNow);
}
public TimeSpan GetDuration (TimeEntryData data)
{
return GetDuration (data, Time.UtcNow);
}
public static TimeSpan GetDuration (TimeEntryData data, DateTime now)
{
if (data.StartTime.IsMinValue ()) {
return TimeSpan.Zero;
}
var duration = (data.StopTime ?? now) - data.StartTime;
if (duration < TimeSpan.Zero) {
duration = TimeSpan.Zero;
}
return duration;
}
public void SetDuration (TimeSpan value)
{
MutateData (data => SetDuration (data, value));
}
private static void SetDuration (TimeEntryData data, TimeSpan value)
{
var now = Time.UtcNow;
if (data.State == TimeEntryState.Finished) {
data.StopTime = data.StartTime + value;
} else if (data.State == TimeEntryState.New) {
if (value == TimeSpan.Zero) {
data.StartTime = DateTime.MinValue;
data.StopTime = null;
} else if (data.StopTime.HasValue) {
data.StartTime = data.StopTime.Value - value;
} else {
data.StartTime = now - value;
data.StopTime = now;
}
} else {
data.StartTime = now - value;
}
data.StartTime = data.StartTime.Truncate (TimeSpan.TicksPerSecond);
data.StopTime = data.StopTime.Truncate (TimeSpan.TicksPerSecond);
}
private ForeignRelation<UserModel> user;
private ForeignRelation<WorkspaceModel> workspace;
private ForeignRelation<ProjectModel> project;
private ForeignRelation<TaskModel> task;
protected override void InitializeRelations ()
{
base.InitializeRelations ();
user = new ForeignRelation<UserModel> () {
ShouldLoad = EnsureLoaded,
Factory = id => new UserModel (id),
Changed = m => MutateData (data => data.UserId = m.Id),
};
workspace = new ForeignRelation<WorkspaceModel> () {
ShouldLoad = EnsureLoaded,
Factory = id => new WorkspaceModel (id),
Changed = m => MutateData (data => data.WorkspaceId = m.Id),
};
project = new ForeignRelation<ProjectModel> () {
Required = false,
ShouldLoad = EnsureLoaded,
Factory = id => new ProjectModel (id),
Changed = m => MutateData (data => {
if (m != null) {
data.IsBillable = m.IsBillable;
}
data.ProjectId = GetOptionalId (m);
}),
};
task = new ForeignRelation<TaskModel> () {
Required = false,
ShouldLoad = EnsureLoaded,
Factory = id => new TaskModel (id),
Changed = m => MutateData (data => data.TaskId = GetOptionalId (m)),
};
}
[ModelRelation]
public UserModel User
{
get { return user.Get (Data.UserId); }
set { user.Set (value); }
}
[ModelRelation]
public WorkspaceModel Workspace
{
get { return workspace.Get (Data.WorkspaceId); }
set { workspace.Set (value); }
}
[ModelRelation (Required = false)]
public ProjectModel Project
{
get { return project.Get (Data.ProjectId); }
set { project.Set (value); }
}
[ModelRelation (Required = false)]
public TaskModel Task
{
get { return task.Get (Data.TaskId); }
set { task.Set (value); }
}
/// <summary>
/// Stores the draft time entry in model store as a running time entry.
/// </summary>
public async Task StartAsync ()
{
await LoadAsync ();
if (Data.State != TimeEntryState.New) {
throw new InvalidOperationException (String.Format ("Cannot start a time entry in {0} state.", Data.State));
}
if (!Data.StartTime.IsMinValue () || Data.StopTime.HasValue) {
throw new InvalidOperationException ("Cannot start tracking time entry with start/stop time set already.");
}
var task = Task;
var project = Project;
var workspace = Workspace;
var user = User;
// Preload all pending relations:
var pending = new List<Task> ();
if (task != null) {
pending.Add (task.LoadAsync ());
}
if (project != null) {
pending.Add (project.LoadAsync ());
}
if (workspace != null) {
pending.Add (workspace.LoadAsync ());
}
if (user != null) {
pending.Add (user.LoadAsync ());
}
await System.Threading.Tasks.Task.WhenAll (pending);
if (ModelExists (task)) {
project = task.Project;
}
if (ModelExists (project)) {
workspace = project.Workspace;
}
if (ModelExists (user) && !ModelExists (workspace)) {
workspace = user.DefaultWorkspace;
}
if (!ModelExists (workspace)) {
throw new InvalidOperationException ("Workspace (or user default workspace) must be set.");
}
MutateData (data => {
data.TaskId = task != null ? (Guid?)task.Id : null;
data.ProjectId = project != null ? (Guid?)project.Id : null;
data.WorkspaceId = workspace.Id;
data.UserId = user.Id;
data.State = TimeEntryState.Running;
data.StartTime = Time.UtcNow;
data.StopTime = null;
});
await SaveAsync ();
await AddDefaultTags ();
}
private async Task AddDefaultTags ()
{
if (!ShouldAddDefaultTag) {
return;
}
var dataStore = ServiceContainer.Resolve<IDataStore> ();
var timeEntryId = Data.Id;
var workspaceId = Data.WorkspaceId;
await dataStore.ExecuteInTransactionAsync (ctx => AddDefaultTags (ctx, workspaceId, timeEntryId))
.ConfigureAwait (false);
}
private static void AddDefaultTags (IDataStoreContext ctx, Guid workspaceId, Guid timeEntryId)
{
// Check that there aren't any tags set yet:
var tagCount = ctx.Connection.Table<TimeEntryTagData> ()
.Count (r => r.TimeEntryId == timeEntryId && r.DeletedAt == null);
if (tagCount > 0) {
return;
}
var defaultTag = ctx.Connection.Table<TagData> ()
.Where (r => r.Name == DefaultTag && r.WorkspaceId == workspaceId && r.DeletedAt == null)
.FirstOrDefault ();
if (defaultTag == null) {
defaultTag = ctx.Put (new TagData () {
Name = DefaultTag,
WorkspaceId = workspaceId,
});
}
ctx.Put (new TimeEntryTagData () {
TimeEntryId = timeEntryId,
TagId = defaultTag.Id,
});
}
/// <summary>
/// Stores the draft time entry in model store as a finished time entry.
/// </summary>
public async Task StoreAsync ()
{
await LoadAsync ();
if (Data.State != TimeEntryState.New) {
throw new InvalidOperationException (String.Format ("Cannot store a time entry in {0} state.", Data.State));
}
if (Data.StartTime.IsMinValue () || Data.StopTime == null) {
throw new InvalidOperationException ("Cannot store time entry with start/stop time not set.");
}
var task = Task;
var project = Project;
var workspace = Workspace;
var user = User;
// Preload all pending relations:
var pending = new List<Task> ();
if (task != null) {
pending.Add (task.LoadAsync ());
}
if (project != null) {
pending.Add (project.LoadAsync ());
}
if (workspace != null) {
pending.Add (workspace.LoadAsync ());
}
if (user != null) {
pending.Add (user.LoadAsync ());
}
await System.Threading.Tasks.Task.WhenAll (pending);
if (ModelExists (task)) {
project = task.Project;
}
if (ModelExists (project)) {
workspace = project.Workspace;
}
if (ModelExists (user) && !ModelExists (workspace)) {
workspace = user.DefaultWorkspace;
}
if (!ModelExists (workspace)) {
throw new InvalidOperationException ("Workspace (or user default workspace) must be set.");
}
MutateData (data => {
data.TaskId = task != null ? (Guid?)task.Id : null;
data.ProjectId = project != null ? (Guid?)project.Id : null;
data.WorkspaceId = workspace.Id;
data.UserId = user.Id;
data.State = TimeEntryState.Finished;
});
await SaveAsync ();
await AddDefaultTags ();
}
/// <summary>
/// Marks the currently running time entry as finished.
/// </summary>
public async Task StopAsync ()
{
await LoadAsync ();
if (Data.State != TimeEntryState.Running) {
throw new InvalidOperationException (String.Format ("Cannot stop a time entry in {0} state.", Data.State));
}
MutateData (data => {
data.State = TimeEntryState.Finished;
data.StopTime = Time.UtcNow;
});
await SaveAsync ();
}
/// <summary>
/// Continues the finished time entry, either by creating a new time entry or restarting the current one.
/// </summary>
public async Task<TimeEntryModel> ContinueAsync ()
{
var store = ServiceContainer.Resolve<IDataStore> ();
await LoadAsync ();
// Validate the current state
switch (Data.State) {
case TimeEntryState.Running:
return this;
case TimeEntryState.Finished:
break;
default:
throw new InvalidOperationException (String.Format ("Cannot continue a time entry in {0} state.", Data.State));
}
// We can continue time entries which haven't been synced yet:
if (Data.DurationOnly && Data.StartTime.ToLocalTime ().Date == Time.Now.Date) {
if (Data.RemoteId == null) {
MutateData (data => {
data.State = TimeEntryState.Running;
data.StartTime = Time.UtcNow - GetDuration ();
data.StopTime = null;
});
await SaveAsync ();
return this;
}
}
// Create new time entry:
var newData = new TimeEntryData () {
WorkspaceId = Data.WorkspaceId,
ProjectId = Data.ProjectId,
TaskId = Data.TaskId,
UserId = Data.UserId,
Description = Data.Description,
StartTime = Time.UtcNow,
DurationOnly = Data.DurationOnly,
IsBillable = Data.IsBillable,
State = TimeEntryState.Running,
};
MarkDirty (newData);
var parentId = Data.Id;
await store.ExecuteInTransactionAsync (ctx => {
newData = ctx.Put (newData);
// Duplicate tag relations as well
if (parentId != Guid.Empty) {
var q = ctx.Connection.Table<TimeEntryTagData> ()
.Where (r => r.TimeEntryId == parentId && r.DeletedAt == null);
foreach (var row in q) {
ctx.Put (new TimeEntryTagData () {
TimeEntryId = newData.Id,
TagId = row.TagId,
});
}
}
});
var model = new TimeEntryModel (newData);
return model;
}
public async Task MapTagsFromModel (TimeEntryModel model)
{
var dataStore = ServiceContainer.Resolve<IDataStore> ();
var oldTags = await dataStore.Table<TimeEntryTagData> ()
.QueryAsync (r => r.TimeEntryId == Id && r.DeletedAt == null);
var task1 = oldTags.Select (d => new TimeEntryTagModel (d).DeleteAsync ()).ToList();
var modelTags = await dataStore.Table<TimeEntryTagData> ()
.QueryAsync (r => r.TimeEntryId == model.Id && r.DeletedAt == null);
var task2 = modelTags.Select (d => new TimeEntryTagModel () { TimeEntry = this, Tag = new TagModel (d.TagId) } .SaveAsync()).ToList();
await System.Threading.Tasks.Task.WhenAll (task1.Concat (task2));
if (modelTags.Count > 0) {
Touch ();
}
}
public async Task MapMinorsFromModel (TimeEntryModel model)
{
await MapTagsFromModel (model);
Workspace = model.Workspace;
Project = model.Project;
Description = model.Description;
IsBillable = model.IsBillable;
Task = model.Task;
await SaveAsync ();
}
TimeEntryData ITimeEntryModel.Data
{
get {
return Data;
} set {
Data = value;
}
}
#region Public static methods.
private static TaskCompletionSource<TimeEntryData> draftDataTCS;
public static async Task<TimeEntryModel> GetDraftAsync ()
{
TimeEntryData data = null;
var user = ServiceContainer.Resolve<AuthManager> ().User;
if (user == null) {
return null;
}
// We're already loading draft data, wait for it to load, no need to create several drafts
if (draftDataTCS != null) {
data = await draftDataTCS.Task;
if (data == null) {
return null;
}
data = new TimeEntryData (data);
return new TimeEntryModel (data);
}
draftDataTCS = new TaskCompletionSource<TimeEntryData> ();
try {
var store = ServiceContainer.Resolve<IDataStore> ();
if (user.DefaultWorkspaceId == Guid.Empty) {
// User data has not yet been loaded by AuthManager, duplicate the effort and load ourselves:
var userRows = await store.Table<UserData> ()
.Take (1).QueryAsync (m => m.Id == user.Id);
user = userRows.First ();
}
var rows = await store.Table<TimeEntryData> ()
.Where (m => m.State == TimeEntryState.New && m.DeletedAt == null && m.UserId == user.Id)
.OrderBy (m => m.ModifiedAt)
.Take (1).QueryAsync ();
data = rows.FirstOrDefault ();
if (data == null) {
// Create new draft object
var newData = new TimeEntryData () {
State = TimeEntryState.New,
UserId = user.Id,
WorkspaceId = user.DefaultWorkspaceId,
DurationOnly = user.TrackingMode == TrackingMode.Continue,
};
MarkDirty (newData);
await store.ExecuteInTransactionAsync (ctx => {
newData = ctx.Put (newData);
if (ShouldAddDefaultTag) {
AddDefaultTags (ctx, newData.WorkspaceId, newData.Id);
}
});
data = newData;
}
} catch (Exception ex) {
var log = ServiceContainer.Resolve<ILogger> ();
log.Warning (Tag, ex, "Failed to retrieve/create draft.");
} finally {
draftDataTCS.SetResult (data);
draftDataTCS = null;
}
return new TimeEntryModel (data);
}
public static async Task<TimeEntryData> ContinueTimeEntryDataAsync (TimeEntryData timeEntryData)
{
var store = ServiceContainer.Resolve<IDataStore> ();
// Validate the current state
switch (timeEntryData.State) {
case TimeEntryState.Running:
return timeEntryData;
case TimeEntryState.Finished:
break;
default:
throw new InvalidOperationException (String.Format ("Cannot continue a time entry in {0} state.", timeEntryData.State));
}
// We can continue time entries which haven't been synced yet:
if (timeEntryData.DurationOnly && timeEntryData.StartTime.ToLocalTime ().Date == Time.Now.Date) {
if (timeEntryData.RemoteId == null) {
// Mutate data
timeEntryData = MutateData (timeEntryData, data => {
data.State = TimeEntryState.Running;
data.StartTime = Time.UtcNow - GetDuration (data, Time.UtcNow);
data.StopTime = null;
});
return await SaveTimeEntryDataAsync (timeEntryData);
}
}
// Create new time entry:
var newData = new TimeEntryData () {
WorkspaceId = timeEntryData.WorkspaceId,
ProjectId = timeEntryData.ProjectId,
TaskId = timeEntryData.TaskId,
UserId = timeEntryData.UserId,
Description = timeEntryData.Description,
StartTime = Time.UtcNow,
DurationOnly = timeEntryData.DurationOnly,
IsBillable = timeEntryData.IsBillable,
State = TimeEntryState.Running,
};
MarkDirty (newData);
var parentId = timeEntryData.Id;
await store.ExecuteInTransactionAsync (ctx => {
newData = ctx.Put (newData);
// Duplicate tag relations as well
if (parentId != Guid.Empty) {
var q = ctx.Connection.Table<TimeEntryTagData> ()
.Where (r => r.TimeEntryId == parentId && r.DeletedAt == null);
foreach (var row in q) {
ctx.Put (new TimeEntryTagData () {
TimeEntryId = newData.Id,
TagId = row.TagId,
});
}
}
});
return newData;
}
public static async Task<TimeEntryData> StopAsync (TimeEntryData timeEntryData)
{
if (timeEntryData.State != TimeEntryState.Running) {
throw new InvalidOperationException (String.Format ("Cannot stop a time entry in {0} state.", timeEntryData.State));
}
// Mutate data
timeEntryData = MutateData (timeEntryData, data => {
data.State = TimeEntryState.Finished;
data.StopTime = Time.UtcNow;
});
return await SaveTimeEntryDataAsync (timeEntryData);
}
public static async Task<TimeEntryData> SaveTimeEntryDataAsync (TimeEntryData timeEntryData)
{
var dataStore = ServiceContainer.Resolve<IDataStore> ();
var newData = await dataStore.PutAsync (timeEntryData);
return newData;
}
public static async Task DeleteTimeEntryDataAsync (TimeEntryData data)
{
var dataStore = ServiceContainer.Resolve<IDataStore> ();
if (data.RemoteId == null) {
// We can safely delete the item as it has not been synchronized with the server yet
await dataStore.DeleteAsync (data);
} else {
// Need to just mark this item as deleted so that it could be synced with the server
var newData = new TimeEntryData (data);
newData.DeletedAt = Time.UtcNow;
MarkDirty (newData);
await dataStore.PutAsync (newData);
}
}
protected static TimeEntryData MutateData (TimeEntryData timeEntryData, Action<TimeEntryData> mutator)
{
var newData = new TimeEntryData (timeEntryData);
mutator (newData);
MarkDirty (newData);
return newData;
}
public static async Task<TimeEntryModel> CreateFinishedAsync (TimeSpan duration)
{
var user = ServiceContainer.Resolve<AuthManager> ().User;
if (user == null) {
return null;
}
var store = ServiceContainer.Resolve<IDataStore> ();
var now = Time.UtcNow;
var newData = new TimeEntryData () {
State = TimeEntryState.Finished,
StartTime = now - duration,
StopTime = now,
UserId = user.Id,
WorkspaceId = user.DefaultWorkspaceId,
DurationOnly = user.TrackingMode == TrackingMode.Continue,
};
MarkDirty (newData);
await store.ExecuteInTransactionAsync (ctx => {
newData = ctx.Put (newData);
if (ShouldAddDefaultTag) {
AddDefaultTags (ctx, newData.WorkspaceId, newData.Id);
}
});
return new TimeEntryModel (newData);
}
public static explicit operator TimeEntryModel (TimeEntryData data)
{
if (data == null) {
return null;
}
return new TimeEntryModel (data);
}
public static implicit operator TimeEntryData (TimeEntryModel model)
{
return model.Data;
}
public static string GetFormattedDuration (TimeEntryData data)
{
TimeSpan duration = GetDuration (data, Time.UtcNow);
return GetFormattedDuration (duration);
}
public static string GetFormattedDuration (TimeSpan duration)
{
string formattedString = duration.ToString (@"hh\:mm\:ss");
var user = ServiceContainer.Resolve<AuthManager> ().User;
if (user == null) {
return formattedString;
}
if (user.DurationFormat == DurationFormat.Classic) {
if (duration.TotalMinutes < 1) {
formattedString = duration.ToString (@"s\ \s\e\c");
} else if (duration.TotalMinutes > 1 && duration.TotalMinutes < 60) {
formattedString = duration.ToString (@"mm\:ss\ \m\i\n");
} else {
formattedString = duration.ToString (@"hh\:mm\:ss");
}
} else if (user.DurationFormat == DurationFormat.Decimal) {
formattedString = String.Format ("{0:0.00} h", duration.TotalHours);
}
return formattedString;
}
#endregion
}
}
| |
// 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.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId
{
public partial class SymbolKeyTest : SymbolKeyTestBase
{
#region "Metadata vs. Source"
[WpfFact]
public void M2SNamedTypeSymbols01()
{
var src1 = @"using System;
public delegate void D(int p1, string p2);
namespace N1.N2
{
public interface I { }
namespace N3
{
public class C
{
public struct S
{
public enum E { Zero, One, Two }
public void M(int n) { Console.WriteLine(n); }
}
}
}
}
";
var src2 = @"using System;
using N1.N2.N3;
public class App : C
{
private event D myEvent;
internal N1.N2.I Prop { get; set; }
protected C.S.E this[int x] { set { } }
public void M(C.S s) { s.M(123); }
}
";
var comp1 = CreateCompilationWithMscorlib(src1);
// Compilation to Compilation
var comp2 = CreateCompilationWithMscorlib(src2, new MetadataReference[] { new CSharpCompilationReference(comp1) });
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType).OrderBy(s => s.Name).ToList();
Assert.Equal(5, originalSymbols.Count);
// ---------------------------
// Metadata symbols
var typesym = comp2.SourceModule.GlobalNamespace.GetTypeMembers("App").FirstOrDefault() as NamedTypeSymbol;
// 'D'
var member01 = (typesym.GetMembers("myEvent").Single() as EventSymbol).Type;
// 'I'
var member02 = (typesym.GetMembers("Prop").Single() as PropertySymbol).Type;
// 'C'
var member03 = typesym.BaseType;
// 'S'
var member04 = (typesym.GetMembers("M").Single() as MethodSymbol).Parameters[0].Type;
// 'E'
var member05 = (typesym.GetMembers(WellKnownMemberNames.Indexer).Single() as PropertySymbol).Type;
ResolveAndVerifySymbol(member03, comp2, originalSymbols[0], comp1, SymbolKeyComparison.CaseSensitive);
ResolveAndVerifySymbol(member01, comp2, originalSymbols[1], comp1, SymbolKeyComparison.CaseSensitive);
ResolveAndVerifySymbol(member05, comp2, originalSymbols[2], comp1, SymbolKeyComparison.CaseSensitive);
ResolveAndVerifySymbol(member02, comp2, originalSymbols[3], comp1, SymbolKeyComparison.CaseSensitive);
ResolveAndVerifySymbol(member04, comp2, originalSymbols[4], comp1, SymbolKeyComparison.CaseSensitive);
}
[WorkItem(542700)]
[WpfFact]
public void M2SNonTypeMemberSymbols01()
{
var src1 = @"using System;
namespace N1
{
public interface IFoo
{
void M(int p1, int p2);
void M(params short[] ary);
void M(string p1);
void M(ref string p1);
}
public struct S
{
public event Action<S> PublicEvent { add { } remove { } }
public IFoo PublicField;
public string PublicProp { get; set; }
public short this[sbyte p] { get { return p; } }
}
}
";
var src2 = @"using System;
using AN = N1;
public class App
{
static void Main()
{
var obj = new AN.S();
/*<bind0>*/obj.PublicEvent/*</bind0>*/ += EH;
var ifoo = /*<bind1>*/obj.PublicField/*</bind1>*/;
/*<bind3>*/ifoo.M(/*<bind2>*/obj.PublicProp/*</bind2>*/)/*</bind3>*/;
/*<bind5>*/ifoo.M(obj[12], /*<bind4>*/obj[123]/*</bind4>*/)/*</bind5>*/;
}
static void EH(AN.S s) { }
}
";
var comp1 = CreateCompilationWithMscorlib(src1);
// Compilation to Assembly
var comp2 = CreateCompilationWithMscorlib(src2, new MetadataReference[] { comp1.EmitToImageReference() });
// ---------------------------
// Source symbols
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter).ToList();
originalSymbols = originalSymbols.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).Select(s => s).ToList();
Assert.Equal(8, originalSymbols.Count);
// ---------------------------
// Metadata symbols
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp2);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(6, list.Count);
// event
ResolveAndVerifySymbol(list[0], originalSymbols[4], model, comp1, SymbolKeyComparison.CaseSensitive);
// field
ResolveAndVerifySymbol(list[1], originalSymbols[5], model, comp1, SymbolKeyComparison.CaseSensitive);
// prop
ResolveAndVerifySymbol(list[2], originalSymbols[6], model, comp1, SymbolKeyComparison.CaseSensitive);
// index:
ResolveAndVerifySymbol(list[4], originalSymbols[7], model, comp1, SymbolKeyComparison.CaseSensitive);
// M(string p1)
ResolveAndVerifySymbol(list[3], originalSymbols[2], model, comp1, SymbolKeyComparison.CaseSensitive);
// M(params short[] ary)
ResolveAndVerifySymbol(list[5], originalSymbols[1], model, comp1, SymbolKeyComparison.CaseSensitive);
}
#endregion
#region "Metadata vs. Metadata"
[WpfFact]
public void M2MMultiTargetingMsCorLib01()
{
var src1 = @"using System;
using System.IO;
public class A
{
public FileInfo GetFileInfo(string path)
{
if (File.Exists(path))
{
return new FileInfo(path);
}
return null;
}
public void PrintInfo(Array ary, ref DateTime time)
{
if (ary != null)
Console.WriteLine(ary);
else
Console.WriteLine(""null"");
time = DateTime.Now;
}
}
";
var src2 = @"using System;
class Test
{
static void Main()
{
var a = new A();
var fi = a.GetFileInfo(null);
Console.WriteLine(fi);
var dt = DateTime.Now;
var ary = Array.CreateInstance(typeof(string), 2);
a.PrintInfo(ary, ref dt);
}
}
";
var comp20 = CreateCompilation(src1, new[] { TestReferences.NetFx.v4_0_21006.mscorlib });
// "Compilation 2 Assembly"
var comp40 = CreateCompilationWithMscorlib(src2, new MetadataReference[] { comp20.EmitToImageReference() });
var typeA = comp20.SourceModule.GlobalNamespace.GetTypeMembers("A").Single();
var mem20_1 = typeA.GetMembers("GetFileInfo").Single() as MethodSymbol;
var mem20_2 = typeA.GetMembers("PrintInfo").Single() as MethodSymbol;
// FileInfo
var mtsym20_1 = mem20_1.ReturnType;
Assert.Equal(2, mem20_2.Parameters.Length);
// Array
var mtsym20_2 = mem20_2.Parameters[0].Type;
// ref DateTime
var mtsym20_3 = mem20_2.Parameters[1].Type;
// ====================
var typeTest = comp40.SourceModule.GlobalNamespace.GetTypeMembers("Test").FirstOrDefault();
var mem40 = typeTest.GetMembers("Main").Single() as MethodSymbol;
var list = GetBlockSyntaxList(mem40);
var model = comp40.GetSemanticModel(comp40.SyntaxTrees[0]);
foreach (var body in list)
{
var df = model.AnalyzeDataFlow(body.Statements.First(), body.Statements.Last());
if (df.VariablesDeclared != null)
{
foreach (var local in df.VariablesDeclared)
{
var localType = ((LocalSymbol)local).Type;
if (local.Name == "fi")
{
ResolveAndVerifySymbol(localType, comp40, mtsym20_1, comp20, SymbolKeyComparison.CaseSensitive);
}
else if (local.Name == "ary")
{
ResolveAndVerifySymbol(localType, comp40, mtsym20_2, comp20, SymbolKeyComparison.CaseSensitive);
}
else if (local.Name == "dt")
{
ResolveAndVerifySymbol(localType, comp40, mtsym20_3, comp20, SymbolKeyComparison.CaseSensitive);
}
}
}
}
}
[WpfFact, WorkItem(546255)]
public void M2MMultiTargetingMsCorLib02()
{
var src1 = @"using System;
namespace Mscorlib20
{
public interface IFoo
{
// interface
IDisposable Prop { get; set; }
// class
Exception this[ArgumentException t] { get; }
}
public class CFoo : IFoo
{
// enum
public DayOfWeek PublicField;
// delegate
public event System.Threading.ParameterizedThreadStart PublicEventField;
public IDisposable Prop { get; set; }
public Exception this[ArgumentException t] { get { return t; } }
}
}
";
var src2 = @"using System;
using N20 = Mscorlib20;
class Test
{
public IDisposable M()
{
var obj = new N20::CFoo();
N20.IFoo ifoo = obj;
/*<bind0>*/obj.PublicEventField/*</bind0>*/ += /*<bind1>*/MyEveHandler/*</bind1>*/;
var local = /*<bind2>*/ifoo[null]/*</bind2>*/;
if (/*<bind3>*/obj.PublicField /*</bind3>*/== DayOfWeek.Friday)
{
return /*<bind4>*/(obj as N20.IFoo).Prop/*</bind4>*/;
}
return null;
}
public void MyEveHandler(object o) { }
}
";
var comp20 = CreateCompilation(src1, new[] { TestReferences.NetFx.v4_0_21006.mscorlib });
// "Compilation ref Compilation"
var comp40 = CreateCompilationWithMscorlib(src2, new[] { new CSharpCompilationReference(comp20) });
var originals = GetSourceSymbols(comp20, SymbolCategory.NonTypeMember | SymbolCategory.Parameter);
var originalSymbols = originals.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).ToList();
// IFoo.Prop, CFoo.Prop, Event, Field, IFoo.This, CFoo.This
Assert.Equal(6, originalSymbols.Count);
// ====================
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp40);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(5, list.Count);
// PublicEventField
ResolveAndVerifySymbol(list[0], originalSymbols[2], model, comp20);
// delegate ParameterizedThreadStart
ResolveAndVerifyTypeSymbol(list[0], (originalSymbols[2] as EventSymbol).Type, model, comp20);
// MethodGroup
ResolveAndVerifyTypeSymbol(list[1], (originalSymbols[2] as EventSymbol).Type, model, comp20);
// Indexer
ResolveAndVerifySymbol(list[2], originalSymbols[4], model, comp20);
// class Exception
ResolveAndVerifyTypeSymbol(list[2], (originalSymbols[4] as PropertySymbol).Type, model, comp20);
// PublicField
ResolveAndVerifySymbol(list[3], originalSymbols[3], model, comp20);
// enum DayOfWeek
ResolveAndVerifyTypeSymbol(list[3], (originalSymbols[3] as FieldSymbol).Type, model, comp20);
// Prop
ResolveAndVerifySymbol(list[4], originalSymbols[0], model, comp20);
// interface IDisposable
ResolveAndVerifyTypeSymbol(list[4], (originalSymbols[0] as PropertySymbol).Type, model, comp20);
}
[WpfFact, WorkItem(546255)]
public void M2MMultiTargetingMsCorLib03()
{
var src1 = @"using System;
namespace Mscorlib20
{
public interface IFoo
{
// interface
IDisposable Prop { get; set; }
// class
Exception this[ArgumentException t] { get; }
}
public class CFoo : IFoo
{
// explicit
IDisposable IFoo.Prop { get; set; }
Exception IFoo.this[ArgumentException t] { get { return t; } }
}
}
";
var src2 = @"using System;
using N20 = Mscorlib20;
class Test
{
public IDisposable M()
{
N20.IFoo ifoo = new N20::CFoo();
var local = /*<bind0>*/ifoo[new ArgumentException()]/*</bind0>*/;
return /*<bind1>*/ifoo.Prop/*</bind1>*/;
}
}
";
var comp20 = CreateCompilation(src1, new[] { TestReferences.NetFx.v4_0_21006.mscorlib });
// "Compilation ref Compilation"
var comp40 = CreateCompilationWithMscorlib(src2, new[] { new CSharpCompilationReference(comp20) });
var originals = GetSourceSymbols(comp20, SymbolCategory.NonTypeMember | SymbolCategory.Parameter);
var originalSymbols = originals.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).ToList();
// CFoo.Prop, CFoo.This, IFoo.Prop, IFoo.This
Assert.Equal(4, originalSymbols.Count);
// ====================
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp40);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(2, list.Count);
// Indexer
ResolveAndVerifySymbol(list[0], originalSymbols[3], model, comp20);
// class Exception
ResolveAndVerifyTypeSymbol(list[0], (originalSymbols[3] as PropertySymbol).Type, model, comp20);
// Prop
ResolveAndVerifySymbol(list[1], originalSymbols[2], model, comp20);
// interface IDisposable
ResolveAndVerifyTypeSymbol(list[1], (originalSymbols[2] as PropertySymbol).Type, model, comp20);
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/iam/v1/policy.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Iam.V1 {
/// <summary>Holder for reflection information generated from google/iam/v1/policy.proto</summary>
public static partial class PolicyReflection {
#region Descriptor
/// <summary>File descriptor for google/iam/v1/policy.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PolicyReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chpnb29nbGUvaWFtL3YxL3BvbGljeS5wcm90bxINZ29vZ2xlLmlhbS52MRoc",
"Z29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90byJRCgZQb2xpY3kSDwoHdmVy",
"c2lvbhgBIAEoBRIoCghiaW5kaW5ncxgEIAMoCzIWLmdvb2dsZS5pYW0udjEu",
"QmluZGluZxIMCgRldGFnGAMgASgMIigKB0JpbmRpbmcSDAoEcm9sZRgBIAEo",
"CRIPCgdtZW1iZXJzGAIgAygJIkIKC1BvbGljeURlbHRhEjMKDmJpbmRpbmdf",
"ZGVsdGFzGAEgAygLMhsuZ29vZ2xlLmlhbS52MS5CaW5kaW5nRGVsdGEilwEK",
"DEJpbmRpbmdEZWx0YRIyCgZhY3Rpb24YASABKA4yIi5nb29nbGUuaWFtLnYx",
"LkJpbmRpbmdEZWx0YS5BY3Rpb24SDAoEcm9sZRgCIAEoCRIOCgZtZW1iZXIY",
"AyABKAkiNQoGQWN0aW9uEhYKEkFDVElPTl9VTlNQRUNJRklFRBAAEgcKA0FE",
"RBABEgoKBlJFTU9WRRACQm0KEWNvbS5nb29nbGUuaWFtLnYxQgtQb2xpY3lQ",
"cm90b1ABWjBnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlz",
"L2lhbS92MTtpYW34AQGqAhNHb29nbGUuQ2xvdWQuSWFtLlYxYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Iam.V1.Policy), global::Google.Cloud.Iam.V1.Policy.Parser, new[]{ "Version", "Bindings", "Etag" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Iam.V1.Binding), global::Google.Cloud.Iam.V1.Binding.Parser, new[]{ "Role", "Members" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Iam.V1.PolicyDelta), global::Google.Cloud.Iam.V1.PolicyDelta.Parser, new[]{ "BindingDeltas" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Iam.V1.BindingDelta), global::Google.Cloud.Iam.V1.BindingDelta.Parser, new[]{ "Action", "Role", "Member" }, null, new[]{ typeof(global::Google.Cloud.Iam.V1.BindingDelta.Types.Action) }, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Defines an Identity and Access Management (IAM) policy. It is used to
/// specify access control policies for Cloud Platform resources.
///
/// A `Policy` consists of a list of `bindings`. A `Binding` binds a list of
/// `members` to a `role`, where the members can be user accounts, Google groups,
/// Google domains, and service accounts. A `role` is a named list of permissions
/// defined by IAM.
///
/// **Example**
///
/// {
/// "bindings": [
/// {
/// "role": "roles/owner",
/// "members": [
/// "user:mike@example.com",
/// "group:admins@example.com",
/// "domain:google.com",
/// "serviceAccount:my-other-app@appspot.gserviceaccount.com",
/// ]
/// },
/// {
/// "role": "roles/viewer",
/// "members": ["user:sean@example.com"]
/// }
/// ]
/// }
///
/// For a description of IAM and its features, see the
/// [IAM developer's guide](https://cloud.google.com/iam).
/// </summary>
public sealed partial class Policy : pb::IMessage<Policy> {
private static readonly pb::MessageParser<Policy> _parser = new pb::MessageParser<Policy>(() => new Policy());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Policy> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Iam.V1.PolicyReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Policy() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Policy(Policy other) : this() {
version_ = other.version_;
bindings_ = other.bindings_.Clone();
etag_ = other.etag_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Policy Clone() {
return new Policy(this);
}
/// <summary>Field number for the "version" field.</summary>
public const int VersionFieldNumber = 1;
private int version_;
/// <summary>
/// Version of the `Policy`. The default version is 0.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Version {
get { return version_; }
set {
version_ = value;
}
}
/// <summary>Field number for the "bindings" field.</summary>
public const int BindingsFieldNumber = 4;
private static readonly pb::FieldCodec<global::Google.Cloud.Iam.V1.Binding> _repeated_bindings_codec
= pb::FieldCodec.ForMessage(34, global::Google.Cloud.Iam.V1.Binding.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Iam.V1.Binding> bindings_ = new pbc::RepeatedField<global::Google.Cloud.Iam.V1.Binding>();
/// <summary>
/// Associates a list of `members` to a `role`.
/// Multiple `bindings` must not be specified for the same `role`.
/// `bindings` with no members will result in an error.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Iam.V1.Binding> Bindings {
get { return bindings_; }
}
/// <summary>Field number for the "etag" field.</summary>
public const int EtagFieldNumber = 3;
private pb::ByteString etag_ = pb::ByteString.Empty;
/// <summary>
/// `etag` is used for optimistic concurrency control as a way to help
/// prevent simultaneous updates of a policy from overwriting each other.
/// It is strongly suggested that systems make use of the `etag` in the
/// read-modify-write cycle to perform policy updates in order to avoid race
/// conditions: An `etag` is returned in the response to `getIamPolicy`, and
/// systems are expected to put that etag in the request to `setIamPolicy` to
/// ensure that their change will be applied to the same version of the policy.
///
/// If no `etag` is provided in the call to `setIamPolicy`, then the existing
/// policy is overwritten blindly.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Etag {
get { return etag_; }
set {
etag_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Policy);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Policy other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Version != other.Version) return false;
if(!bindings_.Equals(other.bindings_)) return false;
if (Etag != other.Etag) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Version != 0) hash ^= Version.GetHashCode();
hash ^= bindings_.GetHashCode();
if (Etag.Length != 0) hash ^= Etag.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Version != 0) {
output.WriteRawTag(8);
output.WriteInt32(Version);
}
if (Etag.Length != 0) {
output.WriteRawTag(26);
output.WriteBytes(Etag);
}
bindings_.WriteTo(output, _repeated_bindings_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Version != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Version);
}
size += bindings_.CalculateSize(_repeated_bindings_codec);
if (Etag.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Etag);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Policy other) {
if (other == null) {
return;
}
if (other.Version != 0) {
Version = other.Version;
}
bindings_.Add(other.bindings_);
if (other.Etag.Length != 0) {
Etag = other.Etag;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Version = input.ReadInt32();
break;
}
case 26: {
Etag = input.ReadBytes();
break;
}
case 34: {
bindings_.AddEntriesFrom(input, _repeated_bindings_codec);
break;
}
}
}
}
}
/// <summary>
/// Associates `members` with a `role`.
/// </summary>
public sealed partial class Binding : pb::IMessage<Binding> {
private static readonly pb::MessageParser<Binding> _parser = new pb::MessageParser<Binding>(() => new Binding());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Binding> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Iam.V1.PolicyReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Binding() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Binding(Binding other) : this() {
role_ = other.role_;
members_ = other.members_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Binding Clone() {
return new Binding(this);
}
/// <summary>Field number for the "role" field.</summary>
public const int RoleFieldNumber = 1;
private string role_ = "";
/// <summary>
/// Role that is assigned to `members`.
/// For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
/// Required
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Role {
get { return role_; }
set {
role_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "members" field.</summary>
public const int MembersFieldNumber = 2;
private static readonly pb::FieldCodec<string> _repeated_members_codec
= pb::FieldCodec.ForString(18);
private readonly pbc::RepeatedField<string> members_ = new pbc::RepeatedField<string>();
/// <summary>
/// Specifies the identities requesting access for a Cloud Platform resource.
/// `members` can have the following values:
///
/// * `allUsers`: A special identifier that represents anyone who is
/// on the internet; with or without a Google account.
///
/// * `allAuthenticatedUsers`: A special identifier that represents anyone
/// who is authenticated with a Google account or a service account.
///
/// * `user:{emailid}`: An email address that represents a specific Google
/// account. For example, `alice@gmail.com` or `joe@example.com`.
///
/// * `serviceAccount:{emailid}`: An email address that represents a service
/// account. For example, `my-other-app@appspot.gserviceaccount.com`.
///
/// * `group:{emailid}`: An email address that represents a Google group.
/// For example, `admins@example.com`.
///
/// * `domain:{domain}`: A Google Apps domain name that represents all the
/// users of that domain. For example, `google.com` or `example.com`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> Members {
get { return members_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Binding);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Binding other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Role != other.Role) return false;
if(!members_.Equals(other.members_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Role.Length != 0) hash ^= Role.GetHashCode();
hash ^= members_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Role.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Role);
}
members_.WriteTo(output, _repeated_members_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Role.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Role);
}
size += members_.CalculateSize(_repeated_members_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Binding other) {
if (other == null) {
return;
}
if (other.Role.Length != 0) {
Role = other.Role;
}
members_.Add(other.members_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Role = input.ReadString();
break;
}
case 18: {
members_.AddEntriesFrom(input, _repeated_members_codec);
break;
}
}
}
}
}
/// <summary>
/// The difference delta between two policies.
/// </summary>
public sealed partial class PolicyDelta : pb::IMessage<PolicyDelta> {
private static readonly pb::MessageParser<PolicyDelta> _parser = new pb::MessageParser<PolicyDelta>(() => new PolicyDelta());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PolicyDelta> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Iam.V1.PolicyReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PolicyDelta() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PolicyDelta(PolicyDelta other) : this() {
bindingDeltas_ = other.bindingDeltas_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PolicyDelta Clone() {
return new PolicyDelta(this);
}
/// <summary>Field number for the "binding_deltas" field.</summary>
public const int BindingDeltasFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Iam.V1.BindingDelta> _repeated_bindingDeltas_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Iam.V1.BindingDelta.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Iam.V1.BindingDelta> bindingDeltas_ = new pbc::RepeatedField<global::Google.Cloud.Iam.V1.BindingDelta>();
/// <summary>
/// The delta for Bindings between two policies.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Iam.V1.BindingDelta> BindingDeltas {
get { return bindingDeltas_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PolicyDelta);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PolicyDelta other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!bindingDeltas_.Equals(other.bindingDeltas_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= bindingDeltas_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
bindingDeltas_.WriteTo(output, _repeated_bindingDeltas_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += bindingDeltas_.CalculateSize(_repeated_bindingDeltas_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PolicyDelta other) {
if (other == null) {
return;
}
bindingDeltas_.Add(other.bindingDeltas_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
bindingDeltas_.AddEntriesFrom(input, _repeated_bindingDeltas_codec);
break;
}
}
}
}
}
/// <summary>
/// One delta entry for Binding. Each individual change (only one member in each
/// entry) to a binding will be a separate entry.
/// </summary>
public sealed partial class BindingDelta : pb::IMessage<BindingDelta> {
private static readonly pb::MessageParser<BindingDelta> _parser = new pb::MessageParser<BindingDelta>(() => new BindingDelta());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<BindingDelta> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Iam.V1.PolicyReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BindingDelta() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BindingDelta(BindingDelta other) : this() {
action_ = other.action_;
role_ = other.role_;
member_ = other.member_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BindingDelta Clone() {
return new BindingDelta(this);
}
/// <summary>Field number for the "action" field.</summary>
public const int ActionFieldNumber = 1;
private global::Google.Cloud.Iam.V1.BindingDelta.Types.Action action_ = 0;
/// <summary>
/// The action that was performed on a Binding.
/// Required
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Iam.V1.BindingDelta.Types.Action Action {
get { return action_; }
set {
action_ = value;
}
}
/// <summary>Field number for the "role" field.</summary>
public const int RoleFieldNumber = 2;
private string role_ = "";
/// <summary>
/// Role that is assigned to `members`.
/// For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
/// Required
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Role {
get { return role_; }
set {
role_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "member" field.</summary>
public const int MemberFieldNumber = 3;
private string member_ = "";
/// <summary>
/// A single identity requesting access for a Cloud Platform resource.
/// Follows the same format of Binding.members.
/// Required
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Member {
get { return member_; }
set {
member_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as BindingDelta);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(BindingDelta other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Action != other.Action) return false;
if (Role != other.Role) return false;
if (Member != other.Member) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Action != 0) hash ^= Action.GetHashCode();
if (Role.Length != 0) hash ^= Role.GetHashCode();
if (Member.Length != 0) hash ^= Member.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Action != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Action);
}
if (Role.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Role);
}
if (Member.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Member);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Action != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Action);
}
if (Role.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Role);
}
if (Member.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Member);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(BindingDelta other) {
if (other == null) {
return;
}
if (other.Action != 0) {
Action = other.Action;
}
if (other.Role.Length != 0) {
Role = other.Role;
}
if (other.Member.Length != 0) {
Member = other.Member;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
action_ = (global::Google.Cloud.Iam.V1.BindingDelta.Types.Action) input.ReadEnum();
break;
}
case 18: {
Role = input.ReadString();
break;
}
case 26: {
Member = input.ReadString();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the BindingDelta message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// The type of action performed on a Binding in a policy.
/// </summary>
public enum Action {
/// <summary>
/// Unspecified.
/// </summary>
[pbr::OriginalName("ACTION_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Addition of a Binding.
/// </summary>
[pbr::OriginalName("ADD")] Add = 1,
/// <summary>
/// Removal of a Binding.
/// </summary>
[pbr::OriginalName("REMOVE")] Remove = 2,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.Linq;
using System.Abstract;
using System.Collections.Generic;
using Autofac;
namespace Contoso.Abstract
{
/// <summary>
/// IAutofacServiceLocator
/// </summary>
public interface IAutofacServiceLocator : IServiceLocator
{
/// <summary>
/// Gets the container.
/// </summary>
IContainer Container { get; }
}
/// <summary>
/// AutofacServiceLocator
/// </summary>
[Serializable]
public class AutofacServiceLocator : IAutofacServiceLocator, IDisposable, ServiceLocatorManager.ISetupRegistration
{
private IContainer _container;
private AutofacServiceRegistrar _registrar;
private Func<IContainer> _containerBuilder;
static AutofacServiceLocator() { ServiceLocatorManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="AutofacServiceLocator"/> class.
/// </summary>
public AutofacServiceLocator()
: this(new ContainerBuilder()) { }
/// <summary>
/// Initializes a new instance of the <see cref="AutofacServiceLocator"/> class.
/// </summary>
/// <param name="container">The container.</param>
public AutofacServiceLocator(IContainer container)
{
if (container == null)
throw new ArgumentNullException("container");
Container = container;
}
/// <summary>
/// Initializes a new instance of the <see cref="AutofacServiceLocator"/> class.
/// </summary>
/// <param name="containerBuilder">The container builder.</param>
public AutofacServiceLocator(ContainerBuilder containerBuilder)
{
if (containerBuilder == null)
throw new ArgumentNullException("containerBuilder");
_registrar = new AutofacServiceRegistrar(this, containerBuilder, out _containerBuilder);
}
private AutofacServiceLocator(IComponentContext container)
{
if (container == null)
throw new ArgumentNullException("container");
//_registrar = new AutofacServiceRegistrar(this, containerBuilder, out _containerBuilder);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (_container != null)
{
var container = _container;
_container = null;
_registrar = null;
_containerBuilder = null;
// prevent cyclical dispose
if (container != null)
container.Dispose();
}
}
Action<IServiceLocator, string> ServiceLocatorManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceLocatorManager.RegisterInstance<IAutofacServiceLocator>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.
/// -or-
/// null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { return Resolve(serviceType); }
/// <summary>
/// Creates the child.
/// </summary>
/// <returns></returns>
public IServiceLocator CreateChild(object tag)
{
//http://nblumhardt.com/2011/01/an-autofac-lifetime-primer/
return new AutofacServiceLocator(_container.BeginLifetimeScope(tag));
}
/// <summary>
/// Gets the underlying container.
/// </summary>
/// <typeparam name="TContainer">The type of the container.</typeparam>
/// <returns></returns>
public TContainer GetUnderlyingContainer<TContainer>()
where TContainer : class { return (_container as TContainer); }
// registrar
/// <summary>
/// Gets the registrar.
/// </summary>
public IServiceRegistrar Registrar
{
get { return _registrar; }
}
// resolve
/// <summary>
/// Resolves this instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns></returns>
public TService Resolve<TService>()
where TService : class
{
try { return (Container.IsRegistered<TService>() ? Container.Resolve<TService>() : Activator.CreateInstance<TService>()); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves the specified name.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="name">The name.</param>
/// <returns></returns>
public TService Resolve<TService>(string name)
where TService : class
{
try { return Container.ResolveNamed<TService>(name); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <returns></returns>
public object Resolve(Type serviceType)
{
try { return (Container.IsRegistered(serviceType) ? Container.Resolve(serviceType) : Activator.CreateInstance(serviceType)); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
/// <summary>
/// Resolves the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public object Resolve(Type serviceType, string name)
{
try { return Container.ResolveNamed(name, serviceType); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
//
/// <summary>
/// Resolves all.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns></returns>
public IEnumerable<TService> ResolveAll<TService>()
where TService : class
{
try { return new List<TService>(Container.Resolve<IEnumerable<TService>>()); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves all.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <returns></returns>
public IEnumerable<object> ResolveAll(Type serviceType)
{
var type = typeof(IEnumerable<>).MakeGenericType(serviceType);
try { return new List<object>((IEnumerable<object>)Container.Resolve(type)); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
// inject
/// <summary>
/// Injects the specified instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
/// <returns></returns>
public TService Inject<TService>(TService instance)
where TService : class { return Container.InjectProperties(instance); }
// release and teardown
/// <summary>
/// Releases the specified instance.
/// </summary>
/// <param name="instance">The instance.</param>
public void Release(object instance) { throw new NotSupportedException(); }
/// <summary>
/// Tears down.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
public void TearDown<TService>(TService instance)
where TService : class { throw new NotSupportedException(); }
#region Domain specific
/// <summary>
/// Gets the container.
/// </summary>
public IContainer Container
{
get
{
if (_container == null)
_container = _containerBuilder();
return _container;
}
private set
{
_container = value;
_registrar = new AutofacServiceRegistrar(this, value);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.CognitiveServices.Vision.Face
{
using Microsoft.CognitiveServices;
using Microsoft.CognitiveServices.Vision;
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// FaceOperations operations.
/// </summary>
public partial class FaceOperations : IServiceOperations<FaceAPI>, IFaceOperations
{
/// <summary>
/// Initializes a new instance of the FaceOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public FaceOperations(FaceAPI client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the FaceAPI
/// </summary>
public FaceAPI Client { get; private set; }
/// <summary>
/// Given query face's faceId, find the similar-looking faces from a faceId
/// array or a faceListId.
/// </summary>
/// <param name='faceId'>
/// FaceId of the query face. User needs to call Face - Detect first to get a
/// valid faceId. Note that this faceId is not persisted and will expire 24
/// hours after the detection call
/// </param>
/// <param name='faceListId'>
/// An existing user-specified unique candidate face list, created in Face List
/// - Create a Face List. Face list contains a set of persistedFaceIds which
/// are persisted and will never expire. Parameter faceListId and faceIds
/// should not be provided at the same time
/// </param>
/// <param name='faceIds'>
/// An array of candidate faceIds. All of them are created by Face - Detect and
/// the faceIds will expire 24 hours after the detection call.
/// </param>
/// <param name='maxNumOfCandidatesReturned'>
/// The number of top similar faces returned. The valid range is [1, 1000].
/// </param>
/// <param name='mode'>
/// Similar face searching mode. It can be "matchPerson" or "matchFace".
/// Possible values include: 'matchPerson', 'matchFace'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// 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<HttpOperationResponse<IList<SimilarFaceResult>>> FindSimilarWithHttpMessagesAsync(string faceId, string faceListId = default(string), IList<string> faceIds = default(IList<string>), int? maxNumOfCandidatesReturned = 20, string mode = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
if (faceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "faceId");
}
if (faceId != null)
{
if (faceId.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "faceId", 64);
}
}
if (faceListId != null)
{
if (faceListId.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "faceListId", 64);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(faceListId, "^[a-z0-9-_]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "faceListId", "^[a-z0-9-_]+$");
}
}
if (faceIds != null)
{
if (faceIds.Count > 1000)
{
throw new ValidationException(ValidationRules.MaxItems, "faceIds", 1000);
}
}
if (maxNumOfCandidatesReturned > 1000)
{
throw new ValidationException(ValidationRules.InclusiveMaximum, "maxNumOfCandidatesReturned", 1000);
}
if (maxNumOfCandidatesReturned < 1)
{
throw new ValidationException(ValidationRules.InclusiveMinimum, "maxNumOfCandidatesReturned", 1);
}
FindSimilarRequest body = new FindSimilarRequest();
if (faceId != null || faceListId != null || faceIds != null || maxNumOfCandidatesReturned != null || mode != null)
{
body.FaceId = faceId;
body.FaceListId = faceListId;
body.FaceIds = faceIds;
body.MaxNumOfCandidatesReturned = maxNumOfCandidatesReturned;
body.Mode = mode;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "FindSimilar", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "findsimilars";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
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(body != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// 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 APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, 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 HttpOperationResponse<IList<SimilarFaceResult>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<SimilarFaceResult>>(_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>
/// Divide candidate faces into groups based on face similarity.
/// </summary>
/// <param name='faceIds'>
/// Array of candidate faceId created by Face - Detect. The maximum is 1000
/// faces
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// 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<HttpOperationResponse<GroupResponse>> GroupWithHttpMessagesAsync(IList<string> faceIds, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
if (faceIds == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "faceIds");
}
if (faceIds != null)
{
if (faceIds.Count > 1000)
{
throw new ValidationException(ValidationRules.MaxItems, "faceIds", 1000);
}
}
GroupRequest body = new GroupRequest();
if (faceIds != null)
{
body.FaceIds = faceIds;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Group", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "group";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
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(body != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// 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 APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, 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 HttpOperationResponse<GroupResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<GroupResponse>(_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>
/// Identify unknown faces from a person group.
/// </summary>
/// <param name='personGroupId'>
/// personGroupId of the target person group, created by PersonGroups.Create
/// </param>
/// <param name='faceIds'>
/// Array of candidate faceId created by Face - Detect.
/// </param>
/// <param name='maxNumOfCandidatesReturned'>
/// The number of top similar faces returned.
/// </param>
/// <param name='confidenceThreshold'>
/// Confidence threshold of identification, used to judge whether one face
/// belong to one person.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// 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<HttpOperationResponse<IList<IdentifyResultItem>>> IdentifyWithHttpMessagesAsync(string personGroupId, IList<string> faceIds, int? maxNumOfCandidatesReturned = 1, double? confidenceThreshold = default(double?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
if (personGroupId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "personGroupId");
}
if (faceIds == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "faceIds");
}
if (faceIds != null)
{
if (faceIds.Count > 1000)
{
throw new ValidationException(ValidationRules.MaxItems, "faceIds", 1000);
}
}
if (maxNumOfCandidatesReturned > 1000)
{
throw new ValidationException(ValidationRules.InclusiveMaximum, "maxNumOfCandidatesReturned", 1000);
}
if (maxNumOfCandidatesReturned < 1)
{
throw new ValidationException(ValidationRules.InclusiveMinimum, "maxNumOfCandidatesReturned", 1);
}
if (confidenceThreshold > 1)
{
throw new ValidationException(ValidationRules.InclusiveMaximum, "confidenceThreshold", 1);
}
if (confidenceThreshold < 0)
{
throw new ValidationException(ValidationRules.InclusiveMinimum, "confidenceThreshold", 0);
}
IdentifyRequest body = new IdentifyRequest();
if (personGroupId != null || faceIds != null || maxNumOfCandidatesReturned != null || confidenceThreshold != null)
{
body.PersonGroupId = personGroupId;
body.FaceIds = faceIds;
body.MaxNumOfCandidatesReturned = maxNumOfCandidatesReturned;
body.ConfidenceThreshold = confidenceThreshold;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Identify", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "identify";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
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(body != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// 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 APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, 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 HttpOperationResponse<IList<IdentifyResultItem>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<IdentifyResultItem>>(_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>
/// Verify whether two faces belong to a same person or whether one face
/// belongs to a person.
/// </summary>
/// <param name='faceId'>
/// faceId the face, comes from Face - Detect
/// </param>
/// <param name='personId'>
/// Specify a certain person in a person group. personId is created in
/// Persons.Create.
/// </param>
/// <param name='personGroupId'>
/// Using existing personGroupId and personId for fast loading a specified
/// person. personGroupId is created in Person Groups.Create.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// 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<HttpOperationResponse<VerifyResult>> VerifyWithHttpMessagesAsync(string faceId, string personId, string personGroupId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
if (faceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "faceId");
}
if (faceId != null)
{
if (faceId.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "faceId", 64);
}
}
if (personId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "personId");
}
if (personGroupId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "personGroupId");
}
VerifyRequest body = new VerifyRequest();
if (faceId != null || personId != null || personGroupId != null)
{
body.FaceId = faceId;
body.PersonId = personId;
body.PersonGroupId = personGroupId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Verify", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "verify";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
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(body != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// 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 APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, 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 HttpOperationResponse<VerifyResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VerifyResult>(_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>
/// Detect human faces in an image and returns face locations, and optionally
/// with faceIds, landmarks, and attributes.
/// </summary>
/// <param name='url'>
/// </param>
/// <param name='returnFaceId'>
/// A value indicating whether the operation should return faceIds of detected
/// faces.
/// </param>
/// <param name='returnFaceLandmarks'>
/// A value indicating whether the operation should return landmarks of the
/// detected faces.
/// </param>
/// <param name='returnFaceAttributes'>
/// Analyze and return the one or more specified face attributes in the
/// comma-separated string like "returnFaceAttributes=age,gender". Supported
/// face attributes include age, gender, headPose, smile, facialHair, glasses
/// and emotion. Note that each face attribute analysis has additional
/// computational and time cost.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// 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<HttpOperationResponse<IList<DetectedFace>>> DetectWithHttpMessagesAsync(string url, bool? returnFaceId = true, bool? returnFaceLandmarks = false, string returnFaceAttributes = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
if (url == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "url");
}
ImageUrl imageUrl = new ImageUrl();
if (url != null)
{
imageUrl.Url = url;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("returnFaceId", returnFaceId);
tracingParameters.Add("returnFaceLandmarks", returnFaceLandmarks);
tracingParameters.Add("returnFaceAttributes", returnFaceAttributes);
tracingParameters.Add("imageUrl", imageUrl);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Detect", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "detect";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
List<string> _queryParameters = new List<string>();
if (returnFaceId != null)
{
_queryParameters.Add(string.Format("returnFaceId={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(returnFaceId, Client.SerializationSettings).Trim('"'))));
}
if (returnFaceLandmarks != null)
{
_queryParameters.Add(string.Format("returnFaceLandmarks={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(returnFaceLandmarks, Client.SerializationSettings).Trim('"'))));
}
if (returnFaceAttributes != null)
{
_queryParameters.Add(string.Format("returnFaceAttributes={0}", System.Uri.EscapeDataString(returnFaceAttributes)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
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(imageUrl != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(imageUrl, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// 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 APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, 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 HttpOperationResponse<IList<DetectedFace>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<DetectedFace>>(_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>
/// Detect human faces in an image and returns face locations, and optionally
/// with faceIds, landmarks, and attributes.
/// </summary>
/// <param name='image'>
/// An image stream.
/// </param>
/// <param name='returnFaceId'>
/// A value indicating whether the operation should return faceIds of detected
/// faces.
/// </param>
/// <param name='returnFaceLandmarks'>
/// A value indicating whether the operation should return landmarks of the
/// detected faces.
/// </param>
/// <param name='returnFaceAttributes'>
/// Analyze and return the one or more specified face attributes in the
/// comma-separated string like "returnFaceAttributes=age,gender". Supported
/// face attributes include age, gender, headPose, smile, facialHair, glasses
/// and emotion. Note that each face attribute analysis has additional
/// computational and time cost.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="APIErrorException">
/// 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<HttpOperationResponse<IList<DetectedFace>>> DetectInStreamWithHttpMessagesAsync(Stream image, bool? returnFaceId = true, bool? returnFaceLandmarks = false, string returnFaceAttributes = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey");
}
if (image == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "image");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("returnFaceId", returnFaceId);
tracingParameters.Add("returnFaceLandmarks", returnFaceLandmarks);
tracingParameters.Add("returnFaceAttributes", returnFaceAttributes);
tracingParameters.Add("image", image);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "DetectInStream", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "detect";
_url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"'));
List<string> _queryParameters = new List<string>();
if (returnFaceId != null)
{
_queryParameters.Add(string.Format("returnFaceId={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(returnFaceId, Client.SerializationSettings).Trim('"'))));
}
if (returnFaceLandmarks != null)
{
_queryParameters.Add(string.Format("returnFaceLandmarks={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(returnFaceLandmarks, Client.SerializationSettings).Trim('"'))));
}
if (returnFaceAttributes != null)
{
_queryParameters.Add(string.Format("returnFaceAttributes={0}", System.Uri.EscapeDataString(returnFaceAttributes)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.SubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey);
}
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(image == null)
{
throw new System.ArgumentNullException("image");
}
if (image != null && image != Stream.Null)
{
_httpRequest.Content = new StreamContent(image);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/octet-stream");
}
// 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 APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, 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 HttpOperationResponse<IList<DetectedFace>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<DetectedFace>>(_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.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Microsoft.ApplicationBlocks.Data;
using ILPathways.Business;
namespace ILPathways.DAL
{
/// <summary>
/// Data access manager for OrganizationMemberManager
/// </summary>
public class OrganizationMemberManager : BaseDataManager
{
static string className = "OrganizationMemberManager";
/// <summary>
/// Base procedures
/// </summary>
const string GET_PROC = "OrganizationMemberGet";
const string SELECT_PROC = "OrganizationMemberSelect";
const string DELETE_PROC = "OrganizationMemberDelete";
const string INSERT_PROC = "OrganizationMemberInsert";
const string UPDATE_PROC = "OrganizationMemberUpdate";
/// <summary>
/// Default constructor
/// </summary>
public OrganizationMemberManager()
{ }//
#region ====== Core Methods ===============================================
/// <summary>
/// Delete a OrganizationMember record
/// </summary>
/// <param name="orgId"></param>
/// <param name="userid"></param>
/// <param name="statusMessage"></param>
/// <returns></returns>
public static bool Delete( int orgId, int userid, ref string statusMessage )
{
return Delete( 0, orgId, userid, ref statusMessage );
}
/// <summary>
/// Delete an OrganizationMember record
/// </summary>
/// <param name="id"></param>
/// <param name="statusMessage"></param>
/// <returns></returns>
public static bool Delete(int id, ref string statusMessage )
{
return Delete( id, 0, 0, ref statusMessage );
}//
private static bool Delete( int id, int orgId, int userid, ref string statusMessage )
{
string connectionString = GatewayConnection();
bool successful = false;
SqlParameter[] sqlParameters = new SqlParameter[ 3 ];
sqlParameters[ 0 ] = new SqlParameter( "@Id", id );
sqlParameters[ 0 ] = new SqlParameter( "@OrgId", orgId );
sqlParameters[ 0 ] = new SqlParameter( "@Userid", userid );
try
{
SqlHelper.ExecuteNonQuery( connectionString, CommandType.StoredProcedure, DELETE_PROC, sqlParameters );
successful = true;
}
catch ( Exception ex )
{
LogError( ex, className + ".Delete() " );
statusMessage = className + "- Unsuccessful: Delete(): " + ex.Message.ToString();
successful = false;
}
return successful;
}
/// <summary>
/// Add an OrganizationMember record
/// </summary>
/// <param name="entity"></param>
/// <param name="statusMessage"></param>
/// <returns></returns>
public static int Create( OrganizationMember entity, ref string statusMessage )
{
string connectionString = GatewayConnection();
int newId = 0;
#region parameters
SqlParameter[] sqlParameters = new SqlParameter[ 4 ];
sqlParameters[ 0 ] = new SqlParameter( "@OrgId", SqlDbType.Int );
sqlParameters[ 0 ].Value = entity.OrgId;
sqlParameters[ 1 ] = new SqlParameter( "@UserId", entity.UserId);
sqlParameters[ 2 ] = new SqlParameter( "@TypeId", entity.OrgMemberTypeId );
sqlParameters[ 3 ] = new SqlParameter( "@CreatedById", entity.CreatedById);
#endregion
try
{
SqlDataReader dr = SqlHelper.ExecuteReader( connectionString, CommandType.StoredProcedure, INSERT_PROC, sqlParameters );
if ( dr.HasRows )
{
dr.Read();
newId = int.Parse( dr[ 0 ].ToString() );
}
dr.Close();
dr = null;
statusMessage = "successful";
} catch ( Exception ex )
{
if ( ex.Message.ToLower().IndexOf( "violation of primary key constraint" ) > -1 )
{
statusMessage = "Error: Duplicate Record. This person is already associated with the current organization and program";
} else
{
LogError( ex, className + string.Format( ".Insert() for orgId: {0} and userid: {1} and contact type: {2}", entity.OrgId.ToString(), entity.UserId.ToString(), entity.OrgMemberType ) );
statusMessage = className + "- Unsuccessful: Insert(): " + ex.Message.ToString();
}
entity.Message = statusMessage;
entity.IsValid = false;
}
return newId;
}
/// <summary>
/// /// Update an OrganizationMember record
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public static string Update( OrganizationMember entity )
{
string message = "successful";
//TODO - if we are going to allow updating of primary contact, then this update won't workm, would have to do
// a delete and add
#region parameters
SqlParameter[] sqlParameters = new SqlParameter[ 3 ];
sqlParameters[ 0 ] = new SqlParameter("@Id", entity.Id);
sqlParameters[ 1 ] = new SqlParameter( "@TypeId", entity.OrgMemberTypeId );
sqlParameters[ 2 ] = new SqlParameter( "@CreatedById", entity.CreatedById );
#endregion
try
{
SqlHelper.ExecuteNonQuery( GatewayConnection(), UPDATE_PROC, sqlParameters );
message = "successful";
} catch ( Exception ex )
{
LogError( ex, className + string.Format(".Update() for Id: {0} and contact type: {1}", entity.Id.ToString(), entity.OrgMemberType));
message = className + "- Unsuccessful: Update(): " + ex.Message.ToString();
entity.Message = message;
entity.IsValid = false;
}
return message;
}//
#endregion
#region ====== Retrieval Methods ===============================================
public static OrganizationMember Get( int pId )
{
return Get( pId, 0, 0 );
}
public static OrganizationMember Get( int orgId, int userId )
{
return Get( 0, orgId, userId );
}
/// <summary>
/// Get a OrganizationMember using the primary key: Id
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
private static OrganizationMember Get( int pId, int pOrgId, int pUserId )
{
OrganizationMember entity = new OrganizationMember();
string connectionString = GatewayConnectionRO();
try
{
SqlParameter[] sqlParameters = new SqlParameter[ 3 ];
sqlParameters[ 0 ] = new SqlParameter( "@Id", pId);
sqlParameters[ 1 ] = new SqlParameter( "@OrgId", pOrgId);
sqlParameters[ 2 ] = new SqlParameter( "@UserId", pUserId);
SqlDataReader dr = SqlHelper.ExecuteReader( connectionString, GET_PROC, sqlParameters );
if ( dr.HasRows )
{
// it should return only one record.
while ( dr.Read() )
{
entity = Fill( dr );
}
} else
{
entity.Message = "Record not found";
entity.IsValid = false;
}
dr.Close();
dr = null;
return entity;
} catch ( Exception ex )
{
LogError( ex, className + ".Get(int userId) " );
entity.Message = className + "- Unsuccessful: Get(int userId): " + ex.ToString();
entity.IsValid = false;
}
return entity;
} //GetOrganizationMember
public static List<OrganizationMember> SearchAsList( string pFilter, string pOrderBy, int pStartPageIndex, int pMaximumRows, ref int pTotalRows )
{
List<OrganizationMember> list = new List<OrganizationMember>();
DataSet ds = Search( pFilter, pOrderBy, pStartPageIndex, pMaximumRows, ref pTotalRows );
if ( DatabaseManager.DoesDataSetHaveRows( ds ) )
{
foreach ( DataRow dr in ds.Tables[ 0 ].DefaultView.Table.Rows )
{
OrganizationMember org = Fill( dr, true );
list.Add( org );
} //end foreach
}
return list;
}//
/// <summary>
/// Select business contacts related data using passed parameters
/// - uses custom paging
/// - only requested range of rows will be returned
/// </summary>
/// <param name="pFilter"></param>
/// <param name="pStartPageIndex"></param>
/// <param name="pMaximumRows"></param>
/// <param name="pTotalRows"></param>
/// <returns></returns>
public static DataSet Search( string pFilter, string pOrderBy, int pStartPageIndex, int pMaximumRows, ref int pTotalRows )
{
int outputCol = 4;
SqlParameter[] sqlParameters = new SqlParameter[ 5 ];
sqlParameters[ 0 ] = new SqlParameter( "@Filter", pFilter );
sqlParameters[ 1 ] = new SqlParameter( "@SortOrder", pOrderBy );
sqlParameters[ 2 ] = new SqlParameter( "@StartPageIndex", pStartPageIndex );
sqlParameters[ 3 ] = new SqlParameter( "@PageSize", pMaximumRows );
sqlParameters[ outputCol ] = new SqlParameter( "@TotalRows", SqlDbType.Int );
sqlParameters[ outputCol ].Direction = ParameterDirection.Output;
using ( SqlConnection conn = new SqlConnection( GatewayConnectionRO() ) )
{
DataSet ds = new DataSet();
try
{
ds = SqlHelper.ExecuteDataset( conn, CommandType.StoredProcedure, "[Organization.MemberSearch]", sqlParameters );
string rows = sqlParameters[ outputCol ].Value.ToString();
try
{
pTotalRows = Int32.Parse( rows );
}
catch
{
pTotalRows = 0;
}
if ( ds.HasErrors )
{
return null;
}
return ds;
}
catch ( Exception ex )
{
LogError( ex, className + ".Search(). filter: " + pFilter );
return null;
}
}
}
#endregion
#region ====== Helper Methods ===============================================
/// <summary>
/// Fill an OrganizationMember object from a DataRow
/// </summary>
/// <param name="dr">DataRow</param>
/// <returns>OrganizationMember</returns>
public static OrganizationMember Fill( DataRow dr, bool fillingUser )
{
OrganizationMember entity = new OrganizationMember();
entity.Id = GetRowPossibleColumn( dr, "OrgMbrId", 0 );
if (entity.Id == 0)
entity.Id = GetRowPossibleColumn( dr, "Id", 0 );
entity.IsValid = true;
entity.OrgId = GetRowColumn( dr, "OrgId", 0 );
entity.IsOrgActive = GetRowColumn( dr, "IsActive", false );
//entity.is
entity.UserId = GetRowColumn( dr, "UserId", 0 );
entity.OrgMemberTypeId = GetRowColumn( dr, "OrgMemberTypeId", 0 );
entity.OrgMemberType = GetRowColumn( dr, "OrgMemberType", "" );
entity.Organization = GetRowColumn( dr, "Organization", "Missing" );
entity.IsIsleApprovedOrg = GetRowColumn( dr, "IsIsleMember", false );
//entity.Comment = dr[ "Comment" ].ToString();
entity.Created = GetRowPossibleColumn( dr, "MemberAdded", entity.DefaultDate );
if (entity.Created == entity.DefaultDate)
entity.Created = GetRowPossibleColumn( dr, "Created", entity.DefaultDate );
entity.CreatedById = GetRowPossibleColumn( dr, "CreatedById", 0 );
entity.LastUpdated = DateTime.Parse( dr[ "LastUpdated" ].ToString() );
if ( fillingUser )
{
entity.FirstName = GetRowColumn( dr, "FirstName", "none" );
entity.LastName = GetRowColumn( dr, "LastName", "none" );
}
//entity.LastUpdatedById = GetRowPossibleColumn( dr, "LastUpdatedById", 0 );
return entity;
}//
/// <summary>
/// Fill an OrganizationMember object from a SqlDataReader
/// </summary>
/// <param name="dr"></param>
/// <returns></returns>
public static OrganizationMember Fill( SqlDataReader dr )
{
OrganizationMember entity = new OrganizationMember();
entity.Id = GetRowPossibleColumn( dr, "OrgMbrId", 0 );
if ( entity.Id == 0 )
entity.Id = GetRowPossibleColumn( dr, "Id", 0 );
entity.IsValid = true;
entity.OrgId = GetRowColumn( dr, "OrgId", 0 );
entity.UserId = GetRowColumn( dr, "UserId", 0 );
entity.OrgMemberTypeId = GetRowColumn( dr, "OrgMemberTypeId", 0 );
entity.OrgMemberType = GetRowColumn( dr, "OrgMemberType", "" );
entity.Organization = GetRowColumn( dr, "Organization", "Missing" );
//entity.Comment = dr[ "Comment" ].ToString();
entity.Created = GetRowPossibleColumn( dr, "MemberAdded", entity.DefaultDate );
if ( entity.Created == entity.DefaultDate )
entity.Created = GetRowPossibleColumn( dr, "Created", entity.DefaultDate );
entity.CreatedById = GetRowPossibleColumn( dr, "CreatedById", 0 );
//entity.LastUpdated = DateTime.Parse( dr[ "LastUpdated" ].ToString() );
//entity.LastUpdatedById = GetRowPossibleColumn( dr, "LastUpdatedById", 0 );
return entity;
}//
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using OpenCVProxy.Interop;
namespace OpenCVProxy
{
public sealed class IplImage : CvUnmanagedObject, ICloneable
{
bool ownHandle;
ImageInfo imageInfo;
public CvSize Size
{
get { return new CvSize(imageInfo.width, imageInfo.height); }
}
public int Depth
{
get { return imageInfo.depth; }
}
public int Channels
{
get { return imageInfo.nChannels; }
}
public int Origin
{
get { return imageInfo.origin; }
}
internal IplImage(IntPtr handle, bool ownHandle) : base(handle)
{
this.ownHandle = ownHandle;
ReadImageInfo();
}
public IplImage(CvSize size, int depth, int channels) : base(CreateImage(size, depth, channels))
{
this.ownHandle = true;
ReadImageInfo();
}
public IplImage(string filename, int isColor) : base(LoadImageFromFile(filename, isColor))
{
this.ownHandle = true;
ReadImageInfo();
}
private void ReadImageInfo()
{
imageInfo = (ImageInfo)Marshal.PtrToStructure(Handle, typeof(ImageInfo));
}
private static IntPtr CreateImage(CvSize size, int depth, int channels)
{
return CxCore.cvCreateImage(size, depth, channels);
}
private static IntPtr LoadImageFromFile(string filename, int isColor)
{
IntPtr handle = HighGui.cvLoadImage(filename, isColor);
if (handle == IntPtr.Zero)
throw new Exception("Image not loaded");
return handle;
}
public CvScalar GetPixel(int x, int y)
{
int pixelSize = imageInfo.nChannels * (imageInfo.depth / 8);
int offset = pixelSize * x + imageInfo.widthStep * y;
IntPtr address = new IntPtr(imageInfo.imageData.ToInt32() + offset);
return new CvScalar(Marshal.ReadByte(address, 0), Marshal.ReadByte(address, 1), Marshal.ReadByte(address, 2));
}
public void SetPixel(int x, int y, CvScalar color)
{
int pixelSize = imageInfo.nChannels * (imageInfo.depth / 8);
int offset = pixelSize * x + imageInfo.widthStep * y;
IntPtr address = new IntPtr(imageInfo.imageData.ToInt32() + offset);
Marshal.WriteByte(address, 0, (byte)Math.Round(color.item1));
Marshal.WriteByte(address, 1, (byte)Math.Round(color.item2));
Marshal.WriteByte(address, 2, (byte)Math.Round(color.item3));
}
public IplImage CloneGray()
{
IplImage newImage = new IplImage(Size, Depth, 1);
ConvertColor(newImage, Cv.CV_BGR2GRAY);
return newImage;
}
public IplImage GaussianSmooth()
{
const int DefaultSmooth = 3;
return GaussianSmooth(DefaultSmooth);
}
public IplImage GaussianSmooth(int size1)
{
IntPtr smoothedImage = CreateImage(Size, Depth, Channels);
Cv.cvSmooth(Handle, smoothedImage, Cv.CV_GAUSSIAN,
size1, 0, 0, 0);
return new IplImage(smoothedImage, true);
}
public void SetZero()
{
CxCore.cvSetZero(Handle);
}
public void CopyTo(IplImage destination)
{
CxCore.cvCopy(Handle, destination.Handle, IntPtr.Zero);
}
public void CopyTo(IplImage destination, IplImage mask)
{
CxCore.cvCopy(Handle, destination.Handle, mask.Handle);
}
public void ConvertColor(IplImage destination, int code)
{
Cv.cvCvtColor(Handle, destination.Handle, code);
}
public static void Copy(IplImage source, IplImage destination)
{
CxCore.cvCopy(source.Handle, destination.Handle, IntPtr.Zero);
}
public static void Copy(IplImage source, IplImage destination, IplImage mask)
{
CxCore.cvCopy(source.Handle, destination.Handle, mask.Handle);
}
public static void Not(IplImage source, IplImage destination)
{
CxCore.cvNot(source.Handle, destination.Handle);
}
public static void Flip(IplImage source, IplImage destination, int mode)
{
CxCore.cvFlip(source.Handle, destination.Handle, mode);
}
public IplImage CloneImage()
{
IntPtr newImage = CxCore.cvCloneImage(Handle);
return new IplImage(newImage, true);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (ownHandle)
{
using (IntPtrSafeMemoryBox releasePad = new IntPtrSafeMemoryBox())
{
releasePad.Value = Handle;
CxCore.cvReleaseImage(releasePad.Pointer);
}
}
}
public object Clone()
{
return CloneImage();
}
[StructLayout(LayoutKind.Sequential)]
private struct ImageInfo
{
public int nSize; /* sizeof(IplImage) */
public int ID; /* version (=0)*/
public int nChannels; /* Most of OpenCV functions support 1,2,3 or 4 channels */
public int alphaChannel; /* ignored by OpenCV */
public int depth; /* pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16U,
IPL_DEPTH_16S, IPL_DEPTH_32S, IPL_DEPTH_32F and IPL_DEPTH_64F are supported */
public uint ignoredColorModel;
public char ignoredChannelSeq;
public int dataOrder; /* 0 - interleaved color channels, 1 - separate color channels.
cvCreateImage can only create interleaved images */
public int origin; /* 0 - top-left origin,
1 - bottom-left origin (Windows bitmaps style) */
public int align; /* Alignment of image rows (4 or 8).
OpenCV ignores it and uses widthStep instead */
public int width; /* image width in pixels */
public int height; /* image height in pixels */
public IntPtr roi; /* image ROI. when it is not NULL, this specifies image region to process */
public IntPtr maskROI;
public IntPtr imageId;
public IntPtr tileInfo;
public int imageSize; /* image data size in bytes
(=image->height*image->widthStep
in case of interleaved data)*/
public IntPtr imageData; /* pointer to aligned image data */
public int widthStep; /* size of aligned image row in bytes */
/* more data present. Ignoring ... */
}
}
}
| |
// This file was automatically generated by the PetaPoco T4 Template
// Do not make changes directly to this file - edit the template instead
//
// The following connection settings were used to generate this file
//
// Connection String Name: `CheetahPocoModel`
// Provider: `System.Data.SqlClient`
// Connection String: `Data Source=(localdb)\ProjectsV12;Initial Catalog=Cheetah;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False`
// Schema: ``
// Include Views: `False`
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PetaPoco;
namespace Cheetah.DataAccess.Models
{
public partial class CheetahPocoModelDB : Database
{
public CheetahPocoModelDB()
: base("CheetahPocoModel")
{
CommonConstruct();
}
public CheetahPocoModelDB(string connectionStringName)
: base(connectionStringName)
{
CommonConstruct();
}
partial void CommonConstruct();
public interface IFactory
{
CheetahPocoModelDB GetInstance();
}
public static IFactory Factory { get; set; }
public static CheetahPocoModelDB GetInstance()
{
if (_instance!=null)
return _instance;
if (Factory!=null)
return Factory.GetInstance();
else
return new CheetahPocoModelDB();
}
[ThreadStatic] static CheetahPocoModelDB _instance;
public override void OnBeginTransaction()
{
if (_instance==null)
_instance=this;
}
public override void OnEndTransaction()
{
if (_instance==this)
_instance=null;
}
public class Record<T> where T:new()
{
public static CheetahPocoModelDB repo { get { return CheetahPocoModelDB.GetInstance(); } }
public bool IsNew() { return repo.IsNew(this); }
public object Insert() { return repo.Insert(this); }
public void Save() { repo.Save(this); }
public int Update() { return repo.Update(this); }
public int Update(IEnumerable<string> columns) { return repo.Update(this, columns); }
public static int Update(string sql, params object[] args) { return repo.Update<T>(sql, args); }
public static int Update(Sql sql) { return repo.Update<T>(sql); }
public int Delete() { return repo.Delete(this); }
public static int Delete(string sql, params object[] args) { return repo.Delete<T>(sql, args); }
public static int Delete(Sql sql) { return repo.Delete<T>(sql); }
public static int Delete(object primaryKey) { return repo.Delete<T>(primaryKey); }
public static bool Exists(object primaryKey) { return repo.Exists<T>(primaryKey); }
public static bool Exists(string sql, params object[] args) { return repo.Exists<T>(sql, args); }
public static T SingleOrDefault(object primaryKey) { return repo.SingleOrDefault<T>(primaryKey); }
public static T SingleOrDefault(string sql, params object[] args) { return repo.SingleOrDefault<T>(sql, args); }
public static T SingleOrDefault(Sql sql) { return repo.SingleOrDefault<T>(sql); }
public static T FirstOrDefault(string sql, params object[] args) { return repo.FirstOrDefault<T>(sql, args); }
public static T FirstOrDefault(Sql sql) { return repo.FirstOrDefault<T>(sql); }
public static T Single(object primaryKey) { return repo.Single<T>(primaryKey); }
public static T Single(string sql, params object[] args) { return repo.Single<T>(sql, args); }
public static T Single(Sql sql) { return repo.Single<T>(sql); }
public static T First(string sql, params object[] args) { return repo.First<T>(sql, args); }
public static T First(Sql sql) { return repo.First<T>(sql); }
public static List<T> Fetch(string sql, params object[] args) { return repo.Fetch<T>(sql, args); }
public static List<T> Fetch(Sql sql) { return repo.Fetch<T>(sql); }
public static List<T> Fetch(long page, long itemsPerPage, string sql, params object[] args) { return repo.Fetch<T>(page, itemsPerPage, sql, args); }
public static List<T> Fetch(long page, long itemsPerPage, Sql sql) { return repo.Fetch<T>(page, itemsPerPage, sql); }
public static List<T> SkipTake(long skip, long take, string sql, params object[] args) { return repo.SkipTake<T>(skip, take, sql, args); }
public static List<T> SkipTake(long skip, long take, Sql sql) { return repo.SkipTake<T>(skip, take, sql); }
public static Page<T> Page(long page, long itemsPerPage, string sql, params object[] args) { return repo.Page<T>(page, itemsPerPage, sql, args); }
public static Page<T> Page(long page, long itemsPerPage, Sql sql) { return repo.Page<T>(page, itemsPerPage, sql); }
public static IEnumerable<T> Query(string sql, params object[] args) { return repo.Query<T>(sql, args); }
public static IEnumerable<T> Query(Sql sql) { return repo.Query<T>(sql); }
}
}
[TableName("AccessTokens")]
[PrimaryKey("Id")]
[ExplicitColumns]
public partial class AccessToken : CheetahPocoModelDB.Record<AccessToken>
{
[Column] public int Id { get; set; }
[Column] public Guid UserId { get; set; }
[Column] public string Token { get; set; }
[Column] public DateTime Expires { get; set; }
[Column] public DateTime CreatedAt { get; set; }
}
[TableName("PasswordHashes")]
[PrimaryKey("Id")]
[ExplicitColumns]
public partial class PasswordHash : CheetahPocoModelDB.Record<PasswordHash>
{
[Column] public int Id { get; set; }
[Column] public Guid UserId { get; set; }
[Column] public string Hash { get; set; }
[Column] public DateTime CreatedAt { get; set; }
}
[TableName("RefreshTokens")]
[PrimaryKey("Id")]
[ExplicitColumns]
public partial class RefreshToken : CheetahPocoModelDB.Record<RefreshToken>
{
[Column] public int Id { get; set; }
[Column] public Guid UserId { get; set; }
[Column] public string Token { get; set; }
[Column] public DateTime CreatedAt { get; set; }
}
[TableName("UserProfiles")]
[PrimaryKey("Id")]
[ExplicitColumns]
public partial class UserProfile : CheetahPocoModelDB.Record<UserProfile>
{
[Column] public int Id { get; set; }
[Column] public string FirstName { get; set; }
[Column] public string LastName { get; set; }
[Column] public DateTime? DateOfBirth { get; set; }
[Column] public string Location { get; set; }
[Column] public string Description { get; set; }
}
[TableName("Users")]
[PrimaryKey("Id")]
[ExplicitColumns]
public partial class User : CheetahPocoModelDB.Record<User>
{
[Column] public int Id { get; set; }
[Column] public Guid UserId { get; set; }
[Column] public string Username { get; set; }
[Column] public DateTime CreatedAt { get; set; }
[Column] public Guid ClientId { get; set; }
[Column] public string Email { get; set; }
[Column] public int? UserProfileId { get; set; }
}
}
| |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Input;
namespace ColorPickerSampleApplication
{
public partial class SampleViewer : Window
{
public SampleViewer()
{
InitializeComponent();
}
#region Dependency Property Fields
public static readonly DependencyProperty SelectedShapeProperty =
DependencyProperty.Register
("SelectedShape", typeof(Shape), typeof(SampleViewer),
new PropertyMetadata(null, selectedShape_Changed));
public static readonly DependencyProperty DrawingModeProperty =
DependencyProperty.Register
("DrawingMode", typeof(DrawingMode), typeof(SampleViewer),
new PropertyMetadata(DrawingMode.Select));
public static readonly DependencyProperty FillColorProperty =
DependencyProperty.Register
("FillColor", typeof(Color), typeof(SampleViewer),
new PropertyMetadata(Colors.LightGray));
public static readonly DependencyProperty StrokeColorProperty =
DependencyProperty.Register
("StrokeColor", typeof(Color), typeof(SampleViewer),
new PropertyMetadata(Colors.Black));
public static readonly DependencyProperty StrokeThicknessProperty =
DependencyProperty.Register
("StrokeThickness", typeof(double), typeof(SampleViewer),
new PropertyMetadata(1.0, strokeThickness_Changed));
#endregion
#region Public Properties
public DrawingMode DrawingMode
{
get
{
return (DrawingMode)GetValue(DrawingModeProperty);
}
set
{
SetValue(DrawingModeProperty, value);
}
}
public Color FillColor
{
get
{
return (Color)GetValue(FillColorProperty);
}
set
{
SetValue(FillColorProperty, value);
}
}
public Color StrokeColor
{
get
{
return (Color)GetValue(StrokeColorProperty);
}
set
{
SetValue(StrokeColorProperty, value);
}
}
public double StrokeThickness
{
get
{
return (double)GetValue(StrokeThicknessProperty);
}
set
{
SetValue(StrokeThicknessProperty, value);
}
}
#endregion
private static void selectedShape_Changed(object sender,
DependencyPropertyChangedEventArgs e)
{
SampleViewer sViewer = (SampleViewer)sender;
sViewer.OnSelectedShapeChanged((Shape)e.OldValue, (Shape)e.NewValue);
}
protected void OnSelectedShapeChanged(Shape oldShape, Shape newShape)
{
if (newShape != null)
{
FillColor = ((SolidColorBrush)newShape.Fill).Color;
StrokeColor = ((SolidColorBrush)newShape.Stroke).Color;
StrokeThickness = newShape.StrokeThickness;
}
}
private static void strokeThickness_Changed(object sender,
DependencyPropertyChangedEventArgs e)
{
SampleViewer sViewer = (SampleViewer)sender;
sViewer.OnStrokeThicknessChanged((double)e.OldValue, (double)e.NewValue);
}
protected void OnStrokeThicknessChanged(double oldThickness, double newThickness)
{
Shape currentShape = (Shape)GetValue(SelectedShapeProperty);
if (currentShape != null)
{
currentShape.StrokeThickness = newThickness;
}
}
private void OnDrawingCanvasMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Point clickPoint = e.GetPosition(DrawingCanvas);
if (DrawingMode == DrawingMode.Select)
{
if (e.OriginalSource is Shape)
{
Shape s = (Shape)e.OriginalSource;
SetValue(SelectedShapeProperty, s);
shapeClickPoint = e.GetPosition(s);
}
else
SetValue(SelectedShapeProperty, null);
}
else if (DrawingMode == DrawingMode.DrawRectangle && e.LeftButton == MouseButtonState.Pressed)
{
newRectangle = new Rectangle();
newRectangle.Stroke = new SolidColorBrush(StrokeColor);
newRectangle.StrokeThickness = StrokeThickness;
newRectangle.Fill = new SolidColorBrush(FillColor);
Canvas.SetLeft(newRectangle, clickPoint.X);
Canvas.SetTop(newRectangle, clickPoint.Y);
DrawingCanvas.Children.Add(newRectangle);
SetValue(SelectedShapeProperty, newRectangle);
}
else if (DrawingMode == DrawingMode.DrawEllipse && e.LeftButton == MouseButtonState.Pressed)
{
newEllipse = new Ellipse();
newEllipse.Stroke = new SolidColorBrush(StrokeColor);
newEllipse.StrokeThickness = StrokeThickness;
newEllipse.Fill = new SolidColorBrush(FillColor);
Canvas.SetLeft(newEllipse, clickPoint.X);
Canvas.SetTop(newEllipse, clickPoint.Y);
DrawingCanvas.Children.Add(newEllipse);
SetValue(SelectedShapeProperty, newEllipse);
}
else if (DrawingMode == DrawingMode.DrawLine && e.LeftButton == MouseButtonState.Pressed)
{
newLine = new Line();
newLine.Stroke = new SolidColorBrush(StrokeColor);
newLine.Fill = new SolidColorBrush(FillColor);;
newLine.X1 = clickPoint.X;
newLine.Y1 = clickPoint.Y;
newLine.StrokeThickness = StrokeThickness;
DrawingCanvas.Children.Add(newLine);
SetValue(SelectedShapeProperty, newLine);
}
}
private void OnDrawingCanvasMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (DrawingMode == DrawingMode.DrawRectangle)
{
newRectangle = null;
}
else if (DrawingMode == DrawingMode.DrawEllipse)
{
newEllipse = null;
}
else if (DrawingMode == DrawingMode.DrawLine)
{
newLine = null;
}
}
private void OnDrawingCanvasMouseMove(object sender, MouseEventArgs e)
{
Point dropPoint = e.GetPosition(DrawingCanvas);
if (DrawingMode == DrawingMode.Select)
{
Shape s = (Shape)GetValue(SelectedShapeProperty);
if (s != null && e.LeftButton == MouseButtonState.Pressed)
{
Canvas.SetLeft(s, dropPoint.X - shapeClickPoint.X);
Canvas.SetTop(s, dropPoint.Y - shapeClickPoint.Y);
s.BitmapEffect = null;
}
}
else if (DrawingMode == DrawingMode.DrawRectangle)
{
if (newRectangle != null)
{
if (dropPoint.X > Canvas.GetLeft(newRectangle))
newRectangle.Width = dropPoint.X - Canvas.GetLeft(newRectangle);
if (dropPoint.Y > Canvas.GetTop(newRectangle))
newRectangle.Height = dropPoint.Y - Canvas.GetTop(newRectangle);
}
}
else if (DrawingMode == DrawingMode.DrawEllipse)
{
if (newEllipse != null)
{
if (dropPoint.X > Canvas.GetLeft(newEllipse))
newEllipse.Width = dropPoint.X - Canvas.GetLeft(newEllipse);
if (dropPoint.Y > Canvas.GetTop(newEllipse))
newEllipse.Height = dropPoint.Y - Canvas.GetTop(newEllipse);
}
}
else if (DrawingMode == DrawingMode.DrawLine)
{
if (newLine != null)
{
newLine.X2 = dropPoint.X;
newLine.Y2 = dropPoint.Y;
}
}
}
private void OnDrawingCanvasKeyDown(object sender, KeyEventArgs e)
{
Shape s = (Shape)GetValue(SelectedShapeProperty);
if (e.Key == Key.Delete && s!= null)
{
DrawingCanvas.Children.Remove(s);
SetValue(SelectedShapeProperty, null);
}
}
private void SetStroke(object sender, RoutedEventArgs e)
{
Shape selectedShape = (Shape)GetValue(SelectedShapeProperty);
Microsoft.Samples.CustomControls.ColorPickerDialog cPicker
= new Microsoft.Samples.CustomControls.ColorPickerDialog();
cPicker.StartingColor = StrokeColor;
cPicker.Owner = this;
cPicker.ShowAlpha = false;
bool? dialogResult = cPicker.ShowDialog();
if (dialogResult != null && (bool)dialogResult == true)
{
if (selectedShape != null)
selectedShape.Stroke = new SolidColorBrush(cPicker.SelectedColor);
StrokeColor = cPicker.SelectedColor;
}
}
private void SetFill(object sender, RoutedEventArgs e)
{
Shape selectedShape = (Shape)GetValue(SelectedShapeProperty);
Microsoft.Samples.CustomControls.ColorPickerDialog cPicker
= new Microsoft.Samples.CustomControls.ColorPickerDialog();
cPicker.StartingColor = FillColor;
cPicker.Owner = this;
bool? dialogResult = cPicker.ShowDialog();
if (dialogResult != null && (bool)dialogResult == true)
{
if (selectedShape != null)
selectedShape.Fill = new SolidColorBrush(cPicker.SelectedColor);
FillColor = cPicker.SelectedColor;
}
}
private void drawingModeChanged(object sender, EventArgs e)
{
RadioButton r = (RadioButton)sender;
SetValue(DrawingModeProperty, Enum.Parse(typeof(DrawingMode), r.Name));
}
private void exitMenuItemClicked(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
#region Private Fields
private Point shapeClickPoint;
private Rectangle newRectangle;
private Line newLine;
private Ellipse newEllipse;
#endregion
}
public enum DrawingMode
{
Select=0, DrawLine=1, DrawRectangle=2, DrawEllipse=3
}
}
| |
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Rb.Forms.Barcode.Droid;
using Rb.Forms.Barcode.Droid.Camera;
using Rb.Forms.Barcode.Droid.Logger;
using Rb.Forms.Barcode.Droid.View;
using Rb.Forms.Barcode.Pcl;
using Rb.Forms.Barcode.Pcl.Logger;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(BarcodeScanner), typeof(BarcodeScannerRenderer))]
namespace Rb.Forms.Barcode.Droid
{
public class BarcodeScannerRenderer : ViewRenderer<BarcodeScanner, SurfaceView>, ISurfaceHolderCallback, ILog
{
/// <summary>
/// The desired BarcodeScannerRenderer configuration.
/// </summary>
/// <see cref="Configuration" />
private static Configuration config;
/// <summary>
/// Camera configuration callback.
/// We want to keep the same instance over the life time of the BarcodeScannerRenderer so that we
/// remember configured options when Enabling/Disabling the camera
/// </summary>
private readonly CameraConfigurator configurator;
/// <summary>
/// Do not use this. Use the Property instead.
/// </summary>
/// <see cref="BarcodeScannerRenderer.CameraService" />
private CameraService cameraServiceHolder;
private CameraService CameraService {
get {
if (null == cameraServiceHolder) {
var factory = new CameraServiceFactory();
cameraServiceHolder = factory.Create(Context, Element, configurator);
}
return cameraServiceHolder;
}
}
private Lazy<Platform> platform;
private Platform Platform {
get {
return platform.Value;
}
}
/// <summary>
/// Checks the surface for validity so its safe to work with it.
/// </summary>
/// <value><c>true</c> if this instance has valid surface; otherwise, <c>false</c>.</value>
private bool HasValidSurface {
get {
return Control?.Holder.Surface.IsValid == true;
}
}
public static void Init()
{
Init(new Configuration());
}
public static void Init(Configuration config)
{
BarcodeScannerRenderer.config = config;
}
public BarcodeScannerRenderer()
{
configurator = new CameraConfigurator().SetConfiguration(config);
platform = new Lazy<Platform>(() => new Platform());
}
public async void SurfaceCreated(ISurfaceHolder holder)
{
this.Debug("SurfaceCreated");
}
public async void SurfaceChanged(ISurfaceHolder holder, global::Android.Graphics.Format format, int width, int height)
{
this.Debug("SurfaceChanged");
if (!HasValidSurface) {
return;
}
// portrait mode
if (height > width) {
CameraService.SetViewSize(height, width);
} else {
CameraService.SetViewSize(width, height);
}
if (!Element.IsEnabled) {
return;
}
CameraService.HaltPreview();
await Task.Run(() => {
CameraService.StartPreview(holder);
});
}
public void SurfaceDestroyed(ISurfaceHolder holder)
{
this.Debug("SurfaceDestroyed");
Element.IsEnabled = false;
}
protected override void OnElementChanged(ElementChangedEventArgs<BarcodeScanner> e)
{
this.Debug("OnElementChanged");
base.OnElementChanged(e);
if (!Platform.HasCameraPermission) {
this.Debug("Unable to setup scanner: Android Manifest '{0}' permission not granted.", Android.Manifest.Permission.Camera);
return;
}
if (!Platform.HasCamera) {
this.Debug("Unable to setup scanner: Device has no camera.");
return;
}
if (!Platform.IsGmsReady) {
this.Debug("Unable to setup scanner: Google mobile services are not ready.");
return;
}
if (Control != null) {
return;
}
var surfaceView = new SurfaceView(Context);
surfaceView.Holder.AddCallback(this);
SetNativeControl(surfaceView);
Element.CameraOpened += async (sender, args) => {
if (Element.PreviewActive) {
await Task.Run(() => CameraService.StartPreview(Control.Holder));
}
};
}
protected async override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
this.Debug("OnElementPropertyChanged");
if (!HasValidSurface) {
return;
}
if (e.PropertyName == BarcodeScanner.IsEnabledProperty.PropertyName) {
this.Debug("Enabled [{0}]", Element.IsEnabled);
if (Element.IsEnabled && HasValidSurface) {
await Task.Run(CameraService.OpenCamera);
}
if (!Element.IsEnabled) {
ReleaseCamera();
}
}
if (e.PropertyName == BarcodeScanner.PreviewActiveProperty.PropertyName) {
this.Debug("ScannerActive [{0}]", Element.PreviewActive);
if (Element.PreviewActive) {
await Task.Run(() => CameraService.StartPreview(Control.Holder));
}
if (!Element.PreviewActive) {
CameraService.HaltPreview();
}
}
if (e.PropertyName == BarcodeScanner.TorchProperty.PropertyName) {
if (!Platform.HasFlashPermission) {
this.Debug("Unable to use flashlight: Android Manifest '{0}' permission not granted.", Android.Manifest.Permission.Flashlight);
return;
}
if (!Platform.HasFlash) {
this.Debug("Unable to use flashlight: Device's camera does not support flash.");
return;
}
this.Debug("Torch [{0}]", Element.Torch);
CameraService.ToggleTorch(Element.Torch);
}
if (e.PropertyName == BarcodeScanner.BarcodeDecoderProperty.PropertyName) {
this.Debug("Decoder state [{0}]", Element.BarcodeDecoder);
if (Element.BarcodeDecoder) {
CameraService.StartDecoder();
}
if (!Element.BarcodeDecoder) {
CameraService.StopDecoder();
}
}
}
protected override void Dispose(bool disposing)
{
this.Debug("Disposing");
ReleaseCamera();
base.Dispose(disposing);
}
private void ReleaseCamera()
{
CameraService?.ReleaseCamera();
cameraServiceHolder = null;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
//
// ********************************************************************************************************
//
// The Original Code is DotSpatial.dll for the DotSpatial project
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in August, 2007.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Data;
using GeoAPI.Geometries;
namespace DotSpatial.Data
{
/// <summary>
/// A layer contains a list of features of a specific type that matches the geometry type.
/// While this supports IRenderable, this merely forwards the drawing instructions to
/// each of its members, but does not allow the control of any default layer properties here.
/// Calling FeatureDataSource.Open will create a number of layers of the appropriate
/// specific type and also create a specific layer type that is derived from this class
/// that does expose default "layer" properties, as well as the symbology elements.
/// </summary>
public interface IFeatureSet : IDataSet, IAttributeSource
{
#region Events
/// <summary>
/// Occurs when the vertices are invalidated, encouraging a re-draw
/// </summary>
event EventHandler VerticesInvalidated;
/// <summary>
/// Occurs when a new feature is added to the list
/// </summary>
event EventHandler<FeatureEventArgs> FeatureAdded;
/// <summary>
/// Occurs when a feature is removed from the list.
/// </summary>
event EventHandler<FeatureEventArgs> FeatureRemoved;
#endregion
#region Methods
/// <summary>
/// For attributes that are small enough to be loaded into a data table, this
/// will join attributes from a foreign table. This method
/// won't create new rows in this table, so only matching members are brought in,
/// but no rows are removed either, so not all rows will receive data.
/// </summary>
/// <param name="table">Foreign data table.</param>
/// <param name="localJoinField">The field name to join on in this table.</param>
/// <param name="dataTableJoinField">The field in the foreign table.</param>
/// <returns>
/// A modified featureset with the changes.
/// </returns>
IFeatureSet Join(DataTable table, string localJoinField, string dataTableJoinField);
/// <summary>
/// For attributes that are small enough to be loaded into a data table, this
/// will join attributes from a foreign table (from an excel file). This method
/// won't create new rows in this table, so only matching members are brought in,
/// but no rows are removed either, so not all rows will receive data.
/// </summary>
/// <param name="xlsFilePath">The complete path of the file to join</param>
/// <param name="localJoinField">The field name to join on in this table</param>
/// <param name="xlsJoinField">The field in the foreign table.</param>
/// <returns>
/// A modified featureset with the changes.
/// </returns>
IFeatureSet Join(string xlsFilePath, string localJoinField, string xlsJoinField);
/// <summary>
/// If this featureset is in index mode, this will append the vertices and shapeindex of the shape.
/// Otherwise, this will add a new feature based on this shape. If the attributes of the shape are not null,
/// this will attempt to append a new datarow It is up to the developer
/// to ensure that the object array of attributes matches the this featureset. If the Attributes of this feature are loaded,
/// this will add the attributes in ram only. Otherwise, this will attempt to insert the attributes as a
/// new record using the "AddRow" method. The schema of the object array should match this featureset's column schema.
/// </summary>
/// <param name="shape">The shape to add to this featureset.</param>
void AddShape(Shape shape);
/// <summary>
/// Adds any type of list or array of shapes. If this featureset is not in index moded,
/// it will add the features to the featurelist and suspend events for faster copying.
/// </summary>
/// <param name="shapes">An enumerable collection of shapes.</param>
void AddShapes(IEnumerable<Shape> shapes);
/// <summary>
/// Gets the specified feature by constructing it from the vertices, rather
/// than requiring that all the features be created. (which takes up a lot of memory).
/// </summary>
/// <param name="index">The integer index</param>
IFeature GetFeature(int index);
/// <summary>
/// Gets a shape at the specified shape index. If the featureset is in IndexMode, this returns a copy of the shape.
/// If not, it will create a new shape based on the specified feature.
/// </summary>
/// <param name="index">The zero based integer index of the shape.</param>
/// <param name="getAttributes">If getAttributes is true, then this also try to get attributes for that shape.
/// If attributes are loaded, then it will use the existing datarow. Otherwise, it will read the attributes
/// from the file. (This second option is not recommended for large repeats. In such a case, the attributes
/// can be set manually from a larger bulk query of the data source.)</param>
/// <returns>The Shape object</returns>
Shape GetShape(int index, bool getAttributes);
/// <summary>
/// Given a datarow, this will return the associated feature. This FeatureSet
/// uses an internal dictionary, so that even if the items are re-ordered
/// or have new members inserted, this lookup will still work.
/// </summary>
/// <param name="row">The DataRow for which to obtaind the feature</param>
/// <returns>The feature to obtain that is associated with the specified data row.</returns>
IFeature FeatureFromRow(DataRow row);
/// <summary>
/// Generates a new feature, adds it to the features and returns the value.
/// </summary>
/// <returns>The feature that was added to this featureset</returns>
IFeature AddFeature(IGeometry geometry);
/// <summary>
/// Adds the FID values as a field called FID, but only if the FID field
/// does not already exist
/// </summary>
void AddFid();
/// <summary>
/// Copies all the features to a new featureset.
/// </summary>
/// <param name="withAttributes">Indicates whether the features attributes should be copied. If this is true,
/// and the attributes are not loaded, a FillAttributes call will be made.</param>
IFeatureSet CopyFeatures(bool withAttributes);
/// <summary>
/// Retrieves a subset using exclusively the features matching the specified values. Attributes are always copied.
/// </summary>
/// <param name="indices">An integer list of indices to copy into the new FeatureSet</param>
/// <returns>A FeatureSet with the new items.</returns>
IFeatureSet CopySubset(List<int> indices);
/// <summary>
/// Retrieves a subset using exclusively the features matching the specified values. Attributes are only copied if withAttributes is true.
/// </summary>
/// <param name="indices">An integer list of indices to copy into the new FeatureSet.</param>
/// <param name="withAttributes">Indicates whether the features attributes should be copied.</param>
/// <returns>A FeatureSet with the new items.</returns>
IFeatureSet CopySubset(List<int> indices, bool withAttributes);
/// <summary>
/// Copies the subset of specified features to create a new featureset that is restricted to
/// just the members specified. Attributes are always copied.
/// </summary>
/// <param name="filterExpression">The string expression to that specifies the features that should be copied.
/// An empty expression copies all features.</param>
/// <returns>A FeatureSet that has members that only match the specified members.</returns>
IFeatureSet CopySubset(string filterExpression);
/// <summary>
/// Copies the subset of specified features to create a new featureset that is restricted to
/// just the members specified.
/// </summary>
/// <param name="filterExpression">The string expression to that specifies the features that should be copied.
/// An empty expression copies all features.</param>
/// <param name="withAttributes">Indicates whether the features attributes should be copied.</param>
/// <returns>A FeatureSet that has members that only match the specified members.</returns>
IFeatureSet CopySubset(string filterExpression, bool withAttributes);
/// <summary>
/// Copies only the names and types of the attribute fields, without copying any of the attributes or features.
/// </summary>
/// <param name="source">The source featureSet to obtain the schema from.</param>
void CopyTableSchema(IFeatureSet source);
/// <summary>
/// Copies the Table schema (column names/data types)
/// from a DatatTable, but doesn't copy any values.
/// </summary>
/// <param name="sourceTable">The Table to obtain schema from.</param>
void CopyTableSchema(DataTable sourceTable);
/// <summary>
/// Instructs the shapefile to read all the attributes from the file.
/// This may also be a cue to read values from a database.
/// </summary>
void FillAttributes();
/// <summary>
/// Instructs the shapefile to read all the attributes from the file.
/// This may also be a cue to read values from a database.
/// </summary>
void FillAttributes(IProgressHandler progressHandler);
/// <summary>
/// This forces the vertex initialization so that Vertices, ShapeIndices, and the
/// ShapeIndex property on each feature will no longer be null.
/// </summary>
void InitializeVertices();
/// <summary>
/// Switches a boolean so that the next time that the vertices are requested,
/// they must be re-calculated from the feature coordinates.
/// </summary>
/// <remarks>This only affects reading values from the Vertices cache</remarks>
void InvalidateVertices();
/// <summary>
/// Attempts to remove the specified shape.
/// </summary>
/// <param name="index">
/// The integer index of the shape to remove.
/// </param>
/// <returns>
/// Boolean, true if the remove was successful.
/// </returns>
bool RemoveShapeAt(int index);
/// <summary>
/// Attempts to remove a range of shapes by index. This is optimized to
/// work better for large numbers. For one or two, using RemoveShapeAt might
/// be faster.
/// </summary>
/// <param name="indices">
/// The enumerable set of indices to remove.
/// </param>
void RemoveShapesAt(IEnumerable<int> indices);
#endregion
#region Properties
/// <summary>
/// Gets whether or not the attributes have all been loaded into the data table.
/// </summary>
bool AttributesPopulated { get; set; }
/// <summary>
/// Gets or sets the coordinate type across the entire featureset.
/// </summary>
CoordinateType CoordinateType { get; set; }
/// <summary>
/// Gets the DataTable associated with this specific feature.
/// </summary>
DataTable DataTable { get; set; }
/// <summary>
/// Gets the list of all the features that are included in this layer.
/// </summary>
IFeatureList Features { get; set; }
/// <summary>
/// This is an optional GeometryFactory that can be set to control how the geometries on features are
/// created. if this is not specified, the default from DotSptaial.Topology is used.
/// </summary>
IGeometryFactory FeatureGeometryFactory { get; set; }
/// <summary>
/// Gets the feature lookup Table itself.
/// </summary>
Dictionary<DataRow, IFeature> FeatureLookup { get; }
/// <summary>
/// Gets an enumeration indicating the type of feature represented in this dataset, if any.
/// </summary>
FeatureType FeatureType { get; set; }
/// <summary>
/// These specifically allow the user to make sense of the Vertices array. These are
/// fast acting sealed classes and are not meant to be overridden or support clever
/// new implementations.
/// </summary>
List<ShapeRange> ShapeIndices { get; set; }
/// <summary>
/// If this is true, then the ShapeIndices and Vertex values are used,
/// and features are created on demand. Otherwise the list of Features
/// is used directly.
/// </summary>
bool IndexMode { get; set; }
/// <summary>
/// Gets an array of Vertex structures with X and Y coordinates
/// </summary>
double[] Vertex { get; set; }
/// <summary>
/// Z coordinates
/// </summary>
double[] Z { get; set; }
/// <summary>
/// M coordinates
/// </summary>
double[] M { get; set; }
/// <summary>
/// Gets a boolean that indicates whether or not the InvalidateVertices has been called
/// more recently than the cached vertex array has been built.
/// </summary>
bool VerticesAreValid { get; }
/// <summary>
/// Skips the features themselves and uses the shapeindicies instead.
/// </summary>
/// <param name="region">The region to select members from</param>
/// <returns>A list of integer valued shape indices that are selected.</returns>
List<int> SelectIndices(Extent region);
#endregion
/// <summary>
/// Exports current shapefile as a zip archive in memory
/// </summary>
/// <returns>Shapefile components.</returns>
ShapefilePackage ExportShapefilePackage();
/// <summary>
/// Saves the information in the Layers provided by this datasource onto its existing file location
/// </summary>
void Save();
/// <summary>
/// Saves a datasource to the file.
/// </summary>
/// <param name="fileName">The string fileName location to save to</param>
/// <param name="overwrite">Boolean, if this is true then it will overwrite a file of the existing name.</param>
void SaveAs(string fileName, bool overwrite);
/// <summary>
/// returns only the features that have envelopes that
/// intersect with the specified envelope.
/// </summary>
/// <param name="region">The specified region to test for intersect with</param>
/// <returns>A List of the IFeature elements that are contained in this region</returns>
List<IFeature> Select(Extent region);
/// <summary>
/// returns only the features that have envelopes that
/// intersect with the specified envelope.
/// </summary>
/// <param name="region">The specified region to test for intersect with</param>
/// <param name="selectedRegion">This returns the geographic extents for the entire selected area.</param>
/// <returns>A List of the IFeature elements that are contained in this region</returns>
List<IFeature> Select(Extent region, out Extent selectedRegion);
/// <summary>
/// The string filter expression to use in order to return the desired features.
/// </summary>
/// <param name="filterExpression">The features to return.</param>
/// <returns>The list of desired features.</returns>
List<IFeature> SelectByAttribute(string filterExpression);
/// <summary>
/// This version is more tightly integrated to the DataTable and returns the row indices, rather
/// than attempting to link the results to features themselves, which may not even exist.
/// </summary>
/// <param name="filterExpression">The filter expression</param>
/// <returns>The list of indices</returns>
List<int> SelectIndexByAttribute(string filterExpression);
/// <summary>
/// After changing coordinates, this will force the re-calculation of envelopes on a feature
/// level as well as on the featureset level.
/// </summary>
void UpdateExtent();
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// Holds the state of a Monad Shell session
/// </summary>
internal sealed partial class SessionStateInternal
{
#region Functions
/// <summary>
/// Add an new SessionState function entry to this session state object...
/// </summary>
/// <param name="entry">The entry to add</param>
internal void AddSessionStateEntry(SessionStateFunctionEntry entry)
{
ScriptBlock sb = entry.ScriptBlock.Clone();
FunctionInfo fn = this.SetFunction(entry.Name, sb, null, entry.Options, false, CommandOrigin.Internal, this.ExecutionContext, entry.HelpFile, true);
fn.Visibility = entry.Visibility;
fn.Module = entry.Module;
fn.ScriptBlock.LanguageMode = PSLanguageMode.FullLanguage;
}
#if !CORECLR // Workflow Not Supported On CSS
internal void AddSessionStateEntry(InitialSessionState initialSessionState, SessionStateWorkflowEntry entry)
{
var converterInstance = Utils.GetAstToWorkflowConverterAndEnsureWorkflowModuleLoaded(null);
var workflowInfo = entry.WorkflowInfo ??
converterInstance.CompileWorkflow(entry.Name, entry.Definition, initialSessionState);
WorkflowInfo wf = new WorkflowInfo(workflowInfo);
wf = this.SetWorkflowRaw(wf, CommandOrigin.Internal);
wf.Visibility = entry.Visibility;
wf.Module = entry.Module;
}
#endif
/// <summary>
/// Gets a flattened view of the functions that are visible using
/// the current scope as a reference and filtering the functions in
/// the other scopes based on the scoping rules.
/// </summary>
///
/// <returns>
/// An IDictionary representing the visible functions.
/// </returns>
///
internal IDictionary GetFunctionTable()
{
SessionStateScopeEnumerator scopeEnumerator =
new SessionStateScopeEnumerator(_currentScope);
Dictionary<string, FunctionInfo> result =
new Dictionary<string, FunctionInfo>(StringComparer.OrdinalIgnoreCase);
foreach (SessionStateScope scope in scopeEnumerator)
{
foreach (FunctionInfo entry in scope.FunctionTable.Values)
{
if (!result.ContainsKey(entry.Name))
{
result.Add(entry.Name, entry);
}
}
}
return result;
} // GetFunctionTable
/// <summary>
/// Gets an IEnumerable for the function table for a given scope
/// </summary>
///
/// <param name="scopeID">
/// A scope identifier that is either one of the "special" scopes like
/// "global", "script", "local", or "private, or a numeric ID of a relative scope
/// to the current scope.
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="scopeID"/> is less than zero, or not
/// a number and not "script", "global", "local", or "private"
/// </exception>
///
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
///
internal IDictionary<string, FunctionInfo> GetFunctionTableAtScope(string scopeID)
{
Dictionary<string, FunctionInfo> result =
new Dictionary<string, FunctionInfo>(StringComparer.OrdinalIgnoreCase);
SessionStateScope scope = GetScopeByID(scopeID);
foreach (FunctionInfo entry in scope.FunctionTable.Values)
{
// Make sure the function/filter isn't private or if it is that the current
// scope is the same scope the alias was retrieved from.
if ((entry.Options & ScopedItemOptions.Private) == 0 ||
scope == _currentScope)
{
result.Add(entry.Name, entry);
}
}
return result;
} // GetFunctionTableAtScope
/// <summary>
/// List of functions/filters to export from this session state object...
/// </summary>
internal List<FunctionInfo> ExportedFunctions { get; } = new List<FunctionInfo>();
/// <summary>
/// List of workflows to export from this session state object...
/// </summary>
internal List<WorkflowInfo> ExportedWorkflows { get; } = new List<WorkflowInfo>();
internal bool UseExportList { get; set; } = false;
/// <summary>
/// Get a functions out of session state.
/// </summary>
///
/// <param name="name">
/// name of function to look up
/// </param>
///
/// <param name="origin">
/// Origin of the command that called this API...
/// </param>
///
/// <returns>
/// The value of the specified function.
/// </returns>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
///
internal FunctionInfo GetFunction(string name, CommandOrigin origin)
{
if (String.IsNullOrEmpty(name))
{
throw PSTraceSource.NewArgumentException("name");
}
FunctionInfo result = null;
FunctionLookupPath lookupPath = new FunctionLookupPath(name);
FunctionScopeItemSearcher searcher =
new FunctionScopeItemSearcher(this, lookupPath, origin);
if (searcher.MoveNext())
{
result = ((IEnumerator<FunctionInfo>)searcher).Current;
}
return result;
} // GetFunction
/// <summary>
/// Get a functions out of session state.
/// </summary>
///
/// <param name="name">
/// name of function to look up
/// </param>
///
/// <returns>
/// The value of the specified function.
/// </returns>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
///
internal FunctionInfo GetFunction(string name)
{
return GetFunction(name, CommandOrigin.Internal);
} // GetFunction
private IEnumerable<string> GetFunctionAliases(IParameterMetadataProvider ipmp)
{
if (ipmp == null || ipmp.Body.ParamBlock == null)
yield break;
var attributes = ipmp.Body.ParamBlock.Attributes;
foreach (var attributeAst in attributes)
{
var attributeType = attributeAst.TypeName.GetReflectionAttributeType();
if (attributeType == typeof(AliasAttribute))
{
var cvv = new ConstantValueVisitor { AttributeArgument = true };
for (int i = 0; i < attributeAst.PositionalArguments.Count; i++)
{
yield return Compiler._attrArgToStringConverter.Target(Compiler._attrArgToStringConverter,
attributeAst.PositionalArguments[i].Accept(cvv));
}
}
}
}
/// <summary>
/// Set a function in the current scope of session state.
/// </summary>
///
/// <param name="name">
/// The name of the function to set.
/// </param>
///
/// <param name="function">
/// The new value of the function being set.
/// </param>
///
/// <param name="origin">
/// Origin of the caller of this API
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="function"/> is null.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the function is read-only or constant.
/// </exception>
///
/// <exception cref="SessionStateOverflowException">
/// If the maximum number of functions have been reached for this scope.
/// </exception>
///
internal FunctionInfo SetFunctionRaw(
string name,
ScriptBlock function,
CommandOrigin origin)
{
if (String.IsNullOrEmpty(name))
{
throw PSTraceSource.NewArgumentException("name");
}
if (function == null)
{
throw PSTraceSource.NewArgumentNullException("function");
}
string originalName = name;
FunctionLookupPath path = new FunctionLookupPath(name);
name = path.UnqualifiedPath;
if (String.IsNullOrEmpty(name))
{
SessionStateException exception =
new SessionStateException(
originalName,
SessionStateCategory.Function,
"ScopedFunctionMustHaveName",
SessionStateStrings.ScopedFunctionMustHaveName,
ErrorCategory.InvalidArgument);
throw exception;
}
ScopedItemOptions options = ScopedItemOptions.None;
if (path.IsPrivate)
{
options |= ScopedItemOptions.Private;
}
FunctionScopeItemSearcher searcher =
new FunctionScopeItemSearcher(
this,
path,
origin);
var functionInfo = searcher.InitialScope.SetFunction(name, function, null, options, false, origin, ExecutionContext);
foreach (var aliasName in GetFunctionAliases(function.Ast as IParameterMetadataProvider))
{
searcher.InitialScope.SetAliasValue(aliasName, name, ExecutionContext, false, origin);
}
return functionInfo;
} // SetFunctionRaw
internal WorkflowInfo SetWorkflowRaw(
WorkflowInfo workflowInfo,
CommandOrigin origin)
{
string originalName = workflowInfo.Name;
string name = originalName;
FunctionLookupPath path = new FunctionLookupPath(name);
name = path.UnqualifiedPath;
if (String.IsNullOrEmpty(name))
{
SessionStateException exception =
new SessionStateException(
originalName,
SessionStateCategory.Function,
"ScopedFunctionMustHaveName",
SessionStateStrings.ScopedFunctionMustHaveName,
ErrorCategory.InvalidArgument);
throw exception;
}
ScopedItemOptions options = ScopedItemOptions.None;
if (path.IsPrivate)
{
options |= ScopedItemOptions.Private;
}
FunctionScopeItemSearcher searcher =
new FunctionScopeItemSearcher(
this,
path,
origin);
// The script that defines a workflowInfo wrapper is fully trusted
workflowInfo.ScriptBlock.LanguageMode = PSLanguageMode.FullLanguage;
if (workflowInfo.Module == null && this.Module != null)
{
workflowInfo.Module = this.Module;
}
var wfInfo = (WorkflowInfo)
searcher.InitialScope.SetFunction(name, workflowInfo.ScriptBlock, null, options, false, origin, ExecutionContext, null,
(arg1, arg2, arg3, arg4, arg5, arg6) => workflowInfo);
foreach (var aliasName in GetFunctionAliases(workflowInfo.ScriptBlock.Ast as IParameterMetadataProvider))
{
searcher.InitialScope.SetAliasValue(aliasName, name, ExecutionContext, false, origin);
}
return wfInfo;
} // SetWorkflowRaw
/// <summary>
/// Set a function in the current scope of session state.
/// </summary>
///
/// <param name="name">
/// The name of the function to set.
/// </param>
///
/// <param name="function">
/// The new value of the function being set.
/// </param>
///
/// <param name="originalFunction">
/// The original function (if any) from which the ScriptBlock is derived.
/// </param>
///
/// <param name="options">
/// The options to set on the function.
/// </param>
///
/// <param name="force">
/// If true, the function will be set even if its ReadOnly.
/// </param>
///
/// <param name="origin">
/// Origin of the caller of this API
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="function"/> is null.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the function is read-only or constant.
/// </exception>
///
/// <exception cref="SessionStateOverflowException">
/// If the maximum number of functions have been reached for this scope.
/// </exception>
///
internal FunctionInfo SetFunction(
string name,
ScriptBlock function,
FunctionInfo originalFunction,
ScopedItemOptions options,
bool force,
CommandOrigin origin)
{
return SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext, null);
} // SetFunction
/// <summary>
/// Set a function in the current scope of session state.
/// </summary>
///
/// <param name="name">
/// The name of the function to set.
/// </param>
///
/// <param name="function">
/// The new value of the function being set.
/// </param>
///
/// <param name="originalFunction">
/// The original function (if any) from which the ScriptBlock is derived.
/// </param>
///
/// <param name="options">
/// The options to set on the function.
/// </param>
///
/// <param name="force">
/// If true, the function will be set even if its ReadOnly.
/// </param>
///
/// <param name="origin">
/// Origin of the caller of this API
/// </param>
///
/// <param name="helpFile">
/// The name of the help file associated with the function.
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="function"/> is null.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the function is read-only or constant.
/// </exception>
///
/// <exception cref="SessionStateOverflowException">
/// If the maximum number of functions have been reached for this scope.
/// </exception>
///
internal FunctionInfo SetFunction(
string name,
ScriptBlock function,
FunctionInfo originalFunction,
ScopedItemOptions options,
bool force,
CommandOrigin origin,
string helpFile)
{
return SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext, helpFile, false);
} // SetFunction
/// <summary>
/// Set a function in the current scope of session state.
/// </summary>
///
/// <param name="name">
/// The name of the function to set.
/// </param>
///
/// <param name="function">
/// The new value of the function being set.
/// </param>
///
/// <param name="originalFunction">
/// The original function (if any) from which the ScriptBlock is derived.
/// </param>
///
/// <param name="options">
/// The options to set on the function.
/// </param>
///
/// <param name="force">
/// If true, the function will be set even if its ReadOnly.
/// </param>
///
/// <param name="origin">
/// Origin of the caller of this API
/// </param>
///
/// <param name="context">
/// The execution context for the function.
/// </param>
///
/// <param name="helpFile">
/// The name of the help file associated with the function.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="function"/> is null.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the function is read-only or constant.
/// </exception>
///
/// <exception cref="SessionStateOverflowException">
/// If the maximum number of functions have been reached for this scope.
/// </exception>
///
internal FunctionInfo SetFunction(
string name,
ScriptBlock function,
FunctionInfo originalFunction,
ScopedItemOptions options,
bool force,
CommandOrigin origin,
ExecutionContext context,
string helpFile)
{
return SetFunction(name, function, originalFunction, options, force, origin, context, helpFile, false);
} // SetFunction
/// <summary>
/// Set a function in the current scope of session state.
/// </summary>
///
/// <param name="name">
/// The name of the function to set.
/// </param>
///
/// <param name="function">
/// The new value of the function being set.
/// </param>
///
/// <param name="originalFunction">
/// The original function (if any) from which the ScriptBlock is derived.
/// </param>
///
/// <param name="options">
/// The options to set on the function.
/// </param>
///
/// <param name="force">
/// If true, the function will be set even if its ReadOnly.
/// </param>
///
/// <param name="origin">
/// Origin of the caller of this API
/// </param>
///
/// <param name="context">
/// The execution context for the function.
/// </param>
///
/// <param name="helpFile">
/// The name of the help file associated with the function.
/// </param>
///
/// <param name="isPreValidated">
/// Set to true if it is a regular function (meaning, we do not need to check this is a workflow or if the script contains JobDefinition Attribute and then process it)
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="function"/> is null.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the function is read-only or constant.
/// </exception>
///
/// <exception cref="SessionStateOverflowException">
/// If the maximum number of functions have been reached for this scope.
/// </exception>
///
internal FunctionInfo SetFunction(
string name,
ScriptBlock function,
FunctionInfo originalFunction,
ScopedItemOptions options,
bool force,
CommandOrigin origin,
ExecutionContext context,
string helpFile,
bool isPreValidated)
{
if (String.IsNullOrEmpty(name))
{
throw PSTraceSource.NewArgumentException("name");
}
if (function == null)
{
throw PSTraceSource.NewArgumentNullException("function");
}
string originalName = name;
FunctionLookupPath path = new FunctionLookupPath(name);
name = path.UnqualifiedPath;
if (String.IsNullOrEmpty(name))
{
SessionStateException exception =
new SessionStateException(
originalName,
SessionStateCategory.Function,
"ScopedFunctionMustHaveName",
SessionStateStrings.ScopedFunctionMustHaveName,
ErrorCategory.InvalidArgument);
throw exception;
}
if (path.IsPrivate)
{
options |= ScopedItemOptions.Private;
}
FunctionScopeItemSearcher searcher =
new FunctionScopeItemSearcher(
this,
path,
origin);
return searcher.InitialScope.SetFunction(name, function, originalFunction, options, force, origin, context, helpFile);
} // SetFunction
/// <summary>
/// Set a function in the current scope of session state.
/// </summary>
///
/// <param name="name">
/// The name of the function to set.
/// </param>
///
/// <param name="function">
/// The new value of the function being set.
/// </param>
///
/// <param name="originalFunction">
/// The original function (if any) from which the ScriptBlock is derived.
/// </param>
///
/// <param name="force">
/// If true, the function will be set even if its ReadOnly.
/// </param>
///
/// <param name="origin">
/// The origin of the caller
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// or
/// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see>
/// or <see cref="FunctionInfo">FunctionInfo</see>
/// </exception>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="function"/> is null.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the function is read-only or constant.
/// </exception>
///
/// <exception cref="SessionStateOverflowException">
/// If the maximum number of functions have been reached for this scope.
/// </exception>
///
internal FunctionInfo SetFunction(
string name,
ScriptBlock function,
FunctionInfo originalFunction,
bool force,
CommandOrigin origin)
{
if (String.IsNullOrEmpty(name))
{
throw PSTraceSource.NewArgumentException("name");
}
if (function == null)
{
throw PSTraceSource.NewArgumentNullException("function");
}
string originalName = name;
FunctionLookupPath path = new FunctionLookupPath(name);
name = path.UnqualifiedPath;
if (String.IsNullOrEmpty(name))
{
SessionStateException exception =
new SessionStateException(
originalName,
SessionStateCategory.Function,
"ScopedFunctionMustHaveName",
SessionStateStrings.ScopedFunctionMustHaveName,
ErrorCategory.InvalidArgument);
throw exception;
}
ScopedItemOptions options = ScopedItemOptions.None;
if (path.IsPrivate)
{
options |= ScopedItemOptions.Private;
}
FunctionScopeItemSearcher searcher =
new FunctionScopeItemSearcher(
this,
path,
origin);
FunctionInfo result = null;
SessionStateScope scope = searcher.InitialScope;
if (searcher.MoveNext())
{
scope = searcher.CurrentLookupScope;
name = searcher.Name;
if (path.IsPrivate)
{
// Need to add the Private flag
FunctionInfo existingFunction = scope.GetFunction(name);
options |= existingFunction.Options;
result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext);
}
else
{
result = scope.SetFunction(name, function, force, origin, ExecutionContext);
}
}
else
{
if (path.IsPrivate)
{
result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext);
}
else
{
result = scope.SetFunction(name, function, force, origin, ExecutionContext);
}
}
return result;
}
/// <summary>
/// Set a function in the current scope of session state.
///
/// BUGBUG: this overload is preserved because a lot of tests use reflection to
/// call it. The tests should be fixed and this API eventually removed.
/// </summary>
///
/// <param name="name">
/// The name of the function to set.
/// </param>
///
/// <param name="function">
/// The new value of the function being set.
/// </param>
///
/// <param name="force">
/// If true, the function will be set even if its ReadOnly.
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// or
/// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see>
/// or <see cref="FunctionInfo">FunctionInfo</see>
/// </exception>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="function"/> is null.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the function is read-only or constant.
/// </exception>
///
/// <exception cref="SessionStateOverflowException">
/// If the maximum number of functions have been reached for this scope.
/// </exception>
///
internal FunctionInfo SetFunction(string name, ScriptBlock function, bool force)
{
return SetFunction(name, function, null, force, CommandOrigin.Internal);
}
/// <summary>
/// Removes a function from the function table.
/// </summary>
///
/// <param name="name">
/// The name of the function to remove.
/// </param>
///
/// <param name="origin">
/// THe origin of the caller of this API
/// </param>
///
/// <param name="force">
/// If true, the function is removed even if it is ReadOnly.
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the function is constant.
/// </exception>
///
internal void RemoveFunction(string name, bool force, CommandOrigin origin)
{
if (String.IsNullOrEmpty(name))
{
throw PSTraceSource.NewArgumentException("name");
}
// Use the scope enumerator to find an existing function
SessionStateScope scope = _currentScope;
FunctionLookupPath path = new FunctionLookupPath(name);
FunctionScopeItemSearcher searcher =
new FunctionScopeItemSearcher(
this,
path,
origin);
if (searcher.MoveNext())
{
scope = searcher.CurrentLookupScope;
}
scope.RemoveFunction(name, force);
} // RemoveFunction
/// <summary>
/// Removes a function from the function table.
/// </summary>
///
/// <param name="name">
/// The name of the function to remove.
/// </param>
///
/// <param name="force">
/// If true, the function is removed even if it is ReadOnly.
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the function is constant.
/// </exception>
///
internal void RemoveFunction(string name, bool force)
{
RemoveFunction(name, force, CommandOrigin.Internal);
}
/// <summary>
/// Removes a function from the function table
/// if the function was imported from the given module.
///
/// BUGBUG: This is only used by the implicit remoting functions...
/// </summary>
///
/// <param name="name">
/// The name of the function to remove.
/// </param>
///
/// <param name="module">
/// Module the function might be imported from.
/// </param>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the function is constant.
/// </exception>
///
internal void RemoveFunction(string name, PSModuleInfo module)
{
Dbg.Assert(module != null, "Caller should verify that module parameter is not null");
FunctionInfo func = GetFunction(name) as FunctionInfo;
if (func != null && func.ScriptBlock != null
&& func.ScriptBlock.File != null
&& func.ScriptBlock.File.Equals(module.Path, StringComparison.OrdinalIgnoreCase))
{
RemoveFunction(name, true);
}
}
#endregion Functions
} // SessionStateInternal class
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableArrayBuilderTest : SimpleElementImmutablesTestBase
{
[Fact]
public void CreateBuilderDefaultCapacity()
{
var builder = ImmutableArray.CreateBuilder<int>();
Assert.NotNull(builder);
Assert.NotSame(builder, ImmutableArray.CreateBuilder<int>());
}
[Fact]
public void CreateBuilderInvalidCapacity()
{
Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateBuilder<int>(-1));
}
[Fact]
public void NormalConstructionValueType()
{
var builder = ImmutableArray.CreateBuilder<int>(3);
Assert.Equal(0, builder.Count);
Assert.False(((ICollection<int>)builder).IsReadOnly);
for (int i = 0; i < builder.Count; i++)
{
Assert.Equal(0, builder[i]);
}
builder.Add(5);
builder.Add(6);
builder.Add(7);
Assert.Equal(5, builder[0]);
Assert.Equal(6, builder[1]);
Assert.Equal(7, builder[2]);
}
[Fact]
public void NormalConstructionRefType()
{
var builder = new ImmutableArray<GenericParameterHelper>.Builder(3);
Assert.Equal(0, builder.Count);
Assert.False(((ICollection<GenericParameterHelper>)builder).IsReadOnly);
for (int i = 0; i < builder.Count; i++)
{
Assert.Null(builder[i]);
}
builder.Add(new GenericParameterHelper(5));
builder.Add(new GenericParameterHelper(6));
builder.Add(new GenericParameterHelper(7));
Assert.Equal(5, builder[0].Data);
Assert.Equal(6, builder[1].Data);
Assert.Equal(7, builder[2].Data);
}
[Fact]
public void AddRangeIEnumerable()
{
var builder = new ImmutableArray<int>.Builder(2);
builder.AddRange((IEnumerable<int>)new[] { 1 });
Assert.Equal(1, builder.Count);
builder.AddRange((IEnumerable<int>)new[] { 2 });
Assert.Equal(2, builder.Count);
// Exceed capacity
builder.AddRange(Enumerable.Range(3, 2)); // use an enumerable without a breakable Count
Assert.Equal(4, builder.Count);
Assert.Equal(Enumerable.Range(1, 4), builder);
}
[Fact]
public void Add()
{
var builder = ImmutableArray.CreateBuilder<int>(0);
builder.Add(1);
builder.Add(2);
Assert.Equal(new int[] { 1, 2 }, builder);
Assert.Equal(2, builder.Count);
builder = ImmutableArray.CreateBuilder<int>(1);
builder.Add(1);
builder.Add(2);
Assert.Equal(new int[] { 1, 2 }, builder);
Assert.Equal(2, builder.Count);
builder = ImmutableArray.CreateBuilder<int>(2);
builder.Add(1);
builder.Add(2);
Assert.Equal(new int[] { 1, 2 }, builder);
Assert.Equal(2, builder.Count);
}
[Fact]
public void AddRangeBuilder()
{
var builder1 = new ImmutableArray<int>.Builder(2);
var builder2 = new ImmutableArray<int>.Builder(2);
builder1.AddRange(builder2);
Assert.Equal(0, builder1.Count);
Assert.Equal(0, builder2.Count);
builder2.Add(1);
builder2.Add(2);
builder1.AddRange(builder2);
Assert.Equal(2, builder1.Count);
Assert.Equal(2, builder2.Count);
Assert.Equal(new[] { 1, 2 }, builder1);
}
[Fact]
public void AddRangeImmutableArray()
{
var builder1 = new ImmutableArray<int>.Builder(2);
var array = ImmutableArray.Create(1, 2, 3);
builder1.AddRange(array);
Assert.Equal(new[] { 1, 2, 3 }, builder1);
}
[Fact]
public void AddRangeDerivedArray()
{
var builder = new ImmutableArray<object>.Builder();
builder.AddRange(new[] { "a", "b" });
Assert.Equal(new[] { "a", "b" }, builder);
}
[Fact]
public void AddRangeDerivedImmutableArray()
{
var builder = new ImmutableArray<object>.Builder();
builder.AddRange(new[] { "a", "b" }.ToImmutableArray());
Assert.Equal(new[] { "a", "b" }, builder);
}
[Fact]
public void AddRangeDerivedBuilder()
{
var builder = new ImmutableArray<string>.Builder();
builder.AddRange(new[] { "a", "b" });
var builderBase = new ImmutableArray<object>.Builder();
builderBase.AddRange(builder);
Assert.Equal(new[] { "a", "b" }, builderBase);
}
[Fact]
public void Contains()
{
var builder = new ImmutableArray<int>.Builder();
Assert.False(builder.Contains(1));
builder.Add(1);
Assert.True(builder.Contains(1));
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => (ImmutableArray<int>.Builder)this.GetEnumerableOf(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => (ImmutableArray<int>.Builder)this.GetEnumerableOf(seq),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void Insert()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3);
builder.Insert(1, 4);
builder.Insert(4, 5);
Assert.Equal(new[] { 1, 4, 2, 3, 5 }, builder);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Insert(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Insert(builder.Count + 1, 0));
}
[Fact]
public void Remove()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3, 4);
Assert.True(builder.Remove(1));
Assert.False(builder.Remove(6));
Assert.Equal(new[] { 2, 3, 4 }, builder);
Assert.True(builder.Remove(3));
Assert.Equal(new[] { 2, 4 }, builder);
Assert.True(builder.Remove(4));
Assert.Equal(new[] { 2 }, builder);
Assert.True(builder.Remove(2));
Assert.Equal(0, builder.Count);
}
[Fact]
public void RemoveAt()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3, 4);
builder.RemoveAt(0);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.RemoveAt(3));
Assert.Equal(new[] { 2, 3, 4 }, builder);
builder.RemoveAt(1);
Assert.Equal(new[] { 2, 4 }, builder);
builder.RemoveAt(1);
Assert.Equal(new[] { 2 }, builder);
builder.RemoveAt(0);
Assert.Equal(0, builder.Count);
}
[Fact]
public void ReverseContents()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3, 4);
builder.ReverseContents();
Assert.Equal(new[] { 4, 3, 2, 1 }, builder);
builder.RemoveAt(0);
builder.ReverseContents();
Assert.Equal(new[] { 1, 2, 3 }, builder);
builder.RemoveAt(0);
builder.ReverseContents();
Assert.Equal(new[] { 3, 2 }, builder);
builder.RemoveAt(0);
builder.ReverseContents();
Assert.Equal(new[] { 2 }, builder);
builder.RemoveAt(0);
builder.ReverseContents();
Assert.Equal(new int[0], builder);
}
[Fact]
public void Sort()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(2, 4, 1, 3);
builder.Sort();
Assert.Equal(new[] { 1, 2, 3, 4 }, builder);
}
[Fact]
public void SortRange()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(2, 4, 1, 3);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Sort(-1, 2, Comparer<int>.Default));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Sort(1, 4, Comparer<int>.Default));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Sort(0, -1, Comparer<int>.Default));
builder.Sort(builder.Count, 0, Comparer<int>.Default);
Assert.Equal(new int[] { 2, 4, 1, 3 }, builder);
Assert.Throws<ArgumentNullException>(() => builder.Sort(1, 2, null));
builder.Sort(1, 2, Comparer<int>.Default);
Assert.Equal(new[] { 2, 1, 4, 3 }, builder);
}
[Fact]
public void SortComparer()
{
var builder1 = new ImmutableArray<string>.Builder();
var builder2 = new ImmutableArray<string>.Builder();
builder1.AddRange("c", "B", "a");
builder2.AddRange("c", "B", "a");
builder1.Sort(StringComparer.OrdinalIgnoreCase);
builder2.Sort(StringComparer.Ordinal);
Assert.Equal(new[] { "a", "B", "c" }, builder1);
Assert.Equal(new[] { "B", "a", "c" }, builder2);
}
[Fact]
public void Count()
{
var builder = new ImmutableArray<int>.Builder(3);
// Initial count is at zero, which is less than capacity.
Assert.Equal(0, builder.Count);
// Expand the accessible region of the array by increasing the count, but still below capacity.
builder.Count = 2;
Assert.Equal(2, builder.Count);
Assert.Equal(2, builder.ToList().Count);
Assert.Equal(0, builder[0]);
Assert.Equal(0, builder[1]);
Assert.Throws<IndexOutOfRangeException>(() => builder[2]);
// Expand the accessible region of the array beyond the current capacity.
builder.Count = 4;
Assert.Equal(4, builder.Count);
Assert.Equal(4, builder.ToList().Count);
Assert.Equal(0, builder[0]);
Assert.Equal(0, builder[1]);
Assert.Equal(0, builder[2]);
Assert.Equal(0, builder[3]);
Assert.Throws<IndexOutOfRangeException>(() => builder[4]);
}
[Fact]
public void CountContract()
{
var builder = new ImmutableArray<int>.Builder(100);
builder.AddRange(Enumerable.Range(1, 100));
builder.Count = 10;
Assert.Equal(Enumerable.Range(1, 10), builder);
builder.Count = 100;
Assert.Equal(Enumerable.Range(1, 10).Concat(new int[90]), builder);
}
[Fact]
public void IndexSetter()
{
var builder = new ImmutableArray<int>.Builder();
Assert.Throws<IndexOutOfRangeException>(() => builder[0] = 1);
Assert.Throws<IndexOutOfRangeException>(() => builder[-1] = 1);
builder.Count = 1;
builder[0] = 2;
Assert.Equal(2, builder[0]);
builder.Count = 10;
builder[9] = 3;
Assert.Equal(3, builder[9]);
builder.Count = 2;
Assert.Equal(2, builder[0]);
Assert.Throws<IndexOutOfRangeException>(() => builder[2]);
}
[Fact]
public void ToImmutable()
{
var builder = new ImmutableArray<int>.Builder();
builder.AddRange(1, 2, 3);
ImmutableArray<int> array = builder.ToImmutable();
Assert.Equal(1, array[0]);
Assert.Equal(2, array[1]);
Assert.Equal(3, array[2]);
// Make sure that subsequent mutation doesn't impact the immutable array.
builder[1] = 5;
Assert.Equal(5, builder[1]);
Assert.Equal(2, array[1]);
builder.Clear();
Assert.True(builder.ToImmutable().IsEmpty);
}
[Fact]
public void Clear()
{
var builder = new ImmutableArray<int>.Builder(2);
builder.Add(1);
builder.Add(1);
builder.Clear();
Assert.Equal(0, builder.Count);
Assert.Throws<IndexOutOfRangeException>(() => builder[0]);
}
[Fact]
public void MutationsSucceedAfterToImmutable()
{
var builder = new ImmutableArray<int>.Builder(1);
builder.Add(1);
var immutable = builder.ToImmutable();
builder[0] = 0;
Assert.Equal(0, builder[0]);
Assert.Equal(1, immutable[0]);
}
[Fact]
public void Enumerator()
{
var empty = new ImmutableArray<int>.Builder(0);
var enumerator = empty.GetEnumerator();
Assert.False(enumerator.MoveNext());
var manyElements = new ImmutableArray<int>.Builder(3);
manyElements.AddRange(1, 2, 3);
enumerator = manyElements.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(1, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(2, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(3, enumerator.Current);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void IEnumerator()
{
var empty = new ImmutableArray<int>.Builder(0);
var enumerator = ((IEnumerable<int>)empty).GetEnumerator();
Assert.False(enumerator.MoveNext());
var manyElements = new ImmutableArray<int>.Builder(3);
manyElements.AddRange(1, 2, 3);
enumerator = ((IEnumerable<int>)manyElements).GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(1, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(2, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(3, enumerator.Current);
Assert.False(enumerator.MoveNext());
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
var builder = new ImmutableArray<T>.Builder(contents.Length);
builder.AddRange(contents);
return builder;
}
}
}
| |
// 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.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
/// <summary>
/// SemaphoreSlim unit tests
/// </summary>
public class SemaphoreSlimTests
{
/// <summary>
/// SemaphoreSlim public methods and properties to be tested
/// </summary>
private enum SemaphoreSlimActions
{
Constructor,
Wait,
WaitAsync,
Release,
Dispose,
CurrentCount,
AvailableWaitHandle
}
[Fact]
public static void RunSemaphoreSlimTest0_Ctor()
{
RunSemaphoreSlimTest0_Ctor(0, 10, null);
RunSemaphoreSlimTest0_Ctor(5, 10, null);
RunSemaphoreSlimTest0_Ctor(10, 10, null);
}
[Fact]
public static void RunSemaphoreSlimTest0_Ctor_Negative()
{
RunSemaphoreSlimTest0_Ctor(10, 0, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest0_Ctor(10, -1, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest0_Ctor(-1, 10, typeof(ArgumentOutOfRangeException));
}
[Fact]
public static void RunSemaphoreSlimTest1_Wait()
{
// Infinite timeout
RunSemaphoreSlimTest1_Wait(10, 10, -1, true, null);
RunSemaphoreSlimTest1_Wait(1, 10, -1, true, null);
// Zero timeout
RunSemaphoreSlimTest1_Wait(10, 10, 0, true, null);
RunSemaphoreSlimTest1_Wait(1, 10, 0, true, null);
RunSemaphoreSlimTest1_Wait(0, 10, 0, false, null);
// Positive timeout
RunSemaphoreSlimTest1_Wait(10, 10, 10, true, null);
RunSemaphoreSlimTest1_Wait(1, 10, 10, true, null);
RunSemaphoreSlimTest1_Wait(0, 10, 10, false, null);
}
[Fact]
public static void RunSemaphoreSlimTest1_Wait_NegativeCases()
{
// Invalid timeout
RunSemaphoreSlimTest1_Wait(10, 10, -10, true, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest1_Wait
(10, 10, new TimeSpan(0, 0, Int32.MaxValue), true, typeof(ArgumentOutOfRangeException));
}
[Fact]
public static void RunSemaphoreSlimTest1_WaitAsync()
{
// Infinite timeout
RunSemaphoreSlimTest1_WaitAsync(10, 10, -1, true, null);
RunSemaphoreSlimTest1_WaitAsync(1, 10, -1, true, null);
// Zero timeout
RunSemaphoreSlimTest1_WaitAsync(10, 10, 0, true, null);
RunSemaphoreSlimTest1_WaitAsync(1, 10, 0, true, null);
RunSemaphoreSlimTest1_WaitAsync(0, 10, 0, false, null);
// Positive timeout
RunSemaphoreSlimTest1_WaitAsync(10, 10, 10, true, null);
RunSemaphoreSlimTest1_WaitAsync(1, 10, 10, true, null);
RunSemaphoreSlimTest1_WaitAsync(0, 10, 10, false, null);
}
[Fact]
public static void RunSemaphoreSlimTest1_WaitAsync_NegativeCases()
{
// Invalid timeout
RunSemaphoreSlimTest1_WaitAsync(10, 10, -10, true, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest1_WaitAsync
(10, 10, new TimeSpan(0, 0, Int32.MaxValue), true, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest1_WaitAsync2();
}
[Fact]
public static void RunSemaphoreSlimTest2_Release()
{
// Valid release count
RunSemaphoreSlimTest2_Release(5, 10, 1, null);
RunSemaphoreSlimTest2_Release(0, 10, 1, null);
RunSemaphoreSlimTest2_Release(5, 10, 5, null);
}
[Fact]
public static void RunSemaphoreSlimTest2_Release_NegativeCases()
{
// Invalid release count
RunSemaphoreSlimTest2_Release(5, 10, 0, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest2_Release(5, 10, -1, typeof(ArgumentOutOfRangeException));
// Semaphore Full
RunSemaphoreSlimTest2_Release(10, 10, 1, typeof(SemaphoreFullException));
RunSemaphoreSlimTest2_Release(5, 10, 6, typeof(SemaphoreFullException));
RunSemaphoreSlimTest2_Release(int.MaxValue - 1, int.MaxValue, 10, typeof(SemaphoreFullException));
}
[Fact]
public static void RunSemaphoreSlimTest4_Dispose()
{
RunSemaphoreSlimTest4_Dispose(5, 10, null, null);
RunSemaphoreSlimTest4_Dispose(5, 10, SemaphoreSlimActions.CurrentCount, null);
RunSemaphoreSlimTest4_Dispose
(5, 10, SemaphoreSlimActions.Wait, typeof(ObjectDisposedException));
RunSemaphoreSlimTest4_Dispose
(5, 10, SemaphoreSlimActions.WaitAsync, typeof(ObjectDisposedException));
RunSemaphoreSlimTest4_Dispose
(5, 10, SemaphoreSlimActions.Release, typeof(ObjectDisposedException));
RunSemaphoreSlimTest4_Dispose
(5, 10, SemaphoreSlimActions.AvailableWaitHandle, typeof(ObjectDisposedException));
}
[Fact]
public static void RunSemaphoreSlimTest5_CurrentCount()
{
RunSemaphoreSlimTest5_CurrentCount(5, 10, null);
RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.Wait);
RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.WaitAsync);
RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.Release);
}
[Fact]
public static void RunSemaphoreSlimTest7_AvailableWaitHandle()
{
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, null, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(0, 10, null, false);
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.Wait, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(1, 10, SemaphoreSlimActions.Wait, false);
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.Wait, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.WaitAsync, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(1, 10, SemaphoreSlimActions.WaitAsync, false);
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.WaitAsync, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(0, 10, SemaphoreSlimActions.Release, true);
}
/// <summary>
/// Test SemaphoreSlim constructor
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest0_Ctor(int initial, int maximum, Type exceptionType)
{
string methodFailed = "RunSemaphoreSlimTest0_Ctor(" + initial + "," + maximum + "): FAILED. ";
Exception exception = null;
try
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
Assert.Equal(initial, semaphore.CurrentCount);
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
exception = ex;
}
}
/// <summary>
/// Test SemaphoreSlim Wait
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="timeout">The timeout parameter for the wait method, it must be either int or TimeSpan</param>
/// <param name="returnValue">The expected wait return value</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest1_Wait
(int initial, int maximum, object timeout, bool returnValue, Type exceptionType)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
bool result = false;
if (timeout is TimeSpan)
{
result = semaphore.Wait((TimeSpan)timeout);
}
else
{
result = semaphore.Wait((int)timeout);
}
Assert.Equal(returnValue, result);
if (result)
{
Assert.Equal(initial - 1, semaphore.CurrentCount);
}
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
}
}
/// <summary>
/// Test SemaphoreSlim WaitAsync
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="timeout">The timeout parameter for the wait method, it must be either int or TimeSpan</param>
/// <param name="returnValue">The expected wait return value</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest1_WaitAsync
(int initial, int maximum, object timeout, bool returnValue, Type exceptionType)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
bool result = false;
if (timeout is TimeSpan)
{
result = semaphore.WaitAsync((TimeSpan)timeout).Result;
}
else
{
result = semaphore.WaitAsync((int)timeout).Result;
}
Assert.Equal(returnValue, result);
if (result)
{
Assert.Equal(initial - 1, semaphore.CurrentCount);
}
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
}
}
/// <summary>
/// Test SemaphoreSlim WaitAsync
/// The test verifies that SemaphoreSlim.Release() does not execute any user code synchronously.
/// </summary>
private static void RunSemaphoreSlimTest1_WaitAsync2()
{
SemaphoreSlim semaphore = new SemaphoreSlim(1);
ThreadLocal<int> counter = new ThreadLocal<int>(() => 0);
bool nonZeroObserved = false;
const int asyncActions = 20;
int remAsyncActions = asyncActions;
ManualResetEvent mre = new ManualResetEvent(false);
Action<int> doWorkAsync = async delegate (int i)
{
await semaphore.WaitAsync();
if (counter.Value > 0)
{
nonZeroObserved = true;
}
counter.Value = counter.Value + 1;
semaphore.Release();
counter.Value = counter.Value - 1;
if (Interlocked.Decrement(ref remAsyncActions) == 0) mre.Set();
};
semaphore.Wait();
for (int i = 0; i < asyncActions; i++) doWorkAsync(i);
semaphore.Release();
mre.WaitOne();
Assert.False(nonZeroObserved, "RunSemaphoreSlimTest1_WaitAsync2: FAILED. SemaphoreSlim.Release() seems to have synchronously invoked a continuation.");
}
/// <summary>
/// Test SemaphoreSlim Release
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="releaseCount">The release count for the release method</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest2_Release
(int initial, int maximum, int releaseCount, Type exceptionType)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
int oldCount = semaphore.Release(releaseCount);
Assert.Equal(initial, oldCount);
Assert.Equal(initial + releaseCount, semaphore.CurrentCount);
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
}
}
/// <summary>
/// Call specific SemaphoreSlim method or property
/// </summary>
/// <param name="semaphore">The SemaphoreSlim instance</param>
/// <param name="action">The action name</param>
/// <param name="param">The action parameter, null if it takes no parameters</param>
/// <returns>The action return value, null if the action returns void</returns>
private static object CallSemaphoreAction
(SemaphoreSlim semaphore, SemaphoreSlimActions? action, object param)
{
if (action == SemaphoreSlimActions.Wait)
{
if (param is TimeSpan)
{
return semaphore.Wait((TimeSpan)param);
}
else if (param is int)
{
return semaphore.Wait((int)param);
}
semaphore.Wait();
return null;
}
else if (action == SemaphoreSlimActions.WaitAsync)
{
if (param is TimeSpan)
{
return semaphore.WaitAsync((TimeSpan)param).Result;
}
else if (param is int)
{
return semaphore.WaitAsync((int)param).Result;
}
semaphore.WaitAsync().Wait();
return null;
}
else if (action == SemaphoreSlimActions.Release)
{
if (param != null)
{
return semaphore.Release((int)param);
}
return semaphore.Release();
}
else if (action == SemaphoreSlimActions.Dispose)
{
semaphore.Dispose();
return null;
}
else if (action == SemaphoreSlimActions.CurrentCount)
{
return semaphore.CurrentCount;
}
else if (action == SemaphoreSlimActions.AvailableWaitHandle)
{
return semaphore.AvailableWaitHandle;
}
return null;
}
/// <summary>
/// Test SemaphoreSlim Dispose
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="action">SemaphoreSlim action to be called after Dispose</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest4_Dispose(int initial, int maximum, SemaphoreSlimActions? action, Type exceptionType)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
semaphore.Dispose();
CallSemaphoreAction(semaphore, action, null);
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
}
}
/// <summary>
/// Test SemaphoreSlim CurrentCount property
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="action">SemaphoreSlim action to be called before CurrentCount</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest5_CurrentCount(int initial, int maximum, SemaphoreSlimActions? action)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
CallSemaphoreAction(semaphore, action, null);
if (action == null)
{
Assert.Equal(initial, semaphore.CurrentCount);
}
else
{
Assert.Equal(initial + (action == SemaphoreSlimActions.Release ? 1 : -1), semaphore.CurrentCount);
}
}
/// <summary>
/// Test SemaphoreSlim AvailableWaitHandle property
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="action">SemaphoreSlim action to be called before WaitHandle</param>
/// <param name="state">The expected wait handle state</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest7_AvailableWaitHandle(int initial, int maximum, SemaphoreSlimActions? action, bool state)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
CallSemaphoreAction(semaphore, action, null);
Assert.NotNull(semaphore.AvailableWaitHandle);
Assert.Equal(state, semaphore.AvailableWaitHandle.WaitOne(0));
}
/// <summary>
/// Test SemaphoreSlim Wait and Release methods concurrently
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="waitThreads">Number of the threads that call Wait method</param>
/// <param name="releaseThreads">Number of the threads that call Release method</param>
/// <param name="succeededWait">Number of succeeded wait threads</param>
/// <param name="failedWait">Number of failed wait threads</param>
/// <param name="finalCount">The final semaphore count</param>
/// <returns>True if the test succeeded, false otherwise</returns>
[Theory]
[InlineData(5, 1000, 50, 50, 50, 0, 5, 1000)]
[InlineData(0, 1000, 50, 25, 25, 25, 0, 500)]
[InlineData(0, 1000, 50, 0, 0, 50, 0, 100)]
public static void RunSemaphoreSlimTest8_ConcWaitAndRelease(int initial, int maximum,
int waitThreads, int releaseThreads, int succeededWait, int failedWait, int finalCount, int timeout)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
Task[] threads = new Task[waitThreads + releaseThreads];
int succeeded = 0;
int failed = 0;
ManualResetEvent mre = new ManualResetEvent(false);
// launch threads
for (int i = 0; i < threads.Length; i++)
{
if (i < waitThreads)
{
// We are creating the Task using TaskCreationOptions.LongRunning to
// force usage of another thread (which will be the case on the default scheduler
// with its current implementation). Without this, the release tasks will likely get
// queued behind the wait tasks in the pool, making it very likely that the wait tasks
// will starve the very tasks that when run would unblock them.
threads[i] = new Task(delegate ()
{
mre.WaitOne();
if (semaphore.Wait(timeout))
{
Interlocked.Increment(ref succeeded);
}
else
{
Interlocked.Increment(ref failed);
}
}, TaskCreationOptions.LongRunning);
}
else
{
threads[i] = new Task(delegate ()
{
mre.WaitOne();
semaphore.Release();
});
}
threads[i].Start(TaskScheduler.Default);
}
mre.Set();
//wait work to be done;
Task.WaitAll(threads);
//check the number of succeeded and failed wait
Assert.Equal(succeededWait, succeeded);
Assert.Equal(failedWait, failed);
Assert.Equal(finalCount, semaphore.CurrentCount);
}
/// <summary>
/// Test SemaphoreSlim WaitAsync and Release methods concurrently
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="waitThreads">Number of the threads that call Wait method</param>
/// <param name="releaseThreads">Number of the threads that call Release method</param>
/// <param name="succeededWait">Number of succeeded wait threads</param>
/// <param name="failedWait">Number of failed wait threads</param>
/// <param name="finalCount">The final semaphore count</param>
/// <returns>True if the test succeeded, false otherwise</returns>
[Theory]
[InlineData(5, 1000, 50, 50, 50, 0, 5, 500)]
[InlineData(0, 1000, 50, 25, 25, 25, 0, 500)]
[InlineData(0, 1000, 50, 0, 0, 50, 0, 100)]
private static void RunSemaphoreSlimTest8_ConcWaitAsyncAndRelease(int initial, int maximum,
int waitThreads, int releaseThreads, int succeededWait, int failedWait, int finalCount, int timeout)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
Task[] tasks = new Task[waitThreads + releaseThreads];
int succeeded = 0;
int failed = 0;
ManualResetEvent mre = new ManualResetEvent(false);
// launch threads
for (int i = 0; i < tasks.Length; i++)
{
if (i < waitThreads)
{
tasks[i] = Task.Run(async delegate
{
mre.WaitOne();
if (await semaphore.WaitAsync(timeout))
{
Interlocked.Increment(ref succeeded);
}
else
{
Interlocked.Increment(ref failed);
}
});
}
else
{
tasks[i] = Task.Run(delegate
{
mre.WaitOne();
semaphore.Release();
});
}
}
mre.Set();
//wait work to be done;
Task.WaitAll(tasks);
Assert.Equal(succeededWait, succeeded);
Assert.Equal(failedWait, failed);
Assert.Equal(finalCount, semaphore.CurrentCount);
}
[Theory]
[InlineData(10, 10)]
[InlineData(1, 10)]
[InlineData(10, 1)]
public static void TestConcurrentWaitAndWaitAsync(int syncWaiters, int asyncWaiters)
{
int totalWaiters = syncWaiters + asyncWaiters;
var semaphore = new SemaphoreSlim(0);
Task[] tasks = new Task[totalWaiters];
const int ITERS = 10;
int randSeed = unchecked((int)DateTime.Now.Ticks);
for (int i = 0; i < syncWaiters; i++)
{
tasks[i] = Task.Run(delegate
{
//Random rand = new Random(Interlocked.Increment(ref randSeed));
for (int iter = 0; iter < ITERS; iter++)
{
semaphore.Wait();
semaphore.Release();
}
});
}
for (int i = syncWaiters; i < totalWaiters; i++)
{
tasks[i] = Task.Run(async delegate
{
//Random rand = new Random(Interlocked.Increment(ref randSeed));
for (int iter = 0; iter < ITERS; iter++)
{
await semaphore.WaitAsync();
semaphore.Release();
}
});
}
semaphore.Release(totalWaiters / 2);
Task.WaitAll(tasks);
}
}
}
| |
/*
Copyright (C) 2013-2015 MetaMorph Software, Inc
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
=======================
This version of the META tools is a fork of an original version produced
by Vanderbilt University's Institute for Software Integrated Systems (ISIS).
Their license statement:
Copyright (C) 2011-2014 Vanderbilt University
Developed with the sponsorship of the Defense Advanced Research Projects
Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights
as defined in DFARS 252.227-7013.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using GME.CSharp;
using GME;
using GME.MGA;
using GME.MGA.Core;
using System.Linq;
using System.Diagnostics.Contracts;
namespace CLM_light
{
/// <summary>
/// This class implements the necessary COM interfaces for a GME interpreter component.
/// </summary>
[Guid(ComponentConfig.guid),
ProgId(ComponentConfig.progID),
ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class CLM_lightInterpreter : IMgaComponentEx, IGMEVersionInfo
{
public const string ContextErrorMessage = "Run CLM_Light in an 'Alternative' or 'Optional' DesignContainer.";
public const string SelectedObjErrorMessage = "Please Select One ComponentRef.";
/// <summary>
/// Contains information about the GUI event that initiated the invocation.
/// </summary>
public enum ComponentStartMode
{
GME_MAIN_START = 0, // Not used by GME
GME_BROWSER_START = 1, // Right click in the GME Tree Browser window
GME_CONTEXT_START = 2, // Using the context menu by right clicking a model element in the GME modeling window
GME_EMBEDDED_START = 3, // Not used by GME
GME_MENU_START = 16, // Clicking on the toolbar icon, or using the main menu
GME_BGCONTEXT_START = 18, // Using the context menu by right clicking the background of the GME modeling window
GME_ICON_START = 32, // Not used by GME
GME_SILENT_MODE = 128 // Not used by GME, available to testers not using GME
}
/// <summary>
/// This function is called for each interpreter invocation before Main.
/// Don't perform MGA operations here unless you open a tansaction.
/// </summary>
/// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
public void Initialize(MgaProject project)
{
// TODO: Add your initialization code here...
GMEConsole = GMEConsole.CreateFromProject(project);
}
/// <summary>
/// The main entry point of the interpreter. A transaction is already open,
/// GMEConsole is available. A general try-catch block catches all the exceptions
/// coming from this function, you don't need to add it. For more information, see InvokeEx.
/// </summary>
/// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
/// <param name="currentobj">The model open in the active tab in GME. Its value is null if no model is open (no GME modeling windows open). </param>
/// <param name="selectedobjs">
/// A collection for the selected model elements. It is never null.
/// If the interpreter is invoked by the context menu of the GME Tree Browser, then the selected items in the tree browser. Folders
/// are never passed (they are not FCOs).
/// If the interpreter is invoked by clicking on the toolbar icon or the context menu of the modeling window, then the selected items
/// in the active GME modeling window. If nothing is selected, the collection is empty (contains zero elements).
/// </param>
/// <param name="startMode">Contains information about the GUI event that initiated the invocation.</param>
[ComVisible(false)]
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
{
GMEConsole.Clear();
System.Windows.Forms.Application.DoEvents();
IMgaFCO selectedObj = null;
bool isContextValid = CheckForValidContext(currentobj);
if (isContextValid == false)
{
return;
}
// get all the ComponentRefs in the DesignContainer
var crefs = (currentobj as IMgaModel).
ChildFCOs.
Cast<IMgaFCO>().
Where(x => x.MetaBase.Name == "ComponentRef");
// If there is exactly '1', select it
if (crefs.Count() == 1)
{
selectedObj = crefs.FirstOrDefault();
}
if (selectedObj == null)
{
if (selectedobjs.Count != 1)
{
GMEConsole.Error.WriteLine(SelectedObjErrorMessage);
return;
}
selectedObj = selectedobjs.Cast<IMgaFCO>().FirstOrDefault();
}
if (selectedObj == null)
{
GMEConsole.Error.WriteLine(SelectedObjErrorMessage);
return;
}
if (selectedObj.MetaBase.Name != "ComponentRef")
{
GMEConsole.Error.WriteLine(SelectedObjErrorMessage);
return;
}
if ((selectedObj as IMgaReference).Referred == null)
{
GMEConsole.Error.WriteLine("Selected ComponentRef is a null reference.");
return;
}
GMEConsole.Info.WriteLine("Running CLM_light...");
// everything is checked we can operate on the objects
IMgaFCO designContainer = currentobj;
IMgaFCO componentRef = selectedObj;
IMgaModel component = (selectedObj as IMgaReference).Referred as IMgaModel;
GMEConsole.Info.WriteLine("Discovering components.");
//GMEConsole.Info.WriteLine("{0} components were found.", components.Count);
// TODO: filter detected components if needed
using (ComponentSelectionForm csf = new ComponentSelectionForm(component, currentobj as IMgaModel, GMEConsole.Error, GMEConsole.Info))
{
var dialogresult = csf.ShowDialog();
if (dialogresult == System.Windows.Forms.DialogResult.OK)
{
GMEConsole.Info.WriteLine("Inserting new components.");
List<IMgaFCO> components = new List<IMgaFCO>();
foreach (var item in csf.dgvSelector.SelectedRows)
{
var dgvr = item as System.Windows.Forms.DataGridViewRow;
var cli = dgvr.DataBoundItem as ComponentListItem;
components.Add(cli.Fco);
}
GMEConsole.Info.WriteLine("{0} components were selected.", components.Count);
List<KeyValuePair<IMgaFCO, string>> messages = new List<KeyValuePair<IMgaFCO, string>>();
var insertedComponents = InsertComponents(designContainer, componentRef, components, messages);
}
}
GMEConsole.Info.WriteLine("Done.");
}
public bool CheckForValidContext(MgaFCO currentobj)
{
bool contextValid = true;
// check if there is an object open
if (currentobj == null)
{
GMEConsole.Error.WriteLine(ContextErrorMessage);
contextValid = false;
}
// check if the currently opened model is a DesignContainer
if (currentobj.MetaBase.Name != "DesignContainer")
{
GMEConsole.Error.WriteLine(ContextErrorMessage);
contextValid = false;
}
// check if the currently opened model is a Library object
if (currentobj.IsLibObject)
{
GMEConsole.Error.WriteLine("Cannot modify a Library object. Please select a valid DesignContainer.");
contextValid = false;
}
// check if the currently opened model is an Instance
if (currentobj.IsInstance)
{
GMEConsole.Error.WriteLine("Cannot modify an Instance. Please open a non-Instance DesignContainer.");
contextValid = false;
}
// check if the currently opened model is an Alternative- or Optional-type DC
if (currentobj.StrAttrByName["ContainerType"] != "Alternative" &&
currentobj.StrAttrByName["ContainerType"] != "Optional") //added per META-2555
{
GMEConsole.Error.WriteLine(ContextErrorMessage);
contextValid = false;
}
return contextValid;
}
[ComVisible(false)]
public List<IMgaFCO> InsertComponents(
IMgaFCO designContainer,
IMgaFCO componentRef,
List<IMgaFCO> components,
List<KeyValuePair<IMgaFCO, string>> messages)
{
Contract.Requires(designContainer as IMgaModel != null);
Contract.Requires(componentRef as IMgaReference != null);
Contract.Requires((componentRef as IMgaReference).Referred != null);
Contract.Requires(components != null);
List<IMgaFCO> result = new List<IMgaFCO>();
IMgaModel container = designContainer as IMgaModel;
IMgaReference compRef = componentRef as IMgaReference;
var childComps = container.
ChildFCOs.
Cast<IMgaFCO>().
Where(x => x.MetaBase.Name == "ComponentRef").
Cast<IMgaReference>().
Select(x => x.Referred).
ToList();
// get all connections which has the componentRef as an endpoint
var childConnections = container.
ChildFCOs.
Cast<IMgaFCO>().
Where(x => x is IMgaSimpleConnection).
Cast<IMgaSimpleConnection>().
ToList();
// ith new component
int iNewComponent = 0;
foreach (var compToCreate in components)
{
if (childComps.Contains(compToCreate))
{
// If the component already exists this function will not create it again
// skip
messages.Add(new KeyValuePair<IMgaFCO, string>(compToCreate, "Component already exists."));
continue;
}
// create reference
var newRef = container.CreateReference(componentRef.MetaRole, compToCreate as MgaFCO);
newRef.Name = compToCreate.Name;
////////
//VehicleForge.VFSession session = null;
//VFComponentExchange results = session.SendGetRequest<VFComponentExchange>("");
//VFComponentExchange resultjson = Newtonsoft.Json.JsonConvert.DeserializeObject<VFComponentExchange>("");
////////
result.Add(newRef);
bool compatible = true;
// create connections
foreach (var connectionToCreate in childConnections)
{
if (SafeMgaObjectCompare(connectionToCreate.SrcReferences.Cast<IMgaFCO>().FirstOrDefault(), compRef) ||
SafeMgaObjectCompare(connectionToCreate.DstReferences.Cast<IMgaFCO>().FirstOrDefault(), compRef))
{
try
{
var connRole = connectionToCreate.MetaRole;
var connSrc = connectionToCreate.Src;
var connDst = connectionToCreate.Dst;
var connSrcReference = connectionToCreate.SrcReferences.Cast<MgaFCO>().FirstOrDefault();
var connDstReference = connectionToCreate.DstReferences.Cast<MgaFCO>().FirstOrDefault();
// overwrite the new endpoints
if (SafeMgaObjectCompare(connectionToCreate.SrcReferences.Cast<IMgaFCO>().FirstOrDefault(), compRef))
{
connSrcReference = newRef;
// Check for objects with same name and same type
var srcCandidates = compToCreate.ChildObjects.OfType<MgaFCO>().Where(x =>
x.Name == connSrc.Name &&
x.Meta.Name == connSrc.Meta.Name);
MgaFCO srcCandidate = srcCandidates.FirstOrDefault();
if (srcCandidates.Count() > 1)
{
messages.Add(new KeyValuePair<IMgaFCO, string>(
compToCreate,
"Not Inserted. It has more than one matching object named: " + connSrc.Name));
compatible = false;
}
if (srcCandidate == null)
{
messages.Add(new KeyValuePair<IMgaFCO, string>(
compToCreate,
"Not Inserted. It does not have a port with name: " + connSrc.Name));
compatible = false;
}
connSrc = srcCandidate;
}
if (SafeMgaObjectCompare(connectionToCreate.DstReferences.Cast<IMgaFCO>().FirstOrDefault(), compRef))
{
connDstReference = newRef;
//var dstCandidate = compToCreate.ObjectByPath[connDst.Name] as MgaFCO;
var dstCandidates = compToCreate.ChildObjects.OfType<MgaFCO>().Where(x =>
x.Name == connDst.Name &&
x.Meta.Name == connDst.Meta.Name);
MgaFCO dstCandidate = dstCandidates.FirstOrDefault();
if (dstCandidates.Count() > 1)
{
messages.Add(new KeyValuePair<IMgaFCO, string>(
compToCreate,
"Not Inserted. It has more than one matching object named: " + connDst.Name));
compatible = false;
}
if (dstCandidate == null)
{
messages.Add(new KeyValuePair<IMgaFCO, string>(
compToCreate,
"Not Inserted. It does not have port with name: " + connDst.Name));
compatible = false;
}
connDst = dstCandidate;
}
// check end points
if (connSrc != null &&
connDst != null)
{
var newConnection = container.CreateSimpleConnDisp(
connRole,
connSrc,
connDst,
connSrcReference,
connDstReference);
}
}
catch (Exception ex)
{
System.Diagnostics.Trace.TraceError(ex.ToString());
System.Diagnostics.Trace.TraceError("Probably some ports do not match.");
compatible = false;
}
}
}
if (compatible)
{
iNewComponent = iNewComponent + 1;
foreach (IMgaPart part in newRef.Parts)
{
int x = 0;
int y = 0;
string icon;
componentRef.PartByMetaPart[part.Meta].GetGmeAttrs(out icon, out x, out y);
part.SetGmeAttrs(icon, x, y + 80 * iNewComponent);
}
}
else
{
//messages.Add(new KeyValuePair<IMgaFCO, string>(compToCreate, "Component was skipped: " + compToCreate.Name));
result.Remove(newRef);
newRef.DestroyObject();
}
}
foreach (var item in messages)
{
GMEConsole.Error.WriteLine("{0}: {1}", item.Key.ToMgaHyperLink(), item.Value);
}
GMEConsole.Info.WriteLine("{0} components were inserted. Detailed list as follows:", result.Count);
foreach (var item in result)
{
GMEConsole.Info.WriteLine("- {0}", item.ToMgaHyperLink());
}
return result;
}
private bool SafeMgaObjectCompare(IMgaObject obj1, IMgaObject obj2)
{
if (obj1 == obj2)
{
return true;
}
else if (obj1 != null && obj2 != null)
{
return obj1.ID == obj2.ID;
}
else
{
return false;
}
}
#region IMgaComponentEx Members
MgaGateway MgaGateway { get; set; }
GMEConsole GMEConsole { get; set; }
public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
{
if (!enabled)
{
return;
}
try
{
MgaGateway = new MgaGateway(project);
project.CreateTerritoryWithoutSink(out MgaGateway.territory);
MgaGateway.PerformInTransaction(delegate
{
Main(project, currentobj, selectedobjs, Convert(param));
});
}
finally
{
if (MgaGateway.territory != null)
{
MgaGateway.territory.Destroy();
}
MgaGateway = null;
project = null;
currentobj = null;
selectedobjs = null;
GMEConsole = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
private ComponentStartMode Convert(int param)
{
switch (param)
{
case (int)ComponentStartMode.GME_BGCONTEXT_START:
return ComponentStartMode.GME_BGCONTEXT_START;
case (int)ComponentStartMode.GME_BROWSER_START:
return ComponentStartMode.GME_BROWSER_START;
case (int)ComponentStartMode.GME_CONTEXT_START:
return ComponentStartMode.GME_CONTEXT_START;
case (int)ComponentStartMode.GME_EMBEDDED_START:
return ComponentStartMode.GME_EMBEDDED_START;
case (int)ComponentStartMode.GME_ICON_START:
return ComponentStartMode.GME_ICON_START;
case (int)ComponentStartMode.GME_MAIN_START:
return ComponentStartMode.GME_MAIN_START;
case (int)ComponentStartMode.GME_MENU_START:
return ComponentStartMode.GME_MENU_START;
case (int)ComponentStartMode.GME_SILENT_MODE:
return ComponentStartMode.GME_SILENT_MODE;
}
return ComponentStartMode.GME_SILENT_MODE;
}
#region Component Information
public string ComponentName
{
get { return GetType().Name; }
}
public string ComponentProgID
{
get
{
return ComponentConfig.progID;
}
}
public componenttype_enum ComponentType
{
get { return ComponentConfig.componentType; }
}
public string Paradigm
{
get { return ComponentConfig.paradigmName; }
}
#endregion
#region Enabling
bool enabled = true;
public void Enable(bool newval)
{
enabled = newval;
}
#endregion
#region Interactive Mode
protected bool interactiveMode = true;
public bool InteractiveMode
{
get
{
return interactiveMode;
}
set
{
interactiveMode = value;
}
}
#endregion
#region Custom Parameters
SortedDictionary<string, object> componentParameters = null;
public object get_ComponentParameter(string Name)
{
if (Name == "type")
return "csharp";
if (Name == "path")
return GetType().Assembly.Location;
if (Name == "fullname")
return GetType().FullName;
object value;
if (componentParameters != null && componentParameters.TryGetValue(Name, out value))
{
return value;
}
return null;
}
public void set_ComponentParameter(string Name, object pVal)
{
if (componentParameters == null)
{
componentParameters = new SortedDictionary<string, object>();
}
componentParameters[Name] = pVal;
}
#endregion
#region Unused Methods
// Old interface, it is never called for MgaComponentEx interfaces
public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param)
{
throw new NotImplementedException();
}
// Not used by GME
public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param)
{
throw new NotImplementedException();
}
#endregion
#endregion
#region IMgaVersionInfo Members
public GMEInterfaceVersion_enum version
{
get { return GMEInterfaceVersion_enum.GMEInterfaceVersion_Current; }
}
#endregion
#region Registration Helpers
[ComRegisterFunctionAttribute]
public static void GMERegister(Type t)
{
Registrar.RegisterComponentsInGMERegistry();
}
[ComUnregisterFunctionAttribute]
public static void GMEUnRegister(Type t)
{
Registrar.UnregisterComponentsInGMERegistry();
}
#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.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Xunit.Performance;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class SocketSendReceivePerfTest
{
[Benchmark(InnerIterationCount = 10_000), MeasureGCAllocations]
public async Task SendAsyncThenReceiveAsync_Task()
{
await OpenLoopbackConnectionAsync(async (client, server) =>
{
byte[] clientBuffer = new byte[1];
byte[] serverBuffer = new byte[1];
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
long iters = Benchmark.InnerIterationCount;
using (iteration.StartMeasurement())
{
for (int i = 0; i < iters; i++)
{
await client.SendAsync(clientBuffer, SocketFlags.None);
await server.ReceiveAsync(serverBuffer, SocketFlags.None);
}
}
}
});
}
[Benchmark(InnerIterationCount = 10_000), MeasureGCAllocations]
public async Task ReceiveAsyncThenSendAsync_Task()
{
await OpenLoopbackConnectionAsync(async (client, server) =>
{
byte[] clientBuffer = new byte[1];
byte[] serverBuffer = new byte[1];
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
long iters = Benchmark.InnerIterationCount;
using (iteration.StartMeasurement())
{
for (int i = 0; i < iters; i++)
{
Task r = server.ReceiveAsync(serverBuffer, SocketFlags.None);
await client.SendAsync(clientBuffer, SocketFlags.None);
await r;
}
}
}
});
}
[Benchmark(InnerIterationCount = 1_000_000)]
[InlineData(16)]
public async Task ReceiveAsyncThenSendAsync_Task_Parallel(int numConnections)
{
byte[] clientBuffer = new byte[1];
byte[] serverBuffer = new byte[1];
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
await OpenLoopbackConnectionAsync(async (client, server) =>
{
long iters = Benchmark.InnerIterationCount;
using (iteration.StartMeasurement())
{
for (int i = 0; i < iters; i++)
{
Task r = server.ReceiveAsync(serverBuffer, SocketFlags.None);
await client.SendAsync(clientBuffer, SocketFlags.None);
await r;
}
}
});
}
}
[Benchmark(InnerIterationCount = 10_000), MeasureGCAllocations]
public async Task SendAsyncThenReceiveAsync_SocketAsyncEventArgs()
{
await OpenLoopbackConnectionAsync(async (client, server) =>
{
var clientSaea = new AwaitableSocketAsyncEventArgs();
var serverSaea = new AwaitableSocketAsyncEventArgs();
clientSaea.SetBuffer(new byte[1], 0, 1);
serverSaea.SetBuffer(new byte[1], 0, 1);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
long iters = Benchmark.InnerIterationCount;
using (iteration.StartMeasurement())
{
for (int i = 0; i < iters; i++)
{
if (client.SendAsync(clientSaea))
{
await clientSaea;
}
if (server.ReceiveAsync(serverSaea))
{
await serverSaea;
}
}
}
}
});
}
[Benchmark(InnerIterationCount = 10_000), MeasureGCAllocations]
public async Task ReceiveAsyncThenSendAsync_SocketAsyncEventArgs()
{
await OpenLoopbackConnectionAsync(async (client, server) =>
{
var clientSaea = new AwaitableSocketAsyncEventArgs();
var serverSaea = new AwaitableSocketAsyncEventArgs();
clientSaea.SetBuffer(new byte[1], 0, 1);
serverSaea.SetBuffer(new byte[1], 0, 1);
foreach (BenchmarkIteration iteration in Benchmark.Iterations)
{
long iters = Benchmark.InnerIterationCount;
using (iteration.StartMeasurement())
{
for (int i = 0; i < iters; i++)
{
bool pendingServer = server.ReceiveAsync(serverSaea);
if (client.SendAsync(clientSaea))
{
await clientSaea;
}
if (pendingServer)
{
await serverSaea;
}
}
}
}
});
}
private static async Task OpenLoopbackConnectionAsync(Func<Socket, Socket, Task> func)
{
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = listener.AcceptAsync();
Task connectTask = client.ConnectAsync(listener.LocalEndPoint);
await await Task.WhenAny(acceptTask, connectTask);
await Task.WhenAll(acceptTask, connectTask);
using (Socket server = await acceptTask)
{
await func(client, server);
}
}
}
internal sealed class AwaitableSocketAsyncEventArgs : SocketAsyncEventArgs, ICriticalNotifyCompletion
{
private static readonly Action s_completedSentinel = () => { };
private Action _continuation;
public AwaitableSocketAsyncEventArgs()
{
Completed += delegate
{
Action c = _continuation;
if (c != null)
{
c();
}
else
{
Interlocked.CompareExchange(ref _continuation, s_completedSentinel, null)?.Invoke();
}
};
}
public AwaitableSocketAsyncEventArgs GetAwaiter() => this;
public bool IsCompleted => _continuation != null;
public void UnsafeOnCompleted(Action continuation) => OnCompleted(continuation);
public void OnCompleted(Action continuation)
{
if (ReferenceEquals(_continuation, s_completedSentinel) ||
ReferenceEquals(Interlocked.CompareExchange(ref _continuation, continuation, null), s_completedSentinel))
{
Task.Run(continuation);
}
}
public int GetResult()
{
_continuation = null;
if (SocketError != SocketError.Success)
{
throw new SocketException((int)SocketError);
}
return BytesTransferred;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Presentation.TorreHanoi.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
var genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
var genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
var collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
var closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
var dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
var closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
var genericArgs = type.GetGenericArguments();
var parameterValues = new object[genericArgs.Length];
var failedToCreateTuple = true;
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
var result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
var genericArgs = keyValuePairType.GetGenericArguments();
var typeK = genericArgs[0];
var typeV = genericArgs[1];
var objectGenerator = new ObjectGenerator();
var keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
var valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
var result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
var type = arrayType.GetElementType();
var result = Array.CreateInstance(type, size);
var areAllElementsNull = true;
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < size; i++)
{
var element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
var typeK = typeof(object);
var typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
var genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
var result = Activator.CreateInstance(dictionaryType);
var addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
var containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < size; i++)
{
var newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
var containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
var newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
var possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
var isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
var listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
var argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
var asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
var type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
var result = Activator.CreateInstance(collectionType);
var addMethod = collectionType.GetMethod("Add");
var areAllElementsNull = true;
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < size; i++)
{
var element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
var type = nullableType.GetGenericArguments()[0];
var objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
var defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var objectGenerator = new ObjectGenerator();
foreach (var property in properties)
{
if (property.CanWrite)
{
var propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
var objectGenerator = new ObjectGenerator();
foreach (var field in fields)
{
var fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace MovieHunter.API.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
namespace ItIsAlive.Samples.ContactsWeb
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using NHibernate;
using NHibernate.Collection;
using NHibernate.DebugHelpers;
using NHibernate.Engine;
using NHibernate.Loader;
using NHibernate.Persister.Collection;
using NHibernate.Type;
using NHibernate.Util;
using CollectionType = System.Data.Metadata.Edm.CollectionType;
//add to your configuration:
//configuration.Properties[Environment.CollectionTypeFactoryClass]
// = typeof(Net4CollectionTypeFactory).AssemblyQualifiedName;
public class Net4CollectionTypeFactory : DefaultCollectionTypeFactory
{
public override NHibernate.Type.CollectionType Set<T>(string role, string propertyRef, bool embedded)
{
return new GenericSetType<T>(role, propertyRef);
}
public override NHibernate.Type.CollectionType SortedSet<T>(string role, string propertyRef, bool embedded, IComparer<T> comparer)
{
return new GenericSortedSetType<T>(role, propertyRef, comparer);
}
}
[Serializable]
public class GenericSortedSetType<T> : GenericSetType<T>
{
private readonly IComparer<T> comparer;
public GenericSortedSetType(string role, string propertyRef, IComparer<T> comparer)
: base(role, propertyRef)
{
this.comparer = comparer;
}
public override object Instantiate(int anticipatedSize)
{
return new SortedSet<T>(this.comparer);
}
public IComparer<T> Comparer
{
get
{
return this.comparer;
}
}
}
/// <summary>
/// An <see cref="IType"/> that maps an <see cref="ISet{T}"/> collection
/// to the database.
/// </summary>
[Serializable]
public class GenericSetType<T> : SetType
{
/// <summary>
/// Initializes a new instance of a <see cref="GenericSetType{T}"/> class for
/// a specific role.
/// </summary>
/// <param name="role">The role the persistent collection is in.</param>
/// <param name="propertyRef">The name of the property in the
/// owner object containing the collection ID, or <see langword="null" /> if it is
/// the primary key.</param>
public GenericSetType(string role, string propertyRef)
: base(role, propertyRef, false)
{
}
public override Type ReturnedClass
{
get { return typeof (ISet<T>); }
}
/// <summary>
/// Instantiates a new <see cref="IPersistentCollection"/> for the set.
/// </summary>
/// <param name="session">The current <see cref="ISessionImplementor"/> for the set.</param>
/// <param name="persister">The current <see cref="ICollectionPersister" /> for the set.</param>
/// <param name="key"></param>
public override IPersistentCollection Instantiate(ISessionImplementor session, ICollectionPersister persister,
object key)
{
return new PersistentGenericSet<T>(session);
}
/// <summary>
/// Wraps an <see cref="IList{T}"/> in a <see cref="PersistentGenericSet<T>"/>.
/// </summary>
/// <param name="session">The <see cref="ISessionImplementor"/> for the collection to be a part of.</param>
/// <param name="collection">The unwrapped <see cref="IList{T}"/>.</param>
/// <returns>
/// An <see cref="PersistentGenericSet<T>"/> that wraps the non NHibernate <see cref="IList{T}"/>.
/// </returns>
public override IPersistentCollection Wrap(ISessionImplementor session, object collection)
{
var set = collection as ISet<T>;
if (set == null)
{
var stronglyTypedCollection = collection as ICollection<T>;
if (stronglyTypedCollection == null)
throw new HibernateException(Role + " must be an implementation of ISet<T> or ICollection<T>");
set = new HashSet<T>(stronglyTypedCollection);
}
return new PersistentGenericSet<T>(session, set);
}
public override object Instantiate(int anticipatedSize)
{
return new HashSet<T>();
}
protected override void Clear(object collection)
{
((ISet<T>)collection).Clear();
}
protected override void Add(object collection, object element)
{
((ISet<T>)collection).Add((T)element);
}
}
/// <summary>
/// A persistent wrapper for an <see cref="ISet{T}"/>
/// </summary>
[Serializable]
[DebuggerTypeProxy(typeof (CollectionProxy<>))]
public class PersistentGenericSet<T> : AbstractPersistentCollection, ISet<T>
{
/// <summary>
/// The <see cref="ISet{T}"/> that NHibernate is wrapping.
/// </summary>
protected ISet<T> set;
/// <summary>
/// A temporary list that holds the objects while the PersistentSet is being
/// populated from the database.
/// </summary>
/// <remarks>
/// This is necessary to ensure that the object being added to the PersistentSet doesn't
/// have its' <c>GetHashCode()</c> and <c>Equals()</c> methods called during the load
/// process.
/// </remarks>
[NonSerialized] private IList<T> tempList;
public PersistentGenericSet()
{
}
// needed for serialization
/// <summary>
/// Constructor matching super.
/// Instantiates a lazy set (the underlying set is un-initialized).
/// </summary>
/// <param name="session">The session to which this set will belong. </param>
public PersistentGenericSet(ISessionImplementor session) : base(session)
{
}
/// <summary>
/// Instantiates a non-lazy set (the underlying set is constructed
/// from the incoming set reference).
/// </summary>
/// <param name="session">The session to which this set will belong. </param>
/// <param name="original">The underlying set data. </param>
public PersistentGenericSet(ISessionImplementor session, ISet<T> original)
: base(session)
{
// Sets can be just a view of a part of another collection.
// do we need to copy it to be sure it won't be changing
// underneath us?
// ie. this.set.addAll(set);
this.set = original;
SetInitialized();
IsDirectlyAccessible = true;
}
public override bool RowUpdatePossible
{
get { return false; }
}
public override bool Empty
{
get { return this.set.Count == 0; }
}
public bool IsEmpty
{
get { return ReadSize() ? CachedSize == 0 : (this.set.Count == 0); }
}
public object SyncRoot
{
get { return this; }
}
public bool IsSynchronized
{
get { return false; }
}
#region ISet<T> Members
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
this.Read();
return this.set.GetEnumerator();
}
public bool Contains(T o)
{
bool? exists = ReadElementExistence(o);
return exists == null ? this.set.Contains(o) : exists.Value;
}
public void CopyTo(T[] array, int arrayIndex)
{
this.Read();
Array.Copy(this.set.ToArray(), 0, array, arrayIndex, this.Count);
}
//public bool ContainsAll(ICollection c)
//{
// Read();
// return set.ContainsAll(c);
//}
public bool Add(T o)
{
bool? exists = IsOperationQueueEnabled ? ReadElementExistence(o) : null;
if (!exists.HasValue)
{
Initialize(true);
if (this.set.Add(o))
{
Dirty();
return true;
}
return false;
}
if (exists.Value)
{
return false;
}
QueueOperation(new SimpleAddDelayedOperation(this, o));
return true;
}
public void UnionWith(IEnumerable<T> other)
{
this.Read();
this.set.UnionWith(other);
}
public void IntersectWith(IEnumerable<T> other)
{
this.Read();
this.set.IntersectWith(other);
}
public void ExceptWith(IEnumerable<T> other)
{
this.Read();
this.set.ExceptWith(other);
}
public void SymmetricExceptWith(IEnumerable<T> other)
{
this.Read();
this.set.SymmetricExceptWith(other);
}
public bool IsSubsetOf(IEnumerable<T> other)
{
this.Read();
return this.set.IsProperSupersetOf(other);
}
public bool IsSupersetOf(IEnumerable<T> other)
{
this.Read();
return this.set.IsSupersetOf(other);
}
public bool IsProperSupersetOf(IEnumerable<T> other)
{
this.Read();
return this.set.IsProperSupersetOf(other);
}
public bool IsProperSubsetOf(IEnumerable<T> other)
{
this.Read();
return this.set.IsProperSubsetOf(other);
}
public bool Overlaps(IEnumerable<T> other)
{
this.Read();
return this.set.Overlaps(other);
}
public bool SetEquals(IEnumerable<T> other)
{
this.Read();
return this.set.SetEquals(other);
}
public bool Remove(T o)
{
bool? exists = PutQueueEnabled ? ReadElementExistence(o) : null;
if (!exists.HasValue)
{
Initialize(true);
if (this.set.Remove(o))
{
Dirty();
return true;
}
return false;
}
if (exists.Value)
{
QueueOperation(new SimpleRemoveDelayedOperation(this, o));
return true;
}
return false;
}
void ICollection<T>.Add(T item)
{
this.Add(item);
}
public void Clear()
{
if (ClearQueueEnabled)
{
QueueOperation(new ClearDelayedOperation(this));
}
else
{
Initialize(true);
if (this.set.Count != 0)
{
this.set.Clear();
Dirty();
}
}
}
public int Count
{
get { return ReadSize() ? CachedSize : this.set.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public IEnumerator GetEnumerator()
{
this.Read();
return this.set.GetEnumerator();
}
#endregion
#region DelayedOperations
#region Nested type: ClearDelayedOperation
protected sealed class ClearDelayedOperation : IDelayedOperation
{
private readonly PersistentGenericSet<T> enclosingInstance;
public ClearDelayedOperation(PersistentGenericSet<T> enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
#region IDelayedOperation Members
public object AddedInstance
{
get { return null; }
}
public object Orphan
{
get { throw new NotSupportedException("queued clear cannot be used with orphan delete"); }
}
public void Operate()
{
this.enclosingInstance.set.Clear();
}
#endregion
}
#endregion
#region Nested type: SimpleAddDelayedOperation
protected sealed class SimpleAddDelayedOperation : IDelayedOperation
{
private readonly PersistentGenericSet<T> enclosingInstance;
private readonly T value;
public SimpleAddDelayedOperation(PersistentGenericSet<T> enclosingInstance, T value)
{
this.enclosingInstance = enclosingInstance;
this.value = value;
}
#region IDelayedOperation Members
public object AddedInstance
{
get { return this.value; }
}
public object Orphan
{
get { return null; }
}
public void Operate()
{
this.enclosingInstance.set.Add(this.value);
}
#endregion
}
#endregion
#region Nested type: SimpleRemoveDelayedOperation
protected sealed class SimpleRemoveDelayedOperation : IDelayedOperation
{
private readonly PersistentGenericSet<T> enclosingInstance;
private readonly T value;
public SimpleRemoveDelayedOperation(PersistentGenericSet<T> enclosingInstance, T value)
{
this.enclosingInstance = enclosingInstance;
this.value = value;
}
#region IDelayedOperation Members
public object AddedInstance
{
get { return null; }
}
public object Orphan
{
get { return this.value; }
}
public void Operate()
{
this.enclosingInstance.set.Remove(this.value);
}
#endregion
}
#endregion
#endregion
public override ICollection GetSnapshot(ICollectionPersister persister)
{
var entityMode = Session.EntityMode;
var clonedSet = new SetSnapShot<T>(this.set.Count);
var enumerable = from object current in this.set
select persister.ElementType.DeepCopy(current, entityMode, persister.Factory);
foreach (var copied in enumerable)
{
clonedSet.Add((T)copied);
}
return clonedSet;
}
public override ICollection GetOrphans(object snapshot, string entityName)
{
var sn = new SetSnapShot<object>((IEnumerable<object>) snapshot);
if (this.set.Count == 0) return sn;
if (((ICollection) sn).Count == 0) return sn;
return GetOrphans(sn, this.set.ToArray(), entityName, Session);
}
public override bool EqualsSnapshot(ICollectionPersister persister)
{
var elementType = persister.ElementType;
var snapshot = (ISetSnapshot<T>) GetSnapshot();
if (((ICollection) snapshot).Count != this.set.Count)
{
return false;
}
return !(from object obj in this.set
let oldValue = snapshot[(T)obj]
where oldValue == null || elementType.IsDirty(oldValue, obj, Session)
select obj).Any();
}
public override bool IsSnapshotEmpty(object snapshot)
{
return ((ICollection) snapshot).Count == 0;
}
public override void BeforeInitialize(ICollectionPersister persister, int anticipatedSize)
{
this.set = (ISet<T>) persister.CollectionType.Instantiate(anticipatedSize);
}
/// <summary>
/// Initializes this PersistentSet from the cached values.
/// </summary>
/// <param name="persister">The CollectionPersister to use to reassemble the PersistentSet.</param>
/// <param name="disassembled">The disassembled PersistentSet.</param>
/// <param name="owner">The owner object.</param>
public override void InitializeFromCache(ICollectionPersister persister, object disassembled, object owner)
{
var array = (object[]) disassembled;
int size = array.Length;
this.BeforeInitialize(persister, size);
for (int i = 0; i < size; i++)
{
var element = (T) persister.ElementType.Assemble(array[i], Session, owner);
if (element != null)
{
this.set.Add(element);
}
}
SetInitialized();
}
public override string ToString()
{
this.Read();
return StringHelper.CollectionToString(this.set.ToArray());
}
public override object ReadFrom(IDataReader rs, ICollectionPersister role, ICollectionAliases descriptor, object owner)
{
var element = (T) role.ReadElement(rs, owner, descriptor.SuffixedElementAliases, Session);
if (element != null)
{
this.tempList.Add(element);
}
return element;
}
/// <summary>
/// Set up the temporary List that will be used in the EndRead()
/// to fully create the set.
/// </summary>
public override void BeginRead()
{
base.BeginRead();
this.tempList = new List<T>();
}
/// <summary>
/// Takes the contents stored in the temporary list created during <c>BeginRead()</c>
/// that was populated during <c>ReadFrom()</c> and write it to the underlying
/// PersistentSet.
/// </summary>
public override bool EndRead(ICollectionPersister persister)
{
foreach (T item in this.tempList)
{
this.set.Add(item);
}
this.tempList = null;
SetInitialized();
return true;
}
public override IEnumerable Entries(ICollectionPersister persister)
{
return this.set;
}
public override object Disassemble(ICollectionPersister persister)
{
var result = new object[this.set.Count];
int i = 0;
foreach (object obj in this.set)
{
result[i++] = persister.ElementType.Disassemble(obj, Session, null);
}
return result;
}
public override IEnumerable GetDeletes(ICollectionPersister persister, bool indexIsFormula)
{
IType elementType = persister.ElementType;
var sn = (ISetSnapshot<T>) GetSnapshot();
var deletes = new List<T>(((ICollection<T>) sn).Count);
deletes.AddRange(sn.Where(obj => !this.set.Contains(obj)));
deletes.AddRange(from obj in this.set
let oldValue = sn[obj]
where oldValue != null && elementType.IsDirty(obj, oldValue, Session)
select oldValue);
return deletes;
}
public override bool NeedsInserting(object entry, int i, IType elemType)
{
var sn = (ISetSnapshot<T>) GetSnapshot();
object oldKey = sn[(T)entry];
// note that it might be better to iterate the snapshot but this is safe,
// assuming the user implements equals() properly, as required by the PersistentSet
// contract!
return oldKey == null || elemType.IsDirty(oldKey, entry, Session);
}
public override bool NeedsUpdating(object entry, int i, IType elemType)
{
return false;
}
public override object GetIndex(object entry, int i, ICollectionPersister persister)
{
throw new NotSupportedException("Sets don't have indexes");
}
public override object GetElement(object entry)
{
return entry;
}
public override object GetSnapshotElement(object entry, int i)
{
throw new NotSupportedException("Sets don't support updating by element");
}
public new void Read()
{
base.Read();
}
public override bool Equals(object other)
{
var that = other as ISet<T>;
if (that == null)
{
return false;
}
this.Read();
return this.set.SequenceEqual(that);
}
public override int GetHashCode()
{
this.Read();
return this.set.GetHashCode();
}
public override bool EntryExists(object entry, int i)
{
return true;
}
public override bool IsWrapper(object collection)
{
return this.set == collection;
}
public void CopyTo(Array array, int index)
{
// NH : we really need to initialize the set ?
this.Read();
Array.Copy(this.set.ToArray(), 0, array, index, this.Count);
}
#region Nested type: ISetSnapshot
private interface ISetSnapshot<T> : ICollection<T>, ICollection
{
T this[T element] { get; }
}
#endregion
#region Nested type: SetSnapShot
[Serializable]
private class SetSnapShot<T> : ISetSnapshot<T>
{
private readonly List<T> elements;
private SetSnapShot()
{
this.elements = new List<T>();
}
public SetSnapShot(int capacity)
{
this.elements = new List<T>(capacity);
}
public SetSnapShot(IEnumerable<T> collection)
{
this.elements = new List<T>(collection);
}
#region ISetSnapshot<T> Members
public IEnumerator<T> GetEnumerator()
{
return this.elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public void Add(T item)
{
this.elements.Add(item);
}
public void Clear()
{
throw new InvalidOperationException();
}
public bool Contains(T item)
{
return this.elements.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
this.elements.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
throw new InvalidOperationException();
}
public void CopyTo(Array array, int index)
{
((ICollection) this.elements).CopyTo(array, index);
}
int ICollection.Count
{
get { return this.elements.Count; }
}
public object SyncRoot
{
get { return ((ICollection) this.elements).SyncRoot; }
}
public bool IsSynchronized
{
get { return ((ICollection) this.elements).IsSynchronized; }
}
int ICollection<T>.Count
{
get { return this.elements.Count; }
}
public bool IsReadOnly
{
get { return ((ICollection<T>) this.elements).IsReadOnly; }
}
public T this[T element]
{
get
{
int idx = this.elements.IndexOf(element);
if (idx >= 0)
{
return this.elements[idx];
}
return default(T);
}
}
#endregion
}
#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.
#if SUPPORTS_WINDOWSIDENTITY
using System.Collections.Generic;
using System.IdentityModel.Policy;
using System.Runtime;
using System.Security;
using System.Security.Principal;
using System.ServiceModel;
namespace System.IdentityModel.Claims
{
public class WindowsClaimSet : ClaimSet, IIdentityInfo, IDisposable
{
internal const bool DefaultIncludeWindowsGroups = true;
private WindowsIdentity _windowsIdentity;
private DateTime _expirationTime;
private bool _includeWindowsGroups;
private IList<Claim> _claims;
private bool _disposed = false;
private string _authenticationType;
public WindowsClaimSet(WindowsIdentity windowsIdentity)
: this(windowsIdentity, DefaultIncludeWindowsGroups)
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, bool includeWindowsGroups)
: this(windowsIdentity, includeWindowsGroups, DateTime.UtcNow.AddHours(10))
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, DateTime expirationTime)
: this(windowsIdentity, DefaultIncludeWindowsGroups, expirationTime)
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, bool includeWindowsGroups, DateTime expirationTime)
: this(windowsIdentity, null, includeWindowsGroups, expirationTime, true)
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, DateTime expirationTime)
: this(windowsIdentity, authenticationType, includeWindowsGroups, expirationTime, true)
{
}
internal WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, bool clone)
: this(windowsIdentity, authenticationType, includeWindowsGroups, DateTime.UtcNow.AddHours(10), clone)
{
}
internal WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, DateTime expirationTime, bool clone)
{
if (windowsIdentity == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("windowsIdentity");
_windowsIdentity = clone ? SecurityUtils.CloneWindowsIdentityIfNecessary(windowsIdentity, authenticationType) : windowsIdentity;
_includeWindowsGroups = includeWindowsGroups;
_expirationTime = expirationTime;
_authenticationType = authenticationType;
}
private WindowsClaimSet(WindowsClaimSet from)
: this(from.WindowsIdentity, from._authenticationType, from._includeWindowsGroups, from._expirationTime, true)
{
}
public override Claim this[int index]
{
get
{
ThrowIfDisposed();
EnsureClaims();
return _claims[index];
}
}
public override int Count
{
get
{
ThrowIfDisposed();
EnsureClaims();
return _claims.Count;
}
}
IIdentity IIdentityInfo.Identity
{
get
{
ThrowIfDisposed();
return _windowsIdentity;
}
}
public WindowsIdentity WindowsIdentity
{
get
{
ThrowIfDisposed();
return _windowsIdentity;
}
}
public override ClaimSet Issuer
{
get { return ClaimSet.Windows; }
}
public DateTime ExpirationTime
{
get { return _expirationTime; }
}
internal WindowsClaimSet Clone()
{
ThrowIfDisposed();
return new WindowsClaimSet(this);
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
_windowsIdentity.Dispose();
}
}
private IList<Claim> InitializeClaimsCore()
{
if (_windowsIdentity.AccessToken == null)
return new List<Claim>();
List<Claim> claims = new List<Claim>(3);
claims.Add(new Claim(ClaimTypes.Sid, _windowsIdentity.User, Rights.Identity));
Claim claim;
if (TryCreateWindowsSidClaim(_windowsIdentity, out claim))
{
claims.Add(claim);
}
claims.Add(Claim.CreateNameClaim(_windowsIdentity.Name));
if (_includeWindowsGroups)
{
// claims.AddRange(Groups);
}
return claims;
}
private void EnsureClaims()
{
if (_claims != null)
return;
_claims = InitializeClaimsCore();
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
}
private static bool SupportedClaimType(string claimType)
{
return claimType == null ||
ClaimTypes.Sid == claimType ||
ClaimTypes.DenyOnlySid == claimType ||
ClaimTypes.Name == claimType;
}
// Note: null string represents any.
public override IEnumerable<Claim> FindClaims(string claimType, string right)
{
ThrowIfDisposed();
if (!SupportedClaimType(claimType) || !ClaimSet.SupportedRight(right))
{
yield break;
}
else if (_claims == null && (ClaimTypes.Sid == claimType || ClaimTypes.DenyOnlySid == claimType))
{
if (ClaimTypes.Sid == claimType)
{
if (right == null || Rights.Identity == right)
{
yield return new Claim(ClaimTypes.Sid, _windowsIdentity.User, Rights.Identity);
}
}
if (right == null || Rights.PossessProperty == right)
{
Claim sid;
if (TryCreateWindowsSidClaim(_windowsIdentity, out sid))
{
if (claimType == sid.ClaimType)
{
yield return sid;
}
}
}
if (_includeWindowsGroups && (right == null || Rights.PossessProperty == right))
{
// Not sure yet if GroupSidClaimCollections are necessary in .NET Core, but default
// _includeWindowsGroups is true; don't throw here or we bust the default case on UWP/.NET Core
}
}
else
{
EnsureClaims();
bool anyClaimType = (claimType == null);
bool anyRight = (right == null);
for (int i = 0; i < _claims.Count; ++i)
{
Claim claim = _claims[i];
if ((claim != null) &&
(anyClaimType || claimType == claim.ClaimType) &&
(anyRight || right == claim.Right))
{
yield return claim;
}
}
}
}
public override IEnumerator<Claim> GetEnumerator()
{
ThrowIfDisposed();
EnsureClaims();
return _claims.GetEnumerator();
}
public override string ToString()
{
return _disposed ? base.ToString() : SecurityUtils.ClaimSetToString(this);
}
public static bool TryCreateWindowsSidClaim(WindowsIdentity windowsIdentity, out Claim claim)
{
throw ExceptionHelper.PlatformNotSupported("CreateWindowsSidClaim is not yet supported");
}
}
}
#endif // SUPPORTS_WINDOWSIDENTITY
| |
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 Provisioning.Job
{
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
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tenancy_config/rpc/reservation_source_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.TenancyConfig.RPC {
public static partial class ReservationSourceSvc
{
static readonly string __ServiceName = "holms.types.tenancy_config.rpc.ReservationSourceSvc";
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.RPC.ReservationSourceSvcAllResponse> __Marshaller_ReservationSourceSvcAllResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.RPC.ReservationSourceSvcAllResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.Indicators.ReservationSourceIndicator> __Marshaller_ReservationSourceIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.Indicators.ReservationSourceIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.ReservationSource> __Marshaller_ReservationSource = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.ReservationSource.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.ServerActionConfirmation> __Marshaller_ServerActionConfirmation = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.ServerActionConfirmation.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.TenancyConfig.RPC.ReservationSourceSvcAllResponse> __Method_All = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.TenancyConfig.RPC.ReservationSourceSvcAllResponse>(
grpc::MethodType.Unary,
__ServiceName,
"All",
__Marshaller_Empty,
__Marshaller_ReservationSourceSvcAllResponse);
static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.Indicators.ReservationSourceIndicator, global::HOLMS.Types.TenancyConfig.ReservationSource> __Method_GetById = new grpc::Method<global::HOLMS.Types.TenancyConfig.Indicators.ReservationSourceIndicator, global::HOLMS.Types.TenancyConfig.ReservationSource>(
grpc::MethodType.Unary,
__ServiceName,
"GetById",
__Marshaller_ReservationSourceIndicator,
__Marshaller_ReservationSource);
static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.ReservationSource, global::HOLMS.Types.TenancyConfig.ReservationSource> __Method_Create = new grpc::Method<global::HOLMS.Types.TenancyConfig.ReservationSource, global::HOLMS.Types.TenancyConfig.ReservationSource>(
grpc::MethodType.Unary,
__ServiceName,
"Create",
__Marshaller_ReservationSource,
__Marshaller_ReservationSource);
static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.ReservationSource, global::HOLMS.Types.TenancyConfig.ReservationSource> __Method_Update = new grpc::Method<global::HOLMS.Types.TenancyConfig.ReservationSource, global::HOLMS.Types.TenancyConfig.ReservationSource>(
grpc::MethodType.Unary,
__ServiceName,
"Update",
__Marshaller_ReservationSource,
__Marshaller_ReservationSource);
static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.ReservationSource, global::HOLMS.Types.Primitive.ServerActionConfirmation> __Method_Delete = new grpc::Method<global::HOLMS.Types.TenancyConfig.ReservationSource, global::HOLMS.Types.Primitive.ServerActionConfirmation>(
grpc::MethodType.Unary,
__ServiceName,
"Delete",
__Marshaller_ReservationSource,
__Marshaller_ServerActionConfirmation);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.TenancyConfig.RPC.ReservationSourceSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of ReservationSourceSvc</summary>
public abstract partial class ReservationSourceSvcBase
{
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.RPC.ReservationSourceSvcAllResponse> All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.ReservationSource> GetById(global::HOLMS.Types.TenancyConfig.Indicators.ReservationSourceIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.ReservationSource> Create(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.ReservationSource> Update(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Primitive.ServerActionConfirmation> Delete(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for ReservationSourceSvc</summary>
public partial class ReservationSourceSvcClient : grpc::ClientBase<ReservationSourceSvcClient>
{
/// <summary>Creates a new client for ReservationSourceSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public ReservationSourceSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for ReservationSourceSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public ReservationSourceSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected ReservationSourceSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected ReservationSourceSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::HOLMS.Types.TenancyConfig.RPC.ReservationSourceSvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return All(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.TenancyConfig.RPC.ReservationSourceSvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_All, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.RPC.ReservationSourceSvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AllAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.RPC.ReservationSourceSvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_All, null, options, request);
}
public virtual global::HOLMS.Types.TenancyConfig.ReservationSource GetById(global::HOLMS.Types.TenancyConfig.Indicators.ReservationSourceIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetById(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.TenancyConfig.ReservationSource GetById(global::HOLMS.Types.TenancyConfig.Indicators.ReservationSourceIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetById, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.ReservationSource> GetByIdAsync(global::HOLMS.Types.TenancyConfig.Indicators.ReservationSourceIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetByIdAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.ReservationSource> GetByIdAsync(global::HOLMS.Types.TenancyConfig.Indicators.ReservationSourceIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetById, null, options, request);
}
public virtual global::HOLMS.Types.TenancyConfig.ReservationSource Create(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Create(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.TenancyConfig.ReservationSource Create(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Create, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.ReservationSource> CreateAsync(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.ReservationSource> CreateAsync(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Create, null, options, request);
}
public virtual global::HOLMS.Types.TenancyConfig.ReservationSource Update(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Update(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.TenancyConfig.ReservationSource Update(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Update, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.ReservationSource> UpdateAsync(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.ReservationSource> UpdateAsync(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Update, null, options, request);
}
public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Delete(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Delete, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.TenancyConfig.ReservationSource request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Delete, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override ReservationSourceSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new ReservationSourceSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(ReservationSourceSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_All, serviceImpl.All)
.AddMethod(__Method_GetById, serviceImpl.GetById)
.AddMethod(__Method_Create, serviceImpl.Create)
.AddMethod(__Method_Update, serviceImpl.Update)
.AddMethod(__Method_Delete, serviceImpl.Delete).Build();
}
}
}
#endregion
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C02Level1 (editable root object).<br/>
/// This is a generated base class of <see cref="C02Level1"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="C03Level11Objects"/> of type <see cref="C03Level11Coll"/> (1:M relation to <see cref="C04Level11"/>)
/// </remarks>
[Serializable]
public partial class C02Level1 : BusinessBase<C02Level1>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Level_1_IDProperty = RegisterProperty<int>(p => p.Level_1_ID, "Level_1 ID");
/// <summary>
/// Gets the Level_1 ID.
/// </summary>
/// <value>The Level_1 ID.</value>
public int Level_1_ID
{
get { return GetProperty(Level_1_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Level_1_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_NameProperty = RegisterProperty<string>(p => p.Level_1_Name, "Level_1 Name");
/// <summary>
/// Gets or sets the Level_1 Name.
/// </summary>
/// <value>The Level_1 Name.</value>
public string Level_1_Name
{
get { return GetProperty(Level_1_NameProperty); }
set { SetProperty(Level_1_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C03Level11SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C03Level11Child> C03Level11SingleObjectProperty = RegisterProperty<C03Level11Child>(p => p.C03Level11SingleObject, "A3 Level11 Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C03 Level11 Single Object ("self load" child property).
/// </summary>
/// <value>The C03 Level11 Single Object.</value>
public C03Level11Child C03Level11SingleObject
{
get { return GetProperty(C03Level11SingleObjectProperty); }
private set { LoadProperty(C03Level11SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C03Level11ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C03Level11ReChild> C03Level11ASingleObjectProperty = RegisterProperty<C03Level11ReChild>(p => p.C03Level11ASingleObject, "A3 Level11 ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C03 Level11 ASingle Object ("self load" child property).
/// </summary>
/// <value>The C03 Level11 ASingle Object.</value>
public C03Level11ReChild C03Level11ASingleObject
{
get { return GetProperty(C03Level11ASingleObjectProperty); }
private set { LoadProperty(C03Level11ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C03Level11Objects"/> property.
/// </summary>
public static readonly PropertyInfo<C03Level11Coll> C03Level11ObjectsProperty = RegisterProperty<C03Level11Coll>(p => p.C03Level11Objects, "A3 Level11 Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the C03 Level11 Objects ("self load" child property).
/// </summary>
/// <value>The C03 Level11 Objects.</value>
public C03Level11Coll C03Level11Objects
{
get { return GetProperty(C03Level11ObjectsProperty); }
private set { LoadProperty(C03Level11ObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C02Level1"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="C02Level1"/> object.</returns>
public static C02Level1 NewC02Level1()
{
return DataPortal.Create<C02Level1>();
}
/// <summary>
/// Factory method. Loads a <see cref="C02Level1"/> object, based on given parameters.
/// </summary>
/// <param name="level_1_ID">The Level_1_ID parameter of the C02Level1 to fetch.</param>
/// <returns>A reference to the fetched <see cref="C02Level1"/> object.</returns>
public static C02Level1 GetC02Level1(int level_1_ID)
{
return DataPortal.Fetch<C02Level1>(level_1_ID);
}
/// <summary>
/// Factory method. Marks the <see cref="C02Level1"/> object for deletion.
/// The object will be deleted as part of the next save operation.
/// </summary>
/// <param name="level_1_ID">The Level_1_ID of the C02Level1 to delete.</param>
public static void DeleteC02Level1(int level_1_ID)
{
DataPortal.Delete<C02Level1>(level_1_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C02Level1"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private C02Level1()
{
// Prevent direct creation
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="C02Level1"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(Level_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(C03Level11SingleObjectProperty, DataPortal.CreateChild<C03Level11Child>());
LoadProperty(C03Level11ASingleObjectProperty, DataPortal.CreateChild<C03Level11ReChild>());
LoadProperty(C03Level11ObjectsProperty, DataPortal.CreateChild<C03Level11Coll>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="C02Level1"/> object from the database, based on given criteria.
/// </summary>
/// <param name="level_1_ID">The Level_1 ID.</param>
protected void DataPortal_Fetch(int level_1_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetC02Level1", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", level_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, level_1_ID);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
FetchChildren();
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
BusinessRules.CheckRules();
}
}
/// <summary>
/// Loads a <see cref="C02Level1"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_IDProperty, dr.GetInt32("Level_1_ID"));
LoadProperty(Level_1_NameProperty, dr.GetString("Level_1_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
private void FetchChildren()
{
LoadProperty(C03Level11SingleObjectProperty, C03Level11Child.GetC03Level11Child(Level_1_ID));
LoadProperty(C03Level11ASingleObjectProperty, C03Level11ReChild.GetC03Level11ReChild(Level_1_ID));
LoadProperty(C03Level11ObjectsProperty, C03Level11Coll.GetC03Level11Coll(Level_1_ID));
}
/// <summary>
/// Inserts a new <see cref="C02Level1"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddC02Level1", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", ReadProperty(Level_1_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Level_1_Name", ReadProperty(Level_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Level_1_IDProperty, (int) cmd.Parameters["@Level_1_ID"].Value);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="C02Level1"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateC02Level1", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", ReadProperty(Level_1_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_Name", ReadProperty(Level_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="C02Level1"/> object.
/// </summary>
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(Level_1_ID);
}
/// <summary>
/// Deletes the <see cref="C02Level1"/> object from database.
/// </summary>
/// <param name="level_1_ID">The delete criteria.</param>
[Transactional(TransactionalTypes.TransactionScope)]
protected void DataPortal_Delete(int level_1_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteC02Level1", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", level_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, level_1_ID);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(C03Level11SingleObjectProperty, DataPortal.CreateChild<C03Level11Child>());
LoadProperty(C03Level11ASingleObjectProperty, DataPortal.CreateChild<C03Level11ReChild>());
LoadProperty(C03Level11ObjectsProperty, DataPortal.CreateChild<C03Level11Coll>());
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Morph.Specialized
{
/// <summary>
/// Used for efficient memory buffering activities, with minimal memcopy operations
/// </summary>
public unsafe class SystemBuffer
{
private byte* m_pdata;
private int m_totalLength;
private int m_length;
private bool m_shouldFree = false;
private SystemBuffer next = null;
private SystemBuffer prev = null;
private ShortIndexer m_shortIndex;
private UShortIndexer m_ushortIndex;
private IntIndexer m_intIndex;
private UIntIndexer m_uintIndex;
/// <summary>
/// Represents Endianity type
/// </summary>
public enum EndianessEnum
{
BigEndian,
LittleEndian
}
/// <summary>
/// Repersents the Endianity of the buffer, default is BigEndian.
/// When array is joined to another, it accepts the endianity of the header.
/// </summary>
public EndianessEnum Endianess = EndianessEnum.BigEndian;
public int TotalLength
{
get { return m_totalLength; }
}
public int PartLength
{
get { return m_length; }
}
#region constructors
public SystemBuffer(int length, int size, EndianessEnum Endianness)
{
m_totalLength = m_length = length * size;
Endianess = Endianness;
m_pdata = (byte*) Imports.allocate((uint)m_length);
m_shouldFree = true;
internalInit();
}
public SystemBuffer(byte[] data, EndianessEnum Endianness)
{
m_totalLength = m_length = data.Length;
m_pdata = (byte*)Imports.allocate((uint)m_length);
unsafe
{
m_pdata = (byte*)Imports.convert(data);
}
internalInit();
}
internal SystemBuffer(byte* data, int length, EndianessEnum Endianness)
{
m_totalLength = m_length = length;
m_pdata = (byte*)Imports.allocate((uint)m_length);
unsafe
{
m_pdata = data;
}
internalInit();
}
private void internalInit()
{
m_shortIndex = new ShortIndexer(this);
m_ushortIndex = new UShortIndexer(this);
m_intIndex = new IntIndexer(this);
m_uintIndex = new UIntIndexer(this);
}
#endregion constructors
public void Join(SystemBuffer buffer)
{
this.next = buffer;
buffer.prev = this;
}
public void JoinHeader(SystemBuffer buffer)
{
this.prev = buffer;
buffer.next = this;
}
public int TotalByteLength { get {return m_totalLength; } }
public int SegmentByteLength { get {return m_length; } }
private byte* getByte(int index)
{
if (index < m_length)
{
return m_pdata;
}
if (next != null)
{
return next.getByte(index - m_length);
}
//next is null and we are off-bounds
throw new System.IndexOutOfRangeException();
}
/// <summary>
/// This function is the main function for placement of bytes, and is used such internally as well
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
[System.Runtime.CompilerServices.IndexerName("Bytes")]
public byte this[int index]
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
public void SetByte(int index, byte value)
{
throw new System.NotImplementedException();
}
public void GetByte(int index)
{
throw new System.NotImplementedException();
}
public void SetShort(int index, short value)
{
throw new System.NotImplementedException();
}
public short GetShort(int index)
{
throw new System.NotImplementedException();
}
public void SetUShort(int index, ushort value)
{
throw new System.NotImplementedException();
}
public ushort GetUShort(int index)
{
throw new System.NotImplementedException();
}
public void SetInt(int index, int value)
{
throw new System.NotImplementedException();
}
public int GetInt(int index)
{
throw new System.NotImplementedException();
}
public void SetUInt(int index, uint value)
{
throw new System.NotImplementedException();
}
public uint GetUInt(int index)
{
throw new System.NotImplementedException();
}
private void updateLength(int lengthOfFollowingBufs)
{
m_totalLength = m_length + lengthOfFollowingBufs;
if (prev != null)
{
prev.updateLength(m_totalLength);
}
}
public ShortIndexer Short
{
get
{
return m_shortIndex;
}
}
public UShortIndexer UShort
{
get
{
return m_ushortIndex;
}
}
public IntIndexer Int
{
get
{
return m_intIndex;
}
}
public UIntIndexer UInt
{
get
{
return m_uintIndex;
}
}
#region indexer-classes
public class ShortIndexer
{
private SystemBuffer m_buffer;
internal ShortIndexer(SystemBuffer buf)
{
m_buffer = buf;
}
public short this[int index]
{
get
{
return m_buffer.GetShort(index);
}
set
{
m_buffer.SetShort(index, value);
}
}
}
public class UShortIndexer
{
private SystemBuffer m_buffer;
internal UShortIndexer(SystemBuffer buf)
{
m_buffer = buf;
}
public ushort this[int index]
{
get
{
return m_buffer.GetUShort(index);
}
set
{
m_buffer.SetUShort(index, value);
}
}
}
public class IntIndexer
{
private SystemBuffer m_buffer;
internal IntIndexer(SystemBuffer buf)
{
m_buffer = buf;
}
public int this[int index]
{
get
{
return m_buffer.GetInt(index);
}
set
{
m_buffer.SetInt(index, value);
}
}
}
public class UIntIndexer
{
private SystemBuffer m_buffer;
internal UIntIndexer(SystemBuffer buf)
{
m_buffer = buf;
}
public uint this[int index]
{
get
{
return m_buffer.GetUInt(index);
}
set
{
m_buffer.SetUInt(index, value);
}
}
}
#endregion indexer-classes
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryLogicalTests
{
//TODO: Need tests on the short-circuit and non-short-circuit nature of the two forms.
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolAndTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolAnd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolAndAlsoTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolAndAlso(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolOrTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolOrElseTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolOrElse(array[i], array[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyBoolAnd(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.And(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a & b, f());
}
private static void VerifyBoolAndAlso(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.AndAlso(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a && b, f());
}
private static void VerifyBoolOr(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.Or(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a | b, f());
}
private static void VerifyBoolOrElse(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.OrElse(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a || b, f());
}
#endregion
[Fact]
public static void CannotReduceAndAlso()
{
Expression exp = Expression.AndAlso(Expression.Constant(true), Expression.Constant(false));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void CannotReduceOrElse()
{
Expression exp = Expression.OrElse(Expression.Constant(true), Expression.Constant(false));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void AndAlsoThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.AndAlso(null, Expression.Constant(true)));
}
[Fact]
public static void AndAlsoThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.AndAlso(Expression.Constant(true), null));
}
[Fact]
public static void OrElseThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.OrElse(null, Expression.Constant(true)));
}
[Fact]
public static void OrElseThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.OrElse(Expression.Constant(true), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void AndAlsoThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<bool>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.AndAlso(value, Expression.Constant(true)));
}
[Fact]
public static void AndAlsoThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<bool>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.AndAlso(Expression.Constant(true), value));
}
[Fact]
public static void OrElseThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<bool>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.OrElse(value, Expression.Constant(true)));
}
[Fact]
public static void OrElseThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<bool>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.OrElse(Expression.Constant(false), value));
}
}
}
| |
// MvxPictureChooserTask.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com
using System;
using System.IO;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Graphics.Imaging;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Core;
namespace MvvmCross.Plugins.PictureChooser.WindowsPhoneStore
{
public class MvxPictureChooserTask : IMvxPictureChooserTask
{
private int _maxPixelDimension;
private int _percentQuality;
private Action<Stream, string> _pictureAvailable;
private Action _assumeCancelled;
public void ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality, Action<Stream, string> pictureAvailable, Action assumeCancelled)
{
// This method requires that PickFileContinuation is implemented within the Windows Phone project and that
// the ContinueFileOpenPicker method on the View invokes (via the ViewModel) the ContinueFileOpenPicker method
// on this instance of the MvxPictureChooserTask
//
// http://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn614994.aspx
_maxPixelDimension = maxPixelDimension;
_percentQuality = percentQuality;
_pictureAvailable = pictureAvailable;
_assumeCancelled = assumeCancelled;
PickStorageFileFromDisk();
}
public void ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable, Action assumeCancelled)
{
this.ChoosePictureFromLibrary(maxPixelDimension, percentQuality, (stream, name) => pictureAvailable(stream), assumeCancelled);
}
public void ContinueFileOpenPicker(object args)
{
var continuationArgs = args as FileOpenPickerContinuationEventArgs;
if (continuationArgs != null && continuationArgs.Files.Count > 0)
{
var dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
dispatcher.RunAsync(CoreDispatcherPriority.Normal,
async () =>
{
var rawFileStream = await continuationArgs.Files[0].OpenAsync(FileAccessMode.Read);
var resizedStream =
await ResizeJpegStreamAsync(_maxPixelDimension, _percentQuality, rawFileStream);
_pictureAvailable?.Invoke(resizedStream.AsStreamForRead(), continuationArgs.Files[0].DisplayName);
});
}
else
{
_assumeCancelled?.Invoke();
}
}
public void TakePicture(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable, Action assumeCancelled)
{
var dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
dispatcher.RunAsync(CoreDispatcherPriority.Normal,
async () =>
{
await
Process(StorageFileFromCamera, maxPixelDimension, percentQuality, pictureAvailable,
assumeCancelled);
});
}
public Task<Stream> ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality)
{
var task = new TaskCompletionSource<Stream>();
ChoosePictureFromLibrary(maxPixelDimension, percentQuality, (stream, name) => task.SetResult(stream), () => task.SetResult(null));
return task.Task;
}
public Task<Stream> TakePicture(int maxPixelDimension, int percentQuality)
{
var task = new TaskCompletionSource<Stream>();
TakePicture(maxPixelDimension, percentQuality, task.SetResult, () => task.SetResult(null));
return task.Task;
}
private async Task Process(Func<Task<StorageFile>> storageFile, int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable, Action assumeCancelled)
{
var file = await storageFile();
if (file == null)
{
assumeCancelled();
return;
}
var rawFileStream = await file.OpenAsync(FileAccessMode.Read);
var resizedStream = await ResizeJpegStreamAsync(maxPixelDimension, percentQuality, rawFileStream);
pictureAvailable(resizedStream.AsStreamForRead());
}
private static async Task<StorageFile> StorageFileFromCamera()
{
var filename = $"{Guid.NewGuid().ToString()}.jpg";
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
filename, CreationCollisionOption.ReplaceExisting);
var encoding = ImageEncodingProperties.CreateJpeg();
var capture = new MediaCapture();
await capture.InitializeAsync();
await capture.CapturePhotoToStorageFileAsync(encoding, file);
return file;
}
private static void PickStorageFileFromDisk()
{
var filePicker = new FileOpenPicker();
filePicker.FileTypeFilter.Add(".jpg");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.ViewMode = PickerViewMode.Thumbnail;
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
//filePicker.SettingsIdentifier = "picker1";
//filePicker.CommitButtonText = "Open";
filePicker.PickSingleFileAndContinue();
}
private async Task<IRandomAccessStream> ResizeJpegStreamAsyncRubbish(int maxPixelDimension, int percentQuality, IRandomAccessStream input)
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(input);
// create a new stream and encoder for the new image
var ras = new InMemoryRandomAccessStream();
var enc = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder);
int targetHeight;
int targetWidth;
MvxPictureDimensionHelper.TargetWidthAndHeight(maxPixelDimension, (int)decoder.PixelWidth, (int)decoder.PixelHeight, out targetWidth, out targetHeight);
enc.BitmapTransform.ScaledHeight = (uint)targetHeight;
enc.BitmapTransform.ScaledWidth = (uint)targetWidth;
// write out to the stream
await enc.FlushAsync();
return ras;
}
private async Task<IRandomAccessStream> ResizeJpegStreamAsync(int maxPixelDimension, int percentQuality, IRandomAccessStream input)
{
var decoder = await BitmapDecoder.CreateAsync(input);
int targetHeight;
int targetWidth;
MvxPictureDimensionHelper.TargetWidthAndHeight(maxPixelDimension, (int)decoder.PixelWidth, (int)decoder.PixelHeight, out targetWidth, out targetHeight);
var transform = new BitmapTransform() { ScaledHeight = (uint)targetHeight, ScaledWidth = (uint)targetWidth };
var pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Straight,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);
var destinationStream = new InMemoryRandomAccessStream();
var bitmapPropertiesSet = new BitmapPropertySet();
bitmapPropertiesSet.Add("ImageQuality", new BitmapTypedValue(((double)percentQuality) / 100.0, PropertyType.Single));
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream, bitmapPropertiesSet);
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, (uint)targetWidth, (uint)targetHeight, decoder.DpiX, decoder.DpiY, pixelData.DetachPixelData());
await encoder.FlushAsync();
destinationStream.Seek(0L);
return destinationStream;
}
/*
#region IMvxCombinedPictureChooserTask Members
public void ChooseOrTakePicture(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable,
Action assumeCancelled)
{
// note - do not set PixelHeight = maxPixelDimension, PixelWidth = maxPixelDimension here - as that would create square cropping
var chooser = new PhotoChooserTask {ShowCamera = true};
ChoosePictureCommon(chooser, maxPixelDimension, percentQuality, pictureAvailable, assumeCancelled);
}
#endregion IMvxCombinedPictureChooserTask Members
#region IMvxPictureChooserTask Members
public void ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable,
Action assumeCancelled)
{
// note - do not set PixelHeight = maxPixelDimension, PixelWidth = maxPixelDimension here - as that would create square cropping
var chooser = new PhotoChooserTask {ShowCamera = false};
ChoosePictureCommon(chooser, maxPixelDimension, percentQuality, pictureAvailable, assumeCancelled);
}
public void TakePicture(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable,
Action assumeCancelled)
{
var chooser = new CameraCaptureTask {};
ChoosePictureCommon(chooser, maxPixelDimension, percentQuality, pictureAvailable, assumeCancelled);
}
#endregion IMvxPictureChooserTask Members
public void ChoosePictureCommon(ChooserBase<PhotoResult> chooser, int maxPixelDimension, int percentQuality,
Action<Stream> pictureAvailable, Action assumeCancelled)
{
var dialog = new CameraCaptureUI();
// Define the aspect ratio for the photo
var aspectRatio = new Size(16, 9);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
// Perform a photo capture and return the file object
var file = dialog.CaptureFileAsync(CameraCaptureUIMode.Photo).Await();
// Physically save the image to local storage
var bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream = file.OpenAsync(FileAccessMode.Read).Await())
{
bitmapImage.SetSource(fileStream);
}
chooser.Completed += (sender, args) =>
{
if (args.ChosenPhoto != null)
{
ResizeThenCallOnMainThread(maxPixelDimension,
percentQuality,
args.ChosenPhoto,
pictureAvailable);
}
else
assumeCancelled();
};
DoWithInvalidOperationProtection(chooser.Show);
}
private void ResizeThenCallOnMainThread(int maxPixelDimension, int percentQuality, Stream input,
Action<Stream> success)
{
ResizeJpegStream(maxPixelDimension, percentQuality, input, (stream) => CallAsync(stream, success));
}
private void ResizeJpegStream(int maxPixelDimension, int percentQuality, Stream input, Action<Stream> success)
{
var bitmap = new BitmapImage();
bitmap.SetSource(input);
var writeable = new WriteableBitmap(bitmap);
var ratio = 1.0;
if (writeable.PixelWidth > writeable.PixelHeight)
ratio = (maxPixelDimension)/((double) writeable.PixelWidth);
else
ratio = (maxPixelDimension)/((double) writeable.PixelHeight);
var targetWidth = (int) Math.Round(ratio*writeable.PixelWidth);
var targetHeight = (int) Math.Round(ratio*writeable.PixelHeight);
// not - important - we do *not* use using here - disposing of memoryStream is someone else's problem
var memoryStream = new MemoryStream();
writeable.SaveJpeg(memoryStream, targetWidth, targetHeight, 0, percentQuality);
memoryStream.Seek(0L, SeekOrigin.Begin);
success(memoryStream);
}
private void CallAsync(Stream input, Action<Stream> success)
{
Dispatcher.RequestMainThreadAction(() => success(input));
}
*/
}
}
| |
using System;
namespace QuickGraph.Concepts.Traversals
{
using QuickGraph.Concepts.Collections;
using QuickGraph.Concepts.Predicates;
/// <summary>
/// A small helper class for traversals
/// </summary>
public sealed class Traversal
{
private Traversal()
{}
/// <summary>
/// Returns the first vertex of the enumerable that matches the predicate.
/// </summary>
/// <param name="vertices">enumerable collection of <see cref="IVertex"/></param>
/// <param name="pred">vertex predicate</param>
/// <returns>first vertex if any, otherwise a null reference</returns>
public static IVertex FirstVertexIf(IVertexEnumerable vertices, IVertexPredicate pred)
{
if (vertices==null)
throw new ArgumentNullException("vertices");
if (pred==null)
throw new ArgumentNullException("pred");
IVertexEnumerator en = vertices.GetEnumerator();
while(en.MoveNext())
{
if (pred.Test(en.Current))
return en.Current;
}
return null;
}
/// <summary>
/// Returns the first vertex of the enumerable
/// </summary>
/// <param name="vertices">enumerable collection of <see cref="IVertex"/></param>
/// <returns>first vertex if any, otherwise a null reference</returns>
public static IVertex FirstVertex(IVertexEnumerable vertices)
{
if (vertices==null)
throw new ArgumentNullException("vertices");
IVertexEnumerator en = vertices.GetEnumerator();
if (!en.MoveNext())
return null;
else
return en.Current;
}
/// <summary>
/// Returns the first vertex of the graph
/// </summary>
/// <param name="g">graph</param>
/// <returns>first vertex if any, otherwise a null reference</returns>
public static IVertex FirstVertex(IVertexListGraph g)
{
return FirstVertex(g.Vertices);
}
/// <summary>
/// Returns the first vertex of the enumerable
/// </summary>
/// <param name="vertices">enumerable collection of <see cref="IVertex"/></param>
/// <returns>first vertex if any, otherwise a null reference</returns>
public static IVertex LastVertex(IVertexEnumerable vertices)
{
if (vertices==null)
throw new ArgumentNullException("vertices");
IVertexEnumerator en = vertices.GetEnumerator();
IVertex current = null;
while(en.MoveNext())
{
current = en.Current;
}
return current;
}
/// <summary>
/// Returns the last vertex of the graph
/// </summary>
/// <param name="g">graph</param>
/// <returns>last vertex if any, otherwise a null reference</returns>
public static IVertex LastVertex(IVertexListGraph g)
{
return LastVertex(g.Vertices);
}
/// <summary>
/// Returns the first edge of the graph
/// </summary>
/// <param name="edges">graph</param>
/// <returns>first edge if any, otherwise a null reference</returns>
public static IEdge FirstEdge(IEdgeEnumerable edges)
{
if (edges==null)
throw new ArgumentNullException("edges");
IEdgeEnumerator en = edges.GetEnumerator();
if (!en.MoveNext())
return null;
else
return en.Current;
}
/// <summary>
/// Returns the first edge of the graph
/// </summary>
/// <param name="g">graph</param>
/// <returns>first edge if any, otherwise a null reference</returns>
public static IEdge FirstEdge(IEdgeListGraph g)
{
if (g==null)
throw new ArgumentNullException("g");
return FirstEdge(g.Edges);
}
/// <summary>
/// Returns the last edge of the edge collection
/// </summary>
/// <param name="edges">edge collection</param>
/// <returns>last edge if any, otherwise a null reference</returns>
public static IEdge LastEdge(IEdgeEnumerable edges)
{
if (edges==null)
throw new ArgumentNullException("edges");
IEdgeEnumerator en = edges.GetEnumerator();
IEdge current = null;
while(en.MoveNext())
{
current = en.Current;
}
return current;
}
/// <summary>
/// Returns the last edge of the graph
/// </summary>
/// <param name="g">graph</param>
/// <returns>last edge if any, otherwise a null reference</returns>
public static IEdge LastEdge(IEdgeListGraph g)
{
if (g==null)
throw new ArgumentNullException("g");
return LastEdge(g.Edges);
}
/// <summary>
/// Returns the first vertex of the enumerable
/// </summary>
/// <param name="edges">enumerable collection of <see cref="IEdge"/></param>
/// <returns>first target vertex if any, otherwise a null reference</returns>
public static IVertex FirstTargetVertex(IEdgeEnumerable edges)
{
IEdge e = FirstEdge(edges);
if (e!=null)
return e.Target;
else
return null;
}
/// <summary>
/// Returns the first source vertex of the enumerable
/// </summary>
/// <param name="edges">enumerable collection of <see cref="IEdge"/></param>
/// <returns>first source vertex if any, otherwise a null reference</returns>
public static IVertex FirstSourceVertex(IEdgeEnumerable edges)
{
IEdge e = FirstEdge(edges);
if (e!=null)
return e.Source;
else
return null;
}
/// <summary>
/// Returns the last vertex of the enumerable
/// </summary>
/// <param name="edges">enumerable collection of <see cref="IEdge"/></param>
/// <returns>last target vertex if any, otherwise a null reference</returns>
public static IVertex LastTargetVertex(IEdgeEnumerable edges)
{
IEdge e = LastEdge(edges);
if (e!=null)
return e.Target;
else
return null;
}
/// <summary>
/// Returns the last source vertex of the enumerable
/// </summary>
/// <param name="edges">enumerable collection of <see cref="IEdge"/></param>
/// <returns>last source vertex if any, otherwise a null reference</returns>
public static IVertex LastSourceVertex(IEdgeEnumerable edges)
{
IEdge e = LastEdge(edges);
if (e!=null)
return e.Source;
else
return null;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal partial class Dashboard : UserControl, IDisposable
{
private readonly DashboardViewModel _model;
private readonly IWpfTextView _textView;
private readonly IAdornmentLayer _findAdornmentLayer;
private PresentationSource _presentationSource;
private DependencyObject _rootDependencyObject;
private IInputElement _rootInputElement;
private UIElement _focusedElement = null;
private readonly List<UIElement> _tabNavigableChildren;
internal bool ShouldReceiveKeyboardNavigation { get; set; }
private IEnumerable<string> _renameAccessKeys = new[]
{
RenameShortcutKey.RenameOverloads,
RenameShortcutKey.SearchInComments,
RenameShortcutKey.SearchInStrings,
RenameShortcutKey.Apply,
RenameShortcutKey.PreviewChanges
};
public Dashboard(
DashboardViewModel model,
IWpfTextView textView)
{
_model = model;
InitializeComponent();
_tabNavigableChildren = new UIElement[] { this.OverloadsCheckbox, this.CommentsCheckbox, this.StringsCheckbox, this.PreviewChangesCheckbox, this.ApplyButton, this.CloseButton }.ToList();
_textView = textView;
this.DataContext = model;
this.Visibility = textView.HasAggregateFocus ? Visibility.Visible : Visibility.Collapsed;
_textView.GotAggregateFocus += OnTextViewGotAggregateFocus;
_textView.LostAggregateFocus += OnTextViewLostAggregateFocus;
_textView.VisualElement.SizeChanged += OnElementSizeChanged;
this.SizeChanged += OnElementSizeChanged;
PresentationSource.AddSourceChangedHandler(this, OnPresentationSourceChanged);
try
{
_findAdornmentLayer = textView.GetAdornmentLayer("FindUIAdornmentLayer");
((UIElement)_findAdornmentLayer).LayoutUpdated += FindAdornmentCanvas_LayoutUpdated;
}
catch (ArgumentOutOfRangeException)
{
// Find UI doesn't exist in ETA.
}
this.Focus();
textView.Caret.IsHidden = false;
ShouldReceiveKeyboardNavigation = false;
}
private void ShowCaret()
{
// We actually want the caret visible even though the view isn't explicitly focused.
((UIElement)_textView.Caret).Visibility = Visibility.Visible;
}
private void FocusElement(UIElement firstElement, Func<int, int> selector)
{
if (_focusedElement == null)
{
_focusedElement = firstElement;
}
else
{
var current = _tabNavigableChildren.IndexOf(_focusedElement);
current = selector(current);
_focusedElement = _tabNavigableChildren[current];
}
_focusedElement.Focus();
ShowCaret();
}
internal void FocusNextElement()
{
FocusElement(_tabNavigableChildren.First(), i => i == _tabNavigableChildren.Count - 1 ? 0 : i + 1);
}
internal void FocusPreviousElement()
{
FocusElement(_tabNavigableChildren.Last(), i => i == 0 ? _tabNavigableChildren.Count - 1 : i - 1);
}
private void OnPresentationSourceChanged(object sender, SourceChangedEventArgs args)
{
if (args.NewSource == null)
{
this.DisconnectFromPresentationSource();
}
else
{
this.ConnectToPresentationSource(args.NewSource);
}
}
private void ConnectToPresentationSource(PresentationSource presentationSource)
{
if (presentationSource == null)
{
throw new ArgumentNullException(nameof(presentationSource));
}
_presentationSource = presentationSource;
if (Application.Current != null && Application.Current.MainWindow != null)
{
_rootDependencyObject = Application.Current.MainWindow as DependencyObject;
}
else
{
_rootDependencyObject = _presentationSource.RootVisual as DependencyObject;
}
_rootInputElement = _rootDependencyObject as IInputElement;
if (_rootDependencyObject != null && _rootInputElement != null)
{
foreach (string accessKey in _renameAccessKeys)
{
AccessKeyManager.Register(accessKey, _rootInputElement);
}
AccessKeyManager.AddAccessKeyPressedHandler(_rootDependencyObject, OnAccessKeyPressed);
}
}
private void OnAccessKeyPressed(object sender, AccessKeyPressedEventArgs args)
{
foreach (string accessKey in _renameAccessKeys)
{
if (string.Compare(accessKey, args.Key, StringComparison.OrdinalIgnoreCase) == 0)
{
args.Target = this;
args.Handled = true;
return;
}
}
}
protected override void OnAccessKey(AccessKeyEventArgs e)
{
if (e != null)
{
if (string.Equals(e.Key, RenameShortcutKey.RenameOverloads, StringComparison.OrdinalIgnoreCase))
{
this.OverloadsCheckbox.IsChecked = !this.OverloadsCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.SearchInComments, StringComparison.OrdinalIgnoreCase))
{
this.CommentsCheckbox.IsChecked = !this.CommentsCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.SearchInStrings, StringComparison.OrdinalIgnoreCase))
{
this.StringsCheckbox.IsChecked = !this.StringsCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.PreviewChanges, StringComparison.OrdinalIgnoreCase))
{
this.PreviewChangesCheckbox.IsChecked = !this.PreviewChangesCheckbox.IsChecked;
}
else if (string.Equals(e.Key, RenameShortcutKey.Apply, StringComparison.OrdinalIgnoreCase))
{
this.Commit();
}
}
}
private void DisconnectFromPresentationSource()
{
if (_rootInputElement != null)
{
foreach (string registeredKey in _renameAccessKeys)
{
AccessKeyManager.Unregister(registeredKey, _rootInputElement);
}
AccessKeyManager.RemoveAccessKeyPressedHandler(_rootDependencyObject, OnAccessKeyPressed);
}
_presentationSource = null;
_rootDependencyObject = null;
_rootInputElement = null;
}
private void FindAdornmentCanvas_LayoutUpdated(object sender, EventArgs e)
{
PositionDashboard();
}
public string RenameOverloads { get { return EditorFeaturesResources.Include_overload_s; } }
public Visibility RenameOverloadsVisibility { get { return _model.RenameOverloadsVisibility; } }
public bool IsRenameOverloadsEditable { get { return _model.IsRenameOverloadsEditable; } }
public string SearchInComments { get { return EditorFeaturesResources.Include_comments; } }
public string SearchInStrings { get { return EditorFeaturesResources.Include_strings; } }
public string ApplyRename { get { return EditorFeaturesResources.Apply1; } }
public string PreviewChanges { get { return EditorFeaturesResources.Preview_changes1; } }
public string RenameInstructions { get { return EditorFeaturesResources.Modify_any_highlighted_location_to_begin_renaming; } }
public string ApplyToolTip { get { return EditorFeaturesResources.Apply3 + " (Enter)"; } }
public string CancelToolTip { get { return EditorFeaturesResources.Cancel + " (Esc)"; } }
private void OnElementSizeChanged(object sender, SizeChangedEventArgs e)
{
if (e.WidthChanged)
{
PositionDashboard();
}
}
private void PositionDashboard()
{
var top = _textView.ViewportTop;
if (_findAdornmentLayer != null && _findAdornmentLayer.Elements.Count != 0)
{
var adornment = _findAdornmentLayer.Elements[0].Adornment;
top += adornment.RenderSize.Height;
}
Canvas.SetTop(this, top);
Canvas.SetLeft(this, _textView.ViewportLeft + _textView.VisualElement.RenderSize.Width - this.RenderSize.Width);
}
private void OnTextViewGotAggregateFocus(object sender, EventArgs e)
{
this.Visibility = Visibility.Visible;
PositionDashboard();
}
private void OnTextViewLostAggregateFocus(object sender, EventArgs e)
{
this.Visibility = Visibility.Collapsed;
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
_model.Session.Cancel();
_textView.VisualElement.Focus();
}
private void Apply_Click(object sender, RoutedEventArgs e)
{
Commit();
}
private void Commit()
{
_model.Session.Commit();
_textView.VisualElement.Focus();
}
public void Dispose()
{
_textView.GotAggregateFocus -= OnTextViewGotAggregateFocus;
_textView.LostAggregateFocus -= OnTextViewLostAggregateFocus;
_textView.VisualElement.SizeChanged -= OnElementSizeChanged;
this.SizeChanged -= OnElementSizeChanged;
if (_findAdornmentLayer != null)
{
((UIElement)_findAdornmentLayer).LayoutUpdated -= FindAdornmentCanvas_LayoutUpdated;
}
_model.Dispose();
PresentationSource.RemoveSourceChangedHandler(this, OnPresentationSourceChanged);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
ShouldReceiveKeyboardNavigation = false;
e.Handled = true;
}
protected override void OnGotFocus(RoutedEventArgs e)
{
ShouldReceiveKeyboardNavigation = true;
e.Handled = true;
}
protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
ShouldReceiveKeyboardNavigation = true;
e.Handled = true;
}
protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
ShouldReceiveKeyboardNavigation = false;
e.Handled = true;
}
protected override void OnMouseDown(MouseButtonEventArgs e)
{
// Don't send clicks into the text editor below.
e.Handled = true;
}
protected override void OnMouseUp(MouseButtonEventArgs e)
{
e.Handled = true;
}
protected override void OnIsKeyboardFocusWithinChanged(DependencyPropertyChangedEventArgs e)
{
base.OnIsKeyboardFocusWithinChanged(e);
ShouldReceiveKeyboardNavigation = (bool)e.NewValue;
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
public static class ReaderWriterLockSlimTests
{
[Fact]
public static void Ctor()
{
ReaderWriterLockSlim rwls;
using (rwls = new ReaderWriterLockSlim())
{
Assert.Equal(LockRecursionPolicy.NoRecursion, rwls.RecursionPolicy);
}
using (rwls = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion))
{
Assert.Equal(LockRecursionPolicy.NoRecursion, rwls.RecursionPolicy);
}
using (rwls = new ReaderWriterLockSlim((LockRecursionPolicy)12345))
{
Assert.Equal(LockRecursionPolicy.NoRecursion, rwls.RecursionPolicy);
}
using (rwls = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion))
{
Assert.Equal(LockRecursionPolicy.SupportsRecursion, rwls.RecursionPolicy);
}
}
[Fact]
public static void Dispose()
{
ReaderWriterLockSlim rwls;
rwls = new ReaderWriterLockSlim();
rwls.Dispose();
Assert.Throws<ObjectDisposedException>(() => rwls.TryEnterReadLock(0));
Assert.Throws<ObjectDisposedException>(() => rwls.TryEnterUpgradeableReadLock(0));
Assert.Throws<ObjectDisposedException>(() => rwls.TryEnterWriteLock(0));
rwls.Dispose();
for (int i = 0; i < 3; i++)
{
rwls = new ReaderWriterLockSlim();
switch (i)
{
case 0: rwls.EnterReadLock(); break;
case 1: rwls.EnterUpgradeableReadLock(); break;
case 2: rwls.EnterWriteLock(); break;
}
Assert.Throws<SynchronizationLockException>(() => rwls.Dispose());
}
}
[Fact]
public static void EnterExit()
{
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Assert.False(rwls.IsReadLockHeld);
rwls.EnterReadLock();
Assert.True(rwls.IsReadLockHeld);
rwls.ExitReadLock();
Assert.False(rwls.IsReadLockHeld);
Assert.False(rwls.IsUpgradeableReadLockHeld);
rwls.EnterUpgradeableReadLock();
Assert.True(rwls.IsUpgradeableReadLockHeld);
rwls.ExitUpgradeableReadLock();
Assert.False(rwls.IsUpgradeableReadLockHeld);
Assert.False(rwls.IsWriteLockHeld);
rwls.EnterWriteLock();
Assert.True(rwls.IsWriteLockHeld);
rwls.ExitWriteLock();
Assert.False(rwls.IsWriteLockHeld);
Assert.False(rwls.IsUpgradeableReadLockHeld);
rwls.EnterUpgradeableReadLock();
Assert.False(rwls.IsWriteLockHeld);
Assert.True(rwls.IsUpgradeableReadLockHeld);
rwls.EnterWriteLock();
Assert.True(rwls.IsWriteLockHeld);
rwls.ExitWriteLock();
Assert.False(rwls.IsWriteLockHeld);
Assert.True(rwls.IsUpgradeableReadLockHeld);
rwls.ExitUpgradeableReadLock();
Assert.False(rwls.IsUpgradeableReadLockHeld);
Assert.True(rwls.TryEnterReadLock(0));
rwls.ExitReadLock();
Assert.True(rwls.TryEnterReadLock(Timeout.InfiniteTimeSpan));
rwls.ExitReadLock();
Assert.True(rwls.TryEnterUpgradeableReadLock(0));
rwls.ExitUpgradeableReadLock();
Assert.True(rwls.TryEnterUpgradeableReadLock(Timeout.InfiniteTimeSpan));
rwls.ExitUpgradeableReadLock();
Assert.True(rwls.TryEnterWriteLock(0));
rwls.ExitWriteLock();
Assert.True(rwls.TryEnterWriteLock(Timeout.InfiniteTimeSpan));
rwls.ExitWriteLock();
}
}
[Fact]
public static void DeadlockAvoidance()
{
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
rwls.EnterReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterReadLock());
Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock());
Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock());
rwls.ExitReadLock();
rwls.EnterUpgradeableReadLock();
rwls.EnterReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterReadLock());
rwls.ExitReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock());
rwls.EnterWriteLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock());
rwls.ExitWriteLock();
rwls.ExitUpgradeableReadLock();
rwls.EnterWriteLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterReadLock());
Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock());
Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock());
rwls.ExitWriteLock();
}
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion))
{
rwls.EnterReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock());
rwls.EnterReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock());
rwls.ExitReadLock();
rwls.ExitReadLock();
rwls.EnterUpgradeableReadLock();
rwls.EnterReadLock();
rwls.EnterUpgradeableReadLock();
rwls.ExitUpgradeableReadLock();
rwls.EnterReadLock();
rwls.ExitReadLock();
rwls.ExitReadLock();
rwls.EnterWriteLock();
rwls.EnterWriteLock();
rwls.ExitWriteLock();
rwls.ExitWriteLock();
rwls.ExitUpgradeableReadLock();
rwls.EnterWriteLock();
rwls.EnterReadLock();
rwls.ExitReadLock();
rwls.EnterUpgradeableReadLock();
rwls.ExitUpgradeableReadLock();
rwls.EnterWriteLock();
rwls.ExitWriteLock();
rwls.ExitWriteLock();
}
}
[Theory]
[InlineData(LockRecursionPolicy.NoRecursion)]
[InlineData(LockRecursionPolicy.SupportsRecursion)]
public static void InvalidExits(LockRecursionPolicy policy)
{
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim(policy))
{
Assert.Throws<SynchronizationLockException>(() => rwls.ExitReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitUpgradeableReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock());
rwls.EnterReadLock();
Assert.Throws<SynchronizationLockException>(() => rwls.ExitUpgradeableReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock());
rwls.ExitReadLock();
rwls.EnterUpgradeableReadLock();
Assert.Throws<SynchronizationLockException>(() => rwls.ExitReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock());
rwls.ExitUpgradeableReadLock();
rwls.EnterWriteLock();
Assert.Throws<SynchronizationLockException>(() => rwls.ExitReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitUpgradeableReadLock());
rwls.ExitWriteLock();
using (Barrier barrier = new Barrier(2))
{
Task t = Task.Factory.StartNew(() =>
{
rwls.EnterWriteLock();
barrier.SignalAndWait();
barrier.SignalAndWait();
rwls.ExitWriteLock();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
barrier.SignalAndWait();
Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock());
barrier.SignalAndWait();
t.GetAwaiter().GetResult();
}
}
}
[Fact]
public static void InvalidTimeouts()
{
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterReadLock(-2));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterUpgradeableReadLock(-3));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterWriteLock(-4));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterReadLock(TimeSpan.MaxValue));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterUpgradeableReadLock(TimeSpan.MinValue));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterWriteLock(TimeSpan.FromMilliseconds(-2)));
}
}
[Fact]
public static void WritersAreMutuallyExclusiveFromReaders()
{
using (Barrier barrier = new Barrier(2))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Task.WaitAll(
Task.Run(() =>
{
rwls.EnterWriteLock();
barrier.SignalAndWait();
Assert.True(rwls.IsWriteLockHeld);
barrier.SignalAndWait();
rwls.ExitWriteLock();
}),
Task.Run(() =>
{
barrier.SignalAndWait();
Assert.False(rwls.TryEnterReadLock(0));
Assert.False(rwls.IsReadLockHeld);
barrier.SignalAndWait();
}));
}
}
[Fact]
public static void WritersAreMutuallyExclusiveFromWriters()
{
using (Barrier barrier = new Barrier(2))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Task.WaitAll(
Task.Run(() =>
{
rwls.EnterWriteLock();
barrier.SignalAndWait();
Assert.True(rwls.IsWriteLockHeld);
barrier.SignalAndWait();
rwls.ExitWriteLock();
}),
Task.Run(() =>
{
barrier.SignalAndWait();
Assert.False(rwls.TryEnterWriteLock(0));
Assert.False(rwls.IsReadLockHeld);
barrier.SignalAndWait();
}));
}
}
[Fact]
public static void ReadersMayBeConcurrent()
{
using (Barrier barrier = new Barrier(2))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Assert.Equal(0, rwls.CurrentReadCount);
Task.WaitAll(
Task.Run(() =>
{
rwls.EnterReadLock();
barrier.SignalAndWait(); // 1
Assert.True(rwls.IsReadLockHeld);
barrier.SignalAndWait(); // 2
Assert.Equal(2, rwls.CurrentReadCount);
barrier.SignalAndWait(); // 3
barrier.SignalAndWait(); // 4
rwls.ExitReadLock();
}),
Task.Run(() =>
{
barrier.SignalAndWait(); // 1
rwls.EnterReadLock();
barrier.SignalAndWait(); // 2
Assert.True(rwls.IsReadLockHeld);
Assert.Equal(0, rwls.WaitingReadCount);
barrier.SignalAndWait(); // 3
rwls.ExitReadLock();
barrier.SignalAndWait(); // 4
}));
Assert.Equal(0, rwls.CurrentReadCount);
}
}
[Fact]
public static void WriterToWriterChain()
{
using (AutoResetEvent are = new AutoResetEvent(false))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
rwls.EnterWriteLock();
Task t = Task.Factory.StartNew(() =>
{
Assert.False(rwls.TryEnterWriteLock(10));
Task.Run(() => are.Set()); // ideally this won't fire until we've called EnterWriteLock, but it's a benign race in that the test will succeed either way
rwls.EnterWriteLock();
rwls.ExitWriteLock();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
are.WaitOne();
rwls.ExitWriteLock();
t.GetAwaiter().GetResult();
}
}
[Fact]
public static void WriterToReaderChain()
{
using (AutoResetEvent are = new AutoResetEvent(false))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
rwls.EnterWriteLock();
Task t = Task.Factory.StartNew(() =>
{
Assert.False(rwls.TryEnterReadLock(TimeSpan.FromMilliseconds(10)));
Task.Run(() => are.Set()); // ideally this won't fire until we've called EnterReadLock, but it's a benign race in that the test will succeed either way
rwls.EnterReadLock();
rwls.ExitReadLock();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
are.WaitOne();
rwls.ExitWriteLock();
t.GetAwaiter().GetResult();
}
}
[Fact]
public static void WriterToUpgradeableReaderChain()
{
using (AutoResetEvent are = new AutoResetEvent(false))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
rwls.EnterWriteLock();
Task t = Task.Factory.StartNew(() =>
{
Assert.False(rwls.TryEnterUpgradeableReadLock(TimeSpan.FromMilliseconds(10)));
Task.Run(() => are.Set()); // ideally this won't fire until we've called EnterReadLock, but it's a benign race in that the test will succeed either way
rwls.EnterUpgradeableReadLock();
rwls.ExitUpgradeableReadLock();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
are.WaitOne();
rwls.ExitWriteLock();
t.GetAwaiter().GetResult();
}
}
[Fact]
public static void ReleaseReadersWhenWaitingWriterTimesOut()
{
using (var rwls = new ReaderWriterLockSlim())
{
// Enter the read lock
rwls.EnterReadLock();
// Typical order of execution: 0
Thread writeWaiterThread;
using (var beforeTryEnterWriteLock = new ManualResetEvent(false))
{
writeWaiterThread =
new Thread(() =>
{
// Typical order of execution: 1
// Add a writer to the wait list for enough time to allow successive readers to enter the wait list while this
// writer is waiting
beforeTryEnterWriteLock.Set();
if (rwls.TryEnterWriteLock(2000))
{
// The typical order of execution is not guaranteed, as sleep times are not guaranteed. For
// instance, before this write lock is added to the wait list, the two new read locks may be
// acquired. In that case, the test may complete before or while the write lock is taken.
rwls.ExitWriteLock();
}
// Typical order of execution: 4
});
writeWaiterThread.IsBackground = true;
writeWaiterThread.Start();
beforeTryEnterWriteLock.WaitOne();
}
Thread.Sleep(1000); // wait for TryEnterWriteLock to enter the wait list
// A writer should now be waiting, add readers to the wait list. Since a read lock is still acquired, the writer
// should time out waiting, then these readers should enter and exit the lock.
ThreadStart EnterAndExitReadLock = () =>
{
// Typical order of execution: 2, 3
rwls.EnterReadLock();
// Typical order of execution: 5, 6
rwls.ExitReadLock();
};
var readerThreads =
new Thread[]
{
new Thread(EnterAndExitReadLock),
new Thread(EnterAndExitReadLock)
};
foreach (var readerThread in readerThreads)
{
readerThread.IsBackground = true;
readerThread.Start();
}
foreach (var readerThread in readerThreads)
{
readerThread.Join();
}
rwls.ExitReadLock();
// Typical order of execution: 7
writeWaiterThread.Join();
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//#define DEBUG_CMD_PERF
namespace Microsoft.Zelig.Configuration.Environment
{
using System;
using System.Threading;
using System.Collections.Generic;
using Cfg = Microsoft.Zelig.Configuration.Environment;
public abstract class XScaleNorFlashJTagLoaderCategory : JtagLoaderCategory
{
class NorFlashLoader : Emulation.Hosting.JTagCustomer
{
const uint cmd_Signature = 0xDEADC000;
const uint cmd_Mask = 0xFFFFFF00;
const byte cmd_Hello = 0x01;
const byte cmd_EnterCFI = 0x02; // Arg: Address
const byte cmd_ExitCFI = 0x03; // Arg: Address
const byte cmd_ReadMemory8 = 0x04; // Arg: Address, Size => <Size> values
const byte cmd_ReadMemory16 = 0x05; // Arg: Address, Size => <Size> values
const byte cmd_ReadMemory32 = 0x06; // Arg: Address, Size => <Size> values
const byte cmd_ChecksumMemory = 0x07; // Arg: Address, Size => CRC value, AND of all memory
const byte cmd_EraseSector = 0x08; // Arg: Address => Status value
const byte cmd_ProgramMemory = 0x09; // Arg: Address, Size, [32bits words] => Status value
const byte cmd_EndOfStream = 0xFF;
const uint erasedMemoryPattern = 0xFFFFFFFFu;
const uint baseIRAM = 0x5C000000;
const uint blockSize = 64 * 1024;
const uint baseHostToDevice = baseIRAM + blockSize * 1;
const uint baseDeviceToHost = baseIRAM + blockSize * 2;
delegate void ProgressCallback( uint pos, uint total );
//--//
enum ScheduledWork
{
None ,
Program ,
EraseAndProgram,
}
class EraseSection
{
//
// State
//
internal uint m_baseAddress;
internal uint m_endAddress;
internal uint m_numEraseBlocks;
internal uint m_sizeEraseBlocks;
internal ScheduledWork[] m_scheduledWork;
}
class PendingImageSection
{
//
// State
//
internal readonly ImageSection m_imgSection;
internal readonly uint m_offset;
internal readonly uint m_len;
//
// Constructor Methods
//
internal PendingImageSection( ImageSection imgSection ,
uint offset ,
uint len )
{
m_imgSection = imgSection;
m_offset = offset;
m_len = len;
}
}
class ImageSection
{
//
// State
//
internal readonly uint m_address;
internal readonly byte[] m_data;
//
// Constructor Methods
//
internal ImageSection( Configuration.Environment.ImageSection section )
{
m_address = section.Address;
m_data = section.Payload;
}
//
// Helper Methods
//
internal PendingImageSection Intersects( uint eraseStart ,
uint eraseEnd )
{
uint addressStart = m_address;
uint addressEnd = m_address + (uint)m_data.Length;
if(addressStart < eraseStart)
{
if(addressEnd > eraseStart)
{
uint offset = eraseStart - addressStart;
uint len = Math.Min( eraseEnd, addressEnd ) - eraseStart;
return new PendingImageSection( this, offset, len );
}
}
else if(addressStart < eraseEnd)
{
uint offset = 0;
uint len = Math.Min( eraseEnd, addressEnd ) - addressStart;
return new PendingImageSection( this, offset, len );
}
return null;
}
}
class DelayedMemoryAccess
{
//
// State
//
const int maxSize = 1024;
Emulation.Hosting.JTagConnector m_jtag;
uint m_baseAddress;
uint m_currentAddress;
uint[] m_data;
uint m_posWriter;
uint m_posReader;
//
// Constructor Methods
//
internal DelayedMemoryAccess( Emulation.Hosting.JTagConnector jtag ,
uint baseAddress )
{
m_jtag = jtag;
m_baseAddress = baseAddress;
m_currentAddress = m_baseAddress;
}
//
// Helper Methods
//
internal void Reset()
{
m_currentAddress = m_baseAddress;
m_posReader = 0;
m_posWriter = 0;
}
internal void FillBuffer()
{
if(m_posReader == m_posWriter)
{
m_data = m_jtag.ReadMemoryBlock( m_currentAddress, maxSize );
m_currentAddress += maxSize * sizeof(uint);
m_posReader = 0;
m_posWriter = maxSize;
}
}
internal void FlushBuffer()
{
if(m_posWriter != 0)
{
m_jtag.WriteMemoryBlock( m_currentAddress, m_data, 0, (int)m_posWriter );
m_currentAddress += m_posWriter * sizeof(uint);
m_posWriter = 0;
}
}
internal void Write( uint value )
{
if(m_data == null)
{
m_data = new uint[maxSize];
}
if(m_posWriter >= maxSize)
{
FlushBuffer();
}
m_data[m_posWriter++] = value;
}
internal uint Read()
{
FillBuffer();
return m_data[m_posReader++];
}
}
//
// State
//
ProductCategory m_product;
Emulation.Hosting.AbstractHost m_owner;
Emulation.Hosting.JTagConnector m_jtag;
Emulation.Hosting.ProcessorControl m_processorControl;
Emulation.Hosting.ProcessorStatus m_processorStatus;
DelayedMemoryAccess m_writer;
DelayedMemoryAccess m_reader;
uint m_flashBaseAddress;
ulong m_flashSize;
EraseSection[] m_eraseSections;
//
// Constructor Methods
//
public NorFlashLoader()
{
}
//
// Helper Methods
//
public override void Deploy( Emulation.Hosting.AbstractHost owner ,
Cfg.ProductCategory product ,
List< Configuration.Environment.ImageSection > image ,
Emulation.Hosting.ProcessorControl.ProgressCallback callback )
{
m_owner = owner;
m_product = product;
owner.GetHostingService( out m_jtag );
owner.GetHostingService( out m_processorControl );
owner.GetHostingService( out m_processorStatus );
m_writer = new DelayedMemoryAccess( m_jtag, baseHostToDevice );
m_reader = new DelayedMemoryAccess( m_jtag, baseDeviceToHost );
try
{
bool fGot = false;
foreach(MemoryCategory mem in product.SearchValues< MemoryCategory >())
{
if((mem.Characteristics & Runtime.MemoryAttributes.FLASH) != 0)
{
m_flashBaseAddress = mem.BaseAddress;
m_flashSize = mem.SizeInBytes;
fGot = true;
break;
}
}
if(fGot == false)
{
throw TypeConsistencyErrorException.Create( "Product {0} does not have a valid FLASH memory", product.GetType() );
}
//--//
Start();
uint position = 0;
uint total = 0;
uint totalPending = 0;
List< ImageSection > lst = new List< ImageSection >();
List< PendingImageSection > lstPending = new List< PendingImageSection >();
//
// Collect work items.
//
foreach(var section in image)
{
if(section.NeedsRelocation == false)
{
var imgSection = new ImageSection( section );
lst.Add( imgSection );
total += (uint)section.Payload.Length;
}
}
//
// Verify if we need to perform any actions.
//
foreach(var imgSection in lst)
{
bool fMemoryErased;
if(VerifyChecksum( imgSection.m_address, imgSection.m_data, 0, imgSection.m_data.Length, out fMemoryErased ) == false)
{
//
// Found an item that needs attention. Map it to the various FLASH blocks.
//
foreach(var eraseSection in m_eraseSections)
{
for(uint pos = 0; pos < eraseSection.m_numEraseBlocks; pos++)
{
uint eraseStart = eraseSection.m_baseAddress + pos * eraseSection.m_sizeEraseBlocks;
uint eraseEnd = eraseStart + eraseSection.m_sizeEraseBlocks;
PendingImageSection pending = imgSection.Intersects( eraseStart, eraseEnd );
if(pending != null)
{
lstPending.Add( pending );
totalPending += pending.m_len;
//--//
if(eraseSection.m_scheduledWork[pos] != ScheduledWork.EraseAndProgram)
{
if(fMemoryErased == false)
{
callback( "Erasing {1}", 0.0f, (float)total );
EraseMemory( eraseStart, eraseEnd );
eraseSection.m_scheduledWork[pos] = ScheduledWork.EraseAndProgram;
}
else
{
eraseSection.m_scheduledWork[pos] = ScheduledWork.Program;
}
}
}
}
}
}
}
if(lstPending.Count > 0)
{
callback( "Programming {0}/{1} (total image {2})", 0, totalPending, total );
foreach(var pending in lstPending)
{
ProgramMemory( pending.m_imgSection.m_address, pending.m_imgSection.m_data, pending.m_offset, pending.m_len, delegate( uint positionSub, uint totalSub )
{
callback( "Programming {0}/{1} (total image {2})", position + positionSub, totalPending, total );
} );
position += pending.m_len;
callback( "Programming {0}/{1} (total image {2})", position, totalPending, total );
}
}
//--//
callback( "Preparing for execution..." );
Emulation.Hosting.ProcessorControl svcPC; owner.GetHostingService( out svcPC );
svcPC.ResetState( product );
}
finally
{
m_jtag.Cleanup();
}
}
//--//
private void SendData( uint data )
{
//// Console.WriteLine( "Data: 0x{0:X8}", data );
m_writer.Write( data );
}
private uint ReceiveData()
{
return m_reader.Read();
}
private void VerifyData( uint expected )
{
SendData( cmd_Signature | cmd_EndOfStream );
m_writer.FlushBuffer();
LetDeviceRun();
m_writer.Reset();
m_reader.Reset();
uint data = ReceiveData();
if(data != expected)
{
throw TypeConsistencyErrorException.Create( "Failed to synchronize with device, expecting {0:X8}, got {1:X8}", expected, data );
}
}
//--//
private void LoadLoaderImage()
{
JtagLoaderCategory jtagLoader = m_product.SearchValue< Cfg.JtagLoaderCategory >();
if(jtagLoader == null)
{
throw TypeConsistencyErrorException.Create( "Product {0} does not have a JTAG loader", m_product.GetType() );
}
foreach(uint address in jtagLoader.LoaderData.Keys)
{
m_jtag.WriteMemoryBlock( address, ToUint( jtagLoader.LoaderData[address] ) );
}
m_jtag.ProgramCounter = jtagLoader.EntryPoint;
}
private void ParseFlashSectors()
{
for(int tries = 0; tries < 3; tries++)
{
Execute_EnterCFI();
ushort[] cfg = Execute_ReadMemory16( m_flashBaseAddress, 128 );
if(cfg[0x10] == 'Q' &&
cfg[0x11] == 'R' &&
cfg[0x12] == 'Y' )
{
uint numEraseBlockRegions = cfg[0x2C];
uint baseAddress = m_flashBaseAddress;
m_eraseSections = new EraseSection[numEraseBlockRegions];
for(uint pos = 0; pos < numEraseBlockRegions; pos++)
{
EraseSection section = new EraseSection();
section.m_baseAddress = baseAddress;
section.m_numEraseBlocks = ((uint)cfg[0x2D + pos * 4] + ((uint)cfg[0x2E + pos * 4] << 8)) + 1u;
section.m_sizeEraseBlocks = ((uint)cfg[0x2F + pos * 4] + ((uint)cfg[0x30 + pos * 4] << 8)) * 256;
section.m_scheduledWork = new ScheduledWork[section.m_numEraseBlocks];
baseAddress += section.m_numEraseBlocks * section.m_sizeEraseBlocks;
section.m_endAddress = baseAddress;
m_eraseSections[pos] = section;
}
Execute_ExitCFI();
return;
}
Execute_ExitCFI();
}
throw TypeConsistencyErrorException.Create( "Cannot enter CFI mode" );
}
//--//
private void Execute_Hello()
{
SendData( cmd_Signature | cmd_Hello );
VerifyData( cmd_Signature | cmd_Hello );
}
private void Execute_EnterCFI()
{
SendData( cmd_Signature | cmd_EnterCFI );
SendData( m_flashBaseAddress );
VerifyData( cmd_Signature | cmd_EnterCFI );
}
private void Execute_ExitCFI()
{
SendData( cmd_Signature | cmd_ExitCFI );
SendData( m_flashBaseAddress );
VerifyData( cmd_Signature | cmd_ExitCFI );
}
private byte[] Execute_ReadMemory8( uint address ,
int size )
{
SendData( cmd_Signature | cmd_ReadMemory8 );
SendData( address );
SendData( (uint)size );
VerifyData( cmd_Signature | cmd_ReadMemory8 );
byte[] res = new byte[size];
for(int i = 0; i < size; i++)
{
res[i] = (byte)ReceiveData();
}
return res;
}
private ushort[] Execute_ReadMemory16( uint address ,
int size )
{
SendData( cmd_Signature | cmd_ReadMemory16 );
SendData( address );
SendData( (uint)size );
VerifyData( cmd_Signature | cmd_ReadMemory16 );
ushort[] res = new ushort[size];
for(int i = 0; i < size; i++)
{
res[i] = (ushort)ReceiveData();
}
return res;
}
private uint[] Execute_ReadMemory32( uint address ,
int size )
{
SendData( cmd_Signature | cmd_ReadMemory32 );
SendData( address );
SendData( (uint)size );
VerifyData( cmd_Signature | cmd_ReadMemory32 );
uint[] res = new uint[size];
for(int i = 0; i < size; i++)
{
res[i] = ReceiveData();
}
return res;
}
private void Execute_ChecksumMemory( uint address ,
int size ,
out uint checksum ,
out uint memoryAND )
{
SendData( cmd_Signature | cmd_ChecksumMemory );
SendData( address );
SendData( (uint)size );
VerifyData( cmd_Signature | cmd_ChecksumMemory );
checksum = ReceiveData();
memoryAND = ReceiveData();
}
private uint Execute_EraseSector( uint address )
{
SendData( cmd_Signature | cmd_EraseSector );
SendData( address );
VerifyData( cmd_Signature | cmd_EraseSector );
return ReceiveData();
}
private uint Execute_ProgramMemory( uint address ,
uint[] data ,
int size ,
int offset )
{
SendData( cmd_Signature | cmd_ProgramMemory );
SendData( address );
SendData( (uint)size );
while(size-- > 0)
{
SendData( data[offset++] );
}
VerifyData( cmd_Signature | cmd_ProgramMemory );
return ReceiveData();
}
//--//
private void Start()
{
if(m_jtag.IsTargetStopped() == false)
{
m_jtag.StopTarget();
}
LoadLoaderImage();
LetDeviceRun();
ParseFlashSectors();
}
private void LetDeviceRun()
{
#if DEBUG_CMD_PERF
System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();
st.Start();
#endif
if(m_jtag.RunDevice( 10000 ) == false)
{
throw new TimeoutException();
}
#if DEBUG_CMD_PERF
st.Stop();
//// if(m_processorStatus.ProgramCounter != 0x5C000638)
//// {
//// Console.WriteLine( "BAD PC: 0x{0:X8} {1}", m_processorStatus.ProgramCounter, fStop );
//// }
Console.WriteLine( "PC: 0x{0:X8} {1}", m_processorStatus.ProgramCounter, st.ElapsedMilliseconds );
#endif
//
// Skip breakpoint instruction.
//
m_processorStatus.ProgramCounter = m_processorStatus.ProgramCounter + sizeof(uint);
}
private bool VerifyChecksum( uint address ,
byte[] data ,
int offset ,
int size ,
out bool fMemoryErased )
{
uint[] buf = ToUint( data, offset, size );
int len = buf.Length;
if(VerifyChecksumInner( (uint)(address + offset), 0, len, buf, out fMemoryErased))
{
return true;
}
//// if(fMemoryErased == false)
//// {
//// for(uint chunk = 0; chunk < len; chunk += 8192)
//// {
//// int subLen = (int)(Math.Min( (int)(chunk + 8192), len ) - chunk);
////
//// uint[] buf2 = Execute_ReadMemory32( (uint)(address + offset + chunk), subLen );
////
//// for(int pos = 0; pos < subLen; pos++)
//// {
//// if(buf2[pos] != buf[chunk+pos])
//// {
//// Console.WriteLine( "Mismatch: 0x{0:X8}: 0x{1:X8} should be 0x{2:X8}", address + offset + (chunk + pos) * sizeof(uint), buf2[pos], buf[chunk+pos] );
//// }
//// }
//// }
//// }
return false;
}
private bool VerifyChecksumInner( uint address ,
uint offset ,
int len ,
uint[] data ,
out bool fMemoryErased )
{
uint checksum;
uint memoryAND;
Execute_ChecksumMemory( address + offset * sizeof(uint), len, out checksum, out memoryAND );
uint localChecksum = 0;
uint localMemoryAND = erasedMemoryPattern;
for(int pos = 0; pos < len; pos++)
{
uint val = data[offset+pos];
localChecksum = ((localChecksum & 1) << 31) | (localChecksum >> 1);
localChecksum += val;
localMemoryAND &= val;
}
fMemoryErased = (memoryAND == erasedMemoryPattern);
if(localChecksum == checksum)
{
return true;
}
if(fMemoryErased && localMemoryAND == erasedMemoryPattern)
{
return true;
}
return false;
}
private void EraseMemory( uint start ,
uint end )
{
while(true)
{
EraseSection section = FindSector( start );
if(section == null)
{
break;
}
uint address = section.m_baseAddress;
for(int j = 0; j < section.m_numEraseBlocks; j++)
{
uint endAddress = address + section.m_sizeEraseBlocks;
if(address <= start && start < endAddress)
{
Execute_EraseSector( address );
uint checksum;
uint memoryAND;
Execute_ChecksumMemory( address, (int)section.m_sizeEraseBlocks / sizeof(uint), out checksum, out memoryAND );
if(memoryAND != erasedMemoryPattern)
{
throw Emulation.Hosting.AbstractEngineException.Create( Emulation.Hosting.AbstractEngineException.Kind.Deployment, "Hardware problem: failed to erase sector at {0:X8}, size={1}", address, section.m_sizeEraseBlocks );
}
start = endAddress;
if(start >= end)
{
return;
}
}
address = endAddress;
}
}
}
private uint ProgramMemory( uint address ,
byte[] data ,
uint offset ,
uint len ,
ProgressCallback callback )
{
uint rem = offset % sizeof(uint);
if(rem != 0)
{
offset -= rem;
len += rem;
}
uint[] buf = ToUint( data, (int)offset, (int)len );
int lenInWords = buf.Length;
int posInWords = 0;
while(posInWords < lenInWords)
{
uint addressBlock = address + offset + (uint)posInWords * sizeof(uint);
EraseSection section = FindSector( addressBlock );
if(section == null)
{
break;
}
int countInWords = Math.Min( 32768 / sizeof(uint), lenInWords - posInWords );
uint res = Execute_ProgramMemory( addressBlock, buf, countInWords, posInWords );
if(res != 0)
{
return res;
}
posInWords += countInWords;
callback( (uint)(posInWords * sizeof(uint)), (uint)(lenInWords * sizeof(uint)) );
}
return 0;
}
//--//
private EraseSection FindSector( uint address )
{
for(int i = 0; i < m_eraseSections.Length; i++)
{
EraseSection section = m_eraseSections[i];
if(section.m_baseAddress <= address && address < section.m_endAddress)
{
return section;
}
}
return null;
}
}
//--//
protected XScaleNorFlashJTagLoaderCategory( string name ,
byte[] file )
{
using(System.IO.StreamReader reader = new System.IO.StreamReader( new System.IO.MemoryStream( file ) ))
{
List< Emulation.ArmProcessor.SRecordParser.Block > blocks = new List< Emulation.ArmProcessor.SRecordParser.Block >();
m_entryPoint = Emulation.ArmProcessor.SRecordParser.Parse( reader, name, blocks );
foreach(Emulation.ArmProcessor.SRecordParser.Block block in blocks)
{
m_loaderData[block.address] = block.data.ToArray();
}
}
}
protected override object GetServiceInner( Type t )
{
if(t == typeof(Emulation.Hosting.JTagCustomer))
{
return new NorFlashLoader();
}
return base.GetServiceInner( t );
}
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SchoolBusAPI.Models;
namespace SchoolBusAPI.Models
{
/// <summary>
/// Notifications associated about changes (mostly from CCW data) to information related to a specific school bus - e.g. change of owner at ICBC, change in NSC client rating, etc.
/// </summary>
[MetaDataExtension (Description = "Notifications associated about changes (mostly from CCW data) to information related to a specific school bus - e.g. change of owner at ICBC, change in NSC client rating, etc.")]
public partial class NotificationEvent : AuditableEntity, IEquatable<NotificationEvent>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public NotificationEvent()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="NotificationEvent" /> class.
/// </summary>
/// <param name="Id">A system-generated unique identifier for a NotificationEvent (required).</param>
/// <param name="EventTime">The date&#x2F;time of the creation of the event that triggered the creation of the notification..</param>
/// <param name="EventTypeCode">A categorization of the event for which the notification was created. The categories will be defined over time in code based on the requirements of the business. An example might be &quot;ICBCOwnerNameChange&quot; for when a change in the CCWData ICBC Owner Name field is changed..</param>
/// <param name="EventSubTypeCode">A further categorization of the event for which the notification was created..</param>
/// <param name="Notes">An assembled text string about the event that triggered the notification. Includes both static text and data about the notification. User Interface code will be used (based on the eventTypeCode - category) to assemble a dynamic string of information about the event - potentially including links to other relevant data - such as link to the School Bus detail screen..</param>
/// <param name="NotificationGenerated">TO BE REMOVED.</param>
/// <param name="SchoolBus">A foreign key reference to the system-generated unique identifier for a School Bus.</param>
public NotificationEvent(int Id, DateTime? EventTime = null, string EventTypeCode = null, string EventSubTypeCode = null, string Notes = null, bool? NotificationGenerated = null, SchoolBus SchoolBus = null)
{
this.Id = Id;
this.EventTime = EventTime;
this.EventTypeCode = EventTypeCode;
this.EventSubTypeCode = EventSubTypeCode;
this.Notes = Notes;
this.NotificationGenerated = NotificationGenerated;
this.SchoolBus = SchoolBus;
}
/// <summary>
/// A system-generated unique identifier for a NotificationEvent
/// </summary>
/// <value>A system-generated unique identifier for a NotificationEvent</value>
[MetaDataExtension (Description = "A system-generated unique identifier for a NotificationEvent")]
public int Id { get; set; }
/// <summary>
/// The date/time of the creation of the event that triggered the creation of the notification.
/// </summary>
/// <value>The date/time of the creation of the event that triggered the creation of the notification.</value>
[MetaDataExtension (Description = "The date/time of the creation of the event that triggered the creation of the notification.")]
public DateTime? EventTime { get; set; }
/// <summary>
/// A categorization of the event for which the notification was created. The categories will be defined over time in code based on the requirements of the business. An example might be "ICBCOwnerNameChange" for when a change in the CCWData ICBC Owner Name field is changed.
/// </summary>
/// <value>A categorization of the event for which the notification was created. The categories will be defined over time in code based on the requirements of the business. An example might be "ICBCOwnerNameChange" for when a change in the CCWData ICBC Owner Name field is changed.</value>
[MetaDataExtension (Description = "A categorization of the event for which the notification was created. The categories will be defined over time in code based on the requirements of the business. An example might be "ICBCOwnerNameChange" for when a change in the CCWData ICBC Owner Name field is changed.")]
[MaxLength(255)]
public string EventTypeCode { get; set; }
/// <summary>
/// A further categorization of the event for which the notification was created.
/// </summary>
/// <value>A further categorization of the event for which the notification was created.</value>
[MetaDataExtension (Description = "A further categorization of the event for which the notification was created.")]
[MaxLength(255)]
public string EventSubTypeCode { get; set; }
/// <summary>
/// An assembled text string about the event that triggered the notification. Includes both static text and data about the notification. User Interface code will be used (based on the eventTypeCode - category) to assemble a dynamic string of information about the event - potentially including links to other relevant data - such as link to the School Bus detail screen.
/// </summary>
/// <value>An assembled text string about the event that triggered the notification. Includes both static text and data about the notification. User Interface code will be used (based on the eventTypeCode - category) to assemble a dynamic string of information about the event - potentially including links to other relevant data - such as link to the School Bus detail screen.</value>
[MetaDataExtension (Description = "An assembled text string about the event that triggered the notification. Includes both static text and data about the notification. User Interface code will be used (based on the eventTypeCode - category) to assemble a dynamic string of information about the event - potentially including links to other relevant data - such as link to the School Bus detail screen.")]
[MaxLength(2048)]
public string Notes { get; set; }
/// <summary>
/// TO BE REMOVED
/// </summary>
/// <value>TO BE REMOVED</value>
[MetaDataExtension (Description = "TO BE REMOVED")]
public bool? NotificationGenerated { get; set; }
/// <summary>
/// A foreign key reference to the system-generated unique identifier for a School Bus
/// </summary>
/// <value>A foreign key reference to the system-generated unique identifier for a School Bus</value>
[MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a School Bus")]
public SchoolBus SchoolBus { get; set; }
/// <summary>
/// Foreign key for SchoolBus
/// </summary>
[ForeignKey("SchoolBus")]
[JsonIgnore]
[MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a School Bus")]
public int? SchoolBusId { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class NotificationEvent {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" EventTime: ").Append(EventTime).Append("\n");
sb.Append(" EventTypeCode: ").Append(EventTypeCode).Append("\n");
sb.Append(" EventSubTypeCode: ").Append(EventSubTypeCode).Append("\n");
sb.Append(" Notes: ").Append(Notes).Append("\n");
sb.Append(" NotificationGenerated: ").Append(NotificationGenerated).Append("\n");
sb.Append(" SchoolBus: ").Append(SchoolBus).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((NotificationEvent)obj);
}
/// <summary>
/// Returns true if NotificationEvent instances are equal
/// </summary>
/// <param name="other">Instance of NotificationEvent to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(NotificationEvent other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.EventTime == other.EventTime ||
this.EventTime != null &&
this.EventTime.Equals(other.EventTime)
) &&
(
this.EventTypeCode == other.EventTypeCode ||
this.EventTypeCode != null &&
this.EventTypeCode.Equals(other.EventTypeCode)
) &&
(
this.EventSubTypeCode == other.EventSubTypeCode ||
this.EventSubTypeCode != null &&
this.EventSubTypeCode.Equals(other.EventSubTypeCode)
) &&
(
this.Notes == other.Notes ||
this.Notes != null &&
this.Notes.Equals(other.Notes)
) &&
(
this.NotificationGenerated == other.NotificationGenerated ||
this.NotificationGenerated != null &&
this.NotificationGenerated.Equals(other.NotificationGenerated)
) &&
(
this.SchoolBus == other.SchoolBus ||
this.SchoolBus != null &&
this.SchoolBus.Equals(other.SchoolBus)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode(); if (this.EventTime != null)
{
hash = hash * 59 + this.EventTime.GetHashCode();
}
if (this.EventTypeCode != null)
{
hash = hash * 59 + this.EventTypeCode.GetHashCode();
}
if (this.EventSubTypeCode != null)
{
hash = hash * 59 + this.EventSubTypeCode.GetHashCode();
}
if (this.Notes != null)
{
hash = hash * 59 + this.Notes.GetHashCode();
}
if (this.NotificationGenerated != null)
{
hash = hash * 59 + this.NotificationGenerated.GetHashCode();
}
if (this.SchoolBus != null)
{
hash = hash * 59 + this.SchoolBus.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(NotificationEvent left, NotificationEvent right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(NotificationEvent left, NotificationEvent right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Collections;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonArrayContract : JsonContainerContract
{
/// <summary>
/// Gets the <see cref="Type"/> of the collection items.
/// </summary>
/// <value>The <see cref="Type"/> of the collection items.</value>
public Type CollectionItemType { get; private set; }
/// <summary>
/// Gets a value indicating whether the collection type is a multidimensional array.
/// </summary>
/// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value>
public bool IsMultidimensionalArray { get; private set; }
private readonly bool _isCollectionItemTypeNullableType;
private readonly Type _genericCollectionDefinitionType;
private Type _genericWrapperType;
private MethodCall<object, object> _genericWrapperCreator;
private Func<object> _genericTemporaryCollectionCreator;
internal bool IsArray { get; private set; }
internal bool ShouldCreateWrapper { get; private set; }
internal bool CanDeserialize { get; private set; }
internal MethodBase ParametrizedConstructor { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonArrayContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Array;
IsArray = CreatedType.IsArray;
bool canDeserialize;
Type tempCollectionType;
if (IsArray)
{
CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType);
IsReadOnlyOrFixedSize = true;
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
canDeserialize = true;
IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1);
}
else if (typeof(IList).IsAssignableFrom(underlyingType))
{
if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
else
CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType);
if (underlyingType == typeof(IList))
CreatedType = typeof(List<object>);
if (CollectionItemType != null)
ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(underlyingType, CollectionItemType);
IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>));
canDeserialize = true;
}
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
{
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>)))
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
#if !(NET20 || NET35 || PORTABLE40)
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>)))
CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType);
#endif
ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(underlyingType, CollectionItemType);
canDeserialize = true;
ShouldCreateWrapper = true;
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType))
{
CollectionItemType = underlyingType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>)))
CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType);
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(CreatedType, CollectionItemType);
IsReadOnlyOrFixedSize = true;
canDeserialize = (ParametrizedConstructor != null);
}
#endif
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType))
{
CollectionItemType = tempCollectionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>)))
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
ParametrizedConstructor = CollectionUtils.ResolveEnumableCollectionConstructor(underlyingType, CollectionItemType);
#if !(NET35 || NET20 || NETFX_CORE)
if (ParametrizedConstructor == null && underlyingType.Name == FSharpUtils.FSharpListTypeName)
{
FSharpUtils.EnsureInitialized(underlyingType.Assembly());
ParametrizedConstructor = FSharpUtils.CreateSeq(CollectionItemType);
}
#endif
if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
_genericCollectionDefinitionType = tempCollectionType;
IsReadOnlyOrFixedSize = false;
ShouldCreateWrapper = false;
canDeserialize = true;
}
else
{
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
IsReadOnlyOrFixedSize = true;
ShouldCreateWrapper = true;
canDeserialize = (ParametrizedConstructor != null);
}
}
else
{
// types that implement IEnumerable and nothing else
canDeserialize = false;
ShouldCreateWrapper = true;
}
CanDeserialize = canDeserialize;
if (CollectionItemType != null)
_isCollectionItemTypeNullableType = ReflectionUtils.IsNullableType(CollectionItemType);
#if (NET20 || NET35)
// bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object)
// wrapper will handle calling Add(T) instead
if (_isCollectionItemTypeNullableType
&& (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType)
|| (IsArray && !IsMultidimensionalArray)))
{
ShouldCreateWrapper = true;
}
#endif
#if !(NET20 || NET35 || NET40 || PORTABLE40)
Type immutableCreatedType;
MethodBase immutableParameterizedCreator;
if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator))
{
CreatedType = immutableCreatedType;
ParametrizedConstructor = immutableParameterizedCreator;
IsReadOnlyOrFixedSize = true;
CanDeserialize = true;
}
#endif
}
internal IWrappedCollection CreateWrapper(object list)
{
if (_genericWrapperCreator == null)
{
_genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType);
Type constructorArgument;
if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>))
|| _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType);
else
constructorArgument = _genericCollectionDefinitionType;
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(genericWrapperConstructor);
}
return (IWrappedCollection)_genericWrapperCreator(null, list);
}
internal IList CreateTemporaryCollection()
{
if (_genericTemporaryCollectionCreator == null)
{
// multidimensional array will also have array instances in it
Type collectionItemType = (IsMultidimensionalArray) ? typeof(object) : CollectionItemType;
Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType);
_genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType);
}
return (IList)_genericTemporaryCollectionCreator();
}
}
}
| |
//---------------------------------------------------------------------------
//
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Limited Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/limitedpermissivelicense.mspx
// All other rights reserved.
//
// This file is part of the 3D Tools for Windows Presentation Foundation
// project. For more information, see:
//
// http://CodePlex.com/Wiki/View.aspx?ProjectName=3DTools
//
//---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Composition;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Documents;
using System.Collections;
namespace _3DTools
{
/// <summary>
/// Helper class that encapsulates return data needed for the
/// hit test capture methods.
/// </summary>
public class HitTestEdge
{
/// <summary>
/// Constructs a new hit test edge
/// </summary>
/// <param name="p1">First edge point</param>
/// <param name="p2">Second edge point</param>
/// <param name="uv1">Texture coordinate of first edge point</param>
/// <param name="uv2">Texture coordinate of second edge point</param>
public HitTestEdge(Point3D p1,
Point3D p2,
Point uv1,
Point uv2)
{
_p1 = p1;
_p2 = p2;
_uv1 = uv1;
_uv2 = uv2;
}
/// <summary>
/// Projects the stored 3D points in to 2D.
/// </summary>
/// <param name="objectToViewportTransform">The transformation matrix to use</param>
public void Project(Matrix3D objectToViewportTransform)
{
Point3D projPoint1 = objectToViewportTransform.Transform(_p1);
Point3D projPoint2 = objectToViewportTransform.Transform(_p2);
_p1Transformed = new Point(projPoint1.X, projPoint1.Y);
_p2Transformed = new Point(projPoint2.X, projPoint2.Y);
}
public Point3D _p1, _p2;
public Point _uv1, _uv2;
// the transformed Point3D value
public Point _p1Transformed, _p2Transformed;
}
/// <summary>
/// The InteractiveModelVisual3D class represents a model visual 3D that can
/// be interacted with. The class adds some properties that make it easy
/// to construct an interactive 3D object (geometry and visual), and also makes
/// it so those Visual3Ds that want to be interactive can explicitly state this
/// via their type.
/// </summary>
public class InteractiveVisual3D : ModelVisual3D
{
/// <summary>
/// Constructs a new InteractiveModelVisual3D
/// </summary>
public InteractiveVisual3D()
{
InternalVisualBrush = CreateVisualBrush();
// create holders for the intersection plane and content
_content = new GeometryModel3D();
Content = _content;
GenerateMaterial();
}
static InteractiveVisual3D()
{
_defaultMaterialPropertyValue = new DiffuseMaterial();
_defaultMaterialPropertyValue.SetValue(InteractiveVisual3D.IsInteractiveMaterialProperty, true);
_defaultMaterialPropertyValue.Freeze();
MaterialProperty = DependencyProperty.Register("Material",
typeof(Material),
typeof(InteractiveVisual3D),
new PropertyMetadata(_defaultMaterialPropertyValue,
new PropertyChangedCallback(OnMaterialPropertyChanged)));
}
/// <summary>
/// When a property of the IMV3D changes we play it safe and invalidate the saved
/// corner cache.
/// </summary>
/// <param name="e"></param>
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
// invalidate the cache
_lastVisCorners = null;
}
/// <summary>
/// Gets the visual edges that correspond to the passed in texture coordinates of interest.
/// </summary>
/// <param name="texCoordsOfInterest">The texture coordinates whose edges should be found</param>
/// <returns>The visual edges corresponding to the given texture coordinates</returns>
internal List<HitTestEdge> GetVisualEdges(Point[] texCoordsOfInterest)
{
// get and then cache the edges
_lastEdges = GrabValidEdges(texCoordsOfInterest);
_lastVisCorners = texCoordsOfInterest;
return _lastEdges;
}
/// <summary>
/// Function takes the passed in list of texture coordinate points, and then finds the
/// visible outline of the rectangle specified by those points and returns it.
/// </summary>
/// <param name="tc">The points specifying the rectangle to search for</param>
/// <returns>The edges of that rectangle</returns>
private List<HitTestEdge> GrabValidEdges(Point[] tc)
{
// our final edge list
List<HitTestEdge> hitTestEdgeList = new List<HitTestEdge>();
Dictionary<Edge, EdgeInfo> adjInformation = new Dictionary<Edge, EdgeInfo>();
// store some important info in local variables for easier access
MeshGeometry3D contentGeom = ((MeshGeometry3D)_content.Geometry);
Point3DCollection positions = contentGeom.Positions;
PointCollection textureCoords = contentGeom.TextureCoordinates;
Int32Collection triIndices = contentGeom.TriangleIndices;
Transform3D contentTransform = _content.Transform;
// we want to map from the camera space to this visual3D's space
Viewport3DVisual containingVisual;
bool success;
// this call actually gets the object to camera transform, but we will invert it later, and because of that
// the local variable is named cameraToObjecTransform.
Matrix3D cameraToObjectTransform = MathUtils.TryTransformToCameraSpace(this, out containingVisual, out success);
if (!success) return new List<HitTestEdge>();
// take in to account any transform on model
if (contentTransform != null)
{
cameraToObjectTransform.Prepend(contentTransform.Value);
}
// also get the object to screen space transform for use later
Matrix3D objectToViewportTransform = MathUtils.TryTransformTo2DAncestor(this, out containingVisual, out success);
if (!success) return new List<HitTestEdge>();
if (contentTransform != null)
{
objectToViewportTransform.Prepend(contentTransform.Value);
}
// check the cached copy to avoid extra work
bool sameAsBefore = _lastVisCorners != null;
if (_lastVisCorners != null)
{
for (int i = 0; i < tc.Length; i++)
{
if (tc[i] != _lastVisCorners[i])
{
sameAsBefore = false;
break;
}
}
if (_lastMatrix3D != objectToViewportTransform)
{
sameAsBefore = false;
}
}
if (sameAsBefore) return _lastEdges;
// save the matrix that was just used
_lastMatrix3D = objectToViewportTransform;
// try to invert so we actually have the camera->object transform
try
{
cameraToObjectTransform.Invert();
}
catch (InvalidOperationException)
{
return new List<HitTestEdge>();
}
Point3D camPosObjSpace = cameraToObjectTransform.Transform(new Point3D(0, 0, 0));
// get the bounding box around the passed in texture coordinates to help
// with early rejection tests
Rect bbox = Rect.Empty;
for (int i = 0; i < tc.Length; i++)
{
bbox.Union(tc[i]);
}
// walk through the triangles - and look for the triangles we care about
int[] indices = new int[3];
Point3D[] p = new Point3D[3];
Point[] uv = new Point[3];
for (int i = 0; i < triIndices.Count; i += 3)
{
// get the triangle indices
Rect triBBox = Rect.Empty;
for (int j = 0; j < 3; j++)
{
indices[j] = triIndices[i + j];
p[j] = positions[indices[j]];
uv[j] = textureCoords[indices[j]];
triBBox.Union(uv[j]);
}
if (bbox.IntersectsWith(triBBox))
{
ProcessTriangle(p, uv, tc, hitTestEdgeList, adjInformation, camPosObjSpace);
}
}
// also handle the case of an edge that doesn't also have a backface - i.e a single plane
foreach (Edge edge in adjInformation.Keys)
{
EdgeInfo ei = adjInformation[edge];
if (ei.hasFrontFace && ei.numSharing == 1)
{
HandleSilhouetteEdge(ei.uv1, ei.uv2,
edge._start, edge._end,
tc,
hitTestEdgeList);
}
}
// project all the edges to get at the 2D point of interest
for (int i = 0; i < hitTestEdgeList.Count; i++)
{
hitTestEdgeList[i].Project(objectToViewportTransform);
}
return hitTestEdgeList;
}
/// <summary>
/// Processes the passed in triangle by checking to see if it is facing the camera and if
/// so searches to see if the texture coordinate edges intersect it. It also looks
/// to see if there are any silhouette edges and processes these as well.
/// </summary>
/// <param name="p">The triangle's vertices</param>
/// <param name="uv">The texture coordinates for those vertices</param>
/// <param name="tc">The texture coordinate edges to intersect with</param>
/// <param name="edgeList">The edge list that results should be placed on</param>
/// <param name="adjInformation">The adjacency information for the mesh</param>
private void ProcessTriangle(Point3D[] p,
Point[] uv,
Point[] tc,
List<HitTestEdge> edgeList,
Dictionary<Edge, EdgeInfo> adjInformation,
Point3D camPosObjSpace)
{
// calculate the normal of the mesh and the vector from a point on the mesh to the camera
// for back face removal calculations.
Vector3D normal = Vector3D.CrossProduct(p[1] - p[0], p[2] - p[0]);
Vector3D dirToCamera = camPosObjSpace - p[0];
// ignore any triangles that have a normal of (0,0,0)
if (!(normal.X == 0 && normal.Y == 0 && normal.Z == 0))
{
double dotProd = Vector3D.DotProduct(normal, dirToCamera);
// if the dot product is > 0 then the triangle is visible, otherwise invisible
if (dotProd > 0.0)
{
// loop over the triangle and update any edge information
ProcessTriangleEdges(p, uv, tc, PolygonSide.FRONT, edgeList, adjInformation);
// intersect the bounds of the visual with the triangle
ProcessVisualBoundsIntersections(p, uv, tc, edgeList);
}
else
{
ProcessTriangleEdges(p, uv, tc, PolygonSide.BACK, edgeList, adjInformation);
}
}
}
/// <summary>
/// Function intersects the edges specified by tc with the texture coordinates
/// on the passed in triangle. If there are any intersections, the edges
/// of these intersections are added to the edgelist
/// </summary>
/// <param name="p">The vertices of the triangle</param>
/// <param name="uv">The texture coordinates for that triangle</param>
/// <param name="tc">The texture coordinate edges to be intersected against</param>
/// <param name="edgeList">The list of edges any intersecte edges should be added to</param>
private void ProcessVisualBoundsIntersections(Point3D[] p,
Point[] uv,
Point[] tc,
List<HitTestEdge> edgeList)
{
List<Point3D> pointList = new List<Point3D>();
List<Point> uvList = new List<Point>();
// loop over the visual's texture coordinate bounds
for (int i = 0; i < tc.Length; i++)
{
Point visEdgeStart = tc[i];
Point visEdgeEnd = tc[(i + 1) % tc.Length];
// clear out anything that used to be there
pointList.Clear();
uvList.Clear();
// loop over triangle edges
bool skipListProcessing = false;
for (int j = 0; j < uv.Length; j++)
{
Point uv1 = uv[j];
Point uv2 = uv[(j + 1) % uv.Length];
Point3D p3D1 = p[j];
Point3D p3D2 = p[(j + 1) % p.Length];
// initial rejection processing
if (!((Math.Max(visEdgeStart.X, visEdgeEnd.X) < Math.Min(uv1.X, uv2.X)) ||
(Math.Min(visEdgeStart.X, visEdgeEnd.X) > Math.Max(uv1.X, uv2.X)) ||
(Math.Max(visEdgeStart.Y, visEdgeEnd.Y) < Math.Min(uv1.Y, uv2.Y)) ||
(Math.Min(visEdgeStart.Y, visEdgeEnd.Y) > Math.Max(uv1.Y, uv2.Y))))
{
// intersect the two lines
bool areCoincident = false;
Vector dir = uv2 - uv1;
double t = IntersectRayLine(uv1, dir, visEdgeStart, visEdgeEnd, out areCoincident);
// if they are coincident then we have two intersections and don't need to
// do anymore processing
if (areCoincident)
{
HandleCoincidentLines(visEdgeStart, visEdgeEnd,
p3D1, p3D2,
uv1, uv2, edgeList);
skipListProcessing = true;
break;
}
else if (t >= 0 && t <= 1)
{
Point intersUV = uv1 + dir * t;
Point3D intersPoint3D = p3D1 + (p3D2 - p3D1) * t;
double visEdgeDiff = (visEdgeStart - visEdgeEnd).Length;
if ((intersUV - visEdgeStart).Length < visEdgeDiff &&
(intersUV - visEdgeEnd).Length < visEdgeDiff)
{
pointList.Add(intersPoint3D);
uvList.Add(intersUV);
}
}
}
}
if (!skipListProcessing)
{
if (pointList.Count >= 2)
{
edgeList.Add(new HitTestEdge(pointList[0], pointList[1],
uvList[0], uvList[1]));
}
else if (pointList.Count == 1)
{
Point3D outputPoint;
// To avoid an edge cases caused by generating a point extremely
// close to one of the bound points, we test if both points are inside
// the bounds to be on the safe side - in the worst case we do
// extra work or generate a small edge
if (IsPointInTriangle(visEdgeStart, uv, p, out outputPoint))
{
edgeList.Add(new HitTestEdge(pointList[0], outputPoint,
uvList[0], visEdgeStart));
}
if (IsPointInTriangle(visEdgeEnd, uv, p, out outputPoint))
{
edgeList.Add(new HitTestEdge(pointList[0], outputPoint,
uvList[0], visEdgeEnd));
}
}
else
{
Point3D outputPoint1, outputPoint2;
if (IsPointInTriangle(visEdgeStart, uv, p, out outputPoint1) &&
IsPointInTriangle(visEdgeEnd, uv, p, out outputPoint2))
{
edgeList.Add(new HitTestEdge(outputPoint1, outputPoint2,
visEdgeStart, visEdgeEnd));
}
}
}
}
}
/// <summary>
/// Function tests to see if the given texture coordinate point p is contained within the
/// given triangle. If it is it returns the 3D point corresponding to that intersection.
/// </summary>
/// <param name="p">The point to test</param>
/// <param name="triUVVertices">The texture coordinates of the triangle</param>
/// <param name="tri3DVertices">The 3D coordinates of the triangle</param>
/// <param name="inters3DPoint">The 3D point of intersection</param>
/// <returns>True if the point is in the triangle, false otherwise</returns>
private bool IsPointInTriangle(Point p, Point[] triUVVertices, Point3D[] tri3DVertices, out Point3D inters3DPoint)
{
double denom = 0.0;
inters3DPoint = new Point3D();
double A = triUVVertices[0].X - triUVVertices[2].X;
double B = triUVVertices[1].X - triUVVertices[2].X;
double C = triUVVertices[2].X - p.X;
double D = triUVVertices[0].Y - triUVVertices[2].Y;
double E = triUVVertices[1].Y - triUVVertices[2].Y;
double F = triUVVertices[2].Y - p.Y;
denom = (A * E - B * D);
if (denom == 0) return false;
double lambda1 = (B * F - C * E) / denom;
denom = (B * D - A * E);
if (denom == 0) return false;
double lambda2 = (A * F - C * D) / denom;
if (lambda1 < 0 || lambda1 > 1 || lambda2 < 0 || lambda2 > 1 || (lambda1 + lambda2) > 1) return false;
inters3DPoint = (Point3D)(lambda1 * (Vector3D)tri3DVertices[0] +
lambda2 * (Vector3D)tri3DVertices[1] +
(1.0f - lambda1 - lambda2) * (Vector3D)tri3DVertices[2]);
return true;
}
/// <summary>
/// Handles adding an edge when the two line segments are coincident.
/// </summary>
/// <param name="visUV1">The texture coordinates of the boundary edge</param>
/// <param name="visUV2">The texture coordinates of the boundary edge</param>
/// <param name="tri3D1">The 3D coordinate of the triangle edge</param>
/// <param name="tri3D2">The 3D coordinates of the triangle edge</param>
/// <param name="triUV1">The texture coordinates of the triangle edge</param>
/// <param name="triUV2">The texture coordinates of the triangle edge</param>
/// <param name="edgeList">The edge list to add to</param>
private void HandleCoincidentLines(Point visUV1, Point visUV2,
Point3D tri3D1, Point3D tri3D2,
Point triUV1, Point triUV2,
List<HitTestEdge> edgeList)
{
Point minVisUV, maxVisUV;
Point minTriUV, maxTriUV;
Point3D minTri3D, maxTri3D;
// to be used in final edge creation
Point uv1, uv2;
Point3D p1, p2;
// order the points and give refs to them for ease of use
if (Math.Abs(visUV1.X - visUV2.X) > Math.Abs(visUV1.Y - visUV2.Y))
{
if (visUV1.X <= visUV2.X)
{
minVisUV = visUV1;
maxVisUV = visUV2;
}
else
{
minVisUV = visUV2;
maxVisUV = visUV1;
}
if (triUV1.X <= triUV2.X)
{
minTriUV = triUV1;
minTri3D = tri3D1;
maxTriUV = triUV2;
maxTri3D = tri3D2;
}
else
{
minTriUV = triUV2;
minTri3D = tri3D2;
maxTriUV = triUV1;
maxTri3D = tri3D1;
}
// now actually create the edge
// compute the minimum value
if (minVisUV.X < minTriUV.X)
{
uv1 = minTriUV;
p1 = minTri3D;
}
else
{
uv1 = minVisUV;
p1 = minTri3D + (minVisUV.X - minTriUV.X) / (maxTriUV.X - minTriUV.X) * (maxTri3D - minTri3D);
}
// compute the maximum value
if (maxVisUV.X > maxTriUV.X)
{
uv2 = maxTriUV;
p2 = maxTri3D;
}
else
{
uv2 = maxVisUV;
p2 = minTri3D + (maxVisUV.X - minTriUV.X) / (maxTriUV.X - minTriUV.X) * (maxTri3D - minTri3D);
}
}
else
{
if (visUV1.Y <= visUV2.Y)
{
minVisUV = visUV1;
maxVisUV = visUV2;
}
else
{
minVisUV = visUV2;
maxVisUV = visUV1;
}
if (triUV1.Y <= triUV2.Y)
{
minTriUV = triUV1;
minTri3D = tri3D1;
maxTriUV = triUV2;
maxTri3D = tri3D2;
}
else
{
minTriUV = triUV2;
minTri3D = tri3D2;
maxTriUV = triUV1;
maxTri3D = tri3D1;
}
// now actually create the edge
// compute the minimum value
if (minVisUV.Y < minTriUV.Y)
{
uv1 = minTriUV;
p1 = minTri3D;
}
else
{
uv1 = minVisUV;
p1 = minTri3D + (minVisUV.Y - minTriUV.Y) / (maxTriUV.Y - minTriUV.Y) * (maxTri3D - minTri3D);
}
// compute the maximum value
if (maxVisUV.Y > maxTriUV.Y)
{
uv2 = maxTriUV;
p2 = maxTri3D;
}
else
{
uv2 = maxVisUV;
p2 = minTri3D + (maxVisUV.Y - minTriUV.Y) / (maxTriUV.Y - minTriUV.Y) * (maxTri3D - minTri3D);
}
}
// add the edge
edgeList.Add(new HitTestEdge(p1, p2, uv1, uv2));
}
/// <summary>
/// Intersects a ray with the line specified by the passed in end points. The parameterized coordinate along the ray of
/// intersection is returned.
/// </summary>
/// <param name="o">The ray origin</param>
/// <param name="d">The ray direction</param>
/// <param name="p1">First point of the line to intersect against</param>
/// <param name="p2">Second point of the line to intersect against</param>
/// <param name="coinc">Whether the ray and line are coincident</param>
/// <returns>
/// The parameter along the ray of the point of intersection.
/// If the ray and line are parallel and not coincident, this will be -1.
/// </returns>
private double IntersectRayLine(Point o, Vector d, Point p1, Point p2, out bool coinc)
{
coinc = false;
// deltas
double dy = p2.Y - p1.Y;
double dx = p2.X - p1.X;
// handle case of a vertical line
if (dx == 0)
{
if (d.X == 0)
{
coinc = (o.X == p1.X);
return -1;
}
else
{
return (p2.X - o.X) / d.X;
}
}
// now need to do more general intersection
double numer = (o.X - p1.X) * dy / dx - o.Y + p1.Y;
double denom = (d.Y - d.X * dy / dx);
// if denominator is zero, then the lines are parallel
if (denom == 0)
{
double b0 = -o.X * dy / dx + o.Y;
double b1 = -p1.X * dy / dx + p1.Y;
coinc = (b0 == b1);
return -1;
}
else
{
return (numer / denom);
}
}
/// <summary>
/// Helper structure to represent an edge
/// </summary>
private struct Edge
{
public Edge(Point3D s, Point3D e)
{
_start = s;
_end = e;
}
public Point3D _start;
public Point3D _end;
}
/// <summary>
/// Information about an edge such as whether it belongs to a front/back facing
/// triangle, the texture coordinates for the edge, and how many polygons refer
/// to that edge.
/// </summary>
private class EdgeInfo
{
public EdgeInfo()
{
hasFrontFace = hasBackFace = false;
numSharing = 0;
}
public bool hasFrontFace;
public bool hasBackFace;
public Point uv1;
public Point uv2;
public int numSharing;
}
/// <summary>
/// Processes the edges of the given triangle. It does so by updating
/// the adjacency information based on the direction the polygon is facing.
/// If there is a silhouette edge found, then this edge is added to the list
/// of edges if it is within the texture coordinate bounds passed to the function.
/// </summary>
/// <param name="p">The triangle's vertices</param>
/// <param name="uv">The texture coordinates for those vertices</param>
/// <param name="tc">The texture coordinate edges being searched for</param>
/// <param name="polygonSide">Which side the polygon is facing (greateer than 0 front, less than 0 back)</param>
/// <param name="edgeList">The list of edges comprosing the visual outline</param>
/// <param name="adjInformation">The adjacency information structure</param>
private void ProcessTriangleEdges(Point3D[] p,
Point[] uv,
Point[] tc,
PolygonSide polygonSide,
List<HitTestEdge> edgeList,
Dictionary<Edge, EdgeInfo> adjInformation)
{
// loop over all the edges and add them to the adjacency list
for (int i = 0; i < p.Length; i++)
{
Point uv1, uv2;
Point3D p3D1 = p[i];
Point3D p3D2 = p[(i + 1) % p.Length];
Edge edge;
// order the edge points so insertion in to adjInformation is consistent
if (p3D1.X < p3D2.X ||
(p3D1.X == p3D2.X && p3D1.Y < p3D2.Y) ||
(p3D1.X == p3D2.X && p3D1.Y == p3D2.Y && p3D1.Z < p3D1.Z))
{
edge = new Edge(p3D1, p3D2);
uv1 = uv[i];
uv2 = uv[(i + 1) % p.Length];
}
else
{
edge = new Edge(p3D2, p3D1);
uv2 = uv[i];
uv1 = uv[(i + 1) % p.Length];
}
// look up the edge information
EdgeInfo edgeInfo;
if (adjInformation.ContainsKey(edge))
{
edgeInfo = adjInformation[edge];
}
else
{
edgeInfo = new EdgeInfo();
adjInformation[edge] = edgeInfo;
}
edgeInfo.numSharing++;
// whether or not the edge has already been added to the edge list
bool alreadyAdded = edgeInfo.hasBackFace && edgeInfo.hasFrontFace;
// add the edge to the info list
if (polygonSide == PolygonSide.FRONT)
{
edgeInfo.hasFrontFace = true;
edgeInfo.uv1 = uv1;
edgeInfo.uv2 = uv2;
}
else
{
edgeInfo.hasBackFace = true;
}
// if the sides are different we may need to add an edge
if (!alreadyAdded && edgeInfo.hasBackFace && edgeInfo.hasFrontFace)
{
HandleSilhouetteEdge(edgeInfo.uv1, edgeInfo.uv2,
edge._start, edge._end,
tc,
edgeList);
}
}
}
/// <summary>
/// Handles intersecting a silhouette edge against the passed in texture coordinate
/// bounds. It behaves similarly to the case of intersection the bounds with a triangle
/// except the testing order is switched.
/// </summary>
/// <param name="uv1">The texture coordinates of the edge</param>
/// <param name="uv2">The texture coordinates of the edge</param>
/// <param name="p3D1">The 3D point of the edge</param>
/// <param name="p3D2">The 3D point of the edge</param>
/// <param name="bounds">The texture coordinate bounds</param>
/// <param name="edgeList">The list of edges</param>
private void HandleSilhouetteEdge(Point uv1, Point uv2,
Point3D p3D1, Point3D p3D2,
Point[] bounds,
List<HitTestEdge> edgeList)
{
List<Point3D> pointList = new List<Point3D>();
List<Point> uvList = new List<Point>();
Vector dir = uv2 - uv1;
// loop over object bounds
for (int i = 0; i < bounds.Length; i++)
{
Point visEdgeStart = bounds[i];
Point visEdgeEnd = bounds[(i + 1) % bounds.Length];
// initial rejection processing
if (!((Math.Max(visEdgeStart.X, visEdgeEnd.X) < Math.Min(uv1.X, uv2.X)) ||
(Math.Min(visEdgeStart.X, visEdgeEnd.X) > Math.Max(uv1.X, uv2.X)) ||
(Math.Max(visEdgeStart.Y, visEdgeEnd.Y) < Math.Min(uv1.Y, uv2.Y)) ||
(Math.Min(visEdgeStart.Y, visEdgeEnd.Y) > Math.Max(uv1.Y, uv2.Y))))
{
// intersect the two lines
bool areCoincident = false;
double t = IntersectRayLine(uv1, dir, visEdgeStart, visEdgeEnd, out areCoincident);
// silhouette edge processing will only include non-coincident lines
if (areCoincident)
{
// if it's coincident, we'll let the normal processing handle this edge
return;
}
else if (t >= 0 && t <= 1)
{
Point intersUV = uv1 + dir * t;
Point3D intersPoint3D = p3D1 + (p3D2 - p3D1) * t;
double visEdgeDiff = (visEdgeStart - visEdgeEnd).Length;
if ((intersUV - visEdgeStart).Length < visEdgeDiff &&
(intersUV - visEdgeEnd).Length < visEdgeDiff)
{
pointList.Add(intersPoint3D);
uvList.Add(intersUV);
}
}
}
}
if (pointList.Count >= 2)
{
edgeList.Add(new HitTestEdge(pointList[0], pointList[1],
uvList[0], uvList[1]));
}
else if (pointList.Count == 1)
{
// for the case that uv1/2 is actually a point on or extremely close to the bounds
// of the polygon, we do the pointinpolygon test on both to avoid any numerical
// precision issues - in the worst case we end up with a very small edge and
// the right edge
if (IsPointInPolygon(bounds, uv1))
{
edgeList.Add(new HitTestEdge(pointList[0], p3D1,
uvList[0], uv1));
}
if (IsPointInPolygon(bounds, uv2))
{
edgeList.Add(new HitTestEdge(pointList[0], p3D2,
uvList[0], uv2));
}
}
else
{
if (IsPointInPolygon(bounds, uv1) &&
IsPointInPolygon(bounds, uv2))
{
edgeList.Add(new HitTestEdge(p3D1, p3D2,
uv1, uv2));
}
}
}
/// <summary>
/// Function tests to see whether the point p is contained within the polygon
/// specified by the list of points passed to the function. p is considered within
/// this polygon if it is on the same side of all the edges. A point on any of
/// the edges of the polygon is not considered within the polygon.
/// </summary>
/// <param name="polygon">The polygon to test against</param>
/// <param name="p">The point to be tested against</param>
/// <returns>Whether the point is in the polygon</returns>
private bool IsPointInPolygon(Point[] polygon, Point p)
{
bool sign = false;
for (int i = 0; i < polygon.Length; i++)
{
double crossProduct = Vector.CrossProduct(polygon[(i + 1) % polygon.Length] - polygon[i],
polygon[i] - p);
bool currSign = crossProduct > 0;
if (i == 0)
{
sign = currSign;
}
else
{
if (sign != currSign) return false;
}
}
return true;
}
/// <summary>
/// GenerateMaterial creates the material for the InteractiveModelVisual3D. The
/// material is composed of the Visual, which is displayed on a VisualBrush on a
/// DiffuseMaterial, as well as any post materials which are also applied.
/// </summary>
private void GenerateMaterial()
{
Material material;
// begin order dependent operations
InternalVisualBrush.Visual = null;
InternalVisualBrush = CreateVisualBrush();
material = Material.Clone();
_content.Material = material;
InternalVisualBrush.Visual = InternalVisual;
SwapInVisualBrush(material);
// end order dependent operations
if (IsBackVisible)
{
_content.BackMaterial = material;
}
}
/// <summary>
/// Creates the VisualBrush that will be used to hold the interactive
/// 2D content.
/// </summary>
/// <returns>The VisualBrush to hold the interactive 2D content</returns>
private VisualBrush CreateVisualBrush()
{
VisualBrush vb = new VisualBrush();
RenderOptions.SetCachingHint(vb, CachingHint.Cache);
vb.ViewportUnits = BrushMappingMode.Absolute;
vb.TileMode = TileMode.None;
return vb;
}
/// <summary>
/// Replaces any instances of the sentinal brush with the internal visual brush
/// </summary>
/// <param name="material">The material to look through</param>
private void SwapInVisualBrush(Material material)
{
bool foundMaterialToSwap = false;
Stack<Material> materialStack = new Stack<Material>();
materialStack.Push(material);
while (materialStack.Count > 0)
{
Material currMaterial = materialStack.Pop();
if (currMaterial is DiffuseMaterial)
{
DiffuseMaterial diffMaterial = (DiffuseMaterial)currMaterial;
if ((Boolean)diffMaterial.GetValue(InteractiveVisual3D.IsInteractiveMaterialProperty))
{
diffMaterial.Brush = InternalVisualBrush;
foundMaterialToSwap = true;
}
}
else if (currMaterial is EmissiveMaterial)
{
EmissiveMaterial emmMaterial = (EmissiveMaterial)currMaterial;
if ((Boolean)emmMaterial.GetValue(InteractiveVisual3D.IsInteractiveMaterialProperty))
{
emmMaterial.Brush = InternalVisualBrush;
foundMaterialToSwap = true;
}
}
else if (currMaterial is SpecularMaterial)
{
SpecularMaterial specMaterial = (SpecularMaterial)currMaterial;
if ((Boolean)specMaterial.GetValue(InteractiveVisual3D.IsInteractiveMaterialProperty))
{
specMaterial.Brush = InternalVisualBrush;
foundMaterialToSwap = true;
}
}
else if (currMaterial is MaterialGroup)
{
MaterialGroup matGroup = (MaterialGroup)currMaterial;
foreach (Material m in matGroup.Children)
{
materialStack.Push(m);
}
}
else
{
throw new ArgumentException("material needs to be either a DiffuseMaterial, EmissiveMaterial, SpecularMaterial or a MaterialGroup",
"material");
}
}
// make sure there is at least one interactive material
if (!foundMaterialToSwap)
{
throw new ArgumentException("material needs to contain at least one material that has the IsInteractiveMaterial attached property",
"material");
}
}
/// <summary>
/// The visual applied to the VisualBrush, which is then used on the 3D object
/// </summary>
private static DependencyProperty VisualProperty =
DependencyProperty.Register(
"Visual",
typeof(Visual),
typeof(InteractiveVisual3D),
new PropertyMetadata(null, new PropertyChangedCallback(OnVisualChanged)));
public Visual Visual
{
get { return (Visual)GetValue(VisualProperty); }
set { SetValue(VisualProperty, value); }
}
/// <summary>
/// The actual visual being placed on the brush.
/// so that the patterns on visuals caused by tabbing, etc... work,
/// we wrap the Visual DependencyProperty in a AdornerDecorator.
/// </summary>
internal UIElement InternalVisual
{
get { return _internalVisual; }
}
/// <summary>
/// The visual brush that the internal visual is contained on.
/// </summary>
private VisualBrush InternalVisualBrush
{
get
{
return _visualBrush;
}
set
{
_visualBrush = value;
}
}
internal static void OnVisualChanged(Object sender, DependencyPropertyChangedEventArgs e)
{
InteractiveVisual3D imv3D = ((InteractiveVisual3D)sender);
AdornerDecorator ad = null;
if (imv3D.InternalVisual != null)
{
ad = ((AdornerDecorator)imv3D.InternalVisual);
if (ad.Child is VisualDecorator)
{
VisualDecorator oldVisualDecorator = (VisualDecorator)ad.Child;
oldVisualDecorator.Content = null;
}
}
// so that the patterns on visuals caused by tabbing, etc... work,
// we put an adorner layer here so that anything adorned gets adorned
// within the visual and not at the adorner layer on the window
if (ad == null)
{
ad = new AdornerDecorator();
}
UIElement adornerDecoratorChild;
if (imv3D.Visual is UIElement)
{
adornerDecoratorChild = (UIElement)imv3D.Visual;
}
else
{
VisualDecorator visDecorator = new VisualDecorator();
visDecorator.Content = imv3D.Visual;
adornerDecoratorChild = visDecorator;
}
ad.Child = null;
ad.Child = adornerDecoratorChild;
imv3D._internalVisual = ad;
imv3D.InternalVisualBrush.Visual = imv3D.InternalVisual;
}
/// <summary>
/// The BackFaceVisibleProperty specifies whether or not the back face of the 3D object
/// should be considered visible. If it is then when generating the material, the back material
/// is also set.
/// </summary>
private static readonly DependencyProperty IsBackVisibleProperty =
DependencyProperty.Register(
"IsBackVisible",
typeof(bool),
typeof(InteractiveVisual3D),
new PropertyMetadata(false, new PropertyChangedCallback(OnIsBackVisiblePropertyChanged)));
public bool IsBackVisible
{
get { return (bool)GetValue(IsBackVisibleProperty); }
set
{
SetValue(IsBackVisibleProperty, value);
}
}
internal static void OnIsBackVisiblePropertyChanged(Object sender, DependencyPropertyChangedEventArgs e)
{
InteractiveVisual3D imv3D = ((InteractiveVisual3D)sender);
if (imv3D.IsBackVisible)
{
imv3D._content.BackMaterial = imv3D._content.Material;
}
else
{
imv3D._content.BackMaterial = null;
}
}
/// <summary>
/// The emissive color of the material
/// </summary>
private readonly static DiffuseMaterial _defaultMaterialPropertyValue;
public static readonly DependencyProperty MaterialProperty;
public Material Material
{
get { return (Material)GetValue(MaterialProperty); }
set { SetValue(MaterialProperty, value); }
}
internal static void OnMaterialPropertyChanged(Object sender, DependencyPropertyChangedEventArgs e)
{
InteractiveVisual3D imv3D = ((InteractiveVisual3D)sender);
imv3D.GenerateMaterial();
}
/// <summary>
/// The 3D geometry that the InteractiveModelVisual3D represents
/// </summary>
public static readonly DependencyProperty GeometryProperty =
DependencyProperty.Register(
"Geometry",
typeof(Geometry3D),
typeof(InteractiveVisual3D),
new PropertyMetadata(null, new PropertyChangedCallback(OnGeometryChanged)));
public Geometry3D Geometry
{
get { return (Geometry3D)GetValue(GeometryProperty); }
set { SetValue(GeometryProperty, value); }
}
internal static void OnGeometryChanged(Object sender, DependencyPropertyChangedEventArgs e)
{
InteractiveVisual3D imv3D = ((InteractiveVisual3D)sender);
imv3D._content.Geometry = imv3D.Geometry;
}
/// <summary>
/// The attached dependency property used to indicate whether a material should be made
/// interactive.
/// </summary>
public static readonly DependencyProperty IsInteractiveMaterialProperty =
DependencyProperty.RegisterAttached(
"IsInteractiveMaterial",
typeof(Boolean),
typeof(InteractiveVisual3D),
new PropertyMetadata(false));
public static void SetIsInteractiveMaterial(UIElement element, Boolean value)
{
element.SetValue(IsInteractiveMaterialProperty, value);
}
public static Boolean GetIsInteractiveMaterial(UIElement element)
{
return (Boolean)element.GetValue(IsInteractiveMaterialProperty);
}
/// <summary>
/// Done so that the Content property is not serialized and not visible by a visual designer
/// </summary>
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
public new Model3D Content
{
get { return base.Content; }
set { base.Content = value; }
}
//------------------------------------------------------------------------
//
// PRIVATE DATA
//
//------------------------------------------------------------------------
private enum PolygonSide { FRONT, BACK };
// the geometry model that represents this visual3D
internal readonly GeometryModel3D _content;
// helper functions to cache the last created visual edges and also to tell
// if we need to recompute these values, or can use the cache
private Point[] _lastVisCorners = null;
private List<HitTestEdge> _lastEdges = null;
private Matrix3D _lastMatrix3D;
// the actual visual that is created
private UIElement _internalVisual;
private VisualBrush _visualBrush;
}
/// <summary>
/// The VisualDecorator class simply holds one Visual as a child. It is used
/// to provide a bridge between the AdornerDecorator and the Visual that
/// is intended to be placed on the 3D mesh. The reason being that AdornerDecorator
/// only takes a UIElement as a child - so in the case that a Visual (non UI/FE)
/// is to be placed on the 3D mesh, a VisualDecorator is needed to provide that
/// bridge.
/// </summary>
internal class VisualDecorator : FrameworkElement
{
public VisualDecorator()
{
_visual = null;
}
/// <summary>
/// The content/child of the VisualDecorator.
/// </summary>
public Visual Content
{
get
{
return _visual;
}
set
{
// check to make sure we're attempting to set something new
if (_visual != value)
{
Visual oldVisual = _visual;
Visual newVisual = value;
// remove the previous child
RemoveVisualChild(oldVisual);
RemoveLogicalChild(oldVisual);
// set the private variable
_visual = value;
// link in the new child
AddLogicalChild(newVisual);
AddVisualChild(newVisual);
}
}
}
/// <summary>
/// Returns the number of Visual children this element has.
/// </summary>
protected override int VisualChildrenCount
{
get
{
return (Content != null ? 1 : 0);
}
}
/// <summary>
/// Returns the child at the specified index.
/// </summary>
protected override Visual GetVisualChild(int index)
{
if (index == 0 && Content != null) return _visual;
// if we didn't return then the index is out of range - throw an error
throw new ArgumentOutOfRangeException("index", index, "Out of range visual requested");
}
/// <summary>
/// Returns an enumertor to this element's logical children
/// </summary>
protected override IEnumerator LogicalChildren
{
get
{
Visual[] logicalChildren = new Visual[VisualChildrenCount];
for (int i = 0; i < VisualChildrenCount; i++)
{
logicalChildren[i] = GetVisualChild(i);
}
return logicalChildren.GetEnumerator();
}
}
// the visual being referenced
private Visual _visual;
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityModel.Client;
using IdentityServer4;
using IdentityServer4.Configuration;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Test;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace IdentityServer.IntegrationTests.Common
{
public class IdentityServerPipeline
{
public const string BaseUrl = "https://server";
public const string LoginPage = BaseUrl + "/account/login";
public const string ConsentPage = BaseUrl + "/account/consent";
public const string ErrorPage = BaseUrl + "/home/error";
public const string DeviceAuthorization = BaseUrl + "/connect/deviceauthorization";
public const string DiscoveryEndpoint = BaseUrl + "/.well-known/openid-configuration";
public const string DiscoveryKeysEndpoint = BaseUrl + "/.well-known/openid-configuration/jwks";
public const string AuthorizeEndpoint = BaseUrl + "/connect/authorize";
public const string TokenEndpoint = BaseUrl + "/connect/token";
public const string RevocationEndpoint = BaseUrl + "/connect/revocation";
public const string UserInfoEndpoint = BaseUrl + "/connect/userinfo";
public const string IntrospectionEndpoint = BaseUrl + "/connect/introspect";
public const string IdentityTokenValidationEndpoint = BaseUrl + "/connect/identityTokenValidation";
public const string EndSessionEndpoint = BaseUrl + "/connect/endsession";
public const string EndSessionCallbackEndpoint = BaseUrl + "/connect/endsession/callback";
public const string CheckSessionEndpoint = BaseUrl + "/connect/checksession";
public const string FederatedSignOutPath = "/signout-oidc";
public const string FederatedSignOutUrl = BaseUrl + FederatedSignOutPath;
public IdentityServerOptions Options { get; set; }
public List<Client> Clients { get; set; } = new List<Client>();
public List<IdentityResource> IdentityScopes { get; set; } = new List<IdentityResource>();
public List<ApiResource> ApiScopes { get; set; } = new List<ApiResource>();
public List<TestUser> Users { get; set; } = new List<TestUser>();
public TestServer Server { get; set; }
public HttpMessageHandler Handler { get; set; }
public BrowserClient BrowserClient { get; set; }
public HttpClient BackChannelClient { get; set; }
public MockMessageHandler BackChannelMessageHandler { get; set; } = new MockMessageHandler();
public MockMessageHandler JwtRequestMessageHandler { get; set; } = new MockMessageHandler();
public event Action<IServiceCollection> OnPreConfigureServices = services => { };
public event Action<IServiceCollection> OnPostConfigureServices = services => { };
public event Action<IApplicationBuilder> OnPreConfigure = app => { };
public event Action<IApplicationBuilder> OnPostConfigure = app => { };
public Func<HttpContext, Task<bool>> OnFederatedSignout;
public void Initialize(string basePath = null, bool enableLogging = false)
{
var builder = new WebHostBuilder();
builder.ConfigureServices(ConfigureServices);
builder.Configure(app=>
{
if (basePath != null)
{
app.Map(basePath, map =>
{
ConfigureApp(map);
});
}
else
{
ConfigureApp(app);
}
});
if (enableLogging)
{
builder.ConfigureLogging((ctx, b) => b.AddConsole());
}
Server = new TestServer(builder);
Handler = Server.CreateHandler();
BrowserClient = new BrowserClient(new BrowserHandler(Handler));
BackChannelClient = new HttpClient(Handler);
}
public void ConfigureServices(IServiceCollection services)
{
OnPreConfigureServices(services);
services.AddAuthentication(opts =>
{
opts.AddScheme("external", scheme =>
{
scheme.DisplayName = "External";
scheme.HandlerType = typeof(MockExternalAuthenticationHandler);
});
});
services.AddTransient<MockExternalAuthenticationHandler>(svcs =>
{
var handler = new MockExternalAuthenticationHandler(svcs.GetRequiredService<IHttpContextAccessor>());
if (OnFederatedSignout != null) handler.OnFederatedSignout = OnFederatedSignout;
return handler;
});
services.AddIdentityServer(options =>
{
Options = options;
options.Events = new EventsOptions
{
RaiseErrorEvents = true,
RaiseFailureEvents = true,
RaiseInformationEvents = true,
RaiseSuccessEvents = true
};
})
.AddInMemoryClients(Clients)
.AddInMemoryIdentityResources(IdentityScopes)
.AddInMemoryApiResources(ApiScopes)
.AddTestUsers(Users)
.AddDeveloperSigningCredential(persistKey: false);
services.AddHttpClient()
.AddHttpClient<BackChannelLogoutHttpClient>()
.AddHttpMessageHandler(() => BackChannelMessageHandler);
services.AddHttpClient<JwtRequestUriHttpClient>()
.AddHttpMessageHandler(() => JwtRequestMessageHandler);
OnPostConfigureServices(services);
}
public void ConfigureApp(IApplicationBuilder app)
{
OnPreConfigure(app);
app.UseIdentityServer();
// UI endpoints
app.Map(Constants.UIConstants.DefaultRoutePaths.Login.EnsureLeadingSlash(), path =>
{
path.Run(ctx => OnLogin(ctx));
});
app.Map(Constants.UIConstants.DefaultRoutePaths.Logout.EnsureLeadingSlash(), path =>
{
path.Run(ctx => OnLogout(ctx));
});
app.Map(Constants.UIConstants.DefaultRoutePaths.Consent.EnsureLeadingSlash(), path =>
{
path.Run(ctx => OnConsent(ctx));
});
app.Map(Constants.UIConstants.DefaultRoutePaths.Error.EnsureLeadingSlash(), path =>
{
path.Run(ctx => OnError(ctx));
});
OnPostConfigure(app);
}
public bool LoginWasCalled { get; set; }
public AuthorizationRequest LoginRequest { get; set; }
public ClaimsPrincipal Subject { get; set; }
public bool FollowLoginReturnUrl { get; set; }
private async Task OnLogin(HttpContext ctx)
{
LoginWasCalled = true;
await ReadLoginRequest(ctx);
await IssueLoginCookie(ctx);
}
private async Task ReadLoginRequest(HttpContext ctx)
{
var interaction = ctx.RequestServices.GetRequiredService<IIdentityServerInteractionService>();
LoginRequest = await interaction.GetAuthorizationContextAsync(ctx.Request.Query["returnUrl"].FirstOrDefault());
}
private async Task IssueLoginCookie(HttpContext ctx)
{
if (Subject != null)
{
var props = new AuthenticationProperties();
await ctx.SignInAsync(Subject, props);
Subject = null;
var url = ctx.Request.Query[Options.UserInteraction.LoginReturnUrlParameter].FirstOrDefault();
if (url != null)
{
ctx.Response.Redirect(url);
}
}
}
public bool LogoutWasCalled { get; set; }
public LogoutRequest LogoutRequest { get; set; }
private async Task OnLogout(HttpContext ctx)
{
LogoutWasCalled = true;
await ReadLogoutRequest(ctx);
}
private async Task ReadLogoutRequest(HttpContext ctx)
{
var interaction = ctx.RequestServices.GetRequiredService<IIdentityServerInteractionService>();
LogoutRequest = await interaction.GetLogoutContextAsync(ctx.Request.Query["logoutId"].FirstOrDefault());
}
public bool ConsentWasCalled { get; set; }
public AuthorizationRequest ConsentRequest { get; set; }
public ConsentResponse ConsentResponse { get; set; }
private async Task OnConsent(HttpContext ctx)
{
ConsentWasCalled = true;
await ReadConsentMessage(ctx);
await CreateConsentResponse(ctx);
}
private async Task ReadConsentMessage(HttpContext ctx)
{
var interaction = ctx.RequestServices.GetRequiredService<IIdentityServerInteractionService>();
ConsentRequest = await interaction.GetAuthorizationContextAsync(ctx.Request.Query["returnUrl"].FirstOrDefault());
}
private async Task CreateConsentResponse(HttpContext ctx)
{
if (ConsentRequest != null && ConsentResponse != null)
{
var interaction = ctx.RequestServices.GetRequiredService<IIdentityServerInteractionService>();
await interaction.GrantConsentAsync(ConsentRequest, ConsentResponse);
ConsentResponse = null;
var url = ctx.Request.Query[Options.UserInteraction.ConsentReturnUrlParameter].FirstOrDefault();
if (url != null)
{
ctx.Response.Redirect(url);
}
}
}
public bool ErrorWasCalled { get; set; }
public ErrorMessage ErrorMessage { get; set; }
private async Task OnError(HttpContext ctx)
{
ErrorWasCalled = true;
await ReadErrorMessage(ctx);
}
private async Task ReadErrorMessage(HttpContext ctx)
{
var interaction = ctx.RequestServices.GetRequiredService<IIdentityServerInteractionService>();
ErrorMessage = await interaction.GetErrorContextAsync(ctx.Request.Query["errorId"].FirstOrDefault());
}
/* helpers */
public async Task LoginAsync(ClaimsPrincipal subject)
{
var old = BrowserClient.AllowAutoRedirect;
BrowserClient.AllowAutoRedirect = false;
Subject = subject;
await BrowserClient.GetAsync(LoginPage);
BrowserClient.AllowAutoRedirect = old;
}
public async Task LoginAsync(string subject)
{
await LoginAsync(new IdentityServerUser(subject).CreatePrincipal());
}
public void RemoveLoginCookie()
{
BrowserClient.RemoveCookie(BaseUrl, IdentityServerConstants.DefaultCookieAuthenticationScheme);
}
public void RemoveSessionCookie()
{
BrowserClient.RemoveCookie(BaseUrl, IdentityServerConstants.DefaultCheckSessionCookieName);
}
public Cookie GetSessionCookie()
{
return BrowserClient.GetCookie(BaseUrl, IdentityServerConstants.DefaultCheckSessionCookieName);
}
public string CreateAuthorizeUrl(
string clientId = null,
string responseType = null,
string scope = null,
string redirectUri = null,
string state = null,
string nonce = null,
string loginHint = null,
string acrValues = null,
string responseMode = null,
string codeChallenge = null,
string codeChallengeMethod = null,
object extra = null)
{
var url = new RequestUrl(AuthorizeEndpoint).CreateAuthorizeUrl(
clientId: clientId,
responseType: responseType,
scope: scope,
redirectUri: redirectUri,
state: state,
nonce: nonce,
loginHint: loginHint,
acrValues: acrValues,
responseMode: responseMode,
codeChallenge: codeChallenge,
codeChallengeMethod: codeChallengeMethod,
extra: extra);
return url;
}
public AuthorizeResponse ParseAuthorizationResponseUrl(string url)
{
return new AuthorizeResponse(url);
}
public async Task<AuthorizeResponse> RequestAuthorizationEndpointAsync(
string clientId,
string responseType,
string scope = null,
string redirectUri = null,
string state = null,
string nonce = null,
string loginHint = null,
string acrValues = null,
string responseMode = null,
string codeChallenge = null,
string codeChallengeMethod = null,
object extra = null)
{
var old = BrowserClient.AllowAutoRedirect;
BrowserClient.AllowAutoRedirect = false;
var url = CreateAuthorizeUrl(clientId, responseType, scope, redirectUri, state, nonce, loginHint, acrValues, responseMode, codeChallenge, codeChallengeMethod, extra);
var result = await BrowserClient.GetAsync(url);
result.StatusCode.Should().Be(HttpStatusCode.Found);
BrowserClient.AllowAutoRedirect = old;
var redirect = result.Headers.Location.ToString();
if (redirect.StartsWith(IdentityServerPipeline.ErrorPage))
{
// request error page in pipeline so we can get error info
await BrowserClient.GetAsync(redirect);
// no redirect to client
return null;
}
return new AuthorizeResponse(redirect);
}
}
public class MockMessageHandler : DelegatingHandler
{
public bool InvokeWasCalled { get; set; }
public Func<HttpRequestMessage, Task> OnInvoke { get; set; }
public HttpResponseMessage Response { get; set; } = new HttpResponseMessage(HttpStatusCode.OK);
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
InvokeWasCalled = true;
if (OnInvoke != null)
{
await OnInvoke.Invoke(request);
}
return Response;
}
}
public class MockExternalAuthenticationHandler :
IAuthenticationHandler,
IAuthenticationSignInHandler,
IAuthenticationRequestHandler
{
private readonly IHttpContextAccessor _httpContextAccessor;
private HttpContext HttpContext => _httpContextAccessor.HttpContext;
public Func<HttpContext, Task<bool>> OnFederatedSignout =
async context =>
{
await context.SignOutAsync();
return true;
};
public MockExternalAuthenticationHandler(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public async Task<bool> HandleRequestAsync()
{
if (HttpContext.Request.Path == IdentityServerPipeline.FederatedSignOutPath)
{
return await OnFederatedSignout(HttpContext);
}
return false;
}
public Task<AuthenticateResult> AuthenticateAsync()
{
return Task.FromResult(AuthenticateResult.NoResult());
}
public Task ChallengeAsync(AuthenticationProperties properties)
{
return Task.CompletedTask;
}
public Task ForbidAsync(AuthenticationProperties properties)
{
return Task.CompletedTask;
}
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
return Task.CompletedTask;
}
public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
return Task.CompletedTask;
}
public Task SignOutAsync(AuthenticationProperties properties)
{
return Task.CompletedTask;
}
}
}
| |
using System;
using System.Collections;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading;
namespace Spring.Threading.Locks
{
/// <summary>
/// An implementation of <see cref="Spring.Threading.Locks.IReadWriteLock"/> supporting similar
/// semantics to <see cref="Spring.Threading.Locks.ReentrantLock"/>.
/// </summary>
/// <remarks>
/// This class has the following properties:
///
/// <ul>
/// <li><b>Acquisition order</b></li>
/// <p/>
/// The order of entry to the
/// lock need not be in arrival order. If readers are
/// active and a writer enters the lock then no subsequent readers will
/// be granted the read lock until after that writer has acquired and
/// released the write lock.
///
/// <li><b>Reentrancy</b></li>
/// <p/>
/// This lock allows both readers and writers to reacquire read or
/// write locks in the style of a <see cref="Spring.Threading.Locks.ReentrantLock"/>. Readers are not
/// allowed until all write locks held by the writing thread have been
/// released.
/// <p/>
/// Additionally, a writer can acquire the read lock - but not vice-versa.
/// Among other applications, reentrancy can be useful when
/// write locks are held during calls or callbacks to methods that
/// perform reads under read locks.
/// If a reader tries to acquire the write lock it will never succeed.
///
/// <li><b>Lock downgrading</b></li>
/// <p/>
/// Reentrancy also allows downgrading from the write lock to a read lock,
/// by acquiring the write lock, then the read lock and then releasing the
/// write lock. However, upgrading from a read lock to the write lock is
/// <b>not</b> possible.
///
/// <li><b>Interruption of lock acquisition</b></li>
/// <p/>The read lock and write lock both support interruption during lock
/// acquisition.
///
/// <li><b><see cref="Spring.Threading.Locks.ICondition"/> support</b></li>
/// <p/>
/// The write lock provides a <see cref="Spring.Threading.Locks.ICondition"/> implementation that
/// behaves in the same way, with respect to the write lock, as the
/// <see cref="Spring.Threading.Locks.ICondition"/> implementation provided by
/// <see cref="Spring.Threading.Locks.ReentrantLock.NewCondition()"/> does for <see cref="Spring.Threading.Locks.ReentrantLock"/>.
/// This <see cref="Spring.Threading.Locks.ICondition"/> can, of course, only be used with the write lock.
/// <p/>
/// The read lock does not support a <see cref="Spring.Threading.Locks.ICondition"/> and
/// <see cref="Spring.Threading.Locks.ReaderLock.NewCondition()"/> throws
/// <see cref="System.InvalidOperationException"/>.
///
/// <li><b>Instrumentation</b></li>
/// <p/>
/// This class supports methods to determine whether locks
/// are held or contended. These methods are designed for monitoring
/// system state, not for synchronization control.
/// </ul>
///
/// <p/>
/// Serialization of this class behaves in the same way as built-in
/// locks: a deserialized lock is in the unlocked state, regardless of
/// its state when serialized.
///
/// <p/><b>Sample usages</b>
/// Here is a code sketch showing how to exploit
/// reentrancy to perform lock downgrading after updating a cache (exception
/// handling is not shown for simplicity):
/// <code>
/// class CachedData {
/// object data;
/// volatile bool cacheValid;
/// ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
///
/// void processCachedData() {
/// rwl.ReadLock.Lock();
/// if (!cacheValid) {
/// rwl.ReadLock.Unlock();
/// rwl.WriteLock.Lock();
/// if (!cacheValid) {
/// data = ...
/// cacheValid = true;
/// }
/// // downgrade lock
/// rwl.ReadLock.Lock(); // reacquire read without giving up write lock
/// rwl.WriteLock.Unlock(); // unlock write, still hold read
/// }
///
/// use(data);
/// rwl.ReadLock.Unlock();
/// }
/// }
/// </code>
///
/// <see cref="Spring.Threading.Locks.ReentrantReadWriteLock"/>s can be used to improve concurrency in some
/// uses of some kinds of Collections. This is typically worthwhile
/// only when the collections are expected to be large, accessed by
/// more reader threads than writer threads, and entail operations with
/// overhead that outweighs synchronization overhead. For example, here
/// is a class using a TreeMap that is expected to be large and
/// concurrently accessed.
///
/// <code>
/// class RWDictionary {
/// private final IDictionary m = new Hashtable();
/// private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
/// private final Lock r = rwl.ReadLock;
/// private final Lock w = rwl.WriteLock;
///
/// public object Get(string key) {
/// r.Lock(); try { return m[key]; } finally { r.Unlock(); }
/// }
/// public ICollection AllKeys() {
/// r.Lock(); try { return m.Keys; } finally { r.Unlock(); }
/// }
/// public object Put(string key, object value) {
/// w.Lock(); try { return m.Add(key, value); } finally { w.Unlock(); }
/// }
/// public void clear() {
/// w.Lock(); try { m.Clear(); } finally { w.Unlock(); }
/// }
/// }
/// </code>
///
///
/// <h3>Implementation Notes</h3>
///
/// <p/>
/// A reentrant write lock intrinsically defines an owner and can
/// only be released by the thread that acquired it. In contrast, in
/// this implementation, the read lock has no concept of ownership, and
/// there is no requirement that the thread releasing a read lock is
/// the same as the one that acquired it. However, this property is
/// not guaranteed to hold in future implementations of this class.
///
/// <p/> This lock supports a maximum of 65536 recursive write locks
/// and 65536 read locks.
/// </remarks>
/// <author>Doug Lea</author>
/// <author>Griffin Caprio(.NET)</author>
[Serializable]
public class ReentrantReadWriteLock : IReadWriteLock, ISerializable
{
/// <summary>
/// Enumeration indicatiing which lock to signal.
/// </summary>
public enum Signaller
{
/// <summary>
/// No Lock
/// </summary>
NONE = 0,
/// <summary>
/// Reader Lock
/// </summary>
READER = 1,
/// <summary>
/// Writer Lock
/// </summary>
WRITER = 2
}
[NonSerialized] internal int _activeReaders = 0;
[NonSerialized] internal Thread _activeWriter = null;
[NonSerialized] internal int _waitingReaders = 0;
[NonSerialized] internal int _waitingWriters = 0;
[NonSerialized] internal int _writeHolds = 0;
[NonSerialized] internal Hashtable _readers = new Hashtable();
internal ReaderLock _readerLock;
internal WriterLock _writerLock;
internal static readonly int ONE = 1;
[ThreadStatic] internal static readonly NullSignaller Null_Signaller = new NullSignaller();
#region Constructors
/// <summary>
/// Creates a new <see cref="Spring.Threading.Locks.ReentrantReadWriteLock"/> with
/// default ordering properties.
/// </summary>
public ReentrantReadWriteLock()
{
_readerLock = new ReaderLock(this);
_writerLock = new WriterLock(this);
}
/// <summary>
/// Deserializes a <see cref="Spring.Threading.Locks.ReentrantReadWriteLock"/> instance from the supplied <see cref="System.Runtime.Serialization.SerializationInfo"/>
/// </summary>
/// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/> to pull date from.</param>
/// <param name="context">The contextual information about the source or destination.</param>
protected ReentrantReadWriteLock(SerializationInfo info, StreamingContext context)
{
Type thisType = this.GetType();
MemberInfo[] mi = FormatterServices.GetSerializableMembers(thisType, context);
for (int i = 0; i < mi.Length; i++)
{
FieldInfo fi = (FieldInfo) mi[i];
fi.SetValue(this, info.GetValue(fi.Name, fi.FieldType));
}
lock (this)
{
_readers = new Hashtable();
}
}
#endregion
#region Properties
/// <summary>Returns <see lang="true"/> if this lock has fairness set true. This implementation always returns <see lang="false"/></summary>
/// <returns><see lang="false"/> if this lock has fairness set false.</returns>
public bool IsFair
{
get { return false; }
}
/// <summary>
/// Returns the <see cref="System.Threading.Thread"/> that currently owns the write lock, or
/// <see lang="null"/> if not owned. Note that the owner may be
/// momentarily <see lang="null"/> even if there are threads trying to
/// acquire the lock but have not yet done so. This method is
/// designed to facilitate construction of subclasses that provide
/// more extensive lock monitoring facilities.
/// </summary>
/// <returns> the owner, or <see lang="null"/> if not owned.
/// </returns>
protected internal Thread Owner
{
get
{
lock (this)
{
return _activeWriter;
}
}
}
/// <summary>
/// Queries the number of read locks held for this lock. This
/// method is designed for use in monitoring system state, not for
/// synchronization control.
/// </summary>
/// <returns>the number of read locks held.</returns>
public int ReadLockCount
{
get
{
lock (this)
{
return _activeReaders;
}
}
}
/// <summary>
/// Queries if the write lock is held by any thread. This method is
/// designed for use in monitoring system state, not for
/// synchronization control.
/// </summary>
/// <returns> <see lang="true"/> if any thread holds the write lock and
/// <see lang="false"/> otherwise.
/// </returns>
public bool IsWriteLockHeld
{
get
{
lock (this)
{
return _activeWriter != null;
}
}
}
/// <summary>
/// Queries if the write lock is held by the current thread.</summary>
/// <returns> <see lang="true"/> if the current thread holds the write lock and
/// <see lang="false"/> otherwise.
/// </returns>
public bool WriterLockedByCurrentThread
{
get
{
lock (this)
{
return _activeWriter == Thread.CurrentThread;
}
}
}
/// <summary>
/// Queries the number of reentrant write holds on this lock by the
/// current thread. A writer thread has a hold on a lock for
/// each lock action that is not matched by an unlock action.
/// </summary>
/// <returns> the number of holds on the write lock by the current thread,
/// or zero if the write lock is not held by the current thread.
/// </returns>
public int WriteHoldCount
{
get
{
lock (this)
{
return _writeHolds;
}
}
}
/// <summary>
/// Returns an estimate of the number of threads waiting to acquire
/// either the read or write lock. The value is only an estimate
/// because the number of threads may change dynamically while this
/// method traverses internal data structures. This method is
/// designed for use in monitoring of the system state, not for
/// synchronization control.
/// </summary>
/// <returns>the estimated number of threads waiting for this lock</returns>
public int QueueLength
{
get
{
lock (this)
{
return _waitingWriters + _waitingReaders;
}
}
}
/// <summary>
/// Gets the write lock associated with this <see cref="Spring.Threading.Locks.ReentrantReadWriteLock"/> instance.
/// </summary>
public ILock WriterLock
{
get { return _writerLock; }
}
/// <summary>
/// Gets the read lock associated with this <see cref="Spring.Threading.Locks.ReentrantReadWriteLock"/> instance.
/// </summary>
public ILock ReaderLock
{
get { return _readerLock; }
}
/// <summary>
/// Gets the ReaderLock signaller for this <see cref="Spring.Threading.Locks.ReentrantReadWriteLock"/> instance.
/// </summary>
internal ISignaller SignallerReaderLock
{
get { return _readerLock; }
}
/// <summary>
/// Gets the WriterLock signaller for this <see cref="Spring.Threading.Locks.ReentrantReadWriteLock"/> instance.
/// </summary>
internal ISignaller SignallerWriterLock
{
get { return _writerLock; }
}
#endregion
#region Public Methods
/// <summary>
/// Returns a string identifying this lock, as well as its lock state.
/// The state, in brackets, includes the string "Write locks ="
/// followed by the number of reentrantly held write locks, and the
/// string "Read locks =" followed by the number of held
/// read locks.
/// </summary>
/// <returns> a string identifying this lock, as well as its lock state.
/// </returns>
public override String ToString()
{
return base.ToString() + "[Write locks = " + WriteHoldCount + ", Read locks = " + ReadLockCount + "]";
}
/// <summary>
/// Populates a <see cref="System.Runtime.Serialization.SerializationInfo"/> with the data needed to serialize the target object.
/// </summary>
/// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/> to populate with data.</param>
/// <param name="context">The destination (see <see cref="System.Runtime.Serialization.StreamingContext"/>) for this serialization. </param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
Type thisType = this.GetType();
MemberInfo[] mi = FormatterServices.GetSerializableMembers(thisType, context);
for (int i = 0; i < mi.Length; i++)
{
info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(this));
}
}
#endregion
#region Internal Lock Management Methods
/// <summary>
/// Attemptes to aquire a new read lock for the current thread. If the read lock was not aquired, the number of readers waiting for a
/// read lock is incremented.
/// </summary>
/// <returns><see lang="true"/> if a read lock was aquired, <see lang="false"/> otherwise.</returns>
internal bool StartReadFromNewReader()
{
lock (this)
{
bool pass = StartRead();
if (!pass)
++_waitingReaders;
return pass;
}
}
/// <summary>
/// Attemps to aquire a new write lock for the current thread. If the write lock was not aquired, the number of writers waiting for a
/// write lock is incremented.
/// </summary>
/// <returns><see lang="true"/> if the write lock was aquired, <see lang="false"/> otherwise.</returns>
internal bool StartWriteFromNewWriter()
{
lock (this)
{
bool pass = StartWrite();
if (!pass)
++_waitingWriters;
return pass;
}
}
/// <summary>
/// Attemps to aquire a new read lock from the current threads waiting readers. If the read lock was aquired, the number of waiting readers
/// is decremented.
/// </summary>
/// <returns><see lang="true"/> if the read lock was aquired, <see lang="false"/> otherwise.</returns>
internal bool StartReadFromWaitingReader()
{
lock (this)
{
bool pass = StartRead();
if (pass)
--_waitingReaders;
return pass;
}
}
/// <summary>
/// Attempes to aquire a new write lock for the current thread. If the write lock was aquired, the number of waiting writers for a write lock
/// is decremented.
/// </summary>
/// <returns><see lang="true"/> if the write lock was aquired, <see lang="false"/> otherwise.</returns>
internal bool StartWriteFromWaitingWriter()
{
lock (this)
{
bool pass = StartWrite();
if (pass)
--_waitingWriters;
return pass;
}
}
/// <summary>
/// Cancels a reader waiting for a read lock.
/// </summary>
internal void CancelWaitingReader()
{
lock (this)
{
--_waitingReaders;
}
}
/// <summary>
/// Cancels a writer waiting for a write lock.
/// </summary>
internal void CancelWaitingWriter()
{
lock (this)
{
--_waitingWriters;
}
}
/// <summary>
/// Determines if new read locks from the current thread are able to be aquired.
/// </summary>
/// <remarks>
/// The criteria to determine if new read locks from the current thread are able to be aquired are as follows:
/// <ul>
/// <li>
/// If there is no active writer and there are no waiting writers
/// </li>
/// <li>
/// If the active writer is the current thrad.
/// </li>
/// </ul>
/// <p/>
/// If either of the above condidtions is true, readers are allowed. Otherwise, no readers are allowed.
/// </remarks>
internal bool AllowReader
{
get { return (_activeWriter == null && _waitingWriters == 0) || _activeWriter == Thread.CurrentThread; }
}
/// <summary>
/// Determines if new write locks from the current thread can be aquried.
/// </summary>
/// <remarks>
/// The criteria to determine if new write locks from the current thread are able to be aquired are as follows:
/// <ul>
/// <li>
/// The number of active readers is 0.
/// </li>
/// <li>
/// There is only one total reader and it is the current thread.
/// </li>
/// </ul>
/// If either of the above condiditions is true, writers are allowed. Otherwise, no writers are allowed.
/// </remarks>
internal bool AllowWriter
{
get { return _activeReaders == 0 || (_readers.Count == 1 && _readers[Thread.CurrentThread] != null); }
}
/// <summary>
/// Attempts to start a new read lock for the current Thread.
/// </summary>
/// <remarks>
/// If the current thread already has a read lock, the number of active readers is simply incremented, as well as the number of readers for that
/// thread.
/// <p/>
/// If the current thread does <b>not</b> have a read lock, and readers are allowed, the number of active readers is incremented, as well as the
/// number of readers for that thread.
/// <p/>
/// If the current thread does not have a read lock, and new read locks are <b>not</b> allowed, false is returned and a new read lock is <b>not</b>
/// aquired.
/// </remarks>
/// <returns><see lang="trur"/> if a read lock was aquired, <see lang="false"/> otherwise.</returns>
internal bool StartRead()
{
lock (this)
{
Thread currentThread = Thread.CurrentThread;
object currentReaderCountForThread = _readers[currentThread];
if (currentReaderCountForThread != null)
{
_readers[currentThread] = (int) (currentReaderCountForThread) + 1;
++_activeReaders;
return true;
}
else if (AllowReader)
{
_readers[currentThread] = ONE;
++_activeReaders;
return true;
}
else
return false;
}
}
/// <summary>
/// Attempts to start a new write lock for the current Thread.
/// </summary>
/// <remarks>
/// If the current thread is already the active writer, the number of writer holds is simply incremented. Otherwise, if there are no current
/// write holds and writers are allowed, the current thread becomes the active writer.
/// </remarks>
/// <returns><see lang="trur"/> if a write lock was aquired, <see lang="false"/> otherwise.</returns>
internal bool StartWrite()
{
lock (this)
{
if (_activeWriter == Thread.CurrentThread)
{
++_writeHolds;
return true;
}
else if (_writeHolds == 0)
{
if (AllowWriter)
{
_activeWriter = Thread.CurrentThread;
_writeHolds = 1;
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
/// <summary>
/// Ends a read lock for the current thread.
/// </summary>
/// <returns><see cref="Spring.Threading.Locks.WriterLock"/> for this instance if there are no more readers for the current thread, there are no
/// more active readers for the read lock, and there are waiter writers. Otherwise, a a No-Op instance of
/// <see cref="Spring.Threading.Locks.ISignaller"/> is returned.
/// <p/>
/// <b>Note:</b> This deviates from the Java implementation by returning a No-Op instance of <see cref="Spring.Threading.Locks.ISignaller"/> instead
/// of null to avoid having null checks scattered around. This is an example of the Null Object pattern.
/// </returns>
/// <exception cref="System.Threading.ThreadStateException">
/// Thrown if there are no current readers for the lock from the current thread.
/// </exception>
internal Signaller EndRead()
{
lock (this)
{
Thread currentThread = Thread.CurrentThread;
object currentReaderCountForThread = _readers[currentThread];
if (currentReaderCountForThread == null)
{
throw new ThreadStateException("No current readers for the lock from thread " + currentThread.Name + ".");
}
--_activeReaders;
if ((int) currentReaderCountForThread != ONE)
{
int decrementedReaderCountForThread = (int) currentReaderCountForThread - 1;
if (decrementedReaderCountForThread == 1)
{
_readers[currentThread] = ONE;
}
else
{
_readers[currentThread] = decrementedReaderCountForThread;
}
return Signaller.NONE;
}
else
{
_readers.Remove(currentThread);
if (_writeHolds > 0)
return Signaller.NONE;
else if (_activeReaders == 0 && _waitingWriters > 0)
return Signaller.WRITER;
else
return Signaller.NONE;
}
}
}
/// <summary>
/// Ends a write lock from the current lock.
/// </summary>
/// <returns>
/// <see cref="Spring.Threading.Locks.ReaderLock"/> for this instance if there are more write holds, waiting readers, and readers are allowed.
/// If there are more write holds, no waiting readers or readers are not allowed, and waiting writers, then the
/// <see cref="Spring.Threading.Locks.WriterLock"/> for this instance is returned. Other wise a No-Op instance of
/// <see cref="Spring.Threading.Locks.ISignaller"/> is returned.
/// <p/>
/// <b>Note:</b> This deviates from the Java implementation by returning a No-Op instance of <see cref="Spring.Threading.Locks.ISignaller"/> instead
/// of null to avoid having null checks scattered around. This is an example of the Null Object pattern.
/// </returns>
/// <exception cref="System.Threading.SynchronizationLockException">
/// Thrown if the current thread is not currently the active writer.
/// </exception>
internal Signaller EndWrite()
{
lock (this)
{
if (_activeWriter != Thread.CurrentThread)
{
throw new SynchronizationLockException();
}
--_writeHolds;
if (_writeHolds > 0)
{
return Signaller.NONE;
}
else
{
_activeWriter = null;
if (_waitingReaders > 0 && AllowReader)
{
return Signaller.READER;
}
else if (_waitingWriters > 0)
{
return Signaller.WRITER;
}
else
{
return Signaller.NONE;
}
}
}
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="MultiFactorAuthenticationApi.cs" company="LoginRadius">
// Created by LoginRadius Development Team
// Copyright 2019 LoginRadius Inc. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using LoginRadiusSDK.V2.Common;
using System.Threading.Tasks;
using LoginRadiusSDK.V2.Util;
using LoginRadiusSDK.V2.Models.ResponseModels;
using LoginRadiusSDK.V2.Models.ResponseModels.UserProfile;
using LoginRadiusSDK.V2.Models.RequestModels;
using LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects;
namespace LoginRadiusSDK.V2.Api.Advanced
{
public class MultiFactorAuthenticationApi : LoginRadiusResource
{
/// <summary>
/// This API is used to configure the Multi-factor authentication after login by using the access token when MFA is set as optional on the LoginRadius site.
/// </summary>
/// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
/// <param name="smsTemplate2FA">SMS Template Name</param>
/// <returns>Response containing Definition of Complete Multi-Factor Authentication Settings data</returns>
/// 5.7
public async Task<ApiResponse<MultiFactorAuthenticationSettingsResponse>> MFAConfigureByAccessToken(string accessToken, string smsTemplate2FA = null)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
if (!string.IsNullOrWhiteSpace(smsTemplate2FA))
{
queryParameters.Add("smsTemplate2FA", smsTemplate2FA);
}
var resourcePath = "identity/v2/auth/account/2fa";
return await ConfigureAndExecute<MultiFactorAuthenticationSettingsResponse>(HttpMethod.GET, resourcePath, queryParameters, null);
}
/// <summary>
/// This API is used to trigger the Multi-factor authentication settings after login for secure actions
/// </summary>
/// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
/// <param name="multiFactorAuthModelWithLockout">Model Class containing Definition of payload for MultiFactorAuthModel With Lockout API</param>
/// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
/// <returns>Response containing Definition for Complete profile data</returns>
/// 5.9
public async Task<ApiResponse<Identity>> MFAUpdateSetting(string accessToken, MultiFactorAuthModelWithLockout multiFactorAuthModelWithLockout,
string fields = "")
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
if (multiFactorAuthModelWithLockout == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(multiFactorAuthModelWithLockout));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
if (!string.IsNullOrWhiteSpace(fields))
{
queryParameters.Add("fields", fields);
}
var resourcePath = "identity/v2/auth/account/2fa/verification/otp";
return await ConfigureAndExecute<Identity>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(multiFactorAuthModelWithLockout));
}
/// <summary>
/// This API is used to Enable Multi-factor authentication by access token on user login
/// </summary>
/// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
/// <param name="multiFactorAuthModelByGoogleAuthenticatorCode">Model Class containing Definition of payload for MultiFactorAuthModel By GoogleAuthenticator Code API</param>
/// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
/// <param name="smsTemplate">SMS Template name</param>
/// <returns>Response containing Definition for Complete profile data</returns>
/// 5.10
public async Task<ApiResponse<Identity>> MFAUpdateByAccessToken(string accessToken, MultiFactorAuthModelByGoogleAuthenticatorCode multiFactorAuthModelByGoogleAuthenticatorCode,
string fields = "", string smsTemplate = null)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
if (multiFactorAuthModelByGoogleAuthenticatorCode == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(multiFactorAuthModelByGoogleAuthenticatorCode));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
if (!string.IsNullOrWhiteSpace(fields))
{
queryParameters.Add("fields", fields);
}
if (!string.IsNullOrWhiteSpace(smsTemplate))
{
queryParameters.Add("smsTemplate", smsTemplate);
}
var resourcePath = "identity/v2/auth/account/2fa/verification/googleauthenticatorcode";
return await ConfigureAndExecute<Identity>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(multiFactorAuthModelByGoogleAuthenticatorCode));
}
/// <summary>
/// This API is used to update the Multi-factor authentication phone number by sending the verification OTP to the provided phone number
/// </summary>
/// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
/// <param name="phoneNo2FA">Phone Number For 2FA</param>
/// <param name="smsTemplate2FA">SMS Template Name</param>
/// <returns>Response containing Definition for Complete SMS data</returns>
/// 5.11
public async Task<ApiResponse<SMSResponseData>> MFAUpdatePhoneNumberByToken(string accessToken, string phoneNo2FA,
string smsTemplate2FA = null)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
if (string.IsNullOrWhiteSpace(phoneNo2FA))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phoneNo2FA));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
if (!string.IsNullOrWhiteSpace(smsTemplate2FA))
{
queryParameters.Add("smsTemplate2FA", smsTemplate2FA);
}
var bodyParameters = new BodyParameters
{
{ "phoneNo2FA", phoneNo2FA }
};
var resourcePath = "identity/v2/auth/account/2fa";
return await ConfigureAndExecute<SMSResponseData>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API Resets the Google Authenticator configurations on a given account via the access token
/// </summary>
/// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
/// <param name="googleAuthenticator">boolean type value,Enable google Authenticator Code.</param>
/// <returns>Response containing Definition of Delete Request</returns>
/// 5.12.1
public async Task<ApiResponse<DeleteResponse>> MFAResetGoogleAuthByToken(string accessToken, bool googleAuthenticator)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
var bodyParameters = new BodyParameters
{
{ "googleauthenticator", googleAuthenticator }
};
var resourcePath = "identity/v2/auth/account/2fa/authenticator";
return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API resets the SMS Authenticator configurations on a given account via the access token.
/// </summary>
/// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
/// <param name="otpAuthenticator">Pass 'otpauthenticator' to remove SMS Authenticator</param>
/// <returns>Response containing Definition of Delete Request</returns>
/// 5.12.2
public async Task<ApiResponse<DeleteResponse>> MFAResetSMSAuthByToken(string accessToken, bool otpAuthenticator)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
var bodyParameters = new BodyParameters
{
{ "otpauthenticator", otpAuthenticator }
};
var resourcePath = "identity/v2/auth/account/2fa/authenticator";
return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API is used to get a set of backup codes via access token to allow the user login on a site that has Multi-factor Authentication enabled in the event that the user does not have a secondary factor available. We generate 10 codes, each code can only be consumed once. If any user attempts to go over the number of invalid login attempts configured in the Dashboard then the account gets blocked automatically
/// </summary>
/// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
/// <returns>Response containing Definition of Complete Backup Code data</returns>
/// 5.13
public async Task<ApiResponse<BackupCodeResponse>> MFABackupCodeByAccessToken(string accessToken)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
var resourcePath = "identity/v2/auth/account/2fa/backupcode";
return await ConfigureAndExecute<BackupCodeResponse>(HttpMethod.GET, resourcePath, queryParameters, null);
}
/// <summary>
/// API is used to reset the backup codes on a given account via the access token. This API call will generate 10 new codes, each code can only be consumed once
/// </summary>
/// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
/// <returns>Response containing Definition of Complete Backup Code data</returns>
/// 5.14
public async Task<ApiResponse<BackupCodeResponse>> MFAResetBackupCodeByAccessToken(string accessToken)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
var resourcePath = "identity/v2/auth/account/2fa/backupcode/reset";
return await ConfigureAndExecute<BackupCodeResponse>(HttpMethod.GET, resourcePath, queryParameters, null);
}
/// <summary>
/// This API is created to send the OTP to the email if email OTP authenticator is enabled in app's MFA configuration.
/// </summary>
/// <param name="accessToken">access_token</param>
/// <param name="emailId">EmailId</param>
/// <param name="emailTemplate2FA">EmailTemplate2FA</param>
/// <returns>Response containing Definition of Complete Validation data</returns>
/// 5.17
public async Task<ApiResponse<PostResponse>> MFAEmailOtpByAccessToken(string accessToken, string emailId,
string emailTemplate2FA = null)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
if (string.IsNullOrWhiteSpace(emailId))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(emailId));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "emailId", emailId }
};
if (!string.IsNullOrWhiteSpace(emailTemplate2FA))
{
queryParameters.Add("emailTemplate2FA", emailTemplate2FA);
}
var resourcePath = "identity/v2/auth/account/2fa/otp/email";
return await ConfigureAndExecute<PostResponse>(HttpMethod.GET, resourcePath, queryParameters, null);
}
/// <summary>
/// This API is used to set up MFA Email OTP authenticator on profile after login.
/// </summary>
/// <param name="accessToken">access_token</param>
/// <param name="multiFactorAuthModelByEmailOtpWithLockout">payload</param>
/// <returns>Response containing Definition for Complete profile data</returns>
/// 5.18
public async Task<ApiResponse<Identity>> MFAValidateEmailOtpByAccessToken(string accessToken, MultiFactorAuthModelByEmailOtpWithLockout multiFactorAuthModelByEmailOtpWithLockout)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
if (multiFactorAuthModelByEmailOtpWithLockout == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(multiFactorAuthModelByEmailOtpWithLockout));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
var resourcePath = "identity/v2/auth/account/2fa/verification/otp/email";
return await ConfigureAndExecute<Identity>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(multiFactorAuthModelByEmailOtpWithLockout));
}
/// <summary>
/// This API is used to reset the Email OTP Authenticator settings for an MFA-enabled user
/// </summary>
/// <param name="accessToken">access_token</param>
/// <returns>Response containing Definition of Delete Request</returns>
/// 5.19
public async Task<ApiResponse<DeleteResponse>> MFAResetEmailOtpAuthenticatorByAccessToken(string accessToken)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
var resourcePath = "identity/v2/auth/account/2fa/authenticator/otp/email";
return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, null);
}
/// <summary>
/// This API is used to set up MFA Security Question authenticator on profile after login.
/// </summary>
/// <param name="accessToken">access_token</param>
/// <param name="securityQuestionAnswerModelByAccessToken">payload</param>
/// <returns>Response containing Definition of Complete Validation data</returns>
/// 5.20
public async Task<ApiResponse<PostResponse>> MFASecurityQuestionAnswerByAccessToken(string accessToken, SecurityQuestionAnswerModelByAccessToken securityQuestionAnswerModelByAccessToken)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
if (securityQuestionAnswerModelByAccessToken == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(securityQuestionAnswerModelByAccessToken));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
var resourcePath = "identity/v2/auth/account/2fa/securityquestionanswer";
return await ConfigureAndExecute<PostResponse>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(securityQuestionAnswerModelByAccessToken));
}
/// <summary>
/// This API is used to Reset MFA Security Question Authenticator By Access Token
/// </summary>
/// <param name="accessToken">access_token</param>
/// <returns>Response containing Definition of Delete Request</returns>
/// 5.21
public async Task<ApiResponse<DeleteResponse>> MFAResetSecurityQuestionAuthenticatorByAccessToken(string accessToken)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
var resourcePath = "identity/v2/auth/account/2fa/authenticator/securityquestionanswer";
return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, null);
}
/// <summary>
/// This API can be used to login by emailid on a Multi-factor authentication enabled LoginRadius site.
/// </summary>
/// <param name="email">user's email</param>
/// <param name="password">Password for the email</param>
/// <param name="emailTemplate">Email template name</param>
/// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
/// <param name="loginUrl">Url where the user is logging from</param>
/// <param name="smsTemplate">SMS Template name</param>
/// <param name="smsTemplate2FA">SMS Template Name</param>
/// <param name="verificationUrl">Email verification url</param>
/// <param name="emailTemplate2FA">2FA Email Template name</param>
/// <returns>Complete user UserProfile data</returns>
/// 9.8.1
public async Task<ApiResponse<MultiFactorAuthenticationResponse<Identity>>> MFALoginByEmail(string email, string password,
string emailTemplate = null, string fields = "", string loginUrl = null, string smsTemplate = null,
string smsTemplate2FA = null, string verificationUrl = null, string emailTemplate2FA = null)
{
if (string.IsNullOrWhiteSpace(email))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(email));
}
if (string.IsNullOrWhiteSpace(password))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(password));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
if (!string.IsNullOrWhiteSpace(emailTemplate))
{
queryParameters.Add("emailTemplate", emailTemplate);
}
if (!string.IsNullOrWhiteSpace(fields))
{
queryParameters.Add("fields", fields);
}
if (!string.IsNullOrWhiteSpace(loginUrl))
{
queryParameters.Add("loginUrl", loginUrl);
}
if (!string.IsNullOrWhiteSpace(smsTemplate))
{
queryParameters.Add("smsTemplate", smsTemplate);
}
if (!string.IsNullOrWhiteSpace(smsTemplate2FA))
{
queryParameters.Add("smsTemplate2FA", smsTemplate2FA);
}
if (!string.IsNullOrWhiteSpace(verificationUrl))
{
queryParameters.Add("verificationUrl", verificationUrl);
}
if (!string.IsNullOrWhiteSpace(emailTemplate2FA))
{
queryParameters.Add("emailTemplate2FA", emailTemplate2FA);
}
var bodyParameters = new BodyParameters
{
{ "email", email },
{ "password", password }
};
var resourcePath = "identity/v2/auth/login/2fa";
return await ConfigureAndExecute<MultiFactorAuthenticationResponse<Identity>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API can be used to login by username on a Multi-factor authentication enabled LoginRadius site.
/// </summary>
/// <param name="password">Password for the email</param>
/// <param name="username">Username of the user</param>
/// <param name="emailTemplate">Email template name</param>
/// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
/// <param name="loginUrl">Url where the user is logging from</param>
/// <param name="smsTemplate">SMS Template name</param>
/// <param name="smsTemplate2FA">SMS Template Name</param>
/// <param name="verificationUrl">Email verification url</param>
/// <param name="emailTemplate2FA">2FA Email Template name</param>
/// <returns>Complete user UserProfile data</returns>
/// 9.8.2
public async Task<ApiResponse<MultiFactorAuthenticationResponse<Identity>>> MFALoginByUserName(string password, string username,
string emailTemplate = null, string fields = "", string loginUrl = null, string smsTemplate = null,
string smsTemplate2FA = null, string verificationUrl = null, string emailTemplate2FA = null)
{
if (string.IsNullOrWhiteSpace(password))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(password));
}
if (string.IsNullOrWhiteSpace(username))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(username));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
if (!string.IsNullOrWhiteSpace(emailTemplate))
{
queryParameters.Add("emailTemplate", emailTemplate);
}
if (!string.IsNullOrWhiteSpace(fields))
{
queryParameters.Add("fields", fields);
}
if (!string.IsNullOrWhiteSpace(loginUrl))
{
queryParameters.Add("loginUrl", loginUrl);
}
if (!string.IsNullOrWhiteSpace(smsTemplate))
{
queryParameters.Add("smsTemplate", smsTemplate);
}
if (!string.IsNullOrWhiteSpace(smsTemplate2FA))
{
queryParameters.Add("smsTemplate2FA", smsTemplate2FA);
}
if (!string.IsNullOrWhiteSpace(verificationUrl))
{
queryParameters.Add("verificationUrl", verificationUrl);
}
if (!string.IsNullOrWhiteSpace(emailTemplate2FA))
{
queryParameters.Add("emailTemplate2FA", emailTemplate2FA);
}
var bodyParameters = new BodyParameters
{
{ "password", password },
{ "username", username }
};
var resourcePath = "identity/v2/auth/login/2fa";
return await ConfigureAndExecute<MultiFactorAuthenticationResponse<Identity>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API can be used to login by Phone on a Multi-factor authentication enabled LoginRadius site.
/// </summary>
/// <param name="password">Password for the email</param>
/// <param name="phone">New Phone Number</param>
/// <param name="emailTemplate">Email template name</param>
/// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
/// <param name="loginUrl">Url where the user is logging from</param>
/// <param name="smsTemplate">SMS Template name</param>
/// <param name="smsTemplate2FA">SMS Template Name</param>
/// <param name="verificationUrl">Email verification url</param>
/// <param name="emailTemplate2FA">2FA Email Template name</param>
/// <returns>Complete user UserProfile data</returns>
/// 9.8.3
public async Task<ApiResponse<MultiFactorAuthenticationResponse<Identity>>> MFALoginByPhone(string password, string phone,
string emailTemplate = null, string fields = "", string loginUrl = null, string smsTemplate = null,
string smsTemplate2FA = null, string verificationUrl = null, string emailTemplate2FA = null)
{
if (string.IsNullOrWhiteSpace(password))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(password));
}
if (string.IsNullOrWhiteSpace(phone))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phone));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
if (!string.IsNullOrWhiteSpace(emailTemplate))
{
queryParameters.Add("emailTemplate", emailTemplate);
}
if (!string.IsNullOrWhiteSpace(fields))
{
queryParameters.Add("fields", fields);
}
if (!string.IsNullOrWhiteSpace(loginUrl))
{
queryParameters.Add("loginUrl", loginUrl);
}
if (!string.IsNullOrWhiteSpace(smsTemplate))
{
queryParameters.Add("smsTemplate", smsTemplate);
}
if (!string.IsNullOrWhiteSpace(smsTemplate2FA))
{
queryParameters.Add("smsTemplate2FA", smsTemplate2FA);
}
if (!string.IsNullOrWhiteSpace(verificationUrl))
{
queryParameters.Add("verificationUrl", verificationUrl);
}
if (!string.IsNullOrWhiteSpace(emailTemplate2FA))
{
queryParameters.Add("emailTemplate2FA", emailTemplate2FA);
}
var bodyParameters = new BodyParameters
{
{ "password", password },
{ "phone", phone }
};
var resourcePath = "identity/v2/auth/login/2fa";
return await ConfigureAndExecute<MultiFactorAuthenticationResponse<Identity>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API is used to login via Multi-factor authentication by passing the One Time Password received via SMS
/// </summary>
/// <param name="multiFactorAuthModelWithLockout">Model Class containing Definition of payload for MultiFactorAuthModel With Lockout API</param>
/// <param name="secondFactorAuthenticationToken">A Uniquely generated MFA identifier token after successful authentication</param>
/// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
/// <param name="smsTemplate2FA">SMS Template Name</param>
/// <param name="rbaBrowserEmailTemplate"></param>
/// <param name="rbaCityEmailTemplate"></param>
/// <param name="rbaCountryEmailTemplate"></param>
/// <param name="rbaIpEmailTemplate"></param>
/// <returns>Complete user UserProfile data</returns>
/// 9.12
public async Task<ApiResponse<AccessToken<Identity>>> MFAValidateOTPByPhone(MultiFactorAuthModelWithLockout multiFactorAuthModelWithLockout, string secondFactorAuthenticationToken,
string fields = "",string smsTemplate2FA = null, string rbaBrowserEmailTemplate = null, string rbaCityEmailTemplate = null, string rbaCountryEmailTemplate = null, string rbaIpEmailTemplate = null)
{
if (multiFactorAuthModelWithLockout == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(multiFactorAuthModelWithLockout));
}
if (string.IsNullOrWhiteSpace(secondFactorAuthenticationToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(secondFactorAuthenticationToken));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "secondFactorAuthenticationToken", secondFactorAuthenticationToken }
};
if (!string.IsNullOrWhiteSpace(fields))
{
queryParameters.Add("fields", fields);
}
if (!string.IsNullOrWhiteSpace(smsTemplate2FA))
{
queryParameters.Add("smsTemplate2FA", smsTemplate2FA);
}
if (!string.IsNullOrWhiteSpace(rbaBrowserEmailTemplate))
{
queryParameters.Add("rbaBrowserEmailTemplate", rbaBrowserEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaCityEmailTemplate))
{
queryParameters.Add("rbaCityEmailTemplate", rbaCityEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaCountryEmailTemplate))
{
queryParameters.Add("rbaCountryEmailTemplate", rbaCountryEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaIpEmailTemplate))
{
queryParameters.Add("rbaIpEmailTemplate", rbaIpEmailTemplate);
}
var resourcePath = "identity/v2/auth/login/2fa/verification/otp";
return await ConfigureAndExecute<AccessToken<Identity>>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(multiFactorAuthModelWithLockout));
}
/// <summary>
/// This API is used to login via Multi-factor-authentication by passing the google authenticator code.
/// </summary>
/// <param name="googleAuthenticatorCode">The code generated by google authenticator app after scanning QR code</param>
/// <param name="secondFactorAuthenticationToken">SecondFactorAuthenticationToken</param>
/// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
/// <param name="rbaBrowserEmailTemplate">RbaBrowserEmailTemplate</param>
/// <param name="rbaCityEmailTemplate">RbaCityEmailTemplate</param>
/// <param name="rbaCountryEmailTemplate">RbaCountryEmailTemplate</param>
/// <param name="rbaIpEmailTemplate">RbaIpEmailTemplate</param>
/// <returns>Complete user UserProfile data</returns>
/// 9.13
public async Task<ApiResponse<AccessToken<Identity>>> MFAValidateGoogleAuthCode(string googleAuthenticatorCode, string secondFactorAuthenticationToken,
string fields = "", string rbaBrowserEmailTemplate = null, string rbaCityEmailTemplate = null, string rbaCountryEmailTemplate = null, string rbaIpEmailTemplate = null)
{
if (string.IsNullOrWhiteSpace(googleAuthenticatorCode))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(googleAuthenticatorCode));
}
if (string.IsNullOrWhiteSpace(secondFactorAuthenticationToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(secondFactorAuthenticationToken));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "secondFactorAuthenticationToken", secondFactorAuthenticationToken }
};
if (!string.IsNullOrWhiteSpace(fields))
{
queryParameters.Add("fields", fields);
}
if (!string.IsNullOrWhiteSpace(rbaBrowserEmailTemplate))
{
queryParameters.Add("rbaBrowserEmailTemplate", rbaBrowserEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaCityEmailTemplate))
{
queryParameters.Add("rbaCityEmailTemplate", rbaCityEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaCountryEmailTemplate))
{
queryParameters.Add("rbaCountryEmailTemplate", rbaCountryEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaIpEmailTemplate))
{
queryParameters.Add("rbaIpEmailTemplate", rbaIpEmailTemplate);
}
var bodyParameters = new BodyParameters
{
{ "googleAuthenticatorCode", googleAuthenticatorCode }
};
var resourcePath = "identity/v2/auth/login/2fa/verification/googleauthenticatorcode";
return await ConfigureAndExecute<AccessToken<Identity>>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API is used to validate the backup code provided by the user and if valid, we return an access token allowing the user to login incases where Multi-factor authentication (MFA) is enabled and the secondary factor is unavailable. When a user initially downloads the Backup codes, We generate 10 codes, each code can only be consumed once. if any user attempts to go over the number of invalid login attempts configured in the Dashboard then the account gets blocked automatically
/// </summary>
/// <param name="multiFactorAuthModelByBackupCode">Model Class containing Definition of payload for MultiFactorAuth By BackupCode API</param>
/// <param name="secondFactorAuthenticationToken">A Uniquely generated MFA identifier token after successful authentication</param>
/// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
/// <param name="rbaBrowserEmailTemplate"></param>
/// <param name="rbaCityEmailTemplate"></param>
/// <param name="rbaCountryEmailTemplate"></param>
/// <param name="rbaIpEmailTemplate"></param>
/// <returns>Complete user UserProfile data</returns>
/// 9.14
public async Task<ApiResponse<AccessToken<Identity>>> MFAValidateBackupCode(MultiFactorAuthModelByBackupCode multiFactorAuthModelByBackupCode, string secondFactorAuthenticationToken,
string fields = "", string rbaBrowserEmailTemplate = null, string rbaCityEmailTemplate = null, string rbaCountryEmailTemplate = null, string rbaIpEmailTemplate = null)
{
if (multiFactorAuthModelByBackupCode == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(multiFactorAuthModelByBackupCode));
}
if (string.IsNullOrWhiteSpace(secondFactorAuthenticationToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(secondFactorAuthenticationToken));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "secondFactorAuthenticationToken", secondFactorAuthenticationToken }
};
if (!string.IsNullOrWhiteSpace(fields))
{
queryParameters.Add("fields", fields);
}
if (!string.IsNullOrWhiteSpace(rbaBrowserEmailTemplate))
{
queryParameters.Add("rbaBrowserEmailTemplate", rbaBrowserEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaCityEmailTemplate))
{
queryParameters.Add("rbaCityEmailTemplate", rbaCityEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaCountryEmailTemplate))
{
queryParameters.Add("rbaCountryEmailTemplate", rbaCountryEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaIpEmailTemplate))
{
queryParameters.Add("rbaIpEmailTemplate", rbaIpEmailTemplate);
}
var resourcePath = "identity/v2/auth/login/2fa/verification/backupcode";
return await ConfigureAndExecute<AccessToken<Identity>>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(multiFactorAuthModelByBackupCode));
}
/// <summary>
/// This API is used to update (if configured) the phone number used for Multi-factor authentication by sending the verification OTP to the provided phone number
/// </summary>
/// <param name="phoneNo2FA">Phone Number For 2FA</param>
/// <param name="secondFactorAuthenticationToken">A Uniquely generated MFA identifier token after successful authentication</param>
/// <param name="smsTemplate2FA">SMS Template Name</param>
/// <returns>Response containing Definition for Complete SMS data</returns>
/// 9.16
public async Task<ApiResponse<SMSResponseData>> MFAUpdatePhoneNumber(string phoneNo2FA, string secondFactorAuthenticationToken,
string smsTemplate2FA = null)
{
if (string.IsNullOrWhiteSpace(phoneNo2FA))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phoneNo2FA));
}
if (string.IsNullOrWhiteSpace(secondFactorAuthenticationToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(secondFactorAuthenticationToken));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "secondFactorAuthenticationToken", secondFactorAuthenticationToken }
};
if (!string.IsNullOrWhiteSpace(smsTemplate2FA))
{
queryParameters.Add("smsTemplate2FA", smsTemplate2FA);
}
var bodyParameters = new BodyParameters
{
{ "phoneNo2FA", phoneNo2FA }
};
var resourcePath = "identity/v2/auth/login/2fa";
return await ConfigureAndExecute<SMSResponseData>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API is used to resending the verification OTP to the provided phone number
/// </summary>
/// <param name="secondFactorAuthenticationToken">A Uniquely generated MFA identifier token after successful authentication</param>
/// <param name="smsTemplate2FA">SMS Template Name</param>
/// <returns>Response containing Definition for Complete SMS data</returns>
/// 9.17
public async Task<ApiResponse<SMSResponseData>> MFAResendOTP(string secondFactorAuthenticationToken, string smsTemplate2FA = null)
{
if (string.IsNullOrWhiteSpace(secondFactorAuthenticationToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(secondFactorAuthenticationToken));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "secondFactorAuthenticationToken", secondFactorAuthenticationToken }
};
if (!string.IsNullOrWhiteSpace(smsTemplate2FA))
{
queryParameters.Add("smsTemplate2FA", smsTemplate2FA);
}
var resourcePath = "identity/v2/auth/login/2fa/resend";
return await ConfigureAndExecute<SMSResponseData>(HttpMethod.GET, resourcePath, queryParameters, null);
}
/// <summary>
/// An API designed to send the MFA Email OTP to the email.
/// </summary>
/// <param name="emailIdModel">payload</param>
/// <param name="secondFactorAuthenticationToken">SecondFactorAuthenticationToken</param>
/// <param name="emailTemplate2FA">EmailTemplate2FA</param>
/// <returns>Response containing Definition of Complete Validation data</returns>
/// 9.18
public async Task<ApiResponse<PostResponse>> MFAEmailOTP(EmailIdModel emailIdModel, string secondFactorAuthenticationToken,
string emailTemplate2FA = null)
{
if (emailIdModel == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(emailIdModel));
}
if (string.IsNullOrWhiteSpace(secondFactorAuthenticationToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(secondFactorAuthenticationToken));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "secondFactorAuthenticationToken", secondFactorAuthenticationToken }
};
if (!string.IsNullOrWhiteSpace(emailTemplate2FA))
{
queryParameters.Add("emailTemplate2FA", emailTemplate2FA);
}
var resourcePath = "identity/v2/auth/login/2fa/otp/email";
return await ConfigureAndExecute<PostResponse>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(emailIdModel));
}
/// <summary>
/// This API is used to Verify MFA Email OTP by MFA Token
/// </summary>
/// <param name="multiFactorAuthModelByEmailOtp">payload</param>
/// <param name="secondFactorAuthenticationToken">SecondFactorAuthenticationToken</param>
/// <param name="rbaBrowserEmailTemplate">RbaBrowserEmailTemplate</param>
/// <param name="rbaCityEmailTemplate">RbaCityEmailTemplate</param>
/// <param name="rbaCountryEmailTemplate">RbaCountryEmailTemplate</param>
/// <param name="rbaIpEmailTemplate">RbaIpEmailTemplate</param>
/// <returns>Response Containing Access Token and Complete Profile Data</returns>
/// 9.25
public async Task<ApiResponse<AccessToken<UserProfile>>> MFAValidateEmailOtp(MultiFactorAuthModelByEmailOtp multiFactorAuthModelByEmailOtp, string secondFactorAuthenticationToken,
string rbaBrowserEmailTemplate = null, string rbaCityEmailTemplate = null, string rbaCountryEmailTemplate = null, string rbaIpEmailTemplate = null)
{
if (multiFactorAuthModelByEmailOtp == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(multiFactorAuthModelByEmailOtp));
}
if (string.IsNullOrWhiteSpace(secondFactorAuthenticationToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(secondFactorAuthenticationToken));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "secondFactorAuthenticationToken", secondFactorAuthenticationToken }
};
if (!string.IsNullOrWhiteSpace(rbaBrowserEmailTemplate))
{
queryParameters.Add("rbaBrowserEmailTemplate", rbaBrowserEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaCityEmailTemplate))
{
queryParameters.Add("rbaCityEmailTemplate", rbaCityEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaCountryEmailTemplate))
{
queryParameters.Add("rbaCountryEmailTemplate", rbaCountryEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaIpEmailTemplate))
{
queryParameters.Add("rbaIpEmailTemplate", rbaIpEmailTemplate);
}
var resourcePath = "identity/v2/auth/login/2fa/verification/otp/email";
return await ConfigureAndExecute<AccessToken<UserProfile>>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(multiFactorAuthModelByEmailOtp));
}
/// <summary>
/// This API is used to set the security questions on the profile with the MFA token when MFA flow is required.
/// </summary>
/// <param name="securityQuestionAnswerUpdateModel">payload</param>
/// <param name="secondFactorAuthenticationToken">SecondFactorAuthenticationToken</param>
/// <returns>Response Containing Access Token and Complete Profile Data</returns>
/// 9.26
public async Task<ApiResponse<AccessToken<UserProfile>>> MFASecurityQuestionAnswer(SecurityQuestionAnswerUpdateModel securityQuestionAnswerUpdateModel, string secondFactorAuthenticationToken)
{
if (securityQuestionAnswerUpdateModel == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(securityQuestionAnswerUpdateModel));
}
if (string.IsNullOrWhiteSpace(secondFactorAuthenticationToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(secondFactorAuthenticationToken));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "secondFactorAuthenticationToken", secondFactorAuthenticationToken }
};
var resourcePath = "identity/v2/auth/login/2fa/securityquestionanswer";
return await ConfigureAndExecute<AccessToken<UserProfile>>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(securityQuestionAnswerUpdateModel));
}
/// <summary>
/// This API is used to resending the verification OTP to the provided phone number
/// </summary>
/// <param name="securityQuestionAnswerUpdateModel">payload</param>
/// <param name="secondFactorAuthenticationToken">SecondFactorAuthenticationToken</param>
/// <param name="rbaBrowserEmailTemplate">RbaBrowserEmailTemplate</param>
/// <param name="rbaCityEmailTemplate">RbaCityEmailTemplate</param>
/// <param name="rbaCountryEmailTemplate">RbaCountryEmailTemplate</param>
/// <param name="rbaIpEmailTemplate">RbaIpEmailTemplate</param>
/// <returns>Response Containing Access Token and Complete Profile Data</returns>
/// 9.27
public async Task<ApiResponse<AccessToken<UserProfile>>> MFASecurityQuestionAnswerVerification(SecurityQuestionAnswerUpdateModel securityQuestionAnswerUpdateModel, string secondFactorAuthenticationToken,
string rbaBrowserEmailTemplate = null, string rbaCityEmailTemplate = null, string rbaCountryEmailTemplate = null, string rbaIpEmailTemplate = null)
{
if (securityQuestionAnswerUpdateModel == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(securityQuestionAnswerUpdateModel));
}
if (string.IsNullOrWhiteSpace(secondFactorAuthenticationToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(secondFactorAuthenticationToken));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "secondFactorAuthenticationToken", secondFactorAuthenticationToken }
};
if (!string.IsNullOrWhiteSpace(rbaBrowserEmailTemplate))
{
queryParameters.Add("rbaBrowserEmailTemplate", rbaBrowserEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaCityEmailTemplate))
{
queryParameters.Add("rbaCityEmailTemplate", rbaCityEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaCountryEmailTemplate))
{
queryParameters.Add("rbaCountryEmailTemplate", rbaCountryEmailTemplate);
}
if (!string.IsNullOrWhiteSpace(rbaIpEmailTemplate))
{
queryParameters.Add("rbaIpEmailTemplate", rbaIpEmailTemplate);
}
var resourcePath = "identity/v2/auth/login/2fa/verification/securityquestionanswer";
return await ConfigureAndExecute<AccessToken<UserProfile>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(securityQuestionAnswerUpdateModel));
}
/// <summary>
/// This API resets the SMS Authenticator configurations on a given account via the UID.
/// </summary>
/// <param name="otpAuthenticator">Pass 'otpauthenticator' to remove SMS Authenticator</param>
/// <param name="uid">UID, the unified identifier for each user account</param>
/// <returns>Response containing Definition of Delete Request</returns>
/// 18.21.1
public async Task<ApiResponse<DeleteResponse>> MFAResetSMSAuthenticatorByUid(bool otpAuthenticator, string uid)
{
if (string.IsNullOrWhiteSpace(uid))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] },
{ "uid", uid }
};
var bodyParameters = new BodyParameters
{
{ "otpauthenticator", otpAuthenticator }
};
var resourcePath = "identity/v2/manage/account/2fa/authenticator";
return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API resets the Google Authenticator configurations on a given account via the UID.
/// </summary>
/// <param name="googleAuthenticator">boolean type value,Enable google Authenticator Code.</param>
/// <param name="uid">UID, the unified identifier for each user account</param>
/// <returns>Response containing Definition of Delete Request</returns>
/// 18.21.2
public async Task<ApiResponse<DeleteResponse>> MFAResetGoogleAuthenticatorByUid(bool googleAuthenticator, string uid)
{
if (string.IsNullOrWhiteSpace(uid))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] },
{ "uid", uid }
};
var bodyParameters = new BodyParameters
{
{ "googleauthenticator", googleAuthenticator }
};
var resourcePath = "identity/v2/manage/account/2fa/authenticator";
return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API is used to reset the backup codes on a given account via the UID. This API call will generate 10 new codes, each code can only be consumed once.
/// </summary>
/// <param name="uid">UID, the unified identifier for each user account</param>
/// <returns>Response containing Definition of Complete Backup Code data</returns>
/// 18.25
public async Task<ApiResponse<BackupCodeResponse>> MFABackupCodeByUid(string uid)
{
if (string.IsNullOrWhiteSpace(uid))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] },
{ "uid", uid }
};
var resourcePath = "identity/v2/manage/account/2fa/backupcode";
return await ConfigureAndExecute<BackupCodeResponse>(HttpMethod.GET, resourcePath, queryParameters, null);
}
/// <summary>
/// This API is used to reset the backup codes on a given account via the UID. This API call will generate 10 new codes, each code can only be consumed once.
/// </summary>
/// <param name="uid">UID, the unified identifier for each user account</param>
/// <returns>Response containing Definition of Complete Backup Code data</returns>
/// 18.26
public async Task<ApiResponse<BackupCodeResponse>> MFAResetBackupCodeByUid(string uid)
{
if (string.IsNullOrWhiteSpace(uid))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] },
{ "uid", uid }
};
var resourcePath = "identity/v2/manage/account/2fa/backupcode/reset";
return await ConfigureAndExecute<BackupCodeResponse>(HttpMethod.GET, resourcePath, queryParameters, null);
}
/// <summary>
/// This API is used to reset the Email OTP Authenticator settings for an MFA-enabled user.
/// </summary>
/// <param name="uid">UID, the unified identifier for each user account</param>
/// <returns>Response containing Definition of Delete Request</returns>
/// 18.42
public async Task<ApiResponse<DeleteResponse>> MFAResetEmailOtpAuthenticatorByUid(string uid)
{
if (string.IsNullOrWhiteSpace(uid))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] },
{ "uid", uid }
};
var resourcePath = "identity/v2/manage/account/2fa/authenticator/otp/email";
return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, null);
}
/// <summary>
/// This API is used to reset the Security Question Authenticator settings for an MFA-enabled user.
/// </summary>
/// <param name="uid">UID, the unified identifier for each user account</param>
/// <returns>Response containing Definition of Delete Request</returns>
/// 18.43
public async Task<ApiResponse<DeleteResponse>> MFAResetSecurityQuestionAuthenticatorByUid(string uid)
{
if (string.IsNullOrWhiteSpace(uid))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] },
{ "uid", uid }
};
var resourcePath = "identity/v2/manage/account/2fa/authenticator/securityquestionanswer";
return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, null);
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.EC2.Model
{
///<summary>
///Specifies additional launch instance information.
///</summary>
[XmlRootAttribute(IsNullable = false)]
public class LaunchSpecification
{
private string imageIdField;
private string keyNameField;
private List<string> securityGroupField;
private List<string> securityGroupIdField;
private string userDataField;
private string addressingTypeField;
private string instanceTypeField;
private Placement placementField;
private string kernelIdField;
private string ramdiskIdField;
private List<BlockDeviceMapping> blockDeviceMappingField;
private MonitoringSpecification monitoringField;
private string subnetIdField;
private List<InstanceNetworkInterfaceSpecification> networkInterfaceSetField;
private IAMInstanceProfile instanceProfileField;
private bool? ebsOptimizedField;
/// <summary>
/// The AMI ID.
/// </summary>
[XmlElementAttribute(ElementName = "ImageId")]
public string ImageId
{
get { return this.imageIdField; }
set { this.imageIdField = value; }
}
/// <summary>
/// Sets the AMI ID.
/// </summary>
/// <param name="imageId">The AMI ID.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithImageId(string imageId)
{
this.imageIdField = imageId;
return this;
}
/// <summary>
/// Checks if ImageId property is set
/// </summary>
/// <returns>true if ImageId property is set</returns>
public bool IsSetImageId()
{
return this.imageIdField != null;
}
/// <summary>
/// The name of the key pair.
/// </summary>
[XmlElementAttribute(ElementName = "KeyName")]
public string KeyName
{
get { return this.keyNameField; }
set { this.keyNameField = value; }
}
/// <summary>
/// Sets the name of the key pair.
/// </summary>
/// <param name="keyName">The name of the key pair.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithKeyName(string keyName)
{
this.keyNameField = keyName;
return this;
}
/// <summary>
/// Checks if KeyName property is set
/// </summary>
/// <returns>true if KeyName property is set</returns>
public bool IsSetKeyName()
{
return this.keyNameField != null;
}
/// <summary>
/// The Security Groups to associate the launched instance with.
/// </summary>
[XmlElementAttribute(ElementName = "SecurityGroup")]
public List<string> SecurityGroup
{
get
{
if (this.securityGroupField == null)
{
this.securityGroupField = new List<string>();
}
return this.securityGroupField;
}
set { this.securityGroupField = value; }
}
/// <summary>
/// Sets the Security Groups to associate the launched instance with.
/// </summary>
/// <param name="list">The Security Groups to associate the launched
/// instance with.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithSecurityGroup(params string[] list)
{
foreach (string item in list)
{
SecurityGroup.Add(item);
}
return this;
}
/// <summary>
/// Checks if SecurityGroup property is set
/// </summary>
/// <returns>true if SecurityGroup property is set</returns>
public bool IsSetSecurityGroup()
{
return (SecurityGroup.Count > 0);
}
/// <summary>
/// IDs of the security groups.
/// </summary>
[XmlElementAttribute(ElementName = "SecurityGroupId")]
public List<string> SecurityGroupId
{
get
{
if (this.securityGroupIdField == null)
{
this.securityGroupIdField = new List<string>();
}
return this.securityGroupIdField;
}
set { this.securityGroupIdField = value; }
}
/// <summary>
/// Sets the IDs of the security groups.
/// </summary>
/// <param name="list">IDs of the security group.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithSecurityGroupId(params string[] list)
{
foreach (string item in list)
{
SecurityGroupId.Add(item);
}
return this;
}
/// <summary>
/// Checks if SecurityGroupId property is set
/// </summary>
/// <returns>true if SecurityGroupId property is set</returns>
public bool IsSetSecurityGroupId()
{
return (SecurityGroupId.Count > 0);
}
/// <summary>
/// MIME, Base64-encoded user data.
/// </summary>
[XmlElementAttribute(ElementName = "UserData")]
public string UserData
{
get { return this.userDataField; }
set { this.userDataField = value; }
}
/// <summary>
/// Sets the MIME, Base64-encoded user data.
/// </summary>
/// <param name="userData">MIME, Base64-encoded user data.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithUserData(string userData)
{
this.userDataField = userData;
return this;
}
/// <summary>
/// Checks if UserData property is set
/// </summary>
/// <returns>true if UserData property is set</returns>
public bool IsSetUserData()
{
return this.userDataField != null;
}
/// <summary>
/// Addressing type.
/// Deprecated.
/// </summary>
[XmlElementAttribute(ElementName = "AddressingType")]
public string AddressingType
{
get { return this.addressingTypeField; }
set { this.addressingTypeField = value; }
}
/// <summary>
/// Sets Addressing type.
/// </summary>
/// <param name="addressingType">Deprecated.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithAddressingType(string addressingType)
{
this.addressingTypeField = addressingType;
return this;
}
/// <summary>
/// Checks if AddressingType property is set
/// </summary>
/// <returns>true if AddressingType property is set</returns>
public bool IsSetAddressingType()
{
return this.addressingTypeField != null;
}
/// <summary>
/// The instance type.
/// Valid values are: m1.small | m1.medium | m1.large | m1.xlarge |
/// c1.medium | c1.xlarge | m2.2xlarge | m2.4xlarge.
/// Default: m1.small
/// </summary>
[XmlElementAttribute(ElementName = "InstanceType")]
public string InstanceType
{
get { return this.instanceTypeField; }
set { this.instanceTypeField = value; }
}
/// <summary>
/// Sets the instance type.
/// </summary>
/// <param name="instanceType">Specifies the instance type. Valid values are:
/// m1.small | m1.medium | m1.large | m1.xlarge |
/// c1.medium | c1.xlarge | m2.2xlarge | m2.4xlarge.
/// Default: m1.small</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithInstanceType(string instanceType)
{
this.instanceTypeField = instanceType;
return this;
}
/// <summary>
/// Checks if InstanceType property is set
/// </summary>
/// <returns>true if InstanceType property is set</returns>
public bool IsSetInstanceType()
{
return this.instanceTypeField != null;
}
/// <summary>
/// Placement constraints.
/// </summary>
[XmlElementAttribute(ElementName = "Placement")]
public Placement Placement
{
get { return this.placementField; }
set { this.placementField = value; }
}
/// <summary>
/// Sets the placement constraints.
/// </summary>
/// <param name="placement">Specifies the placement constraints.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithPlacement(Placement placement)
{
this.placementField = placement;
return this;
}
/// <summary>
/// Checks if Placement property is set
/// </summary>
/// <returns>true if Placement property is set</returns>
public bool IsSetPlacement()
{
return this.placementField != null;
}
/// <summary>
/// The ID of the kernel to select.
/// </summary>
[XmlElementAttribute(ElementName = "KernelId")]
public string KernelId
{
get { return this.kernelIdField; }
set { this.kernelIdField = value; }
}
/// <summary>
/// Sets the ID of the kernel to select.
/// </summary>
/// <param name="kernelId">The ID of the kernel to select.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithKernelId(string kernelId)
{
this.kernelIdField = kernelId;
return this;
}
/// <summary>
/// Checks if KernelId property is set
/// </summary>
/// <returns>true if KernelId property is set</returns>
public bool IsSetKernelId()
{
return this.kernelIdField != null;
}
/// <summary>
/// The ID of the RAM disk to select.
/// Some kernels require additional drivers at launch.
/// Check the kernel requirements for information on
/// whether you need to specify a RAM disk.
/// </summary>
[XmlElementAttribute(ElementName = "RamdiskId")]
public string RamdiskId
{
get { return this.ramdiskIdField; }
set { this.ramdiskIdField = value; }
}
/// <summary>
/// Sets the ID of the RAM disk to select.
/// </summary>
/// <param name="ramdiskId">The ID of the RAM disk to select. Some kernels
/// require additional drivers at launch. Check the kernel
/// requirements for information on whether you need to
/// specify a RAM disk.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithRamdiskId(string ramdiskId)
{
this.ramdiskIdField = ramdiskId;
return this;
}
/// <summary>
/// Checks if RamdiskId property is set
/// </summary>
/// <returns>true if RamdiskId property is set</returns>
public bool IsSetRamdiskId()
{
return this.ramdiskIdField != null;
}
/// <summary>
/// List of how block devices are exposed to the instance.
/// Each mapping is made up of a virtualName and a deviceName.
/// </summary>
[XmlElementAttribute(ElementName = "BlockDeviceMapping")]
public List<BlockDeviceMapping> BlockDeviceMapping
{
get
{
if (this.blockDeviceMappingField == null)
{
this.blockDeviceMappingField = new List<BlockDeviceMapping>();
}
return this.blockDeviceMappingField;
}
set { this.blockDeviceMappingField = value; }
}
/// <summary>
/// Sets the list of how block devices are exposed to the instance.
/// </summary>
/// <param name="list">Specifies how block devices are exposed to the
/// instance. Each mapping is made up of a virtualName
/// and a deviceName.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithBlockDeviceMapping(params BlockDeviceMapping[] list)
{
foreach (BlockDeviceMapping item in list)
{
BlockDeviceMapping.Add(item);
}
return this;
}
/// <summary>
/// Checks if BlockDeviceMapping property is set
/// </summary>
/// <returns>true if BlockDeviceMapping property is set</returns>
public bool IsSetBlockDeviceMapping()
{
return (BlockDeviceMapping.Count > 0);
}
/// <summary>
/// Whether to enable monitoring for the Spot Instance.
/// </summary>
[XmlElementAttribute(ElementName = "Monitoring")]
public MonitoringSpecification Monitoring
{
get { return this.monitoringField; }
set { this.monitoringField = value; }
}
/// <summary>
/// Sets whether to enable monitoring for the Spot Instance.
/// </summary>
/// <param name="monitoring">Specifies whether to enable monitoring for the Spot Instance.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithMonitoring(MonitoringSpecification monitoring)
{
this.monitoringField = monitoring;
return this;
}
/// <summary>
/// Checks if Monitoring property is set
/// </summary>
/// <returns>true if Monitoring property is set</returns>
public bool IsSetMonitoring()
{
return this.monitoringField != null;
}
/// <summary>
/// Amazon VPC subnet ID within which to launch the instance(s) for Amazon Virtual Private Cloud.
/// </summary>
[XmlElementAttribute(ElementName = "SubnetId")]
public string SubnetId
{
get { return this.subnetIdField; }
set { this.subnetIdField = value; }
}
/// <summary>
/// Sets the Amazon VPC subnet ID within which to launch the instance(s) for Amazon Virtual Private Cloud.
/// </summary>
/// <param name="subnetId">Specifies the Amazon VPC subnet ID within which to
/// launch the instance(s) for Amazon Virtual Private Cloud.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithSubnetId(string subnetId)
{
this.subnetIdField = subnetId;
return this;
}
/// <summary>
/// Checks if SubnetId property is set
/// </summary>
/// <returns>true if SubnetId property is set</returns>
public bool IsSetSubnetId()
{
return this.subnetIdField != null;
}
/// <summary>
/// List of Instance Network Interface Specifications.
/// </summary>
[XmlElementAttribute(ElementName = "InstanceNetworkInterfaceSpecification")]
public List<InstanceNetworkInterfaceSpecification> NetworkInterfaceSet
{
get
{
if (this.networkInterfaceSetField == null)
{
this.networkInterfaceSetField = new List<InstanceNetworkInterfaceSpecification>();
}
return this.networkInterfaceSetField;
}
set { this.networkInterfaceSetField = value; }
}
/// <summary>
/// Sets the list of Instance Network Interface Specifications.
/// </summary>
/// <param name="list">Collection of NetworkInterfaceSet</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithNetworkInterfaceSet(params InstanceNetworkInterfaceSpecification[] list)
{
foreach (InstanceNetworkInterfaceSpecification item in list)
{
NetworkInterfaceSet.Add(item);
}
return this;
}
/// <summary>
/// Checks if the NetworkInterfaceSet property is set
/// </summary>
/// <returns>true if the NetworkInterfaceSet is set</returns>
public bool IsSetNetworkInterfaceSet()
{
return (this.NetworkInterfaceSet.Count > 0);
}
/// <summary>
/// An Identity and Access Management Instance Profile to associate with the instance.
/// </summary>
[XmlElementAttribute(ElementName = "InstanceProfile")]
public IAMInstanceProfile InstanceProfile
{
get { return this.instanceProfileField; }
set { this.instanceProfileField = value; }
}
/// <summary>
/// Sets an Identity and Access Management Instance Profile to associate with the instance.
/// </summary>
/// <param name="instanceProfile">
/// An Identity and Access Management Instance Profile to associate with the instance.
/// </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithInstanceProfile(IAMInstanceProfile instanceProfile)
{
this.instanceProfileField = instanceProfile;
return this;
}
/// <summary>
/// Checks if the InstanceProfile property is set
/// </summary>
/// <returns>true if the InstanceProfile property is set</returns>
public bool IsSetInstanceProfile()
{
return this.instanceProfileField != null;
}
/// <summary>
/// Whether to use the EBS IOPS optimized option.
/// </summary>
[XmlElementAttribute(ElementName = "EbsOptimized")]
public bool EbsOptimized
{
get { return this.ebsOptimizedField.GetValueOrDefault(); }
set { this.ebsOptimizedField = value; }
}
/// <summary>
/// Sets whether to use the EBS IOPS optimized option.
/// </summary>
/// <param name="ebsOptimized">Specifies whether to use the EBS
/// IOPS optimized option.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public LaunchSpecification WithEbsOptimized(bool ebsOptimized)
{
this.ebsOptimizedField = ebsOptimized;
return this;
}
/// <summary>
/// Checks if EbsOptimized property is set
/// </summary>
/// <returns>true if EbsOptimized property is set</returns>
public bool IsSetEbsOptimized()
{
return this.ebsOptimizedField.HasValue;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Web;
using System.Xml;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.Querying;
using umbraco.cms.businesslogic.cache;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
using System.Web.Security;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
using Umbraco.Core.Security;
namespace umbraco.cms.businesslogic.member
{
/// <summary>
/// The Member class represents a member of the public website (not to be confused with umbraco users)
///
/// Members are used when creating communities and collaborative applications using umbraco, or if there are a
/// need for identifying or authentifying the visitor. (extranets, protected/private areas of the public website)
///
/// Inherits generic datafields from it's baseclass content.
/// </summary>
[Obsolete("Use the MemberService and the Umbraco.Core.Models.Member models instead")]
public class Member : Content
{
#region Constants and static members
public static readonly string UmbracoMemberProviderName = Constants.Conventions.Member.UmbracoMemberProviderName;
public static readonly string UmbracoRoleProviderName = Constants.Conventions.Member.UmbracoRoleProviderName;
public static readonly Guid _objectType = new Guid(Constants.ObjectTypes.Member);
// zb-00004 #29956 : refactor cookies names & handling
private const string _sQLOptimizedMany = @"
select
umbracoNode.id, umbracoNode.uniqueId, umbracoNode.level,
umbracoNode.parentId, umbracoNode.path, umbracoNode.sortOrder, umbracoNode.createDate,
umbracoNode.nodeUser, umbracoNode.text,
cmsMember.Email, cmsMember.LoginName, cmsMember.Password
from umbracoNode
inner join cmsContent on cmsContent.nodeId = umbracoNode.id
inner join cmsMember on cmsMember.nodeId = cmsContent.nodeId
where umbracoNode.nodeObjectType = @nodeObjectType AND {0}
order by {1}";
#endregion
#region Private members
private Hashtable _groups = null;
protected internal IMember MemberItem;
#endregion
#region Constructors
internal Member(IMember member)
: base(member)
{
SetupNode(member);
}
/// <summary>
/// Initializes a new instance of the Member class.
/// </summary>
/// <param name="id">Identifier</param>
public Member(int id) : base(id) { }
/// <summary>
/// Initializes a new instance of the Member class.
/// </summary>
/// <param name="id">Identifier</param>
public Member(Guid id) : base(id) { }
/// <summary>
/// Initializes a new instance of the Member class, with an option to only initialize
/// the data used by the tree in the umbraco console.
/// </summary>
/// <param name="id">Identifier</param>
/// <param name="noSetup"></param>
public Member(int id, bool noSetup) : base(id, noSetup) { }
public Member(Guid id, bool noSetup) : base(id, noSetup) { }
#endregion
#region Static methods
/// <summary>
/// A list of all members in the current umbraco install
///
/// Note: is ressource intensive, use with care.
/// </summary>
public static Member[] GetAll
{
get
{
return GetAllAsList().ToArray();
}
}
public static IEnumerable<Member> GetAllAsList()
{
int totalRecs;
return ApplicationContext.Current.Services.MemberService.GetAll(0, int.MaxValue, out totalRecs)
.Select(x => new Member(x))
.ToArray();
}
/// <summary>
/// Retrieves a list of members thats not start with a-z
/// </summary>
/// <returns>array of members</returns>
public static Member[] getAllOtherMembers()
{
//NOTE: This hasn't been ported to the new service layer because it is an edge case, it is only used to render the tree nodes but in v7 we plan on
// changing how the members are shown and not having to worry about letters.
var ids = new List<int>();
using (var sqlHelper = Application.SqlHelper)
using (var dr = sqlHelper.ExecuteReader(
string.Format(_sQLOptimizedMany.Trim(), "LOWER(SUBSTRING(text, 1, 1)) NOT IN ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')", "umbracoNode.text"),
sqlHelper.CreateParameter("@nodeObjectType", Member._objectType)))
{
while (dr.Read())
{
ids.Add(dr.GetInt("id"));
}
}
if (ids.Any())
{
return ApplicationContext.Current.Services.MemberService.GetAllMembers(ids.ToArray())
.Select(x => new Member(x))
.ToArray();
}
return new Member[] { };
}
/// <summary>
/// Retrieves a list of members by the first letter in their name.
/// </summary>
/// <param name="letter">The first letter</param>
/// <returns></returns>
public static Member[] getMemberFromFirstLetter(char letter)
{
int totalRecs;
return ApplicationContext.Current.Services.MemberService.FindMembersByDisplayName(
letter.ToString(CultureInfo.InvariantCulture), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith)
.Select(x => new Member(x))
.ToArray();
}
public static Member[] GetMemberByName(string usernameToMatch, bool matchByNameInsteadOfLogin)
{
int totalRecs;
if (matchByNameInsteadOfLogin)
{
var found = ApplicationContext.Current.Services.MemberService.FindMembersByDisplayName(
usernameToMatch, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith);
return found.Select(x => new Member(x)).ToArray();
}
else
{
var found = ApplicationContext.Current.Services.MemberService.FindByUsername(
usernameToMatch, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith);
return found.Select(x => new Member(x)).ToArray();
}
}
/// <summary>
/// Creates a new member
/// </summary>
/// <param name="Name">Membername</param>
/// <param name="mbt">Member type</param>
/// <param name="u">The umbraco usercontext</param>
/// <returns>The new member</returns>
public static Member MakeNew(string Name, MemberType mbt, User u)
{
return MakeNew(Name, "", "", mbt, u);
}
/// <summary>
/// Creates a new member
/// </summary>
/// <param name="Name">Membername</param>
/// <param name="mbt">Member type</param>
/// <param name="u">The umbraco usercontext</param>
/// <param name="Email">The email of the user</param>
/// <returns>The new member</returns>
public static Member MakeNew(string Name, string Email, MemberType mbt, User u)
{
return MakeNew(Name, "", Email, mbt, u);
}
/// <summary>
/// Creates a new member
/// </summary>
/// <param name="Name">Membername</param>
/// <param name="mbt">Member type</param>
/// <param name="u">The umbraco usercontext</param>
/// <param name="Email">The email of the user</param>
/// <returns>The new member</returns>
public static Member MakeNew(string Name, string LoginName, string Email, MemberType mbt, User u)
{
if (mbt == null) throw new ArgumentNullException("mbt");
var loginName = (string.IsNullOrEmpty(LoginName) == false) ? LoginName : Name;
var provider = MembershipProviderExtensions.GetMembersMembershipProvider();
//NOTE: This check is ONLY for backwards compatibility, this check shouldn't really be here it is up to the Membership provider
// logic to deal with this but it was here before so we can't really change that.
// Test for e-mail
if (Email != "" && GetMemberFromEmail(Email) != null && provider.RequiresUniqueEmail)
throw new Exception(string.Format("Duplicate Email! A member with the e-mail {0} already exists", Email));
if (GetMemberFromLoginName(loginName) != null)
throw new Exception(string.Format("Duplicate User name! A member with the user name {0} already exists", loginName));
var model = ApplicationContext.Current.Services.MemberService.CreateMemberWithIdentity(
loginName, Email.ToLower(), Name, mbt.MemberTypeItem);
//The content object will only have the 'WasCancelled' flag set to 'True' if the 'Saving' event has been cancelled, so we return null.
if (((Entity)model).WasCancelled)
return null;
var legacy = new Member(model);
var e = new NewEventArgs();
legacy.OnNew(e);
legacy.Save();
return legacy;
}
/// <summary>
/// Retrieve a member given the loginname
///
/// Used when authentifying the Member
/// </summary>
/// <param name="loginName">The unique Loginname</param>
/// <returns>The member with the specified loginname - null if no Member with the login exists</returns>
public static Member GetMemberFromLoginName(string loginName)
{
Mandate.ParameterNotNullOrEmpty(loginName, "loginName");
var found = ApplicationContext.Current.Services.MemberService.GetByUsername(loginName);
if (found == null) return null;
return new Member(found);
}
/// <summary>
/// Retrieve a Member given an email, the first if there multiple members with same email
///
/// Used when authentifying the Member
/// </summary>
/// <param name="email">The email of the member</param>
/// <returns>The member with the specified email - null if no Member with the email exists</returns>
public static Member GetMemberFromEmail(string email)
{
if (string.IsNullOrEmpty(email))
return null;
var found = ApplicationContext.Current.Services.MemberService.GetByEmail(email);
if (found == null) return null;
return new Member(found);
}
/// <summary>
/// Retrieve Members given an email
///
/// Used when authentifying a Member
/// </summary>
/// <param name="email">The email of the member(s)</param>
/// <returns>The members with the specified email</returns>
public static Member[] GetMembersFromEmail(string email)
{
if (string.IsNullOrEmpty(email))
return null;
int totalRecs;
var found = ApplicationContext.Current.Services.MemberService.FindByEmail(
email, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact);
return found.Select(x => new Member(x)).ToArray();
}
/// <summary>
/// Retrieve a Member given the credentials
///
/// Used when authentifying the member
/// </summary>
/// <param name="loginName">Member login</param>
/// <param name="password">Member password</param>
/// <returns>The member with the credentials - null if none exists</returns>
[Obsolete("Use the MembershipProvider methods to validate a member")]
public static Member GetMemberFromLoginNameAndPassword(string loginName, string password)
{
if (IsMember(loginName))
{
var provider = MembershipProviderExtensions.GetMembersMembershipProvider();
// validate user via provider
if (provider.ValidateUser(loginName, password))
{
return GetMemberFromLoginName(loginName);
}
else
{
LogHelper.Debug<Member>("Incorrect login/password attempt or member is locked out or not approved (" + loginName + ")", true);
return null;
}
}
else
{
LogHelper.Debug<Member>("No member with loginname: " + loginName + " Exists", true);
return null;
}
}
[Obsolete("This method will not work if the password format is encrypted since the encryption that is performed is not static and a new value will be created each time the same string is encrypted")]
public static Member GetMemberFromLoginAndEncodedPassword(string loginName, string password)
{
using (var sqlHelper = Application.SqlHelper)
{
var o = sqlHelper.ExecuteScalar<object>(
"select nodeID from cmsMember where LoginName = @loginName and Password = @password",
sqlHelper.CreateParameter("loginName", loginName),
sqlHelper.CreateParameter("password", password));
if (o == null)
return null;
int tmpId;
if (!int.TryParse(o.ToString(), out tmpId))
return null;
return new Member(tmpId);
}
}
[Obsolete("Use MembershipProviderExtensions.IsUmbracoMembershipProvider instead")]
public static bool InUmbracoMemberMode()
{
var provider = MembershipProviderExtensions.GetMembersMembershipProvider();
return provider.IsUmbracoMembershipProvider();
}
public static bool IsUsingUmbracoRoles()
{
return Roles.Provider.Name == UmbracoRoleProviderName;
}
/// <summary>
/// Helper method - checks if a Member with the LoginName exists
/// </summary>
/// <param name="loginName">Member login</param>
/// <returns>True if the member exists</returns>
public static bool IsMember(string loginName)
{
Mandate.ParameterNotNullOrEmpty(loginName, "loginName");
return ApplicationContext.Current.Services.MemberService.Exists(loginName);
}
/// <summary>
/// Deletes all members of the membertype specified
///
/// Used when a membertype is deleted
///
/// Use with care
/// </summary>
/// <param name="dt">The membertype which are being deleted</param>
public static void DeleteFromType(MemberType dt)
{
ApplicationContext.Current.Services.MemberService.DeleteMembersOfType(dt.Id);
}
#endregion
#region Public Properties
public override int sortOrder
{
get
{
return MemberItem == null ? base.sortOrder : MemberItem.SortOrder;
}
set
{
if (MemberItem == null)
{
base.sortOrder = value;
}
else
{
MemberItem.SortOrder = value;
}
}
}
public override int Level
{
get
{
return MemberItem == null ? base.Level : MemberItem.Level;
}
set
{
if (MemberItem == null)
{
base.Level = value;
}
else
{
MemberItem.Level = value;
}
}
}
public override int ParentId
{
get
{
return MemberItem == null ? base.ParentId : MemberItem.ParentId;
}
}
public override string Path
{
get
{
return MemberItem == null ? base.Path : MemberItem.Path;
}
set
{
if (MemberItem == null)
{
base.Path = value;
}
else
{
MemberItem.Path = value;
}
}
}
[Obsolete("Obsolete, Use Name property on Umbraco.Core.Models.Content", false)]
public override string Text
{
get
{
return MemberItem.Name;
}
set
{
value = value.Trim();
MemberItem.Name = value;
}
}
/// <summary>
/// The members password, used when logging in on the public website
/// </summary>
[Obsolete("Do not use this property, use GetPassword and ChangePassword instead, if using ChangePassword ensure that the password is encrypted or hashed based on the active membership provider")]
public string Password
{
get
{
return MemberItem.RawPasswordValue;
}
set
{
// We need to use the provider for this in order for hashing, etc. support
// To write directly to the db use the ChangePassword method
// this is not pretty but nessecary due to a design flaw (the membership provider should have been a part of the cms project)
var helper = new MemberShipHelper();
var provider = MembershipProviderExtensions.GetMembersMembershipProvider();
MemberItem.RawPasswordValue = helper.EncodePassword(value, provider.PasswordFormat);
}
}
/// <summary>
/// The loginname of the member, used when logging in
/// </summary>
public string LoginName
{
get
{
return MemberItem.Username;
}
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("The loginname must be different from an empty string", "LoginName");
if (value.Contains(","))
throw new ArgumentException("The parameter 'LoginName' must not contain commas.");
MemberItem.Username = value;
}
}
/// <summary>
/// A list of groups the member are member of
/// </summary>
public Hashtable Groups
{
get
{
if (_groups == null)
PopulateGroups();
return _groups;
}
}
/// <summary>
/// The members email
/// </summary>
public string Email
{
get
{
return MemberItem.Email.IsNullOrWhiteSpace() ? string.Empty : MemberItem.Email.ToLower();
}
set
{
MemberItem.Email = value == null ? "" : value.ToLower();
}
}
#endregion
#region Public Methods
[Obsolete("Obsolete", false)]
protected override void setupNode()
{
if (Id == -1)
{
base.setupNode();
return;
}
var content = ApplicationContext.Current.Services.MemberService.GetById(Id);
if (content == null)
throw new ArgumentException(string.Format("No Member exists with id '{0}'", Id));
SetupNode(content);
}
private void SetupNode(IMember content)
{
MemberItem = content;
//Also need to set the ContentBase item to this one so all the propery values load from it
ContentBase = MemberItem;
//Setting private properties from IContentBase replacing CMSNode.setupNode() / CMSNode.PopulateCMSNodeFromReader()
base.PopulateCMSNodeFromUmbracoEntity(MemberItem, _objectType);
//If the version is empty we update with the latest version from the current IContent.
if (Version == Guid.Empty)
Version = MemberItem.Version;
}
/// <summary>
/// Used to persist object changes to the database
/// </summary>
/// <param name="raiseEvents"></param>
public void Save(bool raiseEvents)
{
var provider = MembershipProviderExtensions.GetMembersMembershipProvider();
//Due to backwards compatibility with this API we need to check for duplicate emails here if required.
// This check should not be done here, as this logic is based on the MembershipProvider
var requireUniqueEmail = provider.RequiresUniqueEmail;
//check if there's anyone with this email in the db that isn't us
var membersFromEmail = GetMembersFromEmail(Email);
if (requireUniqueEmail && membersFromEmail != null && membersFromEmail.Any(x => x.Id != Id))
{
throw new Exception(string.Format("Duplicate Email! A member with the e-mail {0} already exists", Email));
}
var e = new SaveEventArgs();
if (raiseEvents)
{
FireBeforeSave(e);
}
foreach (var property in GenericProperties)
{
MemberItem.SetValue(property.PropertyType.Alias, property.Value);
}
if (e.Cancel == false)
{
ApplicationContext.Current.Services.MemberService.Save(MemberItem, raiseEvents);
//base.VersionDate = MemberItem.UpdateDate;
base.Save();
if (raiseEvents)
{
FireAfterSave(e);
}
}
}
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
public override void Save()
{
Save(true);
}
/// <summary>
/// Xmlrepresentation of a member
/// </summary>
/// <param name="xd">The xmldocument context</param>
/// <param name="Deep">Recursive - should always be set to false</param>
/// <returns>A the xmlrepresentation of the current member</returns>
public override XmlNode ToXml(XmlDocument xd, bool Deep)
{
var x = base.ToXml(xd, Deep);
if (x.Attributes != null && x.Attributes["loginName"] == null)
{
x.Attributes.Append(XmlHelper.AddAttribute(xd, "loginName", LoginName));
}
if (x.Attributes != null && x.Attributes["email"] == null)
{
x.Attributes.Append(XmlHelper.AddAttribute(xd, "email", Email));
}
if (x.Attributes != null && x.Attributes["key"] == null)
{
x.Attributes.Append(XmlHelper.AddAttribute(xd, "key", UniqueId.ToString()));
}
return x;
}
/// <summary>
/// Deltes the current member
/// </summary>
[Obsolete("Obsolete, Use Umbraco.Core.Services.MemberService.Delete()", false)]
public override void delete()
{
var e = new DeleteEventArgs();
FireBeforeDelete(e);
if (!e.Cancel)
{
if (MemberItem != null)
{
ApplicationContext.Current.Services.MemberService.Delete(MemberItem);
}
else
{
var member = ApplicationContext.Current.Services.MemberService.GetById(Id);
ApplicationContext.Current.Services.MemberService.Delete(member);
}
// Delete all content and cmsnode specific data!
base.delete();
FireAfterDelete(e);
}
}
/// <summary>
/// Sets the password for the user - ensure it is encrypted or hashed based on the active membership provider - you must
/// call Save() after using this method
/// </summary>
/// <param name="newPassword"></param>
public void ChangePassword(string newPassword)
{
MemberItem.RawPasswordValue = newPassword;
}
/// <summary>
/// Returns the currently stored password - this may be encrypted or hashed string depending on the active membership provider
/// </summary>
/// <returns></returns>
public string GetPassword()
{
return MemberItem.RawPasswordValue;
}
/// <summary>
/// Adds the member to group with the specified id
/// </summary>
/// <param name="GroupId">The id of the group which the member is being added to</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public void AddGroup(int GroupId)
{
var e = new AddGroupEventArgs();
e.GroupId = GroupId;
FireBeforeAddGroup(e);
if (!e.Cancel)
{
using (var sqlHelper = Application.SqlHelper)
{
var parameters = new IParameter[] { sqlHelper.CreateParameter("@id", Id),
sqlHelper.CreateParameter("@groupId", GroupId) };
bool exists = sqlHelper.ExecuteScalar<int>("SELECT COUNT(member) FROM cmsMember2MemberGroup WHERE member = @id AND memberGroup = @groupId",
parameters) > 0;
if (!exists)
sqlHelper.ExecuteNonQuery("INSERT INTO cmsMember2MemberGroup (member, memberGroup) values (@id, @groupId)",
parameters);
}
PopulateGroups();
FireAfterAddGroup(e);
}
}
/// <summary>
/// Removes the member from the MemberGroup specified
/// </summary>
/// <param name="GroupId">The MemberGroup from which the Member is removed</param>
public void RemoveGroup(int GroupId)
{
var e = new RemoveGroupEventArgs();
e.GroupId = GroupId;
FireBeforeRemoveGroup(e);
if (!e.Cancel)
{
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery(
"delete from cmsMember2MemberGroup where member = @id and Membergroup = @groupId",
sqlHelper.CreateParameter("@id", Id), sqlHelper.CreateParameter("@groupId", GroupId));
PopulateGroups();
FireAfterRemoveGroup(e);
}
}
#endregion
#region Protected methods
protected override XmlNode generateXmlWithoutSaving(XmlDocument xd)
{
XmlNode node = xd.CreateNode(XmlNodeType.Element, "node", "");
XmlPopulate(xd, ref node, false);
node.Attributes.Append(xmlHelper.addAttribute(xd, "loginName", LoginName));
node.Attributes.Append(xmlHelper.addAttribute(xd, "email", Email));
return node;
}
#endregion
#region Private methods
private void PopulateGroups()
{
var temp = new Hashtable();
var groupIds = new List<int>();
using (var sqlHelper = Application.SqlHelper)
using (var dr = sqlHelper.ExecuteReader(
"select memberGroup from cmsMember2MemberGroup where member = @id",
sqlHelper.CreateParameter("@id", Id)))
{
while (dr.Read())
groupIds.Add(dr.GetInt("memberGroup"));
}
foreach (var groupId in groupIds)
{
temp.Add(groupId, new MemberGroup(groupId));
}
_groups = temp;
}
private static string GetCacheKey(int id)
{
return string.Format("{0}{1}", CacheKeys.MemberBusinessLogicCacheKey, id);
}
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static void ClearMemberState()
{
// zb-00004 #29956 : refactor cookies names & handling
StateHelper.Cookies.Member.Clear();
FormsAuthentication.SignOut();
}
#endregion
#region MemberHandle functions
/// <summary>
/// Method is used when logging a member in.
///
/// Adds the member to the cache of logged in members
///
/// Uses cookiebased recognition
///
/// Can be used in the runtime
/// </summary>
/// <param name="m">The member to log in</param>
[Obsolete("Use Membership APIs and FormsAuthentication to handle member login")]
public static void AddMemberToCache(Member m)
{
if (m != null)
{
var e = new AddToCacheEventArgs();
m.FireBeforeAddToCache(e);
if (!e.Cancel)
{
// Add cookie with member-id, guid and loginname
// zb-00035 #29931 : cleanup member state management
// NH 4.7.1: We'll no longer use legacy cookies to handle Umbraco Members
//SetMemberState(m);
FormsAuthentication.SetAuthCookie(m.LoginName, true);
//cache the member
var cachedMember = ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem<Member>(
GetCacheKey(m.Id),
timeout: TimeSpan.FromMinutes(30),
getCacheItem: () =>
{
// Debug information
HttpContext.Current.Trace.Write("member",
string.Format("Member added to cache: {0}/{1} ({2})",
m.Text, m.LoginName, m.Id));
return m;
});
m.FireAfterAddToCache(e);
}
}
}
// zb-00035 #29931 : remove old cookie code
/// <summary>
/// Method is used when logging a member in.
///
/// Adds the member to the cache of logged in members
///
/// Uses cookie or session based recognition
///
/// Can be used in the runtime
/// </summary>
/// <param name="m">The member to log in</param>
/// <param name="UseSession">create a persistent cookie</param>
/// <param name="TimespanForCookie">Has no effect</param>
[Obsolete("Use the membership api and FormsAuthentication to log users in, this method is no longer used anymore")]
public static void AddMemberToCache(Member m, bool UseSession, TimeSpan TimespanForCookie)
{
if (m != null)
{
var e = new AddToCacheEventArgs();
m.FireBeforeAddToCache(e);
if (!e.Cancel)
{
// zb-00035 #29931 : cleanup member state management
// NH 4.7.1: We'll no longer use Umbraco legacy cookies to handle members
//SetMemberState(m, UseSession, TimespanForCookie.TotalDays);
FormsAuthentication.SetAuthCookie(m.LoginName, !UseSession);
//cache the member
var cachedMember = ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem<Member>(
GetCacheKey(m.Id),
timeout: TimeSpan.FromMinutes(30),
getCacheItem: () =>
{
// Debug information
HttpContext.Current.Trace.Write("member",
string.Format("Member added to cache: {0}/{1} ({2})",
m.Text, m.LoginName, m.Id));
return m;
});
m.FireAfterAddToCache(e);
}
}
}
/// <summary>
/// Removes the member from the cache
///
/// Can be used in the public website
/// </summary>
/// <param name="m">Member to remove</param>
[Obsolete("Obsolete, use the RemoveMemberFromCache(int NodeId) instead", false)]
public static void RemoveMemberFromCache(Member m)
{
RemoveMemberFromCache(m.Id);
}
/// <summary>
/// Removes the member from the cache
///
/// Can be used in the public website
/// </summary>
/// <param name="NodeId">Node Id of the member to remove</param>
[Obsolete("Member cache is automatically cleared when members are updated")]
public static void RemoveMemberFromCache(int NodeId)
{
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(GetCacheKey(NodeId));
}
/// <summary>
/// Deletes the member cookie from the browser
///
/// Can be used in the public website
/// </summary>
/// <param name="m">Member</param>
[Obsolete("Obsolete, use the ClearMemberFromClient(int NodeId) instead", false)]
public static void ClearMemberFromClient(Member m)
{
if (m != null)
ClearMemberFromClient(m.Id);
else
{
// If the member doesn't exists as an object, we'll just make sure that cookies are cleared
// zb-00035 #29931 : cleanup member state management
ClearMemberState();
}
FormsAuthentication.SignOut();
}
/// <summary>
/// Deletes the member cookie from the browser
///
/// Can be used in the public website
/// </summary>
/// <param name="NodeId">The Node id of the member to clear</param>
[Obsolete("Use FormsAuthentication.SignOut instead")]
public static void ClearMemberFromClient(int NodeId)
{
// zb-00035 #29931 : cleanup member state management
// NH 4.7.1: We'll no longer use legacy Umbraco cookies to handle members
// ClearMemberState();
FormsAuthentication.SignOut();
RemoveMemberFromCache(NodeId);
}
/// <summary>
/// Retrieve a collection of members in the cache
///
/// Can be used from the public website
/// </summary>
/// <returns>A collection of cached members</returns>
public static Hashtable CachedMembers()
{
var h = new Hashtable();
var items = ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItemsByKeySearch<Member>(
CacheKeys.MemberBusinessLogicCacheKey);
foreach (var i in items)
{
h.Add(i.Id, i);
}
return h;
}
/// <summary>
/// Retrieve a member from the cache
///
/// Can be used from the public website
/// </summary>
/// <param name="id">Id of the member</param>
/// <returns>If the member is cached it returns the member - else null</returns>
public static Member GetMemberFromCache(int id)
{
Hashtable members = CachedMembers();
if (members.ContainsKey(id))
return (Member)members[id];
else
return null;
}
/// <summary>
/// An indication if the current visitor is logged in
///
/// Can be used from the public website
/// </summary>
/// <returns>True if the the current visitor is logged in</returns>
[Obsolete("Use the standard ASP.Net procedures for hanlding FormsAuthentication, simply check the HttpContext.User and HttpContext.User.Identity.IsAuthenticated to determine if a member is logged in or not")]
public static bool IsLoggedOn()
{
return HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated;
}
/// <summary>
/// Gets the current visitors memberid
/// </summary>
/// <returns>The current visitors members id, if the visitor is not logged in it returns 0</returns>
public static int CurrentMemberId()
{
int currentMemberId = 0;
// For backwards compatibility between umbraco members and .net membership
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
var provider = MembershipProviderExtensions.GetMembersMembershipProvider();
var member = provider.GetCurrentUser();
if (member == null)
{
throw new InvalidOperationException("No member object found with username " + provider.GetCurrentUserName());
}
int.TryParse(member.ProviderUserKey.ToString(), out currentMemberId);
}
return currentMemberId;
}
/// <summary>
/// Get the current member
/// </summary>
/// <returns>Returns the member, if visitor is not logged in: null</returns>
public static Member GetCurrentMember()
{
try
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
var provider = MembershipProviderExtensions.GetMembersMembershipProvider();
var member = provider.GetCurrentUser();
if (member == null)
{
throw new InvalidOperationException("No member object found with username " + provider.GetCurrentUserName());
}
int currentMemberId = 0;
if (int.TryParse(member.ProviderUserKey.ToString(), out currentMemberId))
{
var m = new Member(currentMemberId);
return m;
}
}
}
catch (Exception ex)
{
LogHelper.Error<Member>("An error occurred in GetCurrentMember", ex);
}
return null;
}
#endregion
#region Events
/// <summary>
/// The save event handler
/// </summary>
public delegate void SaveEventHandler(Member sender, SaveEventArgs e);
/// <summary>
/// The new event handler
/// </summary>
public delegate void NewEventHandler(Member sender, NewEventArgs e);
/// <summary>
/// The delete event handler
/// </summary>
public delegate void DeleteEventHandler(Member sender, DeleteEventArgs e);
/// <summary>
/// The add to cache event handler
/// </summary>
public delegate void AddingToCacheEventHandler(Member sender, AddToCacheEventArgs e);
/// <summary>
/// The add group event handler
/// </summary>
public delegate void AddingGroupEventHandler(Member sender, AddGroupEventArgs e);
/// <summary>
/// The remove group event handler
/// </summary>
public delegate void RemovingGroupEventHandler(Member sender, RemoveGroupEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
new public static event SaveEventHandler BeforeSave;
/// <summary>
/// Raises the <see cref="E:BeforeSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
new protected virtual void FireBeforeSave(SaveEventArgs e)
{
if (BeforeSave != null)
{
BeforeSave(this, e);
}
}
new public static event SaveEventHandler AfterSave;
new protected virtual void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
{
AfterSave(this, e);
}
}
public static event NewEventHandler New;
protected virtual void OnNew(NewEventArgs e)
{
if (New != null)
{
New(this, e);
}
}
public static event AddingGroupEventHandler BeforeAddGroup;
protected virtual void FireBeforeAddGroup(AddGroupEventArgs e)
{
if (BeforeAddGroup != null)
{
BeforeAddGroup(this, e);
}
}
public static event AddingGroupEventHandler AfterAddGroup;
protected virtual void FireAfterAddGroup(AddGroupEventArgs e)
{
if (AfterAddGroup != null)
{
AfterAddGroup(this, e);
}
}
public static event RemovingGroupEventHandler BeforeRemoveGroup;
protected virtual void FireBeforeRemoveGroup(RemoveGroupEventArgs e)
{
if (BeforeRemoveGroup != null)
{
BeforeRemoveGroup(this, e);
}
}
public static event RemovingGroupEventHandler AfterRemoveGroup;
protected virtual void FireAfterRemoveGroup(RemoveGroupEventArgs e)
{
if (AfterRemoveGroup != null)
{
AfterRemoveGroup(this, e);
}
}
public static event AddingToCacheEventHandler BeforeAddToCache;
protected virtual void FireBeforeAddToCache(AddToCacheEventArgs e)
{
if (BeforeAddToCache != null)
{
BeforeAddToCache(this, e);
}
}
public static event AddingToCacheEventHandler AfterAddToCache;
protected virtual void FireAfterAddToCache(AddToCacheEventArgs e)
{
if (AfterAddToCache != null)
{
AfterAddToCache(this, e);
}
}
new public static event DeleteEventHandler BeforeDelete;
new protected virtual void FireBeforeDelete(DeleteEventArgs e)
{
if (BeforeDelete != null)
{
BeforeDelete(this, e);
}
}
new public static event DeleteEventHandler AfterDelete;
new protected virtual void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
{
AfterDelete(this, e);
}
}
#endregion
#region Membership helper class used for encryption methods
/// <summary>
/// ONLY FOR INTERNAL USE.
/// This is needed due to a design flaw where the Umbraco membership provider is located
/// in a separate project referencing this project, which means we can't call special methods
/// directly on the UmbracoMemberShipMember class.
/// This is a helper implementation only to be able to use the encryption functionality
/// of the membership provides (which are protected).
///
/// ... which means this class should have been marked internal with a Friend reference to the other assembly right??
/// </summary>
internal class MemberShipHelper : MembershipProvider
{
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new NotImplementedException();
}
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
throw new NotImplementedException();
}
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
throw new NotImplementedException();
}
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
throw new NotImplementedException();
}
public string EncodePassword(string password, MembershipPasswordFormat pwFormat)
{
string encodedPassword = password;
switch (pwFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
encodedPassword =
Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
break;
case MembershipPasswordFormat.Hashed:
HMACSHA1 hash = new HMACSHA1();
hash.Key = Encoding.Unicode.GetBytes(password);
encodedPassword =
Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
break;
}
return encodedPassword;
}
public override bool EnablePasswordReset
{
get { throw new NotImplementedException(); }
}
public override bool EnablePasswordRetrieval
{
get { throw new NotImplementedException(); }
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override int GetNumberOfUsersOnline()
{
throw new NotImplementedException();
}
public override string GetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override MembershipUser GetUser(string username, bool userIsOnline)
{
throw new NotImplementedException();
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
throw new NotImplementedException();
}
public override string GetUserNameByEmail(string email)
{
throw new NotImplementedException();
}
public override int MaxInvalidPasswordAttempts
{
get { throw new NotImplementedException(); }
}
public override int MinRequiredNonAlphanumericCharacters
{
get { throw new NotImplementedException(); }
}
public override int MinRequiredPasswordLength
{
get { throw new NotImplementedException(); }
}
public override int PasswordAttemptWindow
{
get { throw new NotImplementedException(); }
}
public override MembershipPasswordFormat PasswordFormat
{
get { throw new NotImplementedException(); }
}
public override string PasswordStrengthRegularExpression
{
get { throw new NotImplementedException(); }
}
public override bool RequiresQuestionAndAnswer
{
get { throw new NotImplementedException(); }
}
public override bool RequiresUniqueEmail
{
get { throw new NotImplementedException(); }
}
public override string ResetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override bool UnlockUser(string userName)
{
throw new NotImplementedException();
}
public override void UpdateUser(MembershipUser user)
{
throw new NotImplementedException();
}
public override bool ValidateUser(string username, string password)
{
throw new NotImplementedException();
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
namespace Factotum
{
// This is the base class for finding and listing three types of changes made to a table
// during an outage: 1) Insertions, 2) Modifications, 3) Assignment Changes.
// Note: we are not concerned with Deletions. The outage interface will prevent deletion of any record
// created prior to the outage.
// This class and its subclasses will connect to both the system master database file
// and the database file returned from an outage.
// They will create a new un-typed dataset and fill two tables: 'original' and 'modified'
// They will then relate the two tables by their primary keys with the 'modified' table
// as the parent and loop through the modified table, looking for insertions (no child records)
// or modifications (field values different).
// For each insertion, modification, or assignment change found, an info object will be added to a list
// that describes this change.
// The
class ChangeFinder
{
protected SqlCeConnection cnnOrig;
protected SqlCeConnection cnnMod;
protected DataSet ds;
protected SqlCeDataAdapter daOrig;
protected SqlCeDataAdapter daMod;
protected List<InfoInsertion> insertions;
protected List<InfoModification> modifications;
protected List<InfoAssignmentChange> assignmentChanges;
// These fields should be set by the inheriting class constructor.
protected SqlCeCommand cmdSelOrig;
protected SqlCeCommand cmdUpdOrig;
protected SqlCeCommand cmdInsOrig;
protected SqlCeCommand cmdDelOrig;
protected SqlCeCommand cmdSelMod;
protected string tableName;
protected string tableName_friendly;
// These two fields should be set if we're comparing map tables.
protected string primaryParentTableName;
protected string secondaryParentTableName;
protected string primaryParentTableName_friendly;
protected string secondaryParentTableName_friendly;
public List<InfoInsertion> Insertions
{
get { return insertions;}
}
public List<InfoModification> Modifications
{
get { return modifications;}
}
public List<InfoAssignmentChange> AssignmentChanges
{
get { return assignmentChanges;}
}
public ChangeFinder(SqlCeConnection cnnOrig, SqlCeConnection cnnMod)
{
this.cnnOrig = cnnOrig;
this.cnnMod = cnnMod;
ds = new DataSet("Comparer");
daOrig = new SqlCeDataAdapter();
daMod = new SqlCeDataAdapter();
insertions = new List<InfoInsertion>();
modifications = new List<InfoModification>();
assignmentChanges = new List<InfoAssignmentChange>();
cmdSelOrig = null;
cmdUpdOrig = null;
cmdInsOrig = null;
cmdDelOrig = null;
cmdSelMod = null;
tableName = null;
}
// Note: this function should not be called until you have set the commands for the data adapters
// This function performs comparisons of standard tables which have the following fields:
// Guid? ID, string Name and that ID is the first column.
public void CompareTables_std()
{
// These commands and their associated parameters should be set by the inheriting class.
daOrig.SelectCommand = cmdSelOrig;
daOrig.InsertCommand = cmdInsOrig;
daOrig.UpdateCommand = cmdUpdOrig;
daMod.SelectCommand = cmdSelMod;
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
daOrig.Fill(ds, "Original");
// Leave the original connection open...
if (cnnMod.State != ConnectionState.Open) cnnMod.Open();
daMod.Fill(ds, "Modified");
cnnMod.Close();
int columnCount = ds.Tables["Original"].Columns.Count;
// Make Modified table the parent. We should only have insertions and changed
// records. If we loop through the rows of the modified table, any time
// getChildRows() returns no rows, we'll know that it's a new record.
DataRelation dr = new DataRelation("linkIDs", ds.Tables["Modified"].Columns[0], ds.Tables["Original"].Columns[0], false);
ds.Relations.Add(dr);
foreach (DataRow modRow in ds.Tables["Modified"].Rows)
{
DataRow[] origRows = modRow.GetChildRows("linkIDs");
if (origRows.Length == 0)
{
insertions.Add(new InfoInsertion(tableName, tableName_friendly, modRow["Name"], modRow["ID"]));
ds.Tables["Original"].Rows.Add(modRow.ItemArray);
}
else
{
// start at 1, assuming column 0 is the ID...
for (int col = 1; col < ds.Tables["Original"].Columns.Count; col++)
{
if (!fieldValuesEqual(origRows[0], modRow, col))
{
modifications.Add(new InfoModification(tableName, tableName_friendly,
ds.Tables["Original"].Columns[col].ColumnName,
modRow["Name"], modRow["ID"], origRows[0][col], modRow[col]));
origRows[0][col] = modRow[col];
}
}
}
}
}
// Note: this function should not be called until you have set the commands for the data adapters
// This function performs comparisons of map tables which have two Guid? primary foreign keys:
public void CompareTables_map()
{
DataColumn[] parentColumns;
DataColumn[] childColumns;
DataRelation dr;
// These commands and their associated parameters should be set by the inheriting class.
// The select commands should join to the parent tables and include their name fields as
// "PrimaryName" and "SecondaryName"
daOrig.SelectCommand = cmdSelOrig;
daMod.SelectCommand = cmdSelMod;
daOrig.InsertCommand = cmdInsOrig;
// The update command is not used for map tables
// The delete command is only used for map tables (to un-assign)
daOrig.DeleteCommand = cmdDelOrig;
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
daOrig.Fill(ds, "Original");
// Don't close the original connection...
if (cnnMod.State != ConnectionState.Open) cnnMod.Open();
daMod.Fill(ds, "Modified");
cnnMod.Close();
// Make Modified table the parent. We should only have insertions and changed
// records. If we loop through the rows of the modified table, any time
// getChildRows() returns no rows, we'll know that it's a new record.
parentColumns = new DataColumn[] {
ds.Tables["Modified"].Columns[0],
ds.Tables["Modified"].Columns[1] };
childColumns = new DataColumn[] {
ds.Tables["Original"].Columns[0],
ds.Tables["Original"].Columns[1] };
dr = new DataRelation("linkIDs", parentColumns, childColumns, false);
ds.Relations.Add(dr);
foreach (DataRow modRow in ds.Tables["Modified"].Rows)
{
DataRow[] origRows = modRow.GetChildRows("linkIDs");
if (origRows.Length == 0)
{
assignmentChanges.Add(new InfoAssignmentChange(primaryParentTableName,primaryParentTableName_friendly,
secondaryParentTableName, secondaryParentTableName_friendly,
modRow["PrimaryName"], modRow["PrimaryID"], modRow["SecondaryName"], modRow["SecondaryID"], true));
ds.Tables["Original"].Rows.Add(modRow.ItemArray);
}
}
// Now Make Original table the parent so we can find deletions.
// If we loop through the rows of the original table, any time
// getChildRows() returns no rows, we'll know we need to delete the current record.
parentColumns = new DataColumn[] {
ds.Tables["Original"].Columns[0],
ds.Tables["Original"].Columns[1] };
childColumns = new DataColumn[] {
ds.Tables["Modified"].Columns[0],
ds.Tables["Modified"].Columns[1] };
ds.Relations.Remove("linkIDs");
dr = new DataRelation("linkIDs", parentColumns, childColumns, false);
ds.Relations.Add(dr);
foreach (DataRow origRow in ds.Tables["Original"].Rows)
{
DataRow[] modRows = origRow.GetChildRows("linkIDs");
if (modRows.Length == 0)
{
assignmentChanges.Add(new InfoAssignmentChange(primaryParentTableName, primaryParentTableName_friendly,
secondaryParentTableName, secondaryParentTableName_friendly,
origRow["PrimaryName"], origRow["PrimaryID"], origRow["SecondaryName"], origRow["SecondaryID"], false));
origRow.Delete();
}
}
}
// Call Update to assert the dataset changes to the table in the original database
public void UpdateOriginalTable()
{
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
int rowsAffected = daOrig.Update(ds,"Original");
}
// Check whehther two field values are "equal"
private bool fieldValuesEqual(DataRow dr1, DataRow dr2, int idx)
{
if (dr1[idx] == null && dr2[idx] == null) return true;
if (dr1[idx] != null && dr2[idx] != null && dr1[idx].Equals(dr2[idx])) return true;
return false;
}
// Append insertion information to a temporary table, creating or clearing the table first
// as required. This table will contain changes for the last outage imported and will be
// used to report to the master user which items have been inserted at the outage.
public void AppendInsertionInfo(bool createNew)
{
// Check whether or not the temp table exists.
SqlCeCommand cmd;
cmd = cnnOrig.CreateCommand();
cmd.CommandText =
@"SELECT Count(*)
FROM Information_schema.tables
WHERE table_name = 'tmpOutageInsertions'";
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
bool tableExists = ((int)cmd.ExecuteScalar() != 0);
if (tableExists && createNew)
{
// the table exists, but we're supposed to start fresh, so drop the table
// Note: I think it's better to drop than just delete records because it makes
// it easy to change the table structure later if need be.
cmd = cnnOrig.CreateCommand();
cmd.CommandText = "drop table tmpOutageInsertions";
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
cmd.ExecuteNonQuery();
tableExists = false;
}
if (!tableExists)
{
// the table doesn't exist, so create it
cmd = cnnOrig.CreateCommand();
cmd.CommandText =
"create table tmpOutageInsertions" +
string.Format(" (tableName Nvarchar({0}) NOT NULL,", InfoInsertion.TableNameSize) +
string.Format(" tableName_friendly Nvarchar({0}) NOT NULL,", InfoInsertion.TableNameSize) +
string.Format(" recordName Nvarchar({0}) NOT NULL,", InfoInsertion.RecordNameSize) +
" recordGuid UniqueIdentifier NOT NULL)";
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
cmd.ExecuteNonQuery();
}
// Fill the temp table with any insertions in our collection.
cmd = cnnOrig.CreateCommand();
cmd.CommandText =
@"insert into tmpOutageInsertions (tableName, tableName_friendly, recordName, recordGuid)
values (@p0, @p1, @p2, @p3)";
cmd.Parameters.Add("@p0", "");
cmd.Parameters.Add("@p1", "");
cmd.Parameters.Add("@p2", "");
cmd.Parameters.Add("@p3", Guid.Empty);
foreach (InfoInsertion insertion in insertions)
{
cmd.Parameters["@p0"].Value = insertion.tableName;
cmd.Parameters["@p1"].Value = insertion.tableName_friendly;
cmd.Parameters["@p2"].Value = insertion.recordName;
cmd.Parameters["@p3"].Value = insertion.recordGuid;
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
cmd.ExecuteNonQuery();
}
}
// Append update information to a temporary table, creating or clearing the table first
// as required. This table will contain changes for the last outage imported and will be
// used to report to the master user which items have been inserted at the outage.
public void AppendModificationInfo(bool createNew)
{
// Check whether or not the temp table exists.
SqlCeCommand cmd;
cmd = cnnOrig.CreateCommand();
cmd.CommandText =
@"SELECT Count(*)
FROM Information_schema.tables
WHERE table_name = 'tmpOutageUpdates'";
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
bool tableExists = ((int)cmd.ExecuteScalar() != 0);
if (tableExists && createNew)
{
// the table exists, but we're supposed to start fresh, so drop the table
// Note: I think it's better to drop than just delete records because it makes
// it easy to change the table structure later if need be.
cmd = cnnOrig.CreateCommand();
cmd.CommandText = "drop table tmpOutageUpdates";
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
cmd.ExecuteNonQuery();
tableExists = false;
}
if (!tableExists)
{
// the table doesn't exist, so create it
cmd = cnnOrig.CreateCommand();
cmd.CommandText =
"create table tmpOutageUpdates" +
string.Format(" (tableName Nvarchar({0}) NOT NULL,", InfoModification.TableNameSize) +
string.Format(" tableName_friendly Nvarchar({0}) NOT NULL,", InfoModification.TableNameSize) +
string.Format(" recordName Nvarchar({0}) NOT NULL,", InfoModification.RecordNameSize) +
" recordGuid UniqueIdentifier NOT NULL," +
string.Format(" fieldName Nvarchar({0}) NOT NULL,", InfoModification.FieldNameSize) +
string.Format(" oldValue Nvarchar({0}) NOT NULL,", InfoModification.ValueSize) +
string.Format(" newValue Nvarchar({0}) NOT NULL)", InfoModification.ValueSize);
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
cmd.ExecuteNonQuery();
}
// Fill the temp table with any insertions in our collection.
cmd = cnnOrig.CreateCommand();
cmd.CommandText =
@"insert into tmpOutageUpdates
(tableName,
tableName_friendly,
recordName,
recordGuid,
fieldName,
oldValue,
newValue)
values (@p0, @p1, @p2, @p3, @p4, @p5, @p6)";
cmd.Parameters.Add("@p0", "");
cmd.Parameters.Add("@p1", "");
cmd.Parameters.Add("@p2", "");
cmd.Parameters.Add("@p3", Guid.Empty);
cmd.Parameters.Add("@p4", "");
cmd.Parameters.Add("@p5", "");
cmd.Parameters.Add("@p6", "");
foreach (InfoModification modification in modifications)
{
if (excludeField(modification)) continue;
cmd.Parameters["@p0"].Value = modification.tableName;
cmd.Parameters["@p1"].Value = modification.tableName_friendly;
cmd.Parameters["@p2"].Value = modification.recordName;
cmd.Parameters["@p3"].Value = modification.recordGuid;
cmd.Parameters["@p4"].Value = modification.fieldName;
cmd.Parameters["@p5"].Value = modification.oldValue;
cmd.Parameters["@p6"].Value = modification.newValue;
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
cmd.ExecuteNonQuery();
}
}
private bool excludeField(InfoModification mod)
{
// Shouldn't have to worry about IsLclChange flags, they should all be reset before
// starting the import.
string fld = mod.fieldName;
// Exclude foreign keys. If they can change, they'll have associated string fields.
if (fld.Length > 2 && fld.EndsWith("ID")) return true;
// The user doesn't need to know about these changes.
if (fld.EndsWith("UsedInOutage")) return true;
// We do want the user to know about active/inactive status changes, just not with this
if (fld.EndsWith("IsActive")) return true;
// Miscellaneous flags and byte enums to exclude
string[] excludes = new string[] { "CbkMaterialType", "CbkType",
"CmpHighRad", "CmpHardToAccess","CmpHasDs","CmpHasBranch",
"CmtCalBlockMaterial","InsLevel","OtgGridColDefaultCCW"};
foreach (string exFld in excludes)
if (fld == exFld) return true;
return false;
}
// Append assignment change information to a temporary table, creating or clearing the table first
// as required. This table will contain changes for the last outage imported and will be
// used to report to the master user which items have been inserted at the outage.
public void AppendAssignmentChangeInfo(bool createNew)
{
// Check whether or not the temp table exists.
SqlCeCommand cmd;
cmd = cnnOrig.CreateCommand();
cmd.CommandText =
@"SELECT Count(*)
FROM Information_schema.tables
WHERE table_name = 'tmpOutageAssignmentChanges'";
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
bool tableExists = ((int)cmd.ExecuteScalar() != 0);
if (tableExists && createNew)
{
// the table exists, but we're supposed to start fresh, so drop the table
// Note: I think it's better to drop than just delete records because it makes
// it easy to change the table structure later if need be.
cmd = cnnOrig.CreateCommand();
cmd.CommandText = "drop table tmpOutageAssignmentChanges";
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
cmd.ExecuteNonQuery();
tableExists = false;
}
if (!tableExists)
{
// the table doesn't exist, so create it
cmd = cnnOrig.CreateCommand();
cmd.CommandText =
"create table tmpOutageAssignmentChanges" +
string.Format(" (primaryTableName Nvarchar({0}) NOT NULL,", InfoAssignmentChange.TableNameSize) +
string.Format(" primaryTableName_friendly Nvarchar({0}) NOT NULL,", InfoAssignmentChange.TableNameSize) +
string.Format(" primaryTableRecordName Nvarchar({0}) NOT NULL,", InfoAssignmentChange.RecordNameSize) +
" primaryTableRecordGuid UniqueIdentifier NOT NULL," +
string.Format(" secondaryTableName Nvarchar({0}) NOT NULL,", InfoAssignmentChange.TableNameSize) +
string.Format(" secondaryTableName_friendly Nvarchar({0}) NOT NULL,", InfoAssignmentChange.TableNameSize) +
string.Format(" secondaryTableRecordName Nvarchar({0}) NOT NULL,", InfoAssignmentChange.RecordNameSize) +
" secondaryTableRecordGuid UniqueIdentifier NOT NULL," +
string.Format(" isNowAssigned Bit NOT NULL)", InfoAssignmentChange.RecordNameSize);
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
cmd.ExecuteNonQuery();
}
// Fill the temp table with any insertions in our collection.
cmd = cnnOrig.CreateCommand();
cmd.CommandText =
@"insert into tmpOutageAssignmentChanges
(primaryTableName,
primaryTableName_friendly,
primaryTableRecordName,
primaryTableRecordGuid,
secondaryTableName,
secondaryTableName_friendly,
secondaryTableRecordName,
secondaryTableRecordGuid,
isNowAssigned)
values (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8)";
cmd.Parameters.Add("@p0", "");
cmd.Parameters.Add("@p1", "");
cmd.Parameters.Add("@p2", "");
cmd.Parameters.Add("@p3", Guid.Empty);
cmd.Parameters.Add("@p4", "");
cmd.Parameters.Add("@p5", "");
cmd.Parameters.Add("@p6", "");
cmd.Parameters.Add("@p7", Guid.Empty);
cmd.Parameters.Add("@p8", false);
foreach (InfoAssignmentChange assignmentChange in assignmentChanges)
{
cmd.Parameters["@p0"].Value = assignmentChange.primaryTableName;
cmd.Parameters["@p1"].Value = assignmentChange.primaryTableName_friendly;
cmd.Parameters["@p2"].Value = assignmentChange.primaryTableRecordName;
cmd.Parameters["@p3"].Value = assignmentChange.primaryTableRecordGuid;
cmd.Parameters["@p4"].Value = assignmentChange.secondaryTableName;
cmd.Parameters["@p5"].Value = assignmentChange.secondaryTableName_friendly;
cmd.Parameters["@p6"].Value = assignmentChange.secondaryTableRecordName;
cmd.Parameters["@p7"].Value = assignmentChange.secondaryTableRecordGuid;
cmd.Parameters["@p8"].Value = assignmentChange.isNowAssigned;
if (cnnOrig.State != ConnectionState.Open) cnnOrig.Open();
cmd.ExecuteNonQuery();
}
}
// Update the number of times inspected for the component
// Do this after updating both the average time to Inspect and
// the average Crew Dose
public static void UpdateTimesInspected(SqlCeConnection cnn)
{
SqlCeCommand cmd;
// Increment the Times inspected for components which were included in reports.
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update Components set CmpTimesInspected = (CmpTimesInspected + 1)
where CmpDBid IN (Select IscCmpID from InspectedComponents)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
}
// This query is a bit too complicated for SQL CE, so use a cursor
public static void UpdateTimeToInspect(SqlCeConnection cnn)
{
SqlCeCommand cmd;
// Get a data reader with the time to inspect each component, summing over inspections.
cmd = cnn.CreateCommand();
cmd.CommandText =
@"select IscCmpID as ComponentID, sum(IspPersonHours) as TotalHours
from InspectedComponents
inner join Inspections on IscDBid = IspIscID
where IspPersonHours is not NULL
group by IscCmpID";
Guid componentID;
float totalHours;
SqlCeConnection cnn2 = new SqlCeConnection(Globals.ConnectionStringFromConnection(cnn));
SqlCeCommand cmd2;
if (cnn.State != ConnectionState.Open) cnn.Open();
SqlCeDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
componentID = (Guid)rdr[0];
totalHours = Convert.ToSingle(rdr[1]);
cmd2 = cnn2.CreateCommand();
cmd2.CommandText =
@"Update Components set
CmpAvgInspectionTime = ((CmpAvgInspectionTime * CmpTimesInspected) + @p1) / (CmpTimesInspected + 1)
where CmpDBid = @p0";
cmd2.Parameters.Add("@p0", componentID);
cmd2.Parameters.Add("@p1", totalHours);
if (cnn2.State != ConnectionState.Open) cnn2.Open();
cmd2.ExecuteNonQuery();
}
cnn2.Close();
rdr.Close();
}
// This query is a bit too complicated for SQL CE, so use a cursor
public static void UpdateCrewDose(SqlCeConnection cnn)
{
SqlCeCommand cmd;
// Get a data reader with the time to inspect each component, summing over inspections.
cmd = cnn.CreateCommand();
cmd.CommandText =
@"select IscCmpID as ComponentID, sum(DstCrewDose) as TotalCrewDose
from InspectedComponents
inner join Inspections on IscDBid = IspIscID
inner join Dsets on IspDBid = DstIspID
where DstCrewDose is not NULL
group by IscCmpID";
Guid componentID;
float totalCrewDose;
SqlCeConnection cnn2 = new SqlCeConnection(Globals.ConnectionStringFromConnection(cnn));
SqlCeCommand cmd2;
if (cnn.State != ConnectionState.Open) cnn.Open();
SqlCeDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
componentID = (Guid)rdr[0];
totalCrewDose = Convert.ToSingle(rdr[1]);
cmd2 = cnn2.CreateCommand();
cmd2.CommandText =
@"Update Components set
CmpAvgCrewDose = ((CmpAvgCrewDose * CmpTimesInspected) + @p1) / (CmpTimesInspected + 1)
where CmpDBid = @p0";
cmd2.Parameters.Add("@p0", componentID);
cmd2.Parameters.Add("@p1", totalCrewDose);
if (cnn2.State != ConnectionState.Open) cnn2.Open();
cmd2.ExecuteNonQuery();
}
cnn2.Close();
rdr.Close();
}
// Used by the info classes below
public static string truncateAndNA(object input, int max)
{
if (input == DBNull.Value || input == null) return "N/A";
string strInput = input.ToString();
if (strInput.Length > max)
return strInput.Substring(0, max - 3) + "...";
else
return strInput;
}
public static void CleanUpOutageDatabase(SqlCeConnection cnn)
{
SqlCeCommand cmd;
// Update the components table with the avg time to inspect,
// avg crew dose and times inspected.
UpdateTimeToInspect(cnn);
UpdateCrewDose(cnn);
UpdateTimesInspected(cnn);
cmd = cnn.CreateCommand();
// This will take care of clearing any references to kits.
cmd.CommandText = "Delete from Kits";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Reset all IsLclChg flags -- records that were inserted locally.
// These flags are only relevant in the sphere of the outage.
cmd = cnn.CreateCommand();
cmd.CommandText = "Update CalBlocks set CbkIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update CalibrationProcedures set ClpIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update Components set CmpIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update ComponentMaterials set CmtIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update ComponentTypes set CtpIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update CouplantTypes set CptIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update Ducers set DcrIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update DucerModels set DmdIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update GridProcedures set GrpIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update GridSizes set GszIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update Inspectors set InsIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update Lines set LinIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update MeterModels set MmlIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update Meters set MtrIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update PipeScheduleLookup set PslIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update RadialLocations set RdlIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update SpecialCalParams set ScpIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update Systems set SysIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText = "Update Thermos set ThmIsLclChg = 0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Update the Outage DataImportedOn date
cmd = cnn.CreateCommand();
cmd.CommandText = "Update Outages set OtgDataImportedOn = @p0";
cmd.Parameters.Add("@p0", DateTime.Today);
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Update the UsedInOutage flags for all records which are referenced by another record
// Cal blocks
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update CalBlocks set CbkUsedInOutage = 1
where CbkDBid IN(Select DstCbkID from Dsets)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Components
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update Components set CmpUsedInOutage = 1
where CmpDBid IN(Select IscCmpID from InspectedComponents)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Couplant Types
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update CouplantTypes set CptUsedInOutage = 1
where CptDBid IN(Select OtgCptID from Outages)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Ducers
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update Ducers set DcrUsedInOutage = 1
where DcrDBid IN(Select DstDcrID from Dsets)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Ducer Models
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update DucerModels set DmdUsedInOutage = 1
where DmdDBid IN(Select DcrDmdID from Ducers
inner join Dsets on DcrDBid = DstDcrID)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Grid Procedures
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update GridProcedures set GrpUsedInOutage = 1
where GrpDBid IN(Select IscGrpID from InspectedComponents)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Grid Sizes
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update GridSizes set GszUsedInOutage = 1
where GszDBid IN(Select GrdGszID from Grids)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Inspectors
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update Inspectors set InsUsedInOutage = 1
where InsDBid IN(Select DstInsID from Dsets)
or InsDBid IN(Select IscInsID from InspectedComponents)
or InsDBid IN(Select OinInsID from OutageInspectors)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Meters
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update Meters set MtrUsedInOutage = 1
where MtrDBid IN(Select DstMtrID from Dsets)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Meter Models
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update MeterModels set MmlUsedInOutage = 1
where MmlDBid IN(Select MtrMmlID from Meters
inner join Dsets on MtrDBid = DstMtrID)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Radial Locations
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update RadialLocations set RdlUsedInOutage = 1
where RdlDBid IN(Select GrdRdlID from Grids)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Special Cal Params
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update SpecialCalParams set ScpUsedInOutage = 1
where ScpDBid IN(Select ScvScpID from SpecialCalValues)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Thermos
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update Thermos set ThmUsedInOutage = 1
where ThmDBid IN(Select DstThmID from Dsets)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
}
} // End ChangeFinder Class
class InfoInsertion
{
public const int TableNameSize = 100;
public const int RecordNameSize = 100;
public string tableName;
public string recordName;
public string tableName_friendly;
public Guid recordGuid;
public InfoInsertion(object tableName, object tableName_friendly, object recordName, object recordGuid)
{
this.tableName = ChangeFinder.truncateAndNA(tableName, TableNameSize);
this.tableName_friendly = ChangeFinder.truncateAndNA(tableName_friendly, TableNameSize);
this.recordName = ChangeFinder.truncateAndNA(recordName, RecordNameSize);
this.recordGuid = (Guid)recordGuid;
}
}
class InfoModification
{
public const int TableNameSize = 100;
public const int FieldNameSize = 100;
public const int RecordNameSize = 100;
public const int ValueSize = 255;
public string tableName;
public string tableName_friendly;
public string fieldName;
public string recordName;
public Guid recordGuid;
public string oldValue;
public string newValue;
public InfoModification(object tableName, object tableName_friendly,
object fieldName, object recordName, object recordGuid, object oldValue, object newValue)
{
this.tableName = ChangeFinder.truncateAndNA(tableName, TableNameSize);
this.tableName_friendly = ChangeFinder.truncateAndNA(tableName_friendly, TableNameSize);
this.fieldName = ChangeFinder.truncateAndNA(fieldName, FieldNameSize);
this.recordName = ChangeFinder.truncateAndNA(recordName, RecordNameSize);
this.recordGuid = (Guid)recordGuid;
this.oldValue = ChangeFinder.truncateAndNA(oldValue, ValueSize);
this.newValue = ChangeFinder.truncateAndNA(newValue, ValueSize);
}
}
class InfoAssignmentChange
{
public const int TableNameSize = 100;
public const int RecordNameSize = 100;
public string primaryTableName;
public string secondaryTableName;
public string primaryTableName_friendly;
public string secondaryTableName_friendly;
public string primaryTableRecordName;
public string secondaryTableRecordName;
public Guid primaryTableRecordGuid;
public Guid secondaryTableRecordGuid;
public bool isNowAssigned;
public InfoAssignmentChange(object primaryTableName, object primaryTableName_friendly,
object secondaryTableName, object secondaryTableName_friendly,
object primaryTableRecordName, object primaryTableRecordGuid,
object secondaryTableRecordName, object secondaryTableRecordGuid, bool isNowAssigned)
{
this.primaryTableName = ChangeFinder.truncateAndNA(primaryTableName, TableNameSize);
this.secondaryTableName = ChangeFinder.truncateAndNA(secondaryTableName, TableNameSize);
this.primaryTableName_friendly = ChangeFinder.truncateAndNA(primaryTableName_friendly, TableNameSize);
this.secondaryTableName_friendly = ChangeFinder.truncateAndNA(secondaryTableName_friendly, TableNameSize);
this.primaryTableRecordName = ChangeFinder.truncateAndNA(primaryTableRecordName, RecordNameSize);
this.secondaryTableRecordName = ChangeFinder.truncateAndNA(secondaryTableRecordName, RecordNameSize);
this.primaryTableRecordGuid = (Guid)primaryTableRecordGuid;
this.secondaryTableRecordGuid = (Guid)secondaryTableRecordGuid;
this.isNowAssigned = isNowAssigned;
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using umbraco;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Web.Scheduling;
namespace Umbraco.Web.PublishedCache.XmlPublishedCache
{
/// <summary>
/// This is the background task runner that persists the xml file to the file system
/// </summary>
/// <remarks>
/// This is used so that all file saving is done on a web aware worker background thread and all logic is performed async so this
/// process will not interfere with any web requests threads. This is also done as to not require any global locks and to ensure that
/// if multiple threads are performing publishing tasks that the file will be persisted in accordance with the final resulting
/// xml structure since the file writes are queued.
/// </remarks>
internal class XmlCacheFilePersister : LatchedBackgroundTaskBase
{
private readonly IBackgroundTaskRunner<XmlCacheFilePersister> _runner;
private readonly content _content;
private readonly ProfilingLogger _logger;
private readonly object _locko = new object();
private bool _released;
private Timer _timer;
private DateTime _initialTouch;
private readonly AsyncLock _runLock = new AsyncLock(); // ensure we run once at a time
// note:
// as long as the runner controls the runs, we know that we run once at a time, but
// when the AppDomain goes down and the runner has completed and yet the persister is
// asked to save, then we need to run immediately - but the runner may be running, so
// we need to make sure there's no collision - hence _runLock
private const int WaitMilliseconds = 4000; // save the cache 4s after the last change (ie every 4s min)
private const int MaxWaitMilliseconds = 30000; // save the cache after some time (ie no more than 30s of changes)
// save the cache when the app goes down
public override bool RunsOnShutdown { get { return _timer != null; } }
// initialize the first instance, which is inactive (not touched yet)
public XmlCacheFilePersister(IBackgroundTaskRunner<XmlCacheFilePersister> runner, content content, ProfilingLogger logger)
: this(runner, content, logger, false)
{ }
private XmlCacheFilePersister(IBackgroundTaskRunner<XmlCacheFilePersister> runner, content content, ProfilingLogger logger, bool touched)
{
_runner = runner;
_content = content;
_logger = logger;
if (runner.TryAdd(this) == false)
{
_runner = null; // runner's down
_released = true; // don't mess with timer
return;
}
// runner could decide to run it anytime now
if (touched == false) return;
_logger.Logger.Debug<XmlCacheFilePersister>("Created, save in {0}ms.", () => WaitMilliseconds);
_initialTouch = DateTime.Now;
_timer = new Timer(_ => TimerRelease());
_timer.Change(WaitMilliseconds, 0);
}
public XmlCacheFilePersister Touch()
{
// if _released is false then we're going to setup a timer
// then the runner wants to shutdown & run immediately
// this sets _released to true & the timer will trigger eventualy & who cares?
// if _released is true, either it's a normal release, or
// a runner shutdown, in which case we won't be able to
// add a new task, and so we'll run immediately
var ret = this;
var runNow = false;
lock (_locko)
{
if (_released) // our timer has triggered OR the runner is shutting down
{
_logger.Logger.Debug<XmlCacheFilePersister>("Touched, was released...");
// release: has run or is running, too late, return a new task (adds itself to runner)
if (_runner == null)
{
_logger.Logger.Debug<XmlCacheFilePersister>("Runner is down, run now.");
runNow = true;
}
else
{
_logger.Logger.Debug<XmlCacheFilePersister>("Create new...");
ret = new XmlCacheFilePersister(_runner, _content, _logger, true);
if (ret._runner == null)
{
// could not enlist with the runner, runner is completed, must run now
_logger.Logger.Debug<XmlCacheFilePersister>("Runner is down, run now.");
runNow = true;
}
}
}
else if (_timer == null) // we don't have a timer yet
{
_logger.Logger.Debug<XmlCacheFilePersister>("Touched, was idle, start and save in {0}ms.", () => WaitMilliseconds);
_initialTouch = DateTime.Now;
_timer = new Timer(_ => TimerRelease());
_timer.Change(WaitMilliseconds, 0);
}
else // we have a timer
{
// change the timer to trigger in WaitMilliseconds unless we've been touched first more
// than MaxWaitMilliseconds ago and then leave the time unchanged
if (DateTime.Now - _initialTouch < TimeSpan.FromMilliseconds(MaxWaitMilliseconds))
{
_logger.Logger.Debug<XmlCacheFilePersister>("Touched, was waiting, can delay, save in {0}ms.", () => WaitMilliseconds);
_timer.Change(WaitMilliseconds, 0);
}
else
{
_logger.Logger.Debug<XmlCacheFilePersister>("Touched, was waiting, cannot delay.");
}
}
}
if (runNow)
//Run();
LogHelper.Warn<XmlCacheFilePersister>("Cannot write now because we are going down, changes may be lost.");
return ret; // this, by default, unless we created a new one
}
private void TimerRelease()
{
lock (_locko)
{
_logger.Logger.Debug<XmlCacheFilePersister>("Timer: release.");
_released = true;
Release();
}
}
public override async Task RunAsync(CancellationToken token)
{
lock (_locko)
{
_logger.Logger.Debug<XmlCacheFilePersister>("Run now (async).");
// just make sure - in case the runner is running the task on shutdown
_released = true;
}
// http://stackoverflow.com/questions/13489065/best-practice-to-call-configureawait-for-all-server-side-code
// http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
// do we really need that ConfigureAwait here?
// - In theory, no, because we are already executing on a background thread because we know it is there and
// there won't be any SynchronizationContext to resume to, however this is 'library' code and
// who are we to say that this will never be executed in a sync context... this is best practice to be sure
// it won't cause problems.
// .... so yes we want it.
using (await _runLock.LockAsync())
{
await _content.SaveXmlToFileAsync().ConfigureAwait(false);
}
}
public override bool IsAsync
{
get { return true; }
}
public override void Run()
{
lock (_locko)
{
_logger.Logger.Debug<XmlCacheFilePersister>("Run now (sync).");
// not really needed but safer (it's only us invoking Run, but the method is public...)
_released = true;
}
using (_runLock.Lock())
{
_content.SaveXmlToFile();
}
}
protected override void DisposeResources()
{
base.DisposeResources();
// stop the timer
if (_timer == null) return;
_timer.Change(Timeout.Infinite, Timeout.Infinite);
_timer.Dispose();
}
}
}
| |
//
// https://github.com/mythz/ServiceStack.Redis
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2010 Liquidbit Ltd.
//
// Licensed under the same terms of Redis and ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NServiceKit.Common.Extensions;
using NServiceKit.Common.Utils;
using NServiceKit.DesignPatterns.Model;
using NServiceKit.Text;
namespace NServiceKit.Redis.Generic
{
/// <summary>
/// Allows you to get Redis value operations to operate against POCO types.
/// </summary>
/// <typeparam name="T"></typeparam>
internal partial class RedisTypedClient<T>
: IRedisTypedClient<T>
{
readonly ITypeSerializer<T> serializer = new JsonSerializer<T>();
private readonly RedisClient client;
internal IRedisNativeClient NativeClient
{
get { return client; }
}
/// <summary>
/// Use this to share the same redis connection with another
/// </summary>
/// <param name="client">The client.</param>
public RedisTypedClient(RedisClient client)
{
this.client = client;
this.Lists = new RedisClientLists(this);
this.Sets = new RedisClientSets(this);
this.SortedSets = new RedisClientSortedSets(this);
this.SequenceKey = client.GetTypeSequenceKey<T>();
this.TypeIdsSetKey = client.GetTypeIdsSetKey<T>();
this.TypeLockKey = "lock:" + typeof(T).Name;
}
public string TypeIdsSetKey { get; set; }
public string TypeLockKey { get; set; }
public IRedisTypedTransaction<T> CreateTransaction()
{
return new RedisTypedTransaction<T>(this);
}
public IDisposable AcquireLock()
{
return client.AcquireLock(this.TypeLockKey);
}
public IDisposable AcquireLock(TimeSpan timeOut)
{
return client.AcquireLock(this.TypeLockKey, timeOut);
}
public IRedisQueableTransaction CurrentTransaction
{
get
{
return client.CurrentTransaction;
}
set
{
client.CurrentTransaction = value;
}
}
public void Multi()
{
this.client.Multi();
}
public void Discard()
{
this.client.Discard();
}
public int Exec()
{
return this.client.Exec();
}
internal void AddTypeIdsRegisteredDuringTransaction()
{
client.AddTypeIdsRegisteredDuringTransaction();
}
internal void ClearTypeIdsRegisteredDuringTransaction()
{
client.ClearTypeIdsRegisteredDuringTransaction();
}
public List<string> GetAllKeys()
{
return client.GetAllKeys();
}
public T this[string key]
{
get { return GetValue(key); }
set { SetEntry(key, value); }
}
public byte[] SerializeValue(T value)
{
var strValue = serializer.SerializeToString(value);
return Encoding.UTF8.GetBytes(strValue);
}
public T DeserializeValue(byte[] value)
{
var strValue = value != null ? Encoding.UTF8.GetString(value) : null;
return serializer.DeserializeFromString(strValue);
}
public void SetEntry(string key, T value)
{
if (key == null)
throw new ArgumentNullException("key");
client.Set(key, SerializeValue(value));
client.RegisterTypeId(value);
}
public void SetEntry(string key, T value, TimeSpan expireIn)
{
if (key == null)
throw new ArgumentNullException("key");
client.Set(key, SerializeValue(value), expireIn);
client.RegisterTypeId(value);
}
public bool SetEntryIfNotExists(string key, T value)
{
var success = client.SetNX(key, SerializeValue(value)) == RedisNativeClient.Success;
if (success) client.RegisterTypeId(value);
return success;
}
public T GetValue(string key)
{
return DeserializeValue(client.Get(key));
}
public T GetAndSetValue(string key, T value)
{
return DeserializeValue(client.GetSet(key, SerializeValue(value)));
}
public bool ContainsKey(string key)
{
return client.Exists(key) == RedisNativeClient.Success;
}
public bool RemoveEntry(string key)
{
return client.Del(key) == RedisNativeClient.Success;
}
public bool RemoveEntry(params string[] keys)
{
return client.Del(keys) == RedisNativeClient.Success;
}
public bool RemoveEntry(params IHasStringId[] entities)
{
var ids = entities.ConvertAll(x => x.Id);
var success = client.Del(ids.ToArray()) == RedisNativeClient.Success;
if (success) client.RemoveTypeIds(ids.ToArray());
return success;
}
public int IncrementValue(string key)
{
return client.Incr(key);
}
public int IncrementValueBy(string key, int count)
{
return client.IncrBy(key, count);
}
public int DecrementValue(string key)
{
return client.Decr(key);
}
public int DecrementValueBy(string key, int count)
{
return client.DecrBy(key, count);
}
public string SequenceKey { get; set; }
public void SetSequence(int value)
{
client.GetSet(SequenceKey, Encoding.UTF8.GetBytes(value.ToString()));
}
public int GetNextSequence()
{
return IncrementValue(SequenceKey);
}
public RedisKeyType GetEntryType(string key)
{
return client.GetEntryType(key);
}
public string GetRandomKey()
{
return client.RandomKey();
}
public bool ExpireEntryIn(string key, TimeSpan expireIn)
{
return client.Expire(key, (int)expireIn.TotalSeconds) == RedisNativeClient.Success;
}
public bool ExpireEntryAt(string key, DateTime expireAt)
{
return client.ExpireAt(key, expireAt.ToUnixTime()) == RedisNativeClient.Success;
}
public TimeSpan GetTimeToLive(string key)
{
return TimeSpan.FromSeconds(client.Ttl(key));
}
public void Save()
{
client.Save();
}
public void SaveAsync()
{
client.SaveAsync();
}
public void FlushDb()
{
client.FlushDb();
}
public void FlushAll()
{
client.FlushAll();
}
public T[] SearchKeys(string pattern)
{
var strKeys = client.SearchKeys(pattern);
var keysCount = strKeys.Count;
var keys = new T[keysCount];
for (var i=0; i < keysCount; i++)
{
keys[i] = serializer.DeserializeFromString(strKeys[i]);
}
return keys;
}
public List<T> GetValues(List<string> keys)
{
var resultBytesArray = client.MGet(keys.ToArray());
var results = new List<T>();
foreach (var resultBytes in resultBytesArray)
{
if (resultBytes == null) continue;
var result = DeserializeValue(resultBytes);
results.Add(result);
}
return results;
}
#region Implementation of IBasicPersistenceProvider<T>
public T GetById(string id)
{
var key = IdUtils.CreateUrn<T>(id);
return this.GetValue(key);
}
public IList<T> GetByIds(ICollection<string> ids)
{
if (ids == null || ids.Count == 0)
return new List<T>();
var urnKeys = ids.ConvertAll(x => IdUtils.CreateUrn<T>(x));
return GetValues(urnKeys);
}
public IList<T> GetAll()
{
var allKeys = client.GetAllItemsFromSet(this.TypeIdsSetKey);
return this.GetByIds(allKeys);
}
public T Store(T entity)
{
var urnKey = entity.CreateUrn();
this.SetEntry(urnKey, entity);
return entity;
}
public void StoreAll(IEnumerable<T> entities)
{
if (entities == null) return;
var entitiesList = entities.ToList();
var len = entitiesList.Count;
var keys = new byte[len][];
var values = new byte[len][];
for (var i = 0; i < len; i++)
{
keys[i] = entitiesList[i].CreateUrn().ToUtf8Bytes();
values[i] = RedisClient.SerializeToUtf8Bytes(entitiesList[i]);
}
client.MSet(keys, values);
client.RegisterTypeIds(entitiesList);
}
public void Delete(T entity)
{
var urnKey = entity.CreateUrn();
this.RemoveEntry(urnKey);
client.RemoveTypeIds(entity);
}
public void DeleteById(string id)
{
var urnKey = IdUtils.CreateUrn<T>(id);
this.RemoveEntry(urnKey);
client.RemoveTypeIds<T>(id);
}
public void DeleteByIds(ICollection<string> ids)
{
if (ids == null) return;
var urnKeys = ids.ConvertAll(x => IdUtils.CreateUrn<T>(x));
this.RemoveEntry(urnKeys.ToArray());
client.RemoveTypeIds<T>(ids.ToArray());
}
public void DeleteAll()
{
var urnKeys = client.GetAllItemsFromSet(this.TypeIdsSetKey);
this.RemoveEntry(urnKeys.ToArray());
this.RemoveEntry(this.TypeIdsSetKey);
}
#endregion
public void Dispose() {}
}
}
| |
//! \file ArcSWF.cs
//! \date 2018 Sep 16
//! \brief Shockwave Flash presentation.
//
// Copyright (C) 2018 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Compression;
namespace GameRes.Formats.Macromedia
{
internal class SwfEntry : Entry
{
public SwfChunk Chunk;
}
internal class SwfSoundEntry : SwfEntry
{
public readonly List<SwfChunk> SoundStream = new List<SwfChunk>();
}
[Export(typeof(ArchiveFormat))]
public class SwfOpener : ArchiveFormat
{
public override string Tag { get { return "SWF"; } }
public override string Description { get { return "Shockwave Flash presentation"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public SwfOpener ()
{
Signatures = new uint[] { 0x08535743, 0x08535746, 0 };
}
public override ArcFile TryOpen (ArcView file)
{
if (!file.View.AsciiEqual (0, "CWS") &&
!file.View.AsciiEqual (0, "FWS"))
return null;
bool is_compressed = file.View.ReadByte (0) == 'C';
int version = file.View.ReadByte (3);
using (var reader = new SwfReader (file.CreateStream(), version, is_compressed))
{
var chunks = reader.Parse();
var base_name = Path.GetFileNameWithoutExtension (file.Name);
var dir = chunks.Where (t => t.Length > 2 && TypeMap.ContainsKey (t.Type))
.Select (t => new SwfEntry {
Name = string.Format ("{0}#{1:D5}", base_name, t.Id),
Type = GetTypeFromId (t.Type),
Chunk = t,
Offset = 0,
Size = (uint)t.Length
} as Entry).ToList();
SwfSoundEntry current_stream = null;
foreach (var chunk in chunks.Where (t => IsSoundStream (t)))
{
switch (chunk.Type)
{
case Types.SoundStreamHead:
case Types.SoundStreamHead2:
if ((chunk.Data[1] & 0x30) != 0x20) // not mp3 stream
{
current_stream = null;
continue;
}
current_stream = new SwfSoundEntry {
Name = string.Format ("{0}#{1:D5}", base_name, chunk.Id),
Type = "audio",
Chunk = chunk,
Offset = 0,
};
dir.Add (current_stream);
break;
case Types.SoundStreamBlock:
if (current_stream != null)
{
current_stream.Size += (uint)(chunk.Data.Length - 4);
current_stream.SoundStream.Add (chunk);
}
break;
}
}
return new ArcFile (file, this, dir);
}
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var swent = (SwfEntry)entry;
Extractor extract;
if (!ExtractMap.TryGetValue (swent.Chunk.Type, out extract))
extract = ExtractChunk;
return extract (swent);
}
static string GetTypeFromId (Types type_id)
{
string type;
if (TypeMap.TryGetValue (type_id, out type))
return type;
return type_id.ToString();
}
static Stream ExtractChunk (SwfEntry entry)
{
return new BinMemoryStream (entry.Chunk.Data);
}
static Stream ExtractChunkContents (SwfEntry entry)
{
var source = entry.Chunk;
return new BinMemoryStream (source.Data, 2, source.Length-2);
}
static Stream ExtractSoundStream (SwfEntry entry)
{
var swe = (SwfSoundEntry)entry;
var output = new MemoryStream ((int)swe.Size);
foreach (var chunk in swe.SoundStream)
output.Write (chunk.Data, 4, chunk.Data.Length-4);
output.Position = 0;
return output;
}
static Stream ExtractAudio (SwfEntry entry)
{
var chunk = entry.Chunk;
int flags = chunk.Data[2];
int format = flags >> 4;
if (2 == format)
return new BinMemoryStream (chunk.Data, 9, chunk.Length-9);
int sample_rate = (flags >> 2) & 3;
int bits_per_sample = (flags & 2) != 0 ? 16 : 8;
int channels = (flags & 1) + 1;
return new BinMemoryStream (chunk.Data, 2, chunk.Length-2);
}
public override IImageDecoder OpenImage (ArcFile arc, Entry entry)
{
var swent = (SwfEntry)entry;
switch (swent.Chunk.Type)
{
case Types.DefineBitsLossless:
case Types.DefineBitsLossless2:
return new LosslessImageDecoder (swent.Chunk);
case Types.DefineBitsJpeg2:
return new SwfJpeg2Decoder (swent.Chunk);
case Types.DefineBitsJpeg3:
return new SwfJpeg3Decoder (swent.Chunk);
case Types.DefineBitsJpeg:
return OpenBitsJpeg (swent.Chunk);
default:
return base.OpenImage (arc, entry);
}
}
IImageDecoder OpenBitsJpeg (SwfChunk chunk)
{
int jpeg_pos = 0;
for (int i = 0; i < chunk.Data.Length - 2; ++i)
{
if (chunk.Data[i] == 0xFF && chunk.Data[i+1] == 0xD8)
{
jpeg_pos = i;
break;
}
}
var input = new BinMemoryStream (chunk.Data, jpeg_pos, chunk.Data.Length - jpeg_pos);
return ImageFormatDecoder.Create (input);
}
delegate Stream Extractor (SwfEntry entry);
static Dictionary<Types, Extractor> ExtractMap = new Dictionary<Types, Extractor> {
// { Types.DoAction, ExtractChunkContents },
{ Types.DefineBitsJpeg, ExtractChunkContents },
{ Types.DefineBitsLossless, ExtractChunk },
{ Types.DefineBitsLossless2, ExtractChunk },
{ Types.DefineSound, ExtractAudio },
{ Types.SoundStreamHead, ExtractSoundStream },
{ Types.SoundStreamHead2, ExtractSoundStream },
};
static Dictionary<Types, string> TypeMap = new Dictionary<Types, string> {
{ Types.DefineBitsJpeg, "image" },
{ Types.DefineBitsJpeg2, "image" },
{ Types.DefineBitsJpeg3, "image" },
{ Types.DefineBitsLossless, "image" },
{ Types.DefineBitsLossless2, "image" },
{ Types.DefineSound, "audio" },
{ Types.DoAction, "" },
{ Types.JpegTables, "JpegTables" },
/*
{ Types.DefineText, "Text" },
{ Types.DefineText2, "Text2" },
{ Types.DefineVideoStream, "VideoStream" },
{ Types.VideoFrame, "VideoFrame" },
*/
};
internal static bool IsSoundStream (SwfChunk chunk)
{
return chunk.Type == Types.SoundStreamHead
|| chunk.Type == Types.SoundStreamHead2
|| chunk.Type == Types.SoundStreamBlock;
}
}
internal enum Types : short
{
End = 0,
ShowFrame = 1,
DefineShape = 2,
DefineBitsJpeg = 6,
JpegTables = 8,
DefineText = 11,
DoAction = 12,
DefineSound = 14,
SoundStreamHead = 18,
SoundStreamBlock = 19,
DefineBitsLossless = 20,
DefineBitsJpeg2 = 21,
DefineShape2 = 22,
DefineShape3 = 32,
DefineText2 = 33,
DefineBitsJpeg3 = 35,
DefineBitsLossless2 = 36,
DefineSprite = 39,
SoundStreamHead2 = 45,
ExportAssets = 56,
DefineVideoStream = 60,
VideoFrame = 61,
FileAttributes = 69,
Font3 = 75,
DefineBinary = 87,
};
internal class SwfChunk
{
public Types Type;
public byte[] Data;
public int Length { get { return Data.Length; } }
public int Id { get { return Data.Length > 2 ? Data.ToUInt16 (0) : -1; } }
public SwfChunk (Types id, int length)
{
Type = id;
Data = length > 0 ? new byte[length] : Array.Empty<byte>();
}
}
internal sealed class SwfReader : IDisposable
{
IBinaryStream m_input;
MsbBitStream m_bits;
int m_version;
Int32Rect m_dim;
public SwfReader (IBinaryStream input, int version, bool is_compressed)
{
m_input = input;
m_version = version;
m_input.Position = 8;
if (is_compressed)
{
var zstream = new ZLibStream (input.AsStream, CompressionMode.Decompress);
m_input = new BinaryStream (zstream, m_input.Name);
}
m_bits = new MsbBitStream (m_input.AsStream, true);
}
int m_frame_rate;
int m_frame_count;
List<SwfChunk> m_chunks = new List<SwfChunk>();
public List<SwfChunk> Parse ()
{
ReadDimensions();
m_bits.Reset();
m_frame_rate = m_input.ReadUInt16();
m_frame_count = m_input.ReadUInt16();
for (;;)
{
var chunk = ReadChunk();
if (null == chunk)
break;
m_chunks.Add (chunk);
}
return m_chunks;
}
void ReadDimensions ()
{
int rsize = m_bits.GetBits (5);
m_dim.X = GetSignedBits (rsize);
m_dim.Y = GetSignedBits (rsize);
m_dim.Width = GetSignedBits (rsize) - m_dim.X;
m_dim.Height = GetSignedBits (rsize) - m_dim.Y;
}
byte[] m_buffer = new byte[4];
SwfChunk ReadChunk ()
{
if (m_input.Read (m_buffer, 0, 2) != 2)
return null;
int length = m_buffer.ToUInt16 (0);
Types id = (Types)(length >> 6);
length &= 0x3F;
if (0x3F == length)
length = m_input.ReadInt32();
if (Types.DefineSprite == id)
length = 4;
var chunk = new SwfChunk (id, length);
if (length > 0)
{
if (m_input.Read (chunk.Data, 0, length) < length)
return null;
}
return chunk;
}
int GetSignedBits (int count)
{
int v = m_bits.GetBits (count);
if ((v >> (count - 1)) != 0)
v |= -1 << count;
return v;
}
#region IDisposable Members
bool m_disposed = false;
public void Dispose ()
{
if (!m_disposed)
{
m_input.Dispose();
m_bits.Dispose();
m_disposed = true;
}
}
#endregion
}
internal sealed class LosslessImageDecoder : BinaryImageDecoder
{
Types m_type;
int m_colors;
int m_data_pos;
public PixelFormat Format { get; private set; }
private bool HasAlpha { get { return m_type == Types.DefineBitsLossless2; } }
public LosslessImageDecoder (SwfChunk chunk) : base (new BinMemoryStream (chunk.Data))
{
m_type = chunk.Type;
byte format = chunk.Data[2];
int bpp;
switch (format)
{
case 3:
bpp = 8; Format = PixelFormats.Indexed8;
break;
case 4:
bpp = 16; Format = PixelFormats.Bgr565;
break;
case 5:
bpp = 32;
Format = HasAlpha ? PixelFormats.Bgra32 : PixelFormats.Bgr32;
break;
default: throw new InvalidFormatException();
}
uint width = chunk.Data.ToUInt16 (3);
uint height = chunk.Data.ToUInt16 (5);
m_colors = 0;
m_data_pos = 7;
if (3 == format)
m_colors = chunk.Data[m_data_pos++] + 1;
Info = new ImageMetaData {
Width = width, Height = height, BPP = bpp
};
}
protected override ImageData GetImageData ()
{
m_input.Position = m_data_pos;
using (var input = new ZLibStream (m_input.AsStream, CompressionMode.Decompress, true))
{
BitmapPalette palette = null;
if (8 == Info.BPP)
{
var pal_format = HasAlpha ? PaletteFormat.RgbA : PaletteFormat.RgbX;
palette = ImageFormat.ReadPalette (input, m_colors, pal_format);
}
var pixels = new byte[(int)Info.Width * (int)Info.Height * (Info.BPP / 8)];
input.Read (pixels, 0, pixels.Length);
if (32 == Info.BPP)
{
for (int i = 0; i < pixels.Length; i += 4)
{
byte a = pixels[i];
byte r = pixels[i+1];
byte g = pixels[i+2];
byte b = pixels[i+3];
pixels[i] = b;
pixels[i+1] = g;
pixels[i+2] = r;
pixels[i+3] = a;
}
}
return ImageData.Create (Info, Format, palette, pixels);
}
}
}
internal sealed class SwfJpeg2Decoder : IImageDecoder
{
byte[] m_input;
ImageData m_image;
public Stream Source { get { return Stream.Null; } }
public ImageFormat SourceFormat { get { return null; } }
public ImageMetaData Info { get; private set; }
public ImageData Image { get { return m_image ?? (m_image = Unpack()); } }
public SwfJpeg2Decoder (SwfChunk chunk)
{
m_input = chunk.Data;
}
ImageData Unpack ()
{
int jpeg_pos = FindJpegSignature();
if (jpeg_pos < 0)
throw new InvalidFormatException();
using (var jpeg = new BinMemoryStream (m_input, jpeg_pos, m_input.Length-jpeg_pos))
{
var decoder = new JpegBitmapDecoder (jpeg, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
var frame = decoder.Frames[0];
Info = new ImageMetaData {
Width = (uint)frame.PixelWidth,
Height = (uint)frame.PixelHeight,
BPP = frame.Format.BitsPerPixel,
};
return new ImageData (frame, Info);
}
}
int FindJpegSignature ()
{
int jpeg_pos = 2;
while (jpeg_pos < m_input.Length-4)
{
if (m_input[jpeg_pos] != 0xFF)
jpeg_pos++;
else if (m_input[jpeg_pos+1] == 0xD8)
return jpeg_pos;
else if (m_input[jpeg_pos+1] != 0xD9)
jpeg_pos++;
else if (m_input[jpeg_pos+2] != 0xFF)
jpeg_pos += 3;
else if (m_input[jpeg_pos+3] != 0xD8)
jpeg_pos += 2;
else
return jpeg_pos+4;
}
return -1;
}
public void Dispose ()
{
}
}
internal sealed class SwfJpeg3Decoder : IImageDecoder
{
byte[] m_input;
ImageData m_image;
int m_jpeg_length;
public Stream Source { get { return Stream.Null; } }
public ImageFormat SourceFormat { get { return null; } }
public ImageMetaData Info { get; private set; }
public PixelFormat Format { get; private set; }
public ImageData Image { get { return m_image ?? (m_image = Unpack()); } }
public SwfJpeg3Decoder (SwfChunk chunk)
{
m_input = chunk.Data;
m_jpeg_length = m_input.ToInt32 (2);
}
ImageData Unpack ()
{
BitmapSource image;
using (var jpeg = new BinMemoryStream (m_input, 6, m_jpeg_length))
{
var decoder = new JpegBitmapDecoder (jpeg, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
image = decoder.Frames[0];
}
Info = new ImageMetaData {
Width = (uint)image.PixelWidth,
Height = (uint)image.PixelHeight,
BPP = image.Format.BitsPerPixel,
};
byte[] alpha = new byte[image.PixelWidth * image.PixelHeight];
using (var input = new BinMemoryStream (m_input, 6 + m_jpeg_length, m_input.Length - (6+m_jpeg_length)))
using (var alpha_data = new ZLibStream (input, CompressionMode.Decompress))
{
alpha_data.Read (alpha, 0, alpha.Length);
}
if (image.Format.BitsPerPixel != 32)
image = new FormatConvertedBitmap (image, PixelFormats.Bgr32, null, 0);
int stride = image.PixelWidth * 4;
var pixels = new byte[stride * image.PixelHeight];
image.CopyPixels (pixels, stride, 0);
ApplyAlpha (pixels, alpha);
return ImageData.Create (Info, PixelFormats.Bgra32, null, pixels, stride);
}
void ApplyAlpha (byte[] pixels, byte[] alpha)
{
int src = 0;
for (int dst = 3; dst < pixels.Length; dst += 4)
{
pixels[dst] = alpha[src++];
}
}
public void Dispose ()
{
}
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Models
{
/// <summary>
/// FreeStyleBuild
/// </summary>
[DataContract(Name = "FreeStyleBuild")]
public partial class FreeStyleBuild : IEquatable<FreeStyleBuild>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="FreeStyleBuild" /> class.
/// </summary>
/// <param name="_class">_class.</param>
/// <param name="number">number.</param>
/// <param name="url">url.</param>
/// <param name="actions">actions.</param>
/// <param name="building">building.</param>
/// <param name="description">description.</param>
/// <param name="displayName">displayName.</param>
/// <param name="duration">duration.</param>
/// <param name="estimatedDuration">estimatedDuration.</param>
/// <param name="executor">executor.</param>
/// <param name="fullDisplayName">fullDisplayName.</param>
/// <param name="id">id.</param>
/// <param name="keepLog">keepLog.</param>
/// <param name="queueId">queueId.</param>
/// <param name="result">result.</param>
/// <param name="timestamp">timestamp.</param>
/// <param name="builtOn">builtOn.</param>
/// <param name="changeSet">changeSet.</param>
public FreeStyleBuild(string _class = default(string), int number = default(int), string url = default(string), List<CauseAction> actions = default(List<CauseAction>), bool building = default(bool), string description = default(string), string displayName = default(string), int duration = default(int), int estimatedDuration = default(int), string executor = default(string), string fullDisplayName = default(string), string id = default(string), bool keepLog = default(bool), int queueId = default(int), string result = default(string), int timestamp = default(int), string builtOn = default(string), EmptyChangeLogSet changeSet = default(EmptyChangeLogSet))
{
this.Class = _class;
this.Number = number;
this.Url = url;
this.Actions = actions;
this.Building = building;
this.Description = description;
this.DisplayName = displayName;
this.Duration = duration;
this.EstimatedDuration = estimatedDuration;
this.Executor = executor;
this.FullDisplayName = fullDisplayName;
this.Id = id;
this.KeepLog = keepLog;
this.QueueId = queueId;
this.Result = result;
this.Timestamp = timestamp;
this.BuiltOn = builtOn;
this.ChangeSet = changeSet;
}
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name = "_class", EmitDefaultValue = false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Number
/// </summary>
[DataMember(Name = "number", EmitDefaultValue = false)]
public int Number { get; set; }
/// <summary>
/// Gets or Sets Url
/// </summary>
[DataMember(Name = "url", EmitDefaultValue = false)]
public string Url { get; set; }
/// <summary>
/// Gets or Sets Actions
/// </summary>
[DataMember(Name = "actions", EmitDefaultValue = false)]
public List<CauseAction> Actions { get; set; }
/// <summary>
/// Gets or Sets Building
/// </summary>
[DataMember(Name = "building", EmitDefaultValue = true)]
public bool Building { get; set; }
/// <summary>
/// Gets or Sets Description
/// </summary>
[DataMember(Name = "description", EmitDefaultValue = false)]
public string Description { get; set; }
/// <summary>
/// Gets or Sets DisplayName
/// </summary>
[DataMember(Name = "displayName", EmitDefaultValue = false)]
public string DisplayName { get; set; }
/// <summary>
/// Gets or Sets Duration
/// </summary>
[DataMember(Name = "duration", EmitDefaultValue = false)]
public int Duration { get; set; }
/// <summary>
/// Gets or Sets EstimatedDuration
/// </summary>
[DataMember(Name = "estimatedDuration", EmitDefaultValue = false)]
public int EstimatedDuration { get; set; }
/// <summary>
/// Gets or Sets Executor
/// </summary>
[DataMember(Name = "executor", EmitDefaultValue = false)]
public string Executor { get; set; }
/// <summary>
/// Gets or Sets FullDisplayName
/// </summary>
[DataMember(Name = "fullDisplayName", EmitDefaultValue = false)]
public string FullDisplayName { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets KeepLog
/// </summary>
[DataMember(Name = "keepLog", EmitDefaultValue = true)]
public bool KeepLog { get; set; }
/// <summary>
/// Gets or Sets QueueId
/// </summary>
[DataMember(Name = "queueId", EmitDefaultValue = false)]
public int QueueId { get; set; }
/// <summary>
/// Gets or Sets Result
/// </summary>
[DataMember(Name = "result", EmitDefaultValue = false)]
public string Result { get; set; }
/// <summary>
/// Gets or Sets Timestamp
/// </summary>
[DataMember(Name = "timestamp", EmitDefaultValue = false)]
public int Timestamp { get; set; }
/// <summary>
/// Gets or Sets BuiltOn
/// </summary>
[DataMember(Name = "builtOn", EmitDefaultValue = false)]
public string BuiltOn { get; set; }
/// <summary>
/// Gets or Sets ChangeSet
/// </summary>
[DataMember(Name = "changeSet", EmitDefaultValue = false)]
public EmptyChangeLogSet ChangeSet { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class FreeStyleBuild {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Number: ").Append(Number).Append("\n");
sb.Append(" Url: ").Append(Url).Append("\n");
sb.Append(" Actions: ").Append(Actions).Append("\n");
sb.Append(" Building: ").Append(Building).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" DisplayName: ").Append(DisplayName).Append("\n");
sb.Append(" Duration: ").Append(Duration).Append("\n");
sb.Append(" EstimatedDuration: ").Append(EstimatedDuration).Append("\n");
sb.Append(" Executor: ").Append(Executor).Append("\n");
sb.Append(" FullDisplayName: ").Append(FullDisplayName).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" KeepLog: ").Append(KeepLog).Append("\n");
sb.Append(" QueueId: ").Append(QueueId).Append("\n");
sb.Append(" Result: ").Append(Result).Append("\n");
sb.Append(" Timestamp: ").Append(Timestamp).Append("\n");
sb.Append(" BuiltOn: ").Append(BuiltOn).Append("\n");
sb.Append(" ChangeSet: ").Append(ChangeSet).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as FreeStyleBuild);
}
/// <summary>
/// Returns true if FreeStyleBuild instances are equal
/// </summary>
/// <param name="input">Instance of FreeStyleBuild to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FreeStyleBuild input)
{
if (input == null)
return false;
return
(
this.Class == input.Class ||
(this.Class != null &&
this.Class.Equals(input.Class))
) &&
(
this.Number == input.Number ||
this.Number.Equals(input.Number)
) &&
(
this.Url == input.Url ||
(this.Url != null &&
this.Url.Equals(input.Url))
) &&
(
this.Actions == input.Actions ||
this.Actions != null &&
input.Actions != null &&
this.Actions.SequenceEqual(input.Actions)
) &&
(
this.Building == input.Building ||
this.Building.Equals(input.Building)
) &&
(
this.Description == input.Description ||
(this.Description != null &&
this.Description.Equals(input.Description))
) &&
(
this.DisplayName == input.DisplayName ||
(this.DisplayName != null &&
this.DisplayName.Equals(input.DisplayName))
) &&
(
this.Duration == input.Duration ||
this.Duration.Equals(input.Duration)
) &&
(
this.EstimatedDuration == input.EstimatedDuration ||
this.EstimatedDuration.Equals(input.EstimatedDuration)
) &&
(
this.Executor == input.Executor ||
(this.Executor != null &&
this.Executor.Equals(input.Executor))
) &&
(
this.FullDisplayName == input.FullDisplayName ||
(this.FullDisplayName != null &&
this.FullDisplayName.Equals(input.FullDisplayName))
) &&
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.KeepLog == input.KeepLog ||
this.KeepLog.Equals(input.KeepLog)
) &&
(
this.QueueId == input.QueueId ||
this.QueueId.Equals(input.QueueId)
) &&
(
this.Result == input.Result ||
(this.Result != null &&
this.Result.Equals(input.Result))
) &&
(
this.Timestamp == input.Timestamp ||
this.Timestamp.Equals(input.Timestamp)
) &&
(
this.BuiltOn == input.BuiltOn ||
(this.BuiltOn != null &&
this.BuiltOn.Equals(input.BuiltOn))
) &&
(
this.ChangeSet == input.ChangeSet ||
(this.ChangeSet != null &&
this.ChangeSet.Equals(input.ChangeSet))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Class != null)
hashCode = hashCode * 59 + this.Class.GetHashCode();
hashCode = hashCode * 59 + this.Number.GetHashCode();
if (this.Url != null)
hashCode = hashCode * 59 + this.Url.GetHashCode();
if (this.Actions != null)
hashCode = hashCode * 59 + this.Actions.GetHashCode();
hashCode = hashCode * 59 + this.Building.GetHashCode();
if (this.Description != null)
hashCode = hashCode * 59 + this.Description.GetHashCode();
if (this.DisplayName != null)
hashCode = hashCode * 59 + this.DisplayName.GetHashCode();
hashCode = hashCode * 59 + this.Duration.GetHashCode();
hashCode = hashCode * 59 + this.EstimatedDuration.GetHashCode();
if (this.Executor != null)
hashCode = hashCode * 59 + this.Executor.GetHashCode();
if (this.FullDisplayName != null)
hashCode = hashCode * 59 + this.FullDisplayName.GetHashCode();
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
hashCode = hashCode * 59 + this.KeepLog.GetHashCode();
hashCode = hashCode * 59 + this.QueueId.GetHashCode();
if (this.Result != null)
hashCode = hashCode * 59 + this.Result.GetHashCode();
hashCode = hashCode * 59 + this.Timestamp.GetHashCode();
if (this.BuiltOn != null)
hashCode = hashCode * 59 + this.BuiltOn.GetHashCode();
if (this.ChangeSet != null)
hashCode = hashCode * 59 + this.ChangeSet.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace UnityEditor.PackageManager.UI
{
[Serializable]
internal class PackageCollection
{
private static PackageCollection instance = new PackageCollection();
public static PackageCollection Instance { get { return instance; } }
public event Action<IEnumerable<Package>> OnPackagesChanged = delegate { };
public event Action<PackageFilter> OnFilterChanged = delegate { };
private readonly Dictionary<string, Package> packages;
private PackageFilter filter;
private string selectedListPackage;
private string selectedSearchPackage;
internal string lastUpdateTime;
private List<PackageInfo> listPackagesOffline;
private List<PackageInfo> listPackages;
private List<PackageInfo> searchPackages;
private List<PackageError> packageErrors;
private int listPackagesVersion;
private int listPackagesOfflineVersion;
private bool searchOperationOngoing;
private bool listOperationOngoing;
private bool listOperationOfflineOngoing;
private IListOperation listOperationOffline;
private IListOperation listOperation;
private ISearchOperation searchOperation;
public readonly OperationSignal<ISearchOperation> SearchSignal = new OperationSignal<ISearchOperation>();
public readonly OperationSignal<IListOperation> ListSignal = new OperationSignal<IListOperation>();
public static void InitInstance(ref PackageCollection value)
{
if (value == null) // UI window opened
{
value = instance;
Instance.OnPackagesChanged = delegate { };
Instance.OnFilterChanged = delegate { };
Instance.SearchSignal.ResetEvents();
Instance.ListSignal.ResetEvents();
Instance.FetchListOfflineCache(true);
Instance.FetchListCache(true);
Instance.FetchSearchCache(true);
}
else // Domain reload
{
instance = value;
Instance.RebuildPackageDictionary();
// Resume operations interrupted by domain reload
Instance.FetchListOfflineCache(Instance.listOperationOfflineOngoing);
Instance.FetchListCache(Instance.listOperationOngoing);
Instance.FetchSearchCache(Instance.searchOperationOngoing);
}
}
public PackageFilter Filter
{
get { return filter; }
// For public usage, use SetFilter() instead
private set
{
var changed = value != filter;
filter = value;
if (changed)
OnFilterChanged(filter);
}
}
public List<PackageInfo> LatestListPackages
{
get { return listPackagesVersion > listPackagesOfflineVersion? listPackages : listPackagesOffline; }
}
public List<PackageInfo> LatestSearchPackages { get { return searchPackages; } }
public string SelectedPackage
{
get { return PackageFilter.All == Filter ? selectedSearchPackage : selectedListPackage; }
set
{
if (PackageFilter.All == Filter)
selectedSearchPackage = value;
else
selectedListPackage = value;
}
}
private PackageCollection()
{
packages = new Dictionary<string, Package>();
listPackagesOffline = new List<PackageInfo>();
listPackages = new List<PackageInfo>();
searchPackages = new List<PackageInfo>();
packageErrors = new List<PackageError>();
listPackagesVersion = 0;
listPackagesOfflineVersion = 0;
searchOperationOngoing = false;
listOperationOngoing = false;
listOperationOfflineOngoing = false;
Filter = PackageFilter.All;
}
public bool SetFilter(PackageFilter value, bool refresh = true)
{
if (value == Filter)
return false;
Filter = value;
if (refresh)
{
UpdatePackageCollection();
}
return true;
}
public void UpdatePackageCollection(bool rebuildDictionary = false)
{
if (rebuildDictionary)
{
lastUpdateTime = DateTime.Now.ToString("HH:mm");
RebuildPackageDictionary();
}
if (packages.Any())
OnPackagesChanged(OrderedPackages());
}
internal void FetchListOfflineCache(bool forceRefetch = false)
{
if (!forceRefetch && (listOperationOfflineOngoing || listPackagesOffline.Any())) return;
if (listOperationOffline != null)
listOperationOffline.Cancel();
listOperationOfflineOngoing = true;
listOperationOffline = OperationFactory.Instance.CreateListOperation(true);
listOperationOffline.OnOperationFinalized += () =>
{
listOperationOfflineOngoing = false;
UpdatePackageCollection(true);
};
listOperationOffline.GetPackageListAsync(
infos =>
{
var version = listPackagesVersion;
UpdateListPackageInfosOffline(infos, version);
},
error => { Debug.LogError("Error fetching package list (offline mode)."); });
}
internal void FetchListCache(bool forceRefetch = false)
{
if (!forceRefetch && (listOperationOngoing || listPackages.Any())) return;
if (listOperation != null)
listOperation.Cancel();
listOperationOngoing = true;
listOperation = OperationFactory.Instance.CreateListOperation();
listOperation.OnOperationFinalized += () =>
{
listOperationOngoing = false;
UpdatePackageCollection(true);
};
listOperation.GetPackageListAsync(UpdateListPackageInfos,
error => { Debug.LogError("Error fetching package list."); });
ListSignal.SetOperation(listOperation);
}
internal void FetchSearchCache(bool forceRefetch = false)
{
if (!forceRefetch && (searchOperationOngoing || searchPackages.Any())) return;
if (searchOperation != null)
searchOperation.Cancel();
searchOperationOngoing = true;
searchOperation = OperationFactory.Instance.CreateSearchOperation();
searchOperation.OnOperationFinalized += () =>
{
searchOperationOngoing = false;
UpdatePackageCollection(true);
};
searchOperation.GetAllPackageAsync(UpdateSearchPackageInfos,
error => { Debug.LogError("Error searching packages online."); });
SearchSignal.SetOperation(searchOperation);
}
private void UpdateListPackageInfosOffline(IEnumerable<PackageInfo> newInfos, int version)
{
listPackagesOfflineVersion = version;
listPackagesOffline = newInfos.Where(p => p.IsUserVisible).ToList();
}
private void UpdateListPackageInfos(IEnumerable<PackageInfo> newInfos)
{
// Each time we fetch list packages, the cache for offline mode will be updated
// We keep track of the list packages version so that we know which version of cache
// we are getting with the offline fetch operation.
listPackagesVersion++;
listPackages = newInfos.Where(p => p.IsUserVisible).ToList();
listPackagesOffline = listPackages;
}
private void UpdateSearchPackageInfos(IEnumerable<PackageInfo> newInfos)
{
searchPackages = newInfos.Where(p => p.IsUserVisible).ToList();
}
private IEnumerable<Package> OrderedPackages()
{
return packages.Values.OrderBy(pkg => pkg.Versions.LastOrDefault() == null ? pkg.Name : pkg.Versions.Last().DisplayName).AsEnumerable();
}
public Package GetPackageByName(string name)
{
Package package;
packages.TryGetValue(name, out package);
return package;
}
public Error GetPackageError(Package package)
{
if (null == package) return null;
var firstMatchingError = packageErrors.FirstOrDefault(p => p.PackageName == package.Name);
return firstMatchingError != null ? firstMatchingError.Error : null;
}
public void AddPackageError(Package package, Error error)
{
if (null == package || null == error) return;
packageErrors.Add(new PackageError(package.Name, error));
}
public void RemovePackageErrors(Package package)
{
if (null == package) return;
packageErrors.RemoveAll(p => p.PackageName == package.Name);
}
private void RebuildPackageDictionary()
{
// Merge list & search packages
var allPackageInfos = new List<PackageInfo>(LatestListPackages);
var installedPackageIds = new HashSet<string>(allPackageInfos.Select(p => p.PackageId));
allPackageInfos.AddRange(searchPackages.Where(p => !installedPackageIds.Contains(p.PackageId)));
if (!PackageManagerPrefs.ShowPreviewPackages)
{
allPackageInfos = allPackageInfos.Where(p => !p.IsPreRelease || installedPackageIds.Contains(p.PackageId)).ToList();
}
// Rebuild packages dictionary
packages.Clear();
foreach (var p in allPackageInfos)
{
var packageName = p.Name;
if (packages.ContainsKey(packageName))
continue;
var packageQuery = from pkg in allPackageInfos where pkg.Name == packageName select pkg;
var package = new Package(packageName, packageQuery);
packages[packageName] = package;
}
}
}
}
| |
/* Copyright notice and license
Copyright 2007-2010 WebDriver committers
Copyright 2007-2010 Google Inc.
Portions copyright 2007 ThoughtWorks, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Text.RegularExpressions;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium
{
/// <summary>
/// Provides a mechanism by which to find elements within a document.
/// </summary>
/// <remarks>It is possible to create your own locating mechanisms for finding documents.
/// In order to do this,subclass this class and override the protected methods. However,
/// it is expected that that all subclasses rely on the basic finding mechanisms provided
/// through static methods of this class.
/// </remarks>
/// <example>This example shows a subclass for finding by name or by id.
/// <code>
/// public class FindByIdOrName
/// {
/// private string selector;
/// <para></para>
/// public FindByIdOrName(string idOrNameSelector)
/// {
/// selector = idOrNameSelector;
/// }
/// <para></para>
/// public IWebElement FindElement(IWebDriver driver)
/// {
/// IWebElement element = driver.FindElement(By.Id(selector));
/// if (element == null)
/// {
/// element = driver.FindElement(By.Name(selector);
/// }
/// return element;
/// }
/// }
/// </code>
/// </example>
public class By
{
private FindElementDelegate findElementMethod;
private FindElementsDelegate findElementsMethod;
private delegate IWebElement FindElementDelegate(ISearchContext context);
private delegate ReadOnlyCollection<IWebElement> FindElementsDelegate(ISearchContext context);
/// <summary>
/// Gets a mechanism to find elements by their ID.
/// </summary>
/// <param name="idToFind">The ID to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By Id(string idToFind)
{
if (idToFind == null)
{
throw new ArgumentNullException("idToFind", "Cannot find elements with a null id attribute.");
}
By by = new By();
by.findElementMethod = delegate(ISearchContext context)
{
return ((IFindsById)context).FindElementById(idToFind);
};
by.findElementsMethod = delegate(ISearchContext context)
{
return ((IFindsById)context).FindElementsById(idToFind);
};
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their link text.
/// </summary>
/// <param name="linkTextToFind">The link text to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By LinkText(string linkTextToFind)
{
if (linkTextToFind == null)
{
throw new ArgumentNullException("linkTextToFind", "Cannot find elements when link text is null.");
}
By by = new By();
by.findElementMethod = delegate(ISearchContext context)
{
return ((IFindsByLinkText)context).FindElementByLinkText(linkTextToFind);
};
by.findElementsMethod = delegate(ISearchContext context)
{
return ((IFindsByLinkText)context).FindElementsByLinkText(linkTextToFind);
};
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their name.
/// </summary>
/// <param name="nameToFind">The name to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By Name(string nameToFind)
{
if (nameToFind == null)
{
throw new ArgumentNullException("nameToFind", "Cannot find elements when name text is null.");
}
By by = new By();
by.findElementMethod = delegate(ISearchContext context)
{
return ((IFindsByName)context).FindElementByName(nameToFind);
};
by.findElementsMethod = delegate(ISearchContext context)
{
return ((IFindsByName)context).FindElementsByName(nameToFind);
};
return by;
}
/// <summary>
/// Gets a mechanism to find elements by an XPath query.
/// </summary>
/// <param name="xpathToFind">The XPath query to use.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By XPath(string xpathToFind)
{
if (xpathToFind == null)
{
throw new ArgumentNullException("xpathToFind", "Cannot find elements when the XPath expression is null.");
}
By by = new By();
by.findElementMethod = delegate(ISearchContext context)
{
return ((IFindsByXPath)context).FindElementByXPath(xpathToFind);
};
by.findElementsMethod = delegate(ISearchContext context)
{
return ((IFindsByXPath)context).FindElementsByXPath(xpathToFind);
};
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their CSS class.
/// </summary>
/// <param name="classNameToFind">The CSS class to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
/// <remarks>If an element has many classes then this will match against each of them.
/// For example if the value is "one two onone", then the following values for the
/// className parameter will match: "one" and "two".</remarks>
public static By ClassName(string classNameToFind)
{
if (classNameToFind == null)
{
throw new ArgumentNullException("classNameToFind", "Cannot find elements when the class name expression is null.");
}
if (new Regex(".*\\s+.*").IsMatch(classNameToFind))
{
throw new IllegalLocatorException("Compound class names are not supported. Consider searching for one class name and filtering the results.");
}
By by = new By();
by.findElementMethod = delegate(ISearchContext context)
{
return ((IFindsByClassName)context).FindElementByClassName(classNameToFind);
};
by.findElementsMethod = delegate(ISearchContext context)
{
return ((IFindsByClassName)context).FindElementsByClassName(classNameToFind);
};
return by;
}
/// <summary>
/// Gets a mechanism to find elements by a partial match on their link text.
/// </summary>
/// <param name="partialLinkTextToFind">The partial link text to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By PartialLinkText(string partialLinkTextToFind)
{
By by = new By();
by.findElementMethod = delegate(ISearchContext context)
{
return ((IFindsByPartialLinkText)context).FindElementByPartialLinkText(partialLinkTextToFind);
};
by.findElementsMethod = delegate(ISearchContext context)
{
return ((IFindsByPartialLinkText)context).FindElementsByPartialLinkText(partialLinkTextToFind);
};
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their tag name.
/// </summary>
/// <param name="tagNameToFind">The tag name to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By TagName(string tagNameToFind)
{
if (tagNameToFind == null)
{
throw new ArgumentNullException("tagNameToFind", "Cannot find elements when name tag name is null.");
}
By by = new By();
by.findElementMethod = delegate(ISearchContext context)
{
return ((IFindsByTagName)context).FindElementByTagName(tagNameToFind);
};
by.findElementsMethod = delegate(ISearchContext context)
{
return ((IFindsByTagName)context).FindElementsByTagName(tagNameToFind);
};
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their cascading stylesheet (CSS) selector.
/// </summary>
/// <param name="cssSelectorToFind">The CSS selector to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By CssSelector(string cssSelectorToFind)
{
if (cssSelectorToFind == null)
{
throw new ArgumentNullException("cssSelectorToFind", "Cannot find elements when name CSS selector is null.");
}
By by = new By();
by.findElementMethod = delegate(ISearchContext context)
{
return ((IFindsByCssSelector)context).FindElementByCssSelector(cssSelectorToFind);
};
by.findElementsMethod = delegate(ISearchContext context)
{
return ((IFindsByCssSelector)context).FindElementsByCssSelector(cssSelectorToFind);
};
return by;
}
/// <summary>
/// Finds the first element matching the criteria.
/// </summary>
/// <param name="context">An <see cref="ISearchContext"/> object to use to search for the elements.</param>
/// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns>
public IWebElement FindElement(ISearchContext context)
{
return findElementMethod(context);
}
/// <summary>
/// Finds all elements matching the criteria.
/// </summary>
/// <param name="context">An <see cref="ISearchContext"/> object to use to search for the elements.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see>
/// matching the current criteria, or an empty list if nothing matches.</returns>
public ReadOnlyCollection<IWebElement> FindElements(ISearchContext context)
{
return findElementsMethod(context);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System;
namespace RootMotion.FinalIK {
/// <summary>
/// Contains methods common for all heuristic solvers.
/// </summary>
[System.Serializable]
public class IKSolverHeuristic: IKSolver {
#region Main Interface
/// <summary>
/// The target Transform. Solver IKPosition will be automatically set to the position of the target.
/// </summary>
public Transform target;
/// <summary>
/// Minimum distance from last reached position. Will stop solving if difference from previous reached position is less than tolerance. If tolerance is zero, will iterate until maxIterations.
/// </summary>
public float tolerance = 0f;
/// <summary>
/// Max iterations per frame
/// </summary>
public int maxIterations = 4;
/// <summary>
/// If true, rotation limits (if excisting) will be applied on each iteration.
/// </summary>
public bool useRotationLimits = true;
/// <summary>
/// Solve in 2D?
/// </summary>
public bool XY;
/// <summary>
/// The hierarchy of bones.
/// </summary>
public Bone[] bones = new Bone[0];
/// <summary>
/// Rebuild the bone hierarcy and reinitiate the solver.
/// </summary>
/// <returns>
/// Returns true if the new chain is valid.
/// </returns>
public bool SetChain(Transform[] hierarchy, Transform root) {
if (bones == null || bones.Length != hierarchy.Length) bones = new Bone[hierarchy.Length];
for (int i = 0; i < hierarchy.Length; i++) {
if (bones[i] == null) bones[i] = new IKSolver.Bone();
bones[i].transform = hierarchy[i];
}
Initiate(root);
return initiated;
}
/// <summary>
/// Adds a bone to the chain.
/// </summary>
public void AddBone(Transform bone) {
Transform[] newBones = new Transform[bones.Length + 1];
for (int i = 0; i < bones.Length; i++) {
newBones[i] = bones[i].transform;
}
newBones[newBones.Length - 1] = bone;
SetChain(newBones, root);
}
public override void StoreDefaultLocalState() {
for (int i = 0; i < bones.Length; i++) bones[i].StoreDefaultLocalState();
}
public override void FixTransforms() {
for (int i = 0; i < bones.Length; i++) bones[i].FixTransform();
}
public override bool IsValid(ref string message) {
if (bones.Length == 0) {
message = "IK chain has no Bones.";
return false;
}
if (bones.Length < minBones) {
message = "IK chain has less than " + minBones + " Bones.";
return false;
}
foreach (Bone bone in bones) {
if (bone.transform == null) {
message = "One of the Bones is null.";
return false;
}
}
Transform duplicate = ContainsDuplicateBone(bones);
if (duplicate != null) {
message = duplicate.name + " is represented multiple times in the Bones.";
return false;
}
if (!allowCommonParent && !HierarchyIsValid(bones)) {
message = "Invalid bone hierarchy detected. IK requires for it's bones to be parented to each other in descending order.";
return false;
}
if (!boneLengthCanBeZero) {
for (int i = 0; i < bones.Length - 1; i++) {
float l = (bones[i].transform.position - bones[i + 1].transform.position).magnitude;
if (l == 0) {
message = "Bone " + i + " length is zero.";
return false;
}
}
}
return true;
}
public override IKSolver.Point[] GetPoints() {
return bones as IKSolver.Point[];
}
public override IKSolver.Point GetPoint(Transform transform) {
for (int i = 0; i < bones.Length; i++) if (bones[i].transform == transform) return bones[i] as IKSolver.Point;
return null;
}
#endregion Main Interface
protected virtual int minBones { get { return 2; }}
protected virtual bool boneLengthCanBeZero { get { return true; }}
protected virtual bool allowCommonParent { get { return false; }}
protected override void OnInitiate() {}
protected override void OnUpdate() {}
protected Vector3 lastLocalDirection;
protected float chainLength;
/*
* Initiates all bones to match their current state
* */
protected void InitiateBones() {
chainLength = 0;
for (int i = 0; i < bones.Length; i++) {
// Find out which local axis is directed at child/target position
if (i < bones.Length - 1) {
bones[i].length = (bones[i].transform.position - bones[i + 1].transform.position).magnitude;
chainLength += bones[i].length;
Vector3 nextPosition = bones[i + 1].transform.position;
bones[i].axis = Quaternion.Inverse(bones[i].transform.rotation) * (nextPosition - bones[i].transform.position);
// Disable Rotation Limits from updating to take control of their execution order
if (bones[i].rotationLimit != null) {
if (XY) {
if (bones[i].rotationLimit is RotationLimitHinge) {
} else Warning.Log("Only Hinge Rotation Limits should be used on 2D IK solvers.", bones[i].transform);
}
bones[i].rotationLimit.Disable();
}
} else {
bones[i].axis = Quaternion.Inverse(bones[i].transform.rotation) * (bones[bones.Length - 1].transform.position - bones[0].transform.position);
}
}
}
#region Optimizations
/*
* Gets the direction from last bone to first bone in first bone's local space.
* */
protected virtual Vector3 localDirection {
get {
return bones[0].transform.InverseTransformDirection(bones[bones.Length - 1].transform.position - bones[0].transform.position);
}
}
/*
* Gets the offset from last position of the last bone to its current position.
* */
protected float positionOffset {
get {
return Vector3.SqrMagnitude(localDirection - lastLocalDirection);
}
}
#endregion Optimizations
/*
* Get target offset to break out of the linear singularity issue
* */
protected Vector3 GetSingularityOffset() {
if (!SingularityDetected()) return Vector3.zero;
Vector3 IKDirection = (IKPosition - bones[0].transform.position).normalized;
Vector3 secondaryDirection = new Vector3(IKDirection.y, IKDirection.z, IKDirection.x);
// Avoiding getting locked by the Hinge Rotation Limit
if (useRotationLimits && bones[bones.Length - 2].rotationLimit != null && bones[bones.Length - 2].rotationLimit is RotationLimitHinge) {
secondaryDirection = bones[bones.Length - 2].transform.rotation * bones[bones.Length - 2].rotationLimit.axis;
}
return Vector3.Cross(IKDirection, secondaryDirection) * bones[bones.Length - 2].length * 0.5f;
}
/*
* Detects linear singularity issue when the direction from first bone to IKPosition matches the direction from first bone to the last bone.
* */
private bool SingularityDetected() {
if (!initiated) return false;
Vector3 toLastBone = bones[bones.Length - 1].transform.position - bones[0].transform.position;
Vector3 toIKPosition = IKPosition - bones[0].transform.position;
float toLastBoneDistance = toLastBone.magnitude;
float toIKPositionDistance = toIKPosition.magnitude;
if (toLastBoneDistance < toIKPositionDistance) return false;
if (toLastBoneDistance < chainLength - (bones[bones.Length - 2].length * 0.1f)) return false;
if (toLastBoneDistance == 0) return false;
if (toIKPositionDistance == 0) return false;
if (toIKPositionDistance > toLastBoneDistance) return false;
float dot = Vector3.Dot(toLastBone / toLastBoneDistance, toIKPosition / toIKPositionDistance);
if (dot < 0.999f) return false;
return true;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using log4net;
using Nini.Config;
using OpenSim.Framework;
//using OpenSim.Framework.Communications;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Hypergrid;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
public class HGCommands
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private HGGridConnector m_HGGridConnector;
private Scene m_scene;
private static uint m_autoMappingX = 0;
private static uint m_autoMappingY = 0;
private static bool m_enableAutoMapping = false;
public HGCommands(HGGridConnector hgConnector, Scene scene)
{
m_HGGridConnector = hgConnector;
m_scene = scene;
}
//public static Scene CreateScene(RegionInfo regionInfo, AgentCircuitManager circuitManager, CommunicationsManager m_commsManager,
// StorageManager storageManager, ModuleLoader m_moduleLoader, ConfigSettings m_configSettings, OpenSimConfigSource m_config, string m_version)
//{
// HGSceneCommunicationService sceneGridService = new HGSceneCommunicationService(m_commsManager, HGServices);
// return
// new HGScene(
// regionInfo, circuitManager, m_commsManager, sceneGridService, storageManager,
// m_moduleLoader, false, m_configSettings.PhysicalPrim,
// m_configSettings.See_into_region_from_neighbor, m_config.Source, m_version);
//}
public void RunCommand(string module, string[] cmdparams)
{
List<string> args = new List<string>(cmdparams);
if (args.Count < 1)
return;
string command = args[0];
args.RemoveAt(0);
cmdparams = args.ToArray();
RunHGCommand(command, cmdparams);
}
private void RunHGCommand(string command, string[] cmdparams)
{
if (command.Equals("link-mapping"))
{
if (cmdparams.Length == 2)
{
try
{
m_autoMappingX = Convert.ToUInt32(cmdparams[0]);
m_autoMappingY = Convert.ToUInt32(cmdparams[1]);
m_enableAutoMapping = true;
}
catch (Exception)
{
m_autoMappingX = 0;
m_autoMappingY = 0;
m_enableAutoMapping = false;
}
}
}
else if (command.Equals("link-region"))
{
if (cmdparams.Length < 3)
{
if ((cmdparams.Length == 1) || (cmdparams.Length == 2))
{
LoadXmlLinkFile(cmdparams);
}
else
{
LinkRegionCmdUsage();
}
return;
}
if (cmdparams[2].Contains(":"))
{
// New format
int xloc, yloc;
string mapName;
try
{
xloc = Convert.ToInt32(cmdparams[0]);
yloc = Convert.ToInt32(cmdparams[1]);
mapName = cmdparams[2];
if (cmdparams.Length > 3)
for (int i = 3; i < cmdparams.Length; i++)
mapName += " " + cmdparams[i];
m_log.Info(">> MapName: " + mapName);
//internalPort = Convert.ToUInt32(cmdparams[4]);
//remotingPort = Convert.ToUInt32(cmdparams[5]);
}
catch (Exception e)
{
m_log.Warn("[HGrid] Wrong format for link-region command: " + e.Message);
LinkRegionCmdUsage();
return;
}
// Convert cell coordinates given by the user to meters
xloc = xloc * (int)Constants.RegionSize;
yloc = yloc * (int)Constants.RegionSize;
m_HGGridConnector.TryLinkRegionToCoords(m_scene, null, mapName, xloc, yloc);
}
else
{
// old format
GridRegion regInfo;
int xloc, yloc;
uint externalPort;
string externalHostName;
try
{
xloc = Convert.ToInt32(cmdparams[0]);
yloc = Convert.ToInt32(cmdparams[1]);
externalPort = Convert.ToUInt32(cmdparams[3]);
externalHostName = cmdparams[2];
//internalPort = Convert.ToUInt32(cmdparams[4]);
//remotingPort = Convert.ToUInt32(cmdparams[5]);
}
catch (Exception e)
{
m_log.Warn("[HGrid] Wrong format for link-region command: " + e.Message);
LinkRegionCmdUsage();
return;
}
// Convert cell coordinates given by the user to meters
xloc = xloc * (int)Constants.RegionSize;
yloc = yloc * (int)Constants.RegionSize;
if (m_HGGridConnector.TryCreateLink(m_scene, null, xloc, yloc, "", externalPort, externalHostName, out regInfo))
{
if (cmdparams.Length >= 5)
{
regInfo.RegionName = "";
for (int i = 4; i < cmdparams.Length; i++)
regInfo.RegionName += cmdparams[i] + " ";
}
}
}
return;
}
else if (command.Equals("unlink-region"))
{
if (cmdparams.Length < 1)
{
UnlinkRegionCmdUsage();
return;
}
if (m_HGGridConnector.TryUnlinkRegion(m_scene, cmdparams[0]))
m_log.InfoFormat("[HGrid]: Successfully unlinked {0}", cmdparams[0]);
else
m_log.InfoFormat("[HGrid]: Unable to unlink {0}, region not found", cmdparams[0]);
}
}
private void LoadXmlLinkFile(string[] cmdparams)
{
//use http://www.hgurl.com/hypergrid.xml for test
try
{
XmlReader r = XmlReader.Create(cmdparams[0]);
XmlConfigSource cs = new XmlConfigSource(r);
string[] excludeSections = null;
if (cmdparams.Length == 2)
{
if (cmdparams[1].ToLower().StartsWith("excludelist:"))
{
string excludeString = cmdparams[1].ToLower();
excludeString = excludeString.Remove(0, 12);
char[] splitter = { ';' };
excludeSections = excludeString.Split(splitter);
}
}
for (int i = 0; i < cs.Configs.Count; i++)
{
bool skip = false;
if ((excludeSections != null) && (excludeSections.Length > 0))
{
for (int n = 0; n < excludeSections.Length; n++)
{
if (excludeSections[n] == cs.Configs[i].Name.ToLower())
{
skip = true;
break;
}
}
}
if (!skip)
{
ReadLinkFromConfig(cs.Configs[i]);
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
private void ReadLinkFromConfig(IConfig config)
{
GridRegion regInfo;
int xloc, yloc;
uint externalPort;
string externalHostName;
uint realXLoc, realYLoc;
xloc = Convert.ToInt32(config.GetString("xloc", "0"));
yloc = Convert.ToInt32(config.GetString("yloc", "0"));
externalPort = Convert.ToUInt32(config.GetString("externalPort", "0"));
externalHostName = config.GetString("externalHostName", "");
realXLoc = Convert.ToUInt32(config.GetString("real-xloc", "0"));
realYLoc = Convert.ToUInt32(config.GetString("real-yloc", "0"));
if (m_enableAutoMapping)
{
xloc = (int)((xloc % 100) + m_autoMappingX);
yloc = (int)((yloc % 100) + m_autoMappingY);
}
if (((realXLoc == 0) && (realYLoc == 0)) ||
(((realXLoc - xloc < 3896) || (xloc - realXLoc < 3896)) &&
((realYLoc - yloc < 3896) || (yloc - realYLoc < 3896))))
{
xloc = xloc * (int)Constants.RegionSize;
yloc = yloc * (int)Constants.RegionSize;
if (
m_HGGridConnector.TryCreateLink(m_scene, null, xloc, yloc, "", externalPort,
externalHostName, out regInfo))
{
regInfo.RegionName = config.GetString("localName", "");
}
}
}
private void LinkRegionCmdUsage()
{
m_log.Info("Usage: link-region <Xloc> <Yloc> <HostName>:<HttpPort>[:<RemoteRegionName>]");
m_log.Info("Usage: link-region <Xloc> <Yloc> <HostName> <HttpPort> [<LocalName>]");
m_log.Info("Usage: link-region <URI_of_xml> [<exclude>]");
}
private void UnlinkRegionCmdUsage()
{
m_log.Info("Usage: unlink-region <HostName>:<HttpPort>");
m_log.Info("Usage: unlink-region <LocalName>");
}
}
}
| |
// -------------------------------------------------------------------------------------------------------------------
// <copyright file="TankPerformanceTestFactory.cs" company="Orcomp development team">
// Copyright (c) 2014 Orcomp development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace TankLevels.PerformanceTests.Infrastructure
{
using System;
using System.Collections.Generic;
using System.Linq;
using Demo;
using Entities;
using NUnitBenchmarker;
using NUnitBenchmarker.Configuration;
using Tests.Infrastructure;
public class TankPerformanceTestFactory : TankTestBase
{
#region Constants
private const int IterationCount = 100;
private const double TankMinValue = -100;
private const double TankMaxValue = 100;
private const double TankStartHour = 0;
private const double TankEndHour = 168;
private const double ParameterMinQuantity = -120;
private const double ParameterMaxQuantity = 120;
private const double ParameterStartHour = -10;
private const double ParameterEndHour = 168 + 10;
private const double ParameterDurationMin = 0.0;
private const double ParameterDurationMax = 36.0;
private const double Multiplier = 1.0;
#endregion
#region Properties
private IEnumerable<Type> ImplementationTypes
{
// TODO: Remove the dummy implementations and add your own here
get { return new[] { typeof(DummyTank), typeof(OtherDummyTank) }; }
}
private static string[] TestCaseNames
{
get
{
return new[]
{
"Empty Tank",
"100 op. on random tank",
"ZigZag 1",
"ZigZag 2",
"ZigZag 1 start at 50%",
"ZigZag 2 start at 50%",
"ZigZag 1 start at 75%",
"ZigZag 2 start at 75%",
"ZigZag 1 start at 90%",
"ZigZag 2 start at 90%",
"One Interval",
"Calibration (check: size/10)"
};
}
}
private static IEnumerable<TestCase> ZigZag1TestCases
{
get
{
return new[]
{
TestCase.ZiZag1,
TestCase.ZiZag150,
TestCase.ZiZag175,
TestCase.ZiZag190
//TestCase.Calibration,
//TestCase.OneInterval,
};
}
}
private static IEnumerable<TestCase> ZigZag2TestCases
{
get
{
return new[]
{
TestCase.ZiZag2,
TestCase.ZiZag250,
TestCase.ZiZag275,
TestCase.ZiZag290
//TestCase.Calibration,
//TestCase.OneInterval,
};
}
}
private static IEnumerable<TestCase> RandomTestCases
{
get
{
return new[]
{
TestCase.RandomTank
};
}
}
private static IEnumerable<int> Sizes
{
get { return new[] { 100, 500, 1000, 5000, 10000, 25000, 50000, 100000 }; }
}
#endregion
public IEnumerable<TestConfiguration> CheckOperationZigZag1TestCases()
{
return CheckOperationTestCases(ZigZag1TestCases, "ZigZag 1");
}
#region Methods
public IEnumerable<TestConfiguration> CheckOperationZigZag2TestCases()
{
return CheckOperationTestCases(ZigZag2TestCases, "ZigZag 2");
}
public IEnumerable<TestConfiguration> CheckOperationRandomTestCases()
{
return CheckOperationTestCases(RandomTestCases, "Random");
}
public IEnumerable<TestConfiguration> CheckOperationTestCases(IEnumerable<TestCase> testCases, string name)
{
return from implementationType in ImplementationTypes
from testCase in testCases
from size in Sizes
let prepare = new Action<IPerformanceTestCaseConfiguration>(i =>
{
var config = (TestConfiguration) i;
config.Tank = CreateTank(size, testCase, implementationType);
config.TankLevels = CreateTankLevels(size, testCase);
config.Parameters = CreateParameters(size, testCase);
config.Divider = SetDivider(size, testCase);
})
let run = new Action<IPerformanceTestCaseConfiguration>(i =>
{
var config = (TestConfiguration) i;
//var trueCount = 0;
//var falseCount = 0;
//if (config.Parameters.Length == 0)
//{
// Thread.Sleep(config.Size/10);
// return;
//}
foreach (var p in config.Parameters)
{
// ReSharper disable once UnusedVariable
var result = config.Tank.CheckOperation(p.StartTime, p.Duration, p.Quantity, config.TankLevels);
//Debug.WriteLine((result.StartTime - Time(0)).TotalHours);
//var dummy = result.IsSuccess ? trueCount++ : falseCount++;
}
//Debug.WriteLine("I:{0}, S: {1}, C: {2}, NC: {3}", config.Identifier, config.Size, ((SimpleTank)config.Tank).Cache, ((SimpleTank)config.Tank).NoCache);
//Debug.WriteLine("True: {0}, False: {1}", trueCount, falseCount);
})
select new TestConfiguration
{
TestName = name,
TargetImplementationType = implementationType, // Mandatory to set
Identifier = string.Format("{0} {1}", implementationType.GetFriendlyName(), TestCaseNames[(int) testCase]),
Size = size,
Prepare = prepare,
Run = run,
IsReusable = true
};
}
private double SetDivider(int size, TestCase testCase)
{
if (testCase == TestCase.RandomTank)
{
return 100.0;
}
return 1.0;
}
private IEnumerable<TankLevel> CreateTankLevels(int size, TestCase testCase)
{
double minLimit;
double maxLimit;
TankLevel[] result;
GetMinMax(size, testCase, out minLimit, out maxLimit);
DateTime dateTime;
switch (testCase)
{
case TestCase.EmptyTank:
return new List<TankLevel>();
case TestCase.RandomTank:
{
result = new TankLevel[size];
var tickStep = (Time(TankEndHour) - Time(TankStartHour)).Ticks / size + 1;
var levelStep = maxLimit / (2 * size);
dateTime = Time(TankStartHour);
var level = maxLimit / 2;
for (var index = 0; index < result.Length; index++)
{
result[index] = new TankLevel(dateTime, level);
dateTime = dateTime.AddTicks(tickStep);
level -= levelStep;
level = -level;
levelStep = -levelStep;
}
return result;
}
case TestCase.ZiZag1:
case TestCase.ZiZag150:
case TestCase.ZiZag175:
case TestCase.ZiZag190:
{
result = new TankLevel[size + 1];
dateTime = Time(0);
for (var index = 0; index < size; index++)
{
var level = index % 2 == 0 ? index / 2 : (index / 2) + 2;
result[index] = new TankLevel(dateTime, level);
dateTime = dateTime.AddHours(1);
}
result[size] = new TankLevel(dateTime.AddHours(1), size / 2 - 1); // yes, AddHours(_1_)
return result;
}
case TestCase.ZiZag2:
case TestCase.ZiZag250:
case TestCase.ZiZag275:
case TestCase.ZiZag290:
result = new TankLevel[size + 2];
dateTime = Time(0);
for (var index = 0; index < size; index++)
{
var level = index % 2 == 0 ? 0 : 10;
result[index] = new TankLevel(dateTime, level);
dateTime = dateTime.AddHours(1);
}
result[size] = new TankLevel(dateTime, 0);
result[size + 1] = new TankLevel(dateTime.AddHours(1), 9);
return result;
case TestCase.OneInterval:
result = new TankLevel[2];
result[0] = new TankLevel(Time(0), 0);
result[1] = new TankLevel(Time(size), 10);
return result;
case TestCase.Calibration:
return new TankLevel[0];
default:
throw new ArgumentOutOfRangeException("testCase");
}
}
private CheckOperationParameter[] CreateParameters(int size, TestCase testCase)
{
CheckOperationParameter[] result;
switch (testCase)
{
case TestCase.EmptyTank:
case TestCase.RandomTank:
result = new CheckOperationParameter[IterationCount];
for (var index = 0; index < result.Length; index++)
{
var startDate = GetRandomDateTime(Time(ParameterStartHour), Time(ParameterEndHour));
var duration = Duration(GetRandomDouble(ParameterDurationMin, ParameterDurationMax));
var quantity = GetRandomDouble(ParameterMinQuantity, ParameterMaxQuantity);
result[index] = new CheckOperationParameter(startDate, duration, quantity);
}
return result;
case TestCase.ZiZag1:
case TestCase.ZiZag2:
result = new CheckOperationParameter[1];
result[0] = new CheckOperationParameter(Time(0), Duration(1), 1.0);
return result;
case TestCase.ZiZag150:
case TestCase.ZiZag250:
result = new CheckOperationParameter[1];
result[0] = new CheckOperationParameter(Time(size * .5), Duration(1), 1.0);
return result;
case TestCase.ZiZag175:
case TestCase.ZiZag275:
result = new CheckOperationParameter[1];
result[0] = new CheckOperationParameter(Time(size * .75), Duration(1), 1.0);
return result;
case TestCase.ZiZag190:
case TestCase.ZiZag290:
result = new CheckOperationParameter[1];
result[0] = new CheckOperationParameter(Time(size * .9), Duration(1), 1.0);
return result;
case TestCase.OneInterval:
result = new CheckOperationParameter[1];
result[0] = new CheckOperationParameter(Time(0), Duration(1), 1.0);
return result;
case TestCase.Calibration:
return new CheckOperationParameter[0];
default:
throw new ArgumentOutOfRangeException("testCase");
}
}
private ITank CreateTank(int size, TestCase testCase, Type type)
{
double minLimit;
double maxLimit;
GetMinMax(size, testCase, out minLimit, out maxLimit);
// This is for TankTestBase.CreateTank:
ImplementationType = type;
return CreateTank(minLimit, maxLimit);
}
private void GetMinMax(int size, TestCase testCase, out double minLimit, out double maxLimit)
{
switch (testCase)
{
case TestCase.EmptyTank:
minLimit = double.MinValue;
maxLimit = double.MaxValue;
break;
case TestCase.RandomTank:
minLimit = TankMinValue;
maxLimit = TankMaxValue;
break;
case TestCase.ZiZag1:
case TestCase.ZiZag150:
case TestCase.ZiZag175:
case TestCase.ZiZag190:
minLimit = 0;
maxLimit = size / 2 + 1;
break;
case TestCase.ZiZag2:
case TestCase.ZiZag250:
case TestCase.ZiZag275:
case TestCase.ZiZag290:
minLimit = 0;
maxLimit = 10;
break;
case TestCase.OneInterval:
minLimit = 0;
maxLimit = 10;
break;
case TestCase.Calibration:
minLimit = 0; // dummy
maxLimit = 10; // dummy
break;
default:
throw new ArgumentOutOfRangeException("testCase");
}
}
#endregion
}
}
| |
////////////////////////////////////////////////////////////////////////////////
//
// @module Texture Packer Plugin for Unity3D
// @author Osipov Stanislav lacost.st@gmail.com
//
////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
public class TPBaseAnimationEditor : Editor {
private SerializedProperty _useCollider;
private SerializedProperty _pivotCenterX;
private SerializedProperty _pivotCenterY;
private SerializedProperty _opacity;
private SerializedProperty _useSeparateMaterial;
private SerializedProperty _custom_shader;
private SerializedProperty _IsForceSelected;
private SerializedProperty _useImageName;
private SerializedProperty _frameRate;
private SerializedProperty _PlayOnStart;
private SerializedProperty _Loop;
private SerializedProperty _currentFrame;
//--------------------------------------
// INITIALIZE
//--------------------------------------
//--------------------------------------
// PUBLIC METHODS
//--------------------------------------
public virtual void OnEnable () {
_useCollider = serializedObject.FindProperty ("useCollider");
_pivotCenterX = serializedObject.FindProperty ("pivotCenterX");
_pivotCenterY = serializedObject.FindProperty ("pivotCenterY");
_opacity = serializedObject.FindProperty ("opacity");
_useSeparateMaterial = serializedObject.FindProperty("useSeparateMaterial");
_custom_shader = serializedObject.FindProperty("custom_shader");
_IsForceSelected = serializedObject.FindProperty("IsForceSelected");
_useImageName = serializedObject.FindProperty("useImageName");
_frameRate = serializedObject.FindProperty("frameRate");
_PlayOnStart = serializedObject.FindProperty("PlayOnStart");
_Loop = serializedObject.FindProperty("Loop");
_currentFrame = serializedObject.FindProperty("currentFrame");
}
public void DrawAnimationInfo() {
EditorGUILayout.Separator();
if(targets.Length == 1) {
int totalFrames = tpAnim.lastFrameIndex + 1;
float duration = totalFrames * (1f / tpAnim.frameRate);
EditorGUILayout.HelpBox("Total Frames: " + totalFrames + ", Duration: " + duration + " sec", MessageType.Info);
} else {
EditorGUILayout.HelpBox("Multiedition Mode", MessageType.Info);
}
EditorGUILayout.Separator();
}
public void DrawBaseAnimationGUI() {
EditorGUI.BeginChangeCheck();
EditorGUILayout.IntSlider(_currentFrame, 0, minLastFrame);
if (EditorGUI.EndChangeCheck ()) {
OnEditorFrameChange ();
}
EditorGUILayout.IntSlider(_frameRate, 1, 50);
EditorGUILayout.PropertyField(_PlayOnStart);
EditorGUILayout.PropertyField(_Loop);
}
public void DrawButtonsSection() {
EditorGUILayout.PropertyField (_IsForceSelected);
EditorGUILayout.PropertyField (_useImageName);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField (_useCollider);
if (EditorGUI.EndChangeCheck ()) {
serializedObject.ApplyModifiedProperties ();
foreach(TPBaseAnimation a in targets) {
a.OnColliderSettingsChange();
}
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.Slider (_opacity, 0f, 1f);
if (EditorGUI.EndChangeCheck ()) {
OnEditorFrameChange ();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.Slider (_pivotCenterX, 0f, 1f);
EditorGUILayout.Slider (_pivotCenterY, 0f, 1f);
if (EditorGUI.EndChangeCheck ()) {
OnEditorFrameChange();
}
EditorGUILayout.Separator();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField (_useSeparateMaterial);
if (EditorGUI.EndChangeCheck ()) {
OnEditorFrameChange();
}
if(tpAnim.useSeparateMaterial) {
EditorGUI.BeginChangeCheck();
_custom_shader.intValue = EditorGUILayout.Popup ("Shader", _custom_shader.intValue, TPShaders.importedShaders);
if (EditorGUI.EndChangeCheck ()) {
OnEditorFrameChange();
}
}
EditorGUILayout.Separator();
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
string addButtontext = "Add";
if(tpAnim is TPSpriteTexture) {
addButtontext = "Set";
}
if(GUILayout.Button(new GUIContent(addButtontext), GUILayout.Width(80))) {
EditorWindow.GetWindow<TexturePackerEditor>();
}
if(GUILayout.Button(new GUIContent("Clear"), GUILayout.Width(80))) {
Clear();
}
if(GUILayout.Button(new GUIContent("Update"), GUILayout.Width(80))) {
OnEditorFrameChange ();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
serializedObject.ApplyModifiedProperties ();
}
//--------------------------------------
// GET/SET
//--------------------------------------
public int minLastFrame {
get {
int min = tpAnim.lastFrameIndex;
foreach(TPBaseAnimation a in targets) {
if(a.lastFrameIndex < min) {
min = a.lastFrameIndex;
}
}
return min;
}
}
public TPBaseAnimation tpAnim {
get {
return target as TPBaseAnimation;
}
}
//--------------------------------------
// EVENTS
//--------------------------------------
//--------------------------------------
// PRIVATE METHODS
//--------------------------------------
protected void Clear() {
foreach(TPBaseAnimation a in targets) {
a.ClearFrames();
a.OnEditorFrameChange();
}
}
protected void OnEditorFrameChange() {
serializedObject.ApplyModifiedProperties ();
foreach(TPBaseAnimation a in targets) {
a.OnEditorFrameChange();
}
}
//--------------------------------------
// DESTROY
//--------------------------------------
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Xml;
//using System.Collections;
//using System.Text;
using Google.GData.Client;
namespace Google.GData.Extensions.Exif {
/// <summary>
/// helper to instantiate all factories defined in here and attach
/// them to a base object
/// </summary>
public class ExifExtensions
{
/// <summary>
/// adds all ExifExtensions to the passed in baseObject
/// </summary>
/// <param name="baseObject"></param>
public static void AddExtension(AtomBase baseObject)
{
baseObject.AddExtension(new ExifTags());
}
}
/// <summary>
/// short table for constants related to exif xml declarations
/// </summary>
public class ExifNameTable
{
/// <summary>static string to specify the exif namespace
/// </summary>
public const string NSExif = "http://schemas.google.com/photos/exif/2007";
/// <summary>static string to specify the used exif prefix</summary>
public const string ExifPrefix = "exif";
/// <summary>
/// represents the tags container element
/// </summary>
public const string ExifTags = "tags";
/// <summary>
/// represents the distance element
/// </summary>
public const string ExifDistance = "distance";
/// <summary>
/// represents the exposure element
/// </summary>
public const string ExifExposure = "exposure";
/// <summary>
/// represents the flash element
/// </summary>
public const string ExifFlash = "flash";
/// <summary>
/// represents the focallength element
/// </summary>
public const string ExifFocalLength = "focallength";
/// <summary>
/// represents the fstop element
/// </summary>
public const string ExifFStop = "fstop";
/// <summary>
/// represents the unique ID element
/// </summary>
public const string ExifImageUniqueID = "imageUniqueID";
/// <summary>
/// represents the ISO element
/// </summary>
public const string ExifISO = "iso";
/// <summary>
/// represents the Make element
/// </summary>
public const string ExifMake = "make";
/// <summary>
/// represents the Model element
/// </summary>
public const string ExifModel = "model";
/// <summary>
/// represents the Time element
/// </summary>
public const string ExifTime = "time";
}
/// <summary>
/// Tags container element for the Exif namespace
/// </summary>
public class ExifTags : SimpleContainer
{
/// <summary>
/// base constructor, creates an exif:tags representation
/// </summary>
public ExifTags() :
base(ExifNameTable.ExifTags,
ExifNameTable.ExifPrefix,
ExifNameTable.NSExif)
{
this.ExtensionFactories.Add(new ExifDistance());
this.ExtensionFactories.Add(new ExifExposure());
this.ExtensionFactories.Add(new ExifFlash());
this.ExtensionFactories.Add(new ExifFocalLength());
this.ExtensionFactories.Add(new ExifFStop());
this.ExtensionFactories.Add(new ExifImageUniqueID());
this.ExtensionFactories.Add(new ExifISO());
this.ExtensionFactories.Add(new ExifMake());
this.ExtensionFactories.Add(new ExifModel());
this.ExtensionFactories.Add(new ExifTime());
}
/// <summary>
/// returns the media:credit element
/// </summary>
public ExifDistance Distance
{
get
{
return FindExtension(ExifNameTable.ExifDistance,
ExifNameTable.NSExif) as ExifDistance;
}
set
{
ReplaceExtension(ExifNameTable.ExifDistance,
ExifNameTable.NSExif,
value);
}
}
/// <summary>
/// returns the ExifExposure element
/// </summary>
public ExifExposure Exposure
{
get
{
return FindExtension(ExifNameTable.ExifExposure,
ExifNameTable.NSExif) as ExifExposure;
}
set
{
ReplaceExtension(ExifNameTable.ExifExposure,
ExifNameTable.NSExif,
value);
}
}
/// <summary>
/// returns the ExifFlash element
/// </summary>
public ExifFlash Flash
{
get
{
return FindExtension(ExifNameTable.ExifFlash,
ExifNameTable.NSExif) as ExifFlash;
}
set
{
ReplaceExtension(ExifNameTable.ExifFlash,
ExifNameTable.NSExif,
value);
}
}
/// <summary>
/// returns the ExifFocalLength element
/// </summary>
public ExifFocalLength FocalLength
{
get
{
return FindExtension(ExifNameTable.ExifFocalLength,
ExifNameTable.NSExif) as ExifFocalLength;
}
set
{
ReplaceExtension(ExifNameTable.ExifFocalLength,
ExifNameTable.NSExif,
value);
}
}
/// <summary>
/// returns the ExifFStop element
/// </summary>
public ExifFStop FStop
{
get
{
return FindExtension(ExifNameTable.ExifFStop,
ExifNameTable.NSExif) as ExifFStop;
}
set
{
ReplaceExtension(ExifNameTable.ExifFStop,
ExifNameTable.NSExif,
value);
}
}
/// <summary>
/// returns the ExifImageUniqueID element
/// </summary>
public ExifImageUniqueID ImageUniqueID
{
get
{
return FindExtension(ExifNameTable.ExifImageUniqueID,
ExifNameTable.NSExif) as ExifImageUniqueID;
}
set
{
ReplaceExtension(ExifNameTable.ExifImageUniqueID,
ExifNameTable.NSExif,
value);
}
}
/// <summary>
/// returns the ExifISO element
/// </summary>
public ExifISO ISO
{
get
{
return FindExtension(ExifNameTable.ExifISO,
ExifNameTable.NSExif) as ExifISO;
}
set
{
ReplaceExtension(ExifNameTable.ExifISO,
ExifNameTable.NSExif,
value);
}
}
/// <summary>
/// returns the ExifMake element
/// </summary>
public ExifMake Make
{
get
{
return FindExtension(ExifNameTable.ExifMake,
ExifNameTable.NSExif) as ExifMake;
}
set
{
ReplaceExtension(ExifNameTable.ExifMake,
ExifNameTable.NSExif,
value);
}
}
/// <summary>
/// returns the ExifModel element
/// </summary>
public ExifModel Model
{
get
{
return FindExtension(ExifNameTable.ExifModel,
ExifNameTable.NSExif) as ExifModel;
}
set
{
ReplaceExtension(ExifNameTable.ExifModel,
ExifNameTable.NSExif,
value);
}
}
/// <summary>
/// returns the ExifTime element
/// </summary>
public ExifTime Time
{
get
{
return FindExtension(ExifNameTable.ExifTime,
ExifNameTable.NSExif) as ExifTime;
}
set
{
ReplaceExtension(ExifNameTable.ExifTime,
ExifNameTable.NSExif,
value);
}
}
}
// end of ExifTags
/// <summary>
/// ExifDistance schema extension describing an distance
/// </summary>
public class ExifDistance : SimpleElement
{
/// <summary>
/// basse constructor for exif:distance
/// </summary>
public ExifDistance()
: base(ExifNameTable.ExifDistance, ExifNameTable.ExifPrefix, ExifNameTable.NSExif)
{}
/// <summary>
/// base constructor taking an initial value
/// </summary>
/// <param name="initValue"></param>
public ExifDistance(string initValue)
: base(ExifNameTable.ExifDistance, ExifNameTable.ExifPrefix, ExifNameTable.NSExif, initValue)
{}
}
/// <summary>
/// ExifExposure schema extension describing an exposure
/// </summary>
public class ExifExposure : SimpleElement
{
/// <summary>
/// basse constructor for exif:exposure
/// </summary>
public ExifExposure()
: base(ExifNameTable.ExifExposure, ExifNameTable.ExifPrefix, ExifNameTable.NSExif)
{}
/// <summary>
/// base constructor taking an initial value
/// </summary>
/// <param name="initValue"></param>
public ExifExposure(string initValue)
: base(ExifNameTable.ExifExposure, ExifNameTable.ExifPrefix, ExifNameTable.NSExif, initValue)
{}
}
/// <summary>
/// ExifFlash schema extension describing an flash
/// </summary>
public class ExifFlash : SimpleElement
{
/// <summary>
/// basse constructor for exif:flash
/// </summary>
public ExifFlash()
: base(ExifNameTable.ExifFlash, ExifNameTable.ExifPrefix, ExifNameTable.NSExif)
{}
/// <summary>
/// base constructor taking an initial value
/// </summary>
/// <param name="initValue"></param>
public ExifFlash(string initValue)
: base(ExifNameTable.ExifFlash, ExifNameTable.ExifPrefix, ExifNameTable.NSExif, initValue)
{}
}
/// <summary>
/// ExifFocalLength schema extension describing an focallength
/// </summary>
public class ExifFocalLength : SimpleElement
{
/// <summary>
/// basse constructor for exif:focallength
/// </summary>
public ExifFocalLength()
: base(ExifNameTable.ExifFocalLength, ExifNameTable.ExifPrefix, ExifNameTable.NSExif)
{}
/// <summary>
/// base constructor taking an initial value
/// </summary>
/// <param name="initValue"></param>
public ExifFocalLength(string initValue)
: base(ExifNameTable.ExifFocalLength, ExifNameTable.ExifPrefix, ExifNameTable.NSExif, initValue)
{}
}
/// <summary>
/// ExifFStop schema extension describing an fstop
/// </summary>
public class ExifFStop : SimpleElement
{
/// <summary>
/// basse constructor for exif:fstop
/// </summary>
public ExifFStop()
: base(ExifNameTable.ExifFStop, ExifNameTable.ExifPrefix, ExifNameTable.NSExif)
{}
/// <summary>
/// base constructor taking an initial value
/// </summary>
/// <param name="initValue"></param>
public ExifFStop(string initValue)
: base(ExifNameTable.ExifFStop, ExifNameTable.ExifPrefix, ExifNameTable.NSExif, initValue)
{}
}
/// <summary>
/// ExifImageUniqueID schema extension describing an imageUniqueID
/// </summary>
public class ExifImageUniqueID : SimpleElement
{
/// <summary>
/// basse constructor for exif:imageUniqueID
/// </summary>
public ExifImageUniqueID()
: base(ExifNameTable.ExifImageUniqueID, ExifNameTable.ExifPrefix, ExifNameTable.NSExif)
{}
/// <summary>
/// base constructor taking an initial value
/// </summary>
/// <param name="initValue"></param>
public ExifImageUniqueID(string initValue)
: base(ExifNameTable.ExifImageUniqueID, ExifNameTable.ExifPrefix, ExifNameTable.NSExif, initValue)
{}
}
/// <summary>
/// ExifISO schema extension describing an iso
/// </summary>
public class ExifISO : SimpleElement
{
/// <summary>
/// basse constructor for exif:iso
/// </summary>
public ExifISO()
: base(ExifNameTable.ExifISO, ExifNameTable.ExifPrefix, ExifNameTable.NSExif)
{}
/// <summary>
/// base constructor taking an initial value
/// </summary>
/// <param name="initValue"></param>
public ExifISO(string initValue)
: base(ExifNameTable.ExifISO, ExifNameTable.ExifPrefix, ExifNameTable.NSExif, initValue)
{}
}
/// <summary>
/// ExifMake schema extension describing an make
/// </summary>
public class ExifMake : SimpleElement
{
/// <summary>
/// basse constructor for exif:make
/// </summary>
public ExifMake()
: base(ExifNameTable.ExifMake, ExifNameTable.ExifPrefix, ExifNameTable.NSExif)
{}
/// <summary>
/// base constructor taking an initial value
/// </summary>
/// <param name="initValue"></param>
public ExifMake(string initValue)
: base(ExifNameTable.ExifMake, ExifNameTable.ExifPrefix, ExifNameTable.NSExif, initValue)
{}
}
/// <summary>
/// ExifModel schema extension describing an model
/// </summary>
public class ExifModel : SimpleElement
{
/// <summary>
/// basse constructor for exif:model
/// </summary>
public ExifModel()
: base(ExifNameTable.ExifModel, ExifNameTable.ExifPrefix, ExifNameTable.NSExif)
{}
/// <summary>
/// base constructor taking an initial value
/// </summary>
/// <param name="initValue"></param>
public ExifModel(string initValue)
: base(ExifNameTable.ExifModel, ExifNameTable.ExifPrefix, ExifNameTable.NSExif, initValue)
{}
}
/// <summary>
/// ExifTime schema extension describing an time
/// </summary>
public class ExifTime : SimpleElement
{
/// <summary>
/// basse constructor for exif:time
/// </summary>
public ExifTime()
: base(ExifNameTable.ExifTime, ExifNameTable.ExifPrefix, ExifNameTable.NSExif)
{}
/// <summary>
/// base constructor taking an initial value
/// </summary>
/// <param name="initValue"></param>
public ExifTime(string initValue)
: base(ExifNameTable.ExifTime, ExifNameTable.ExifPrefix, ExifNameTable.NSExif, initValue)
{}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
#nullable enable
namespace System.Buffers
{
/// <summary>
/// Block tracking object used by the byte buffer memory pool. A slab is a large allocation which is divided into smaller blocks. The
/// individual blocks are then treated as independent array segments.
/// </summary>
internal sealed class DiagnosticPoolBlock : MemoryManager<byte>
{
/// <summary>
/// Back-reference to the memory pool which this block was allocated from. It may only be returned to this pool.
/// </summary>
private readonly DiagnosticMemoryPool _pool;
private readonly IMemoryOwner<byte> _memoryOwner;
private MemoryHandle? _memoryHandle;
private readonly Memory<byte> _memory;
private readonly object _syncObj = new object();
private bool _isDisposed;
private int _pinCount;
/// <summary>
/// This object cannot be instantiated outside of the static Create method
/// </summary>
internal DiagnosticPoolBlock(DiagnosticMemoryPool pool, IMemoryOwner<byte> memoryOwner)
{
_pool = pool;
_memoryOwner = memoryOwner;
_memory = memoryOwner.Memory;
}
public override Memory<byte> Memory
{
get
{
try
{
lock (_syncObj)
{
if (_isDisposed)
{
MemoryPoolThrowHelper.ThrowObjectDisposedException(MemoryPoolThrowHelper.ExceptionArgument.MemoryPoolBlock);
}
if (_pool.IsDisposed)
{
MemoryPoolThrowHelper.ThrowInvalidOperationException_BlockIsBackedByDisposedSlab(this);
}
return CreateMemory(_memory.Length);
}
}
catch (Exception exception)
{
_pool.ReportException(exception);
throw;
}
}
}
protected override void Dispose(bool disposing)
{
try
{
lock (_syncObj)
{
if (Volatile.Read(ref _pinCount) > 0)
{
MemoryPoolThrowHelper.ThrowInvalidOperationException_ReturningPinnedBlock(this);
}
if (_isDisposed)
{
MemoryPoolThrowHelper.ThrowInvalidOperationException_BlockDoubleDispose(this);
}
_memoryOwner.Dispose();
_pool.Return(this);
_isDisposed = true;
}
}
catch (Exception exception)
{
_pool.ReportException(exception);
throw;
}
}
public override Span<byte> GetSpan()
{
try
{
lock (_syncObj)
{
if (_isDisposed)
{
MemoryPoolThrowHelper.ThrowObjectDisposedException(MemoryPoolThrowHelper.ExceptionArgument.MemoryPoolBlock);
}
if (_pool.IsDisposed)
{
MemoryPoolThrowHelper.ThrowInvalidOperationException_BlockIsBackedByDisposedSlab(this);
}
return _memory.Span;
}
}
catch (Exception exception)
{
_pool.ReportException(exception);
throw;
}
}
public override MemoryHandle Pin(int byteOffset = 0)
{
try
{
lock (_syncObj)
{
if (_isDisposed)
{
MemoryPoolThrowHelper.ThrowObjectDisposedException(MemoryPoolThrowHelper.ExceptionArgument.MemoryPoolBlock);
}
if (_pool.IsDisposed)
{
MemoryPoolThrowHelper.ThrowInvalidOperationException_BlockIsBackedByDisposedSlab(this);
}
if (byteOffset < 0 || byteOffset > _memory.Length)
{
MemoryPoolThrowHelper.ThrowArgumentOutOfRangeException(_memory.Length, byteOffset);
}
_pinCount++;
_memoryHandle = _memoryHandle ?? _memory.Pin();
unsafe
{
return new MemoryHandle(((IntPtr)_memoryHandle.Value.Pointer + byteOffset).ToPointer(), default, this);
}
}
}
catch (Exception exception)
{
_pool.ReportException(exception);
throw;
}
}
protected override bool TryGetArray(out ArraySegment<byte> segment)
{
try
{
lock (_syncObj)
{
if (_isDisposed)
{
MemoryPoolThrowHelper.ThrowObjectDisposedException(MemoryPoolThrowHelper.ExceptionArgument.MemoryPoolBlock);
}
if (_pool.IsDisposed)
{
MemoryPoolThrowHelper.ThrowInvalidOperationException_BlockIsBackedByDisposedSlab(this);
}
return MemoryMarshal.TryGetArray(_memory, out segment);
}
}
catch (Exception exception)
{
_pool.ReportException(exception);
throw;
}
}
public override void Unpin()
{
try
{
lock (_syncObj)
{
if (_pinCount == 0)
{
MemoryPoolThrowHelper.ThrowInvalidOperationException_PinCountZero(this);
}
_pinCount--;
if (_pinCount == 0)
{
Debug.Assert(_memoryHandle.HasValue);
_memoryHandle.Value.Dispose();
_memoryHandle = null;
}
}
}
catch (Exception exception)
{
_pool.ReportException(exception);
throw;
}
}
public StackTrace? Leaser { get; set; }
public void Track()
{
Leaser = new StackTrace(false);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Media.Test
{
public class SoundPlayerTests
{
[Fact]
public void Ctor_Default()
{
var player = new SoundPlayer();
Assert.Null(player.Container);
Assert.False(player.IsLoadCompleted);
Assert.Equal(10000, player.LoadTimeout);
Assert.Null(player.Site);
Assert.Empty(player.SoundLocation);
Assert.Null(player.Stream);
Assert.Null(player.Tag);
}
public static IEnumerable<object[]> Stream_TestData()
{
yield return new object[] { null };
yield return new object[] { new MemoryStream() };
}
[Theory]
[MemberData(nameof(Stream_TestData))]
public void Ctor_Stream(Stream stream)
{
var player = new SoundPlayer(stream);
Assert.Null(player.Container);
Assert.False(player.IsLoadCompleted);
Assert.Equal(10000, player.LoadTimeout);
Assert.Null(player.Site);
Assert.Empty(player.SoundLocation);
Assert.Same(stream, player.Stream);
Assert.Null(player.Tag);
}
[Theory]
[InlineData("http://google.com")]
[InlineData("invalid")]
[InlineData("/file")]
public void Ctor_String(string soundLocation)
{
var player = new SoundPlayer(soundLocation);
Assert.Null(player.Container);
Assert.False(player.IsLoadCompleted);
Assert.Equal(10000, player.LoadTimeout);
Assert.Null(player.Site);
Assert.Equal(soundLocation ?? "", player.SoundLocation);
Assert.Null(player.Stream);
Assert.Null(player.Tag);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Ctor_NullOrEmptyString_ThrowsArgumentException(string soundLocation)
{
AssertExtensions.Throws<ArgumentException>("path", null, () => new SoundPlayer(soundLocation));
}
public static IEnumerable<object[]> Play_String_TestData()
{
yield return new object[] { "adpcm.wav" };
yield return new object[] { "pcm.wav" };
}
public static IEnumerable<object[]> Play_InvalidString_TestData()
{
yield return new object[] { "ccitt.wav" };
yield return new object[] { "ima.wav" };
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[MemberData(nameof(Play_String_TestData))]
[OuterLoop]
public void Load_SourceLocation_Success(string sourceLocation)
{
var soundPlayer = new SoundPlayer(sourceLocation);
soundPlayer.Load();
// Load again.
soundPlayer.Load();
// Play.
soundPlayer.Play();
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[MemberData(nameof(Play_String_TestData))]
[OuterLoop]
public async Task LoadAsync_SourceLocationFromNetwork_Success(string sourceLocation)
{
var player = new SoundPlayer();
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
var ep = (IPEndPoint)listener.LocalEndPoint;
Task serverTask = Task.Run(async () =>
{
using (Socket server = await listener.AcceptAsync())
using (var serverStream = new NetworkStream(server))
using (var reader = new StreamReader(new NetworkStream(server)))
using (FileStream sourceStream = File.OpenRead(sourceLocation.Replace("file://", "")))
{
string line;
while (!string.IsNullOrEmpty(line = await reader.ReadLineAsync()));
byte[] header = Encoding.UTF8.GetBytes($"HTTP/1.1 200 OK\r\nContent-Length: {sourceStream.Length}\r\n\r\n");
serverStream.Write(header, 0, header.Length);
await sourceStream.CopyToAsync(serverStream);
server.Shutdown(SocketShutdown.Both);
}
});
var tcs = new TaskCompletionSource<AsyncCompletedEventArgs>();
player.LoadCompleted += (s, e) => tcs.TrySetResult(e);
player.SoundLocation = $"http://{ep.Address}:{ep.Port}";
player.LoadAsync();
AsyncCompletedEventArgs ea = await tcs.Task;
Assert.Null(ea.Error);
Assert.False(ea.Cancelled);
await serverTask;
}
player.Play();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[OuterLoop]
public void Play_InvalidFile_ShortTimeout_ThrowsWebException()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
var ep = (IPEndPoint)listener.LocalEndPoint;
var player = new SoundPlayer();
player.SoundLocation = $"http://{ep.Address}:{ep.Port}";
player.LoadTimeout = 1;
Assert.Throws<WebException>(() => player.Play());
}
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[MemberData(nameof(Play_String_TestData))]
[OuterLoop]
public void Load_Stream_Success(string sourceLocation)
{
using (FileStream stream = File.OpenRead(sourceLocation.Replace("file://", "")))
{
var soundPlayer = new SoundPlayer(stream);
soundPlayer.Load();
// Load again.
soundPlayer.Load();
// Play.
soundPlayer.Play();
}
}
[Fact]
public void Load_NoSuchFile_ThrowsFileNotFoundException()
{
var soundPlayer = new SoundPlayer("noSuchFile");
Assert.Throws<FileNotFoundException>(() => soundPlayer.Load());
}
[Fact]
public void Load_NullStream_ThrowsNullReferenceException()
{
var player = new SoundPlayer();
Assert.Throws<NullReferenceException>(() => player.Load());
player = new SoundPlayer((Stream)null);
Assert.Throws<NullReferenceException>(() => player.Load());
}
[Theory]
[MemberData(nameof(Play_InvalidString_TestData))]
public void Load_InvalidSourceLocation_Success(string sourceLocation)
{
var soundPlayer = new SoundPlayer(sourceLocation);
soundPlayer.Load();
}
[Theory]
[MemberData(nameof(Play_InvalidString_TestData))]
public void Load_InvalidStream_Success(string sourceLocation)
{
using (FileStream stream = File.OpenRead(sourceLocation))
{
var soundPlayer = new SoundPlayer(stream);
soundPlayer.Load();
}
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[MemberData(nameof(Play_String_TestData))]
[OuterLoop]
public void Play_SourceLocation_Success(string sourceLocation)
{
var soundPlayer = new SoundPlayer(sourceLocation);
soundPlayer.Play();
// Play again.
soundPlayer.Play();
// Load.
soundPlayer.Load();
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
public void Play_NoSuchFile_ThrowsFileNotFoundException()
{
var soundPlayer = new SoundPlayer("noSuchFile");
Assert.Throws<FileNotFoundException>(() => soundPlayer.Play());
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[MemberData(nameof(Play_String_TestData))]
[OuterLoop]
public void Play_Stream_Success(string sourceLocation)
{
using (FileStream stream = File.OpenRead(sourceLocation.Replace("file://", "")))
{
var soundPlayer = new SoundPlayer(stream);
soundPlayer.Play();
// Play again.
soundPlayer.Play();
// Load.
soundPlayer.Load();
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[OuterLoop]
public void Play_NullStream_Success()
{
var player = new SoundPlayer();
player.Play();
player = new SoundPlayer((Stream)null);
player.Play();
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[MemberData(nameof(Play_InvalidString_TestData))]
public void Play_InvalidFile_ThrowsInvalidOperationException(string sourceLocation)
{
var soundPlayer = new SoundPlayer(sourceLocation);
Assert.Throws<InvalidOperationException>(() => soundPlayer.Play());
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[MemberData(nameof(Play_InvalidString_TestData))]
public void Play_InvalidStream_ThrowsInvalidOperationException(string sourceLocation)
{
using (FileStream stream = File.OpenRead(sourceLocation.Replace("file://", "")))
{
var soundPlayer = new SoundPlayer(stream);
Assert.Throws<InvalidOperationException>(() => soundPlayer.Play());
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[OuterLoop]
public void PlayLooping_NullStream_Success()
{
var player = new SoundPlayer();
player.PlayLooping();
player = new SoundPlayer((Stream)null);
player.PlayLooping();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[OuterLoop]
public void PlaySync_NullStream_Success()
{
var player = new SoundPlayer();
player.PlaySync();
player = new SoundPlayer((Stream)null);
player.PlaySync();
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void LoadTimeout_SetValid_GetReturnsExpected(int value)
{
var player = new SoundPlayer { LoadTimeout = value };
Assert.Equal(value, player.LoadTimeout);
}
[Fact]
public void LoadTimeout_SetNegative_ThrowsArgumentOutOfRangeException()
{
var player = new SoundPlayer();
AssertExtensions.Throws<ArgumentOutOfRangeException>("LoadTimeout", () => player.LoadTimeout = -1);
}
[Theory]
[InlineData("http://google.com")]
[InlineData("invalid")]
[InlineData("/file")]
[InlineData("file:///name")]
public void SoundLocation_SetValid_Success(string soundLocation)
{
var player = new SoundPlayer() { SoundLocation = soundLocation };
Assert.Equal(soundLocation, player.SoundLocation);
bool calledHandler = false;
player.SoundLocationChanged += (args, sender) => calledHandler = true;
// Set the same.
player.SoundLocation = soundLocation;
Assert.Equal(soundLocation, player.SoundLocation);
Assert.False(calledHandler);
// Set different.
player.SoundLocation = soundLocation + "a";
Assert.Equal(soundLocation + "a", player.SoundLocation);
Assert.True(calledHandler);
player = new SoundPlayer("location") { SoundLocation = soundLocation };
Assert.Equal(soundLocation, player.SoundLocation);
using (var stream = new MemoryStream())
{
player = new SoundPlayer(stream) { SoundLocation = soundLocation };
Assert.Equal(soundLocation, player.SoundLocation);
}
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void SoundLocation_SetNullOrEmpty_ThrowsArgumentException(string soundLocation)
{
var player = new SoundPlayer() { SoundLocation = soundLocation };
Assert.Equal("", player.SoundLocation);
player = new SoundPlayer("location");
AssertExtensions.Throws<ArgumentException>("path", null, () => player.SoundLocation = soundLocation);
using (var stream = new MemoryStream())
{
player = new SoundPlayer(stream) { SoundLocation = soundLocation };
Assert.Equal("", player.SoundLocation);
}
}
[Theory]
[MemberData(nameof(Stream_TestData))]
public void Stream_SetValid_Success(Stream stream)
{
var player = new SoundPlayer() { Stream = stream };
Assert.Equal(stream, player.Stream);
bool calledHandler = false;
player.StreamChanged += (args, sender) => calledHandler = true;
// Set the same.
player.Stream = stream;
Assert.Equal(stream, player.Stream);
Assert.False(calledHandler);
// Set different.
using (var other = new MemoryStream())
{
player.Stream = other;
Assert.Equal(other, player.Stream);
Assert.True(calledHandler);
}
player = new SoundPlayer("location") { Stream = stream };
Assert.Equal(stream, player.Stream);
using (var other = new MemoryStream())
{
player = new SoundPlayer(other) { Stream = stream };
Assert.Equal(stream, player.Stream);
}
}
[Theory]
[InlineData(null)]
[InlineData("tag")]
public void Tag_Set_GetReturnsExpected(object value)
{
var player = new SoundPlayer { Tag = value };
Assert.Equal(value, player.Tag);
}
[Fact]
public void LoadCompleted_AddRemove_Success()
{
bool calledHandler = false;
void handler(object args, EventArgs sender) => calledHandler = true;
var player = new SoundPlayer();
player.LoadCompleted += handler;
player.LoadCompleted -= handler;
Assert.False(calledHandler);
}
[Fact]
public void SoundLocationChanged_AddRemove_Success()
{
bool calledHandler = false;
void handler(object args, EventArgs sender) => calledHandler = true;
var player = new SoundPlayer();
player.SoundLocationChanged += handler;
player.SoundLocationChanged -= handler;
player.SoundLocation = "location";
Assert.False(calledHandler);
}
[Fact]
public void StreamChanged_AddRemove_Success()
{
bool calledHandler = false;
void handler(object args, EventArgs sender) => calledHandler = true;
var player = new SoundPlayer();
player.StreamChanged += handler;
player.StreamChanged -= handler;
using (var stream = new MemoryStream())
{
player.Stream = stream;
Assert.False(calledHandler);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "netfx aborts a worker thread and never signals operation completion")]
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public async Task LoadAsync_CancelDuringLoad_CompletesAsCanceled(int cancellationCause)
{
var tcs = new TaskCompletionSource<AsyncCompletedEventArgs>();
var player = new SoundPlayer();
player.LoadCompleted += (s, e) => tcs.SetResult(e);
player.Stream = new ReadAsyncBlocksUntilCanceledStream();
player.LoadAsync();
Assert.False(tcs.Task.IsCompleted);
switch (cancellationCause)
{
case 0:
player.Stream = new MemoryStream();
break;
case 1:
player.LoadTimeout = 1;
Assert.Throws<TimeoutException>(() => player.Load());
break;
case 2:
player.SoundLocation = "DoesntExistButThatDoesntMatter";
break;
}
AsyncCompletedEventArgs ea = await tcs.Task;
Assert.Null(ea.Error);
Assert.True(ea.Cancelled);
Assert.Null(ea.UserState);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "netfx hangs")]
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[MemberData(nameof(Play_String_TestData))]
[OuterLoop]
public async Task CancelDuringLoad_ThenPlay_Success(string sourceLocation)
{
using (FileStream stream = File.OpenRead(sourceLocation.Replace("file://", "")))
{
var tcs = new TaskCompletionSource<bool>();
AsyncCompletedEventHandler handler = (s, e) => tcs.SetResult(true);
var player = new SoundPlayer();
player.LoadCompleted += handler;
player.Stream = new ReadAsyncBlocksUntilCanceledStream();
player.LoadAsync();
player.Stream = stream;
await tcs.Task;
player.LoadCompleted -= handler;
player.Play();
}
}
private sealed class ReadAsyncBlocksUntilCanceledStream : Stream
{
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await Task.Delay(-1, cancellationToken);
return 0;
}
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override void Flush() { }
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// Equals(System.Guid)
/// </summary>
public class GuidEquals1
{
#region Private Fields
private const int c_GUID_BYTE_ARRAY_SIZE = 16;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call Equals with self instance");
try
{
Guid guid = Guid.Empty;
if (!guid.Equals(guid))
{
TestLibrary.TestFramework.LogError("001.1", "Calling Equals with self instance returns false");
retVal = false;
}
// double check
if (!guid.Equals(guid))
{
TestLibrary.TestFramework.LogError("001.2", "Calling Equals with self instance returns false");
retVal = false;
}
byte[] bytes = new byte[c_GUID_BYTE_ARRAY_SIZE];
TestLibrary.Generator.GetBytes(-55, bytes);
guid = new Guid(bytes);
if (!guid.Equals(guid))
{
TestLibrary.TestFramework.LogError("001.3", "Calling Equals with self instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
// double check
if (!guid.Equals(guid))
{
TestLibrary.TestFramework.LogError("001.4", "Calling Equals with self instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call Equals with equal instance");
try
{
Guid guid1 = Guid.Empty;
Guid guid2 = new Guid("00000000-0000-0000-0000-000000000000");
if (!guid1.Equals(guid2))
{
TestLibrary.TestFramework.LogError("002.1", "Calling Equals with equal instance returns false");
retVal = false;
}
// double check
if (!guid1.Equals(guid2))
{
TestLibrary.TestFramework.LogError("002.2", "Calling Equals with equal instance returns false");
retVal = false;
}
byte[] bytes = new byte[c_GUID_BYTE_ARRAY_SIZE];
TestLibrary.Generator.GetBytes(-55, bytes);
guid1 = new Guid(bytes);
guid2 = new Guid(bytes);
if (!guid1.Equals(guid2))
{
TestLibrary.TestFramework.LogError("002.3", "Calling Equals with equal instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid1 = " + guid1 + ", guid2 = " + guid2);
retVal = false;
}
// double check
if (!guid1.Equals(guid2))
{
TestLibrary.TestFramework.LogError("002.4", "Calling Equals with equal instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid1 = " + guid1 + ", guid2 = " + guid2);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call Equals with not equal instance");
try
{
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000000000001"), false, "003.1") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000000000100"), false, "003.2") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000000010000"), false, "003.3") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000001000000"), false, "003.4") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000100000000"), false, "003.5") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-010000000000"), false, "003.6") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0001-000000000000"), false, "003.7") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0100-000000000000"), false, "003.8") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0001-0000-000000000000"), false, "003.9") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0100-0000-000000000000"), false, "003.10") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0001-0000-0000-000000000000"), false, "003.11") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0100-0000-0000-000000000000"), false, "003.12") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000001-0000-0000-0000-000000000000"), false, "003.13") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000100-0000-0000-0000-000000000000"), false, "003.14") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00010000-0000-0000-0000-000000000000"), false, "003.15") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("01000000-0000-0000-0000-000000000000"), false, "003.16") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
GuidEquals1 test = new GuidEquals1();
TestLibrary.TestFramework.BeginTestCase("GuidEquals1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private bool VerificationHelper(Guid guid1, Guid guid2, bool expected, string errorNo)
{
bool retVal = true;
bool actual = guid1.Equals(guid2);
if (actual != expected)
{
TestLibrary.TestFramework.LogError(errorNo, "Calling Equals returns wrong result");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid1 = " + guid1 + ", guid2 = " + guid2 + ", actual = " + actual + ", expected = " + expected);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Mdb;
using Mono.Cecil.Pdb;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace AutoDI.Build
{
public abstract class AssemblyRewriteTask : Task, ICancelableTask
{
[Required]
public string AssemblyFile { set; get; }
[Required]
public string References { get; set; }
[Required]
public string DebugType { get; set; }
protected ILogger Logger { get; set; }
protected IAssemblyResolver AssemblyResolver { get; set; }
protected ITypeResolver TypeResolver { get; set; }
protected ModuleDefinition ModuleDefinition { get; private set; }
protected AssemblyDefinition ResolveAssembly(string assemblyName)
{
return AssemblyResolver?.Resolve(AssemblyNameReference.Parse(assemblyName));
}
public override bool Execute()
{
//Debugger.Launch();
if (Logger is null)
{
Logger = new TaskLogger(this);
}
Logger.Info($"Starting AutoDI on '{AssemblyFile}'");
var sw = Stopwatch.StartNew();
using (var assemblyResolver = new AssemblyResolver(GetIncludedReferences(), Logger))
{
if (AssemblyResolver is null)
{
AssemblyResolver = assemblyResolver;
}
if (TypeResolver is null)
{
TypeResolver = assemblyResolver;
}
foreach (var assemblyName in GetAssembliesToInclude())
{
AssemblyResolver.Resolve(new AssemblyNameReference(assemblyName, null));
}
var readerParameters = new ReaderParameters
{
AssemblyResolver = AssemblyResolver,
InMemory = true
};
using (ModuleDefinition = ModuleDefinition.ReadModule(AssemblyFile, readerParameters))
{
bool loadedSymbols;
try
{
ModuleDefinition.ReadSymbols();
loadedSymbols = true;
}
catch
{
loadedSymbols = false;
}
Logger.Info($"Loaded '{AssemblyFile}'");
if (WeaveAssembly())
{
Logger.Info("Weaving complete - updating assembly");
var parameters = new WriterParameters
{
WriteSymbols = loadedSymbols,
};
ModuleDefinition.Write(AssemblyFile, parameters);
}
else
{
Logger.Info("Weaving complete - no update");
}
}
}
sw.Stop();
Logger.Info($"AutoDI Complete {sw.Elapsed}");
return !Logger.ErrorLogged;
}
public virtual void Cancel()
{
}
private IEnumerable<string> GetIncludedReferences()
{
if (!string.IsNullOrWhiteSpace(References))
{
foreach (var reference in References.Split(';').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)))
{
yield return reference;
}
}
}
protected virtual IEnumerable<string> GetAssembliesToInclude()
{
yield return "mscorlib";
yield return "System";
yield return "netstandard";
yield return "System.Collections";
}
private Stream GetSymbolInformation(out ISymbolReaderProvider symbolReaderProvider,
out ISymbolWriterProvider symbolWriterProvider)
{
if (string.Equals("none", DebugType, StringComparison.OrdinalIgnoreCase))
{
Logger.Info("No symbols");
symbolReaderProvider = null;
symbolWriterProvider = null;
return null;
}
if (string.Equals("embedded", DebugType, StringComparison.OrdinalIgnoreCase))
{
Logger.Info("Using embedded symbols");
symbolReaderProvider = new EmbeddedPortablePdbReaderProvider();
symbolWriterProvider = new EmbeddedPortablePdbWriterProvider();
return null;
}
string pdbPath = FindPdbPath();
string mdbPath = FindMdbPath();
if (pdbPath != null && mdbPath != null)
{
if (File.GetLastWriteTimeUtc(pdbPath) >= File.GetLastWriteTimeUtc(mdbPath))
{
mdbPath = null;
Logger.Debug("Found mdb and pdb debug symbols. Selected pdb (newer).", DebugLogLevel.Verbose);
}
else
{
pdbPath = null;
Logger.Debug("Found mdb and pdb debug symbols. Selected mdb (newer).", DebugLogLevel.Verbose);
}
}
if (pdbPath != null)
{
if (IsPortablePdb(pdbPath))
{
Logger.Info($"Using portable symbol file {pdbPath}");
symbolReaderProvider = new PortablePdbReaderProvider();
symbolWriterProvider = new PortablePdbWriterProvider();
}
else
{
Logger.Info($"Using symbol file {pdbPath}");
symbolReaderProvider = new PdbReaderProvider();
symbolWriterProvider = new PdbWriterProvider();
}
string tempPath = pdbPath + ".tmp";
File.Copy(pdbPath, tempPath, true);
return new FileStream(tempPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
else if (mdbPath != null)
{
Logger.Info($"Using symbol file {mdbPath}");
symbolReaderProvider = new MdbReaderProvider();
symbolWriterProvider = new MdbWriterProvider();
string tempPath = mdbPath + ".tmp";
File.Copy(mdbPath, tempPath, true);
return new FileStream(tempPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
symbolReaderProvider = null;
symbolWriterProvider = null;
return null;
string FindPdbPath()
{
// because UWP use a wacky convention for symbols
string path = Path.ChangeExtension(AssemblyFile, "compile.pdb");
if (File.Exists(path))
{
Logger.Debug($"Found debug symbols at '{path}'.", DebugLogLevel.Verbose);
return path;
}
path = Path.ChangeExtension(AssemblyFile, "pdb");
if (File.Exists(path))
{
Logger.Debug($"Found debug symbols at '{path}'.", DebugLogLevel.Verbose);
return path;
}
return null;
}
bool IsPortablePdb(string symbolsPath)
{
using (var fileStream = File.OpenRead(symbolsPath))
using (var reader = new BinaryReader(fileStream))
{
return reader.ReadBytes(4).SequenceEqual(new byte[] { 0x42, 0x4a, 0x53, 0x42 });
}
}
string FindMdbPath()
{
string path = AssemblyFile + ".mdb";
if (File.Exists(path))
{
Logger.Debug($"Found debug symbols at '{path}'.", DebugLogLevel.Verbose);
return path;
}
return null;
}
}
protected abstract bool WeaveAssembly();
}
}
| |
using System;
using NetFusion.Bootstrap.Exceptions;
using NetFusion.Messaging.Plugin.Configs;
using NetFusion.Messaging.Types;
using NetFusion.RabbitMQ.Publisher;
using NetFusion.Test.Container;
using Xunit;
namespace IntegrationTests.RabbitMQ
{
/// <summary>
/// The publisher module contains the logic specific to creating exchanges/queues
/// defined by the publishing host.
/// </summary>
public class PublisherModuleTests
{
/// <summary>
/// The publishing application can determine if a given message has an assocated
/// exchange. The publishing application defines exchanges by declaring one or
/// more IExchangeRegistry or ExchangeRegistryBase classes. This information is
/// queried and cached when the NetFusion.RabbitMQ plugin is bootstrapped.
/// </summary>
[Fact]
public void CanDetermineIfMessage_HasAnAssociatedExchange()
{
ContainerFixture.Test(fixture =>
{
fixture.Arrange
.Configuration(TestSetup.AddValidBusConfig)
.Container(c => { c.WithRabbitMqHost(typeof(ValidExchangeRegistry)); })
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Assert.PluginModule<MockPublisherModule>(m =>
{
var isExchangeMsg = m.IsExchangeMessage(typeof(AutoSalesEvent));
Assert.True(isExchangeMsg);
});
});
}
/// <summary>
/// When publishing a message with an assocated exchange, the exchange definition
/// is retrieved and used to declare the exchange on the RabbitMQ message bus.
/// </summary>
[Fact]
public void CanLookupExchangeDefinition_ForMessageType()
{
ContainerFixture.Test(fixture =>
{
fixture.Arrange
.Configuration(TestSetup.AddValidBusConfig)
.Container(c => { c.WithRabbitMqHost(typeof(ValidExchangeRegistry)); })
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Assert.PluginModule<MockPublisherModule>(m =>
{
var definition = m.GetExchangeMeta(typeof(AutoSalesEvent));
Assert.NotNull(definition);
});
});
}
[Fact]
public void RequestingExchangeDefinition_ForNotExchangeMessageType_RaisesException()
{
ContainerFixture.Test(fixture =>
{
fixture.Arrange
.Configuration(TestSetup.AddValidBusConfig)
.Container(c => { c.WithRabbitMqHost(typeof(ValidExchangeRegistry)); })
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Assert.PluginModule<MockPublisherModule>(m =>
{
Assert.Throws<InvalidOperationException>(() => m.GetExchangeMeta(typeof(TestCommand1)));
});
});
}
/// <summary>
/// All exchange names defined a specific message bus must be unique for a given configured host.
/// </summary>
[Fact]
public void ExchangeName_MustBe_Unique_OnSameBus()
{
ContainerFixture.Test(fixture => {
fixture.Arrange
.Configuration(TestSetup.AddValidBusConfig)
.Container(c =>
{
c.WithRabbitMqHost(typeof(DuplicateExchangeRegistry));
})
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Act.RecordException().ComposeContainer()
.Assert.Exception<ContainerException>(ex =>
{
});
});
}
/// <summary>
/// The same exchange names can be used across different configured hosts.
/// </summary>
[Fact]
public void ExchangeName_CanBeTheSame_OnDifferentBusses()
{
ContainerFixture.Test(fixture => {
fixture.Arrange
.Configuration(TestSetup.AddValidMultipleBusConfig)
.Container(c =>
{
c.WithRabbitMqHost(typeof(ValidDuplicateExchangeRegistry));
})
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Assert.PluginModule<MockPublisherModule>(m =>
{
Assert.NotNull(m.GetExchangeMeta(typeof(TestDomainEvent)));
Assert.NotNull(m.GetExchangeMeta(typeof(TestDomainEvent2)));
});
});
}
/// <summary>
/// All queue names defined a specific message bus must be unique.
/// </summary>
[Fact]
public void QueueName_MustBe_Unique_OnSameBus()
{
ContainerFixture.Test(fixture => {
fixture.Arrange
.Configuration(TestSetup.AddValidBusConfig)
.Container(c =>
{
c.WithRabbitMqHost(typeof(DuplicateQueueRegistry));
})
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Act.RecordException().ComposeContainer()
.Assert.Exception<ContainerException>(ex =>
{
});
});
}
[Fact]
public void QueueName_CanBeTheSame_OnDifferentBusiness()
{
ContainerFixture.Test(fixture => {
fixture.Arrange
.Configuration(TestSetup.AddValidMultipleBusConfig)
.Container(c =>
{
c.WithRabbitMqHost(typeof(ValidDuplicateQueueRegistry));
})
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Assert.PluginModule<MockPublisherModule>(m =>
{
Assert.NotNull(m.GetExchangeMeta(typeof(TestCommand1)));
Assert.NotNull(m.GetExchangeMeta(typeof(TestCommand2)));
});
});
}
public class ValidExchangeRegistry : ExchangeRegistryBase
{
protected override void OnRegister()
{
DefineTopicExchange<AutoSalesEvent>("AutoSales", "TestBus1");
}
}
public class DuplicateExchangeRegistry : ExchangeRegistryBase
{
protected override void OnRegister()
{
DefineTopicExchange<TestDomainEvent>("AutoSales", "TestBus1");
DefineTopicExchange<TestDomainEvent2>("AutoSales", "TestBus1");
}
}
public class ValidDuplicateExchangeRegistry : ExchangeRegistryBase
{
protected override void OnRegister()
{
DefineTopicExchange<TestDomainEvent>("AutoSales", "TestBus1");
DefineTopicExchange<TestDomainEvent2>("AutoSales", "TestBus2");
}
}
public class DuplicateQueueRegistry : ExchangeRegistryBase
{
protected override void OnRegister()
{
DefineWorkQueue<TestCommand1>("GenerateInvoice", "TestBus1");
DefineWorkQueue<TestCommand2>("GenerateInvoice", "TestBus1");
}
}
public class ValidDuplicateQueueRegistry : ExchangeRegistryBase
{
protected override void OnRegister()
{
DefineWorkQueue<TestCommand1>("GenerateInvoice", "TestBus1");
DefineWorkQueue<TestCommand2>("GenerateInvoice", "TestBus2");
}
}
public class RpcExchangeRegistry : ExchangeRegistryBase
{
protected override void OnRegister()
{
DefineRpcQueue<CalculatePropTax>("Calculations", "CalculatePropTax", "TestBus1");
DefineRpcQueue<CalculateAutoTax>("Calculations", "CalculateAutoTax", "TestBus1");
DefineRpcQueue<GetTaxRates>("LookupReferenceData", "GetTaxRates", "TestBus1");
}
}
public class AutoSalesEvent : DomainEvent
{
}
public class TestCommand1 : Command
{
}
public class TestCommand2 : Command
{
}
public class TestDomainEvent : DomainEvent
{
}
public class TestDomainEvent2 : DomainEvent
{
}
public class CalculatePropTax : Command
{
}
public class CalculateAutoTax : Command
{
}
public class GetTaxRates : Command
{
}
}
}
| |
// 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.Reflection;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Runtime.Serialization;
namespace System.Text
{
// Our input file data structures look like:
//
// Header structure looks like:
// struct NLSPlusHeader
// {
// WORD[16] filename; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // e.g.: 3, 2, 0, 0
// WORD count; // 2 bytes = 42 // Number of code page indexes that will follow
// }
//
// Each code page section looks like:
// struct NLSCodePageIndex
// {
// WORD[16] codePageName; // 32 bytes
// WORD codePage; // +2 bytes = 34
// WORD byteCount; // +2 bytes = 36
// DWORD offset; // +4 bytes = 40 // Bytes from beginning of FILE.
// }
//
// Each code page then has its own header
// struct NLSCodePage
// {
// WORD[16] codePageName; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // e.g.: 3.2.0.0
// WORD codePage; // 2 bytes = 42
// WORD byteCount; // 2 bytes = 44 // 1 or 2 byte code page (SBCS or DBCS)
// WORD unicodeReplace; // 2 bytes = 46 // default replacement unicode character
// WORD byteReplace; // 2 bytes = 48 // default replacement byte(s)
// BYTE[] data; // data section
// }
[Serializable]
internal abstract class BaseCodePageEncoding : EncodingNLS, ISerializable
{
internal const String CODE_PAGE_DATA_FILE_NAME = "codepages.nlp";
protected int dataTableCodePage;
// Variables to help us allocate/mark our memory section correctly
protected int iExtraBytes = 0;
// Our private unicode-to-bytes best-fit-array, and vice versa.
protected char[] arrayUnicodeBestFit = null;
protected char[] arrayBytesBestFit = null;
[System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(int codepage)
: this(codepage, codepage)
{
}
[System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(int codepage, int dataCodePage)
: base(codepage, new InternalEncoderBestFitFallback(null), new InternalDecoderBestFitFallback(null))
{
SetFallbackEncoding();
// Remember number of code pages that we'll be using the table for.
dataTableCodePage = dataCodePage;
LoadCodePageTables();
}
internal BaseCodePageEncoding(int codepage, int dataCodePage, EncoderFallback enc, DecoderFallback dec)
: base(codepage, enc, dec)
{
// Remember number of code pages that we'll be using the table for.
dataTableCodePage = dataCodePage;
LoadCodePageTables();
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
CodePageEncodingSurrogate.SerializeEncoding(this, info, context);
info.SetType(typeof(CodePageEncodingSurrogate));
}
// Just a helper as we cannot use 'this' when calling 'base(...)'
private void SetFallbackEncoding()
{
(EncoderFallback as InternalEncoderBestFitFallback).encoding = this;
(DecoderFallback as InternalDecoderBestFitFallback).encoding = this;
}
//
// This is the header for the native data table that we load from CODE_PAGE_DATA_FILE_NAME.
//
// Explicit layout is used here since a syntax like char[16] can not be used in sequential layout.
[StructLayout(LayoutKind.Explicit)]
internal struct CodePageDataFileHeader
{
[FieldOffset(0)]
internal char TableName; // WORD[16]
[FieldOffset(0x20)]
internal ushort Version; // WORD[4]
[FieldOffset(0x28)]
internal short CodePageCount; // WORD
[FieldOffset(0x2A)]
internal short unused1; // Add an unused WORD so that CodePages is aligned with DWORD boundary.
}
private const int CODEPAGE_DATA_FILE_HEADER_SIZE = 44;
[StructLayout(LayoutKind.Explicit, Pack = 2)]
internal unsafe struct CodePageIndex
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal short CodePage; // WORD
[FieldOffset(0x22)]
internal short ByteCount; // WORD
[FieldOffset(0x24)]
internal int Offset; // DWORD
}
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct CodePageHeader
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal ushort VersionMajor; // WORD
[FieldOffset(0x22)]
internal ushort VersionMinor; // WORD
[FieldOffset(0x24)]
internal ushort VersionRevision;// WORD
[FieldOffset(0x26)]
internal ushort VersionBuild; // WORD
[FieldOffset(0x28)]
internal short CodePage; // WORD
[FieldOffset(0x2a)]
internal short ByteCount; // WORD // 1 or 2 byte code page (SBCS or DBCS)
[FieldOffset(0x2c)]
internal char UnicodeReplace; // WORD // default replacement unicode character
[FieldOffset(0x2e)]
internal ushort ByteReplace; // WORD // default replacement bytes
}
private const int CODEPAGE_HEADER_SIZE = 48;
// Initialize our global stuff
private static byte[] s_codePagesDataHeader = new byte[CODEPAGE_DATA_FILE_HEADER_SIZE];
protected static Stream s_codePagesEncodingDataStream = GetEncodingDataStream(CODE_PAGE_DATA_FILE_NAME);
protected static readonly Object s_streamLock = new Object(); // this lock used when reading from s_codePagesEncodingDataStream
// Real variables
protected byte[] m_codePageHeader = new byte[CODEPAGE_HEADER_SIZE];
protected int m_firstDataWordOffset;
protected int m_dataSize;
// Safe handle wrapper around section map view
[System.Security.SecurityCritical] // auto-generated
protected SafeAllocHHandle safeNativeMemoryHandle = null;
internal static Stream GetEncodingDataStream(String tableName)
{
Debug.Assert(tableName != null, "table name can not be null");
// NOTE: We must reflect on a public type that is exposed in the contract here
// (i.e. CodePagesEncodingProvider), otherwise we will not get a reference to
// the right assembly.
Stream stream = typeof(CodePagesEncodingProvider).GetTypeInfo().Assembly.GetManifestResourceStream(tableName);
if (stream == null)
{
// We can not continue if we can't get the resource.
throw new InvalidOperationException();
}
// Read the header
stream.Read(s_codePagesDataHeader, 0, s_codePagesDataHeader.Length);
return stream;
}
// We need to load tables for our code page
[System.Security.SecurityCritical] // auto-generated
private unsafe void LoadCodePageTables()
{
if (!FindCodePage(dataTableCodePage))
{
// Didn't have one
throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage));
}
// We had it, so load it
LoadManagedCodePage();
}
// Look up the code page pointer
[System.Security.SecurityCritical] // auto-generated
private unsafe bool FindCodePage(int codePage)
{
Debug.Assert(m_codePageHeader != null && m_codePageHeader.Length == CODEPAGE_HEADER_SIZE, "m_codePageHeader expected to match in size the struct CodePageHeader");
// Loop through all of the m_pCodePageIndex[] items to find our code page
byte[] codePageIndex = new byte[sizeof(CodePageIndex)];
lock (s_streamLock)
{
// seek to the first CodePageIndex entry
s_codePagesEncodingDataStream.Seek(CODEPAGE_DATA_FILE_HEADER_SIZE, SeekOrigin.Begin);
int codePagesCount;
fixed (byte* pBytes = &s_codePagesDataHeader[0])
{
CodePageDataFileHeader* pDataHeader = (CodePageDataFileHeader*)pBytes;
codePagesCount = pDataHeader->CodePageCount;
}
fixed (byte* pBytes = &codePageIndex[0])
{
CodePageIndex* pCodePageIndex = (CodePageIndex*)pBytes;
for (int i = 0; i < codePagesCount; i++)
{
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
if (pCodePageIndex->CodePage == codePage)
{
// Found it!
long position = s_codePagesEncodingDataStream.Position;
s_codePagesEncodingDataStream.Seek((long)pCodePageIndex->Offset, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(m_codePageHeader, 0, m_codePageHeader.Length);
m_firstDataWordOffset = (int)s_codePagesEncodingDataStream.Position; // stream now pointing to the codepage data
if (i == codePagesCount - 1) // last codepage
{
m_dataSize = (int)(s_codePagesEncodingDataStream.Length - pCodePageIndex->Offset - m_codePageHeader.Length);
}
else
{
// Read Next codepage data to get the offset and then calculate the size
s_codePagesEncodingDataStream.Seek(position, SeekOrigin.Begin);
int currentOffset = pCodePageIndex->Offset;
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
m_dataSize = pCodePageIndex->Offset - currentOffset - m_codePageHeader.Length;
}
return true;
}
}
}
}
// Couldn't find it
return false;
}
// Get our code page byte count
[System.Security.SecurityCritical] // auto-generated
internal static unsafe int GetCodePageByteSize(int codePage)
{
// Loop through all of the m_pCodePageIndex[] items to find our code page
byte[] codePageIndex = new byte[sizeof(CodePageIndex)];
lock (s_streamLock)
{
// seek to the first CodePageIndex entry
s_codePagesEncodingDataStream.Seek(CODEPAGE_DATA_FILE_HEADER_SIZE, SeekOrigin.Begin);
int codePagesCount;
fixed (byte* pBytes = &s_codePagesDataHeader[0])
{
CodePageDataFileHeader* pDataHeader = (CodePageDataFileHeader*)pBytes;
codePagesCount = pDataHeader->CodePageCount;
}
fixed (byte* pBytes = &codePageIndex[0])
{
CodePageIndex* pCodePageIndex = (CodePageIndex*)pBytes;
for (int i = 0; i < codePagesCount; i++)
{
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
if (pCodePageIndex->CodePage == codePage)
{
Debug.Assert(pCodePageIndex->ByteCount == 1 || pCodePageIndex->ByteCount == 2,
"[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePageIndex->ByteCount + ") in table");
// Return what it says for byte count
return pCodePageIndex->ByteCount;
}
}
}
}
// Couldn't find it
return 0;
}
// We have a managed code page entry, so load our tables
[System.Security.SecurityCritical]
protected abstract unsafe void LoadManagedCodePage();
// Allocate memory to load our code page
[System.Security.SecurityCritical] // auto-generated
protected unsafe byte* GetNativeMemory(int iSize)
{
if (safeNativeMemoryHandle == null)
{
byte* pNativeMemory = (byte*)Marshal.AllocHGlobal(iSize);
Debug.Assert(pNativeMemory != null);
safeNativeMemoryHandle = new SafeAllocHHandle((IntPtr)pNativeMemory);
}
return (byte*)safeNativeMemoryHandle.DangerousGetHandle();
}
[System.Security.SecurityCritical]
protected abstract unsafe void ReadBestFitTable();
[System.Security.SecuritySafeCritical]
internal char[] GetBestFitUnicodeToBytesData()
{
// Read in our best fit table if necessary
if (arrayUnicodeBestFit == null) ReadBestFitTable();
Debug.Assert(arrayUnicodeBestFit != null, "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit");
// Normally we don't have any best fit data.
return arrayUnicodeBestFit;
}
[System.Security.SecuritySafeCritical]
internal char[] GetBestFitBytesToUnicodeData()
{
// Read in our best fit table if necessary
if (arrayBytesBestFit == null) ReadBestFitTable();
Debug.Assert(arrayBytesBestFit != null, "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit");
// Normally we don't have any best fit data.
return arrayBytesBestFit;
}
// During the AppDomain shutdown the Encoding class may have already finalized, making the memory section
// invalid. We detect that by validating the memory section handle then re-initializing the memory
// section by calling LoadManagedCodePage() method and eventually the mapped file handle and
// the memory section pointer will get finalized one more time.
[System.Security.SecurityCritical] // auto-generated
internal unsafe void CheckMemorySection()
{
if (safeNativeMemoryHandle != null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero)
{
LoadManagedCodePage();
}
}
}
}
| |
// 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.Net.Http;
using System.Net.Test.Common;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Tests
{
public class HttpWebRequestTest
{
private const string RequestBody = "This is data to POST.";
private readonly byte[] _requestBodyBytes = Encoding.UTF8.GetBytes(RequestBody);
private readonly NetworkCredential _explicitCredential = new NetworkCredential("user", "password", "domain");
private HttpWebRequest _savedHttpWebRequest = null;
private WebHeaderCollection _savedResponseHeaders = null;
private Exception _savedRequestStreamException = null;
private Exception _savedResponseException = null;
private int _requestStreamCallbackCallCount = 0;
private int _responseCallbackCallCount = 0;
private readonly ITestOutputHelper _output;
public readonly static object[][] EchoServers = System.Net.Test.Common.Configuration.Http.EchoServers;
public HttpWebRequestTest(ITestOutputHelper output)
{
_output = output;
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_VerifyDefaults_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Null(request.Accept);
Assert.False(request.AllowReadStreamBuffering);
Assert.Null(request.ContentType);
Assert.Equal(350, request.ContinueTimeout);
Assert.Null(request.CookieContainer);
Assert.Null(request.Credentials);
Assert.False(request.HaveResponse);
Assert.NotNull(request.Headers);
Assert.Equal(0, request.Headers.Count);
Assert.Equal("GET", request.Method);
Assert.NotNull(request.Proxy);
Assert.Equal(remoteServer, request.RequestUri);
Assert.True(request.SupportsCookieContainer);
Assert.False(request.UseDefaultCredentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_CreateHttpWithString_ExpectNotNull(Uri remoteServer)
{
string remoteServerString = remoteServer.ToString();
HttpWebRequest request = WebRequest.CreateHttp(remoteServerString);
Assert.NotNull(request);
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_CreateHttpWithUri_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetValidValue_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
string acceptType = "*/*";
request.Accept = acceptType;
Assert.Equal(acceptType, request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetEmptyValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Accept = string.Empty;
Assert.Null(request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetNullValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Accept = null;
Assert.Null(request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowReadStreamBuffering_SetFalseThenGet_ExpectFalse(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowReadStreamBuffering = false;
Assert.False(request.AllowReadStreamBuffering);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowReadStreamBuffering_SetTrueThenGet_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowReadStreamBuffering = true;
Assert.True(request.AllowReadStreamBuffering);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ContentLength_Get_ExpectSameAsGetResponseStream(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebResponse response = await request.GetResponseAsync();
Stream myStream = response.GetResponseStream();
String strContent;
using (var sr = new StreamReader(myStream))
{
strContent = sr.ReadToEnd();
}
long length = response.ContentLength;
Assert.Equal(strContent.Length, length);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentType_SetThenGet_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
string myContent = "application/x-www-form-urlencoded";
request.ContentType = myContent;
Assert.Equal(myContent, request.ContentType);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentType_SetThenGetEmptyValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContentType = string.Empty;
Assert.Null(request.ContentType);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetThenGetZero_ExpectZero(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueTimeout = 0;
Assert.Equal(0, request.ContinueTimeout);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetNegativeOne_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueTimeout = -1;
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Throws<ArgumentOutOfRangeException>(() => request.ContinueTimeout = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void Credentials_SetDefaultCredentialsThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = CredentialCache.DefaultCredentials;
Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void Credentials_SetExplicitCredentialsThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
Assert.Equal(_explicitCredential, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetTrue_CredentialsEqualsDefaultCredentials(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
request.UseDefaultCredentials = true;
Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetFalse_CredentialsNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
request.UseDefaultCredentials = false;
Assert.Equal(null, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseGETVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseHEADVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Head.Method;
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseCONNECTVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = "CONNECT";
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
request.Abort();
WebException ex = Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null));
Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreatePostRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
_savedHttpWebRequest.Method = "POST";
IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetRequestStream(null, null);
Assert.Throws<InvalidOperationException>(() =>
{
_savedHttpWebRequest.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreateRequestThenBeginGetResponsePrior_ThrowsInvalidOperationException(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetResponse(null, null);
Assert.Throws<InvalidOperationException>(() =>
{
_savedHttpWebRequest.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetResponse_CreateRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetResponse(null, null);
Assert.Throws<InvalidOperationException>(() =>
{
_savedHttpWebRequest.BeginGetResponse(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetResponse_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
request.Abort();
WebException ex = Assert.Throws<WebException>(() => request.BeginGetResponse(null, null));
Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetRequestStreamAsync_WriteAndDisposeRequestStreamThenOpenRequestStream_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
Stream requestStream;
using (requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
Assert.Throws<ArgumentException>(() =>
{
var sr = new StreamReader(requestStream);
});
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetRequestStreamAsync_SetPOSTThenGet_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
Stream requestStream = await request.GetRequestStreamAsync();
Assert.NotNull(requestStream);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_GetResponseStream_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebResponse response = await request.GetResponseAsync();
Assert.NotNull(response.GetResponseStream());
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_GetResponseStream_ContainsHost(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Get.Method;
WebResponse response = await request.GetResponseAsync();
Stream myStream = response.GetResponseStream();
Assert.NotNull(myStream);
String strContent;
using (var sr = new StreamReader(myStream))
{
strContent = sr.ReadToEnd();
}
Assert.True(strContent.Contains("\"Host\": \"" + System.Net.Test.Common.Configuration.Http.Host + "\""));
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_PostRequestStream_ContainsData(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
WebResponse response = await request.GetResponseAsync();
Stream myStream = response.GetResponseStream();
String strContent;
using (var sr = new StreamReader(myStream))
{
strContent = sr.ReadToEnd();
}
Assert.True(strContent.Contains(RequestBody));
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_UseDefaultCredentials_ExpectSuccess(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UseDefaultCredentials = true;
WebResponse response = await request.GetResponseAsync();
}
[OuterLoop] // fails on networks with DNS servers that provide a dummy page for invalid addresses
[Fact]
public void GetResponseAsync_ServerNameNotInDns_ThrowsWebException()
{
string serverUrl = string.Format("http://www.{0}.com/", Guid.NewGuid().ToString());
HttpWebRequest request = WebRequest.CreateHttp(serverUrl);
WebException ex = Assert.Throws<WebException>(() => request.GetResponseAsync().GetAwaiter().GetResult());
Assert.Equal(WebExceptionStatus.NameResolutionFailure, ex.Status);
}
public static object[][] StatusCodeServers = {
new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(false, 404) },
new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(true, 404) },
};
[Theory, MemberData(nameof(StatusCodeServers))]
public async Task GetResponseAsync_ResourceNotFound_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync());
Assert.Equal(WebExceptionStatus.ProtocolError, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task HaveResponse_GetResponseAsync_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebResponse response = await request.GetResponseAsync();
Assert.True(request.HaveResponse);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task Headers_GetResponseHeaders_ContainsExpectedValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync();
String headersString = response.Headers.ToString();
string headersPartialContent = "Content-Type: application/json";
Assert.True(headersString.Contains(headersPartialContent));
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetThenGetToGET_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Get.Method;
Assert.Equal(HttpMethod.Get.Method, request.Method);
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetThenGetToPOST_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
Assert.Equal(HttpMethod.Post.Method, request.Method);
}
[Theory, MemberData(nameof(EchoServers))]
public void Proxy_GetDefault_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request.Proxy);
}
[Theory, MemberData(nameof(EchoServers))]
public void RequestUri_CreateHttpThenGet_ExpectSameUri(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer, request.RequestUri);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ResponseUri_GetResponseAsync_ExpectSameUri(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebResponse response = await request.GetResponseAsync();
Assert.Equal(remoteServer, response.ResponseUri);
}
[Theory, MemberData(nameof(EchoServers))]
public void SupportsCookieContainer_GetDefault_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.True(request.SupportsCookieContainer);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SimpleScenario_UseGETVerb_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync();
Stream responseStream = response.GetResponseStream();
String responseBody;
using (var sr = new StreamReader(responseStream))
{
responseBody = sr.ReadToEnd();
}
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SimpleScenario_UsePOSTVerb_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync();
Stream responseStream = response.GetResponseStream();
String responseBody;
using (var sr = new StreamReader(responseStream))
{
responseBody = sr.ReadToEnd();
}
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ContentType_AddHeaderWithNoContent_SendRequest_HeaderGetsSent(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync();
Stream responseStream = response.GetResponseStream();
String responseBody;
using (var sr = new StreamReader(responseStream))
{
responseBody = sr.ReadToEnd();
}
_output.WriteLine(responseBody);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(responseBody.Contains("Content-Type"));
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_BeginGetRequestStreamThenAbort_EndGetRequestStreamThrowsWebException(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
_savedHttpWebRequest.Method = "POST";
_savedHttpWebRequest.BeginGetResponse(new AsyncCallback(RequestStreamCallback), null);
_savedHttpWebRequest.Abort();
_savedHttpWebRequest = null;
WebException wex = _savedRequestStreamException as WebException;
Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
_savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null);
_savedHttpWebRequest.Abort();
Assert.Equal(1, _responseCallbackCallCount);
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
_savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null);
_savedHttpWebRequest.Abort();
WebException wex = _savedResponseException as WebException;
Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_BeginGetResponseUsingNoCallbackThenAbort_Success(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
_savedHttpWebRequest.BeginGetResponse(null, null);
_savedHttpWebRequest.Abort();
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_CreateRequestThenAbort_Success(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
_savedHttpWebRequest.Abort();
}
private void RequestStreamCallback(IAsyncResult asynchronousResult)
{
_requestStreamCallbackCallCount++;
try
{
Stream stream = (Stream)_savedHttpWebRequest.EndGetRequestStream(asynchronousResult);
stream.Dispose();
}
catch (Exception ex)
{
_savedRequestStreamException = ex;
}
}
private void ResponseCallback(IAsyncResult asynchronousResult)
{
_responseCallbackCallCount++;
try
{
using (HttpWebResponse response = (HttpWebResponse)_savedHttpWebRequest.EndGetResponse(asynchronousResult))
{
_savedResponseHeaders = response.Headers;
}
}
catch (Exception ex)
{
_savedResponseException = ex;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class NoParameterBlockTests : SharedBlockTests
{
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void SingleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void DoubleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void DoubleElementBlockNullArgument()
{
AssertExtensions.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression)));
}
[Fact]
public void DoubleElementBlockUnreadable()
{
AssertExtensions.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void TripleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void TripleElementBlockNullArgument()
{
AssertExtensions.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression)));
}
[Fact]
public void TripleElementBlockUnreadable()
{
AssertExtensions.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void QuadrupleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void QuadrupleElementBlockNullArgument()
{
AssertExtensions.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression)));
}
[Fact]
public void QuadrupleElementBlockUnreadable()
{
AssertExtensions.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void QuintupleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void QuintupleElementBlockNullArgument()
{
AssertExtensions.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg4", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression)));
}
[Fact]
public void QuintupleElementBlockUnreadable()
{
AssertExtensions.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg4", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void SextupleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void NullExpicitType()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Block(default(Type), default(IEnumerable<ParameterExpression>), Expression.Constant(0)));
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Block(default(Type), null, Enumerable.Repeat(Expression.Constant(0), 1)));
}
[Fact]
public void NullExpressionList()
{
AssertExtensions.Throws<ArgumentNullException>("expressions", () => Expression.Block(default(Expression[])));
AssertExtensions.Throws<ArgumentNullException>("expressions", () => Expression.Block(default(IEnumerable<Expression>)));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void NullExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i != expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = null;
AssertExtensions.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(expressions));
AssertExtensions.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(expressions.Skip(0)));
AssertExtensions.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), expressions));
AssertExtensions.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), expressions.Skip(0)));
AssertExtensions.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), null, expressions));
AssertExtensions.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), null, expressions.Skip(0)));
}
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void UnreadableExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i != expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = UnreadableExpression;
AssertExtensions.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(expressions));
AssertExtensions.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(expressions.Skip(0)));
AssertExtensions.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), expressions));
AssertExtensions.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), expressions.Skip(0)));
AssertExtensions.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), null, expressions));
AssertExtensions.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), null, expressions.Skip(0)));
}
}
[Theory]
[PerCompilationType(nameof(ObjectAssignableConstantValuesAndSizes))]
public void BlockExplicitType(object value, int blockSize, bool useInterpreter)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
BlockExpression block = Expression.Block(typeof(object), PadBlock(blockSize - 1, constant));
Assert.Equal(typeof(object), block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void BlockInvalidExplicitType(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Block(typeof(string), expressions));
AssertExtensions.Throws<ArgumentException>(null, (() => Expression.Block(typeof(string), expressions.ToArray())));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void InvalidExpressionIndex(object value, int blockSize)
{
BlockExpression block = Expression.Block(PadBlock(blockSize - 1, Expression.Constant(value, value.GetType())));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[-1]);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[blockSize]);
}
[Fact]
public void EmptyBlockWithNonVoidTypeNotAllowed()
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Block(typeof(int)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Block(typeof(int), Enumerable.Empty<Expression>()));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromParams(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions.ToArray());
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromEnumerable(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void VariableCountZeroOnNonVariableAcceptingForms(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Empty(block.Variables);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void RewriteToSameWithSameValues(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
Assert.Same(block, block.Update(null, expressions));
Assert.Same(block, block.Update(Enumerable.Empty<ParameterExpression>(), expressions));
Assert.Same(block, NoOpVisitor.Instance.Visit(block));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void CanFindItems(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(values);
IList<Expression> expressions = block.Expressions;
for (int i = 0; i != values.Length; ++i)
Assert.Equal(i, expressions.IndexOf(values[i]));
}
[Theory, MemberData(nameof(BlockSizes))]
public void ExpressionListBehavior(int parCount)
{
// This method contains a lot of assertions, which amount to one large assertion that
// the result of the Expressions property behaves correctly.
Expression[] exps = Enumerable.Range(0, parCount).Select(_ => Expression.Constant(0)).ToArray();
BlockExpression block = Expression.Block(exps);
ReadOnlyCollection<Expression> children = block.Expressions;
Assert.Equal(parCount, children.Count);
using (var en = children.GetEnumerator())
{
IEnumerator nonGenEn = ((IEnumerable)children).GetEnumerator();
for (int i = 0; i != parCount; ++i)
{
Assert.True(en.MoveNext());
Assert.True(nonGenEn.MoveNext());
Assert.Same(exps[i], children[i]);
Assert.Same(exps[i], en.Current);
Assert.Same(exps[i], nonGenEn.Current);
Assert.Equal(i, children.IndexOf(exps[i]));
Assert.Contains(exps[i], children);
}
Assert.False(en.MoveNext());
Assert.False(nonGenEn.MoveNext());
(nonGenEn as IDisposable)?.Dispose();
}
Expression[] copyToTest = new Expression[parCount + 1];
Assert.Throws<ArgumentNullException>(() => children.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => children.CopyTo(copyToTest, -1));
Assert.All(copyToTest, Assert.Null); // assert partial copy didn't happen before exception
AssertExtensions.Throws<ArgumentException>(parCount >= 2 && parCount <= 5 ? null : "destinationArray", () => children.CopyTo(copyToTest, 2));
Assert.All(copyToTest, Assert.Null);
children.CopyTo(copyToTest, 1);
Assert.Equal(copyToTest, exps.Prepend(null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => children[-1]);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => children[parCount]);
Assert.Equal(-1, children.IndexOf(Expression.Parameter(typeof(int))));
Assert.DoesNotContain(Expression.Parameter(typeof(int)), children);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void IdentifyNonAbsentItemAsAbsent(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Equal(-1, block.Expressions.IndexOf(Expression.Default(typeof(long))));
Assert.DoesNotContain(null, block.Expressions);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ExpressionsEnumerable(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(values);
Assert.True(values.SequenceEqual(block.Expressions));
int index = 0;
foreach (Expression exp in ((IEnumerable)block.Expressions))
Assert.Same(exp, values[index++]);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void UpdateWithExpressionsReturnsSame(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Same(block, block.Update(block.Variables, block.Expressions));
Assert.Same(block, NoOpVisitor.Instance.Visit(block));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void Visit(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory]
[MemberData(nameof(ObjectAssignableConstantValuesAndSizes))]
public void VisitTyped(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(typeof(object), expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateToNullArguments(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
AssertExtensions.Throws<ArgumentNullException>("expressions", () => block.Update(null, null));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateDoesntRepeatEnumeration(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
Assert.Same(block, block.Update(null, new RunOnceEnumerable<Expression>(expressions)));
Assert.NotSame(
block,
block.Update(null, new RunOnceEnumerable<Expression>(PadBlock(blockSize - 1, Expression.Constant(1)))));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateDifferentSizeReturnsDifferent(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
Assert.NotSame(block, block.Update(null, block.Expressions.Prepend(Expression.Empty())));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateAnyExpressionDifferentReturnsDifferent(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
Expression[] expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
for (int i = 0; i != expressions.Length; ++i)
{
Expression[] newExps = new Expression[expressions.Length];
expressions.CopyTo(newExps, 0);
newExps[i] = Expression.Constant(1);
Assert.NotSame(block, block.Update(null, newExps));
}
}
}
}
| |
using NetApp.Tests.Helpers;
using Microsoft.Azure.Management.NetApp;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using Xunit;
using System;
using Microsoft.Azure.Management.NetApp.Models;
using System.Collections.Generic;
namespace NetApp.Tests.ResourceTests
{
public class AccountTests : TestBase
{
[Fact]
public void CreateDeleteAccount()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the account with only the one required property
var netAppAccount = new NetAppAccount()
{
Location = ResourceUtils.location
};
var resource = netAppMgmtClient.Accounts.CreateOrUpdate(netAppAccount, ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.Equal(resource.Name, ResourceUtils.accountName1);
Assert.Null(resource.Tags);
Assert.Null(resource.ActiveDirectories);
// get all accounts and check
var accountsBefore = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup);
Assert.Single(accountsBefore);
// remove the account and check
netAppMgmtClient.Accounts.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
// get all accounts and check
var accountsAfter = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup);
Assert.Empty(accountsAfter);
}
}
[Fact]
public void CreateAccountWithProperties()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
var dict = new Dictionary<string, string>();
dict.Add("Tag1", "Value1");
// create the account
var resource = ResourceUtils.CreateAccount(netAppMgmtClient, tags: dict, activeDirectory: ResourceUtils.activeDirectory);
Assert.True(resource.Tags.ContainsKey("Tag1"));
Assert.Equal("Value1", resource.Tags["Tag1"]);
Assert.NotNull(resource.ActiveDirectories);
// remove the account
netAppMgmtClient.Accounts.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
}
}
[Fact]
public void UpdateAccount()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the account
ResourceUtils.CreateAccount(netAppMgmtClient);
// perform create/update operation again for same account
// this should be treated as an update and accepted
// could equally do this with some property fields added
var dict = new Dictionary<string, string>();
dict.Add("Tag1", "Value2");
var resource = ResourceUtils.CreateAccount(netAppMgmtClient, tags: dict);
Assert.True(resource.Tags.ContainsKey("Tag1"));
Assert.Equal("Value2", resource.Tags["Tag1"]);
}
}
[Fact]
public void ListAccounts()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create two accounts
ResourceUtils.CreateAccount(netAppMgmtClient);
ResourceUtils.CreateAccount(netAppMgmtClient, ResourceUtils.accountName2);
// get the account list and check
var accounts = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup);
Assert.Equal(accounts.ElementAt(0).Name, ResourceUtils.accountName1);
Assert.Equal(accounts.ElementAt(1).Name, ResourceUtils.accountName2);
Assert.Equal(2, accounts.Count());
// clean up - delete the two accounts
ResourceUtils.DeleteAccount(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient, ResourceUtils.accountName2);
}
}
[Fact]
public void GetAccountByName()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the account
ResourceUtils.CreateAccount(netAppMgmtClient, ResourceUtils.accountName1);
// get and check the account
var account = netAppMgmtClient.Accounts.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.Equal(account.Name, ResourceUtils.accountName1);
// clean up - delete the account
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void GetAccountByNameNotFound()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// get and check the account
try
{
var account = netAppMgmtClient.Accounts.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.True(false); // expecting exception
}
catch (Exception ex)
{
Assert.Equal("The Resource 'Microsoft.NetApp/netAppAccounts/" + ResourceUtils.accountName1 + "' under resource group '" + ResourceUtils.resourceGroup + "' was not found.", ex.Message);
}
}
}
[Fact]
public void PatchAccount()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the account
ResourceUtils.CreateAccount(netAppMgmtClient, activeDirectory: ResourceUtils.activeDirectory);
var dict = new Dictionary<string, string>();
dict.Add("Tag2", "Value1");
// Now try and modify it
var netAppAccountPatch = new NetAppAccountPatch()
{
Tags = dict
};
// tag changes but active directory still present
var resource = netAppMgmtClient.Accounts.Update(netAppAccountPatch, ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.True(resource.Tags.ContainsKey("Tag2"));
Assert.Equal("Value1", resource.Tags["Tag2"]);
Assert.NotNull(resource.ActiveDirectories);
Assert.Equal("sdkuser", resource.ActiveDirectories.First().Username);
// so deleting the active directory requires the put operation
// but changing an active directory can be done but requires the id
ResourceUtils.activeDirectory2.ActiveDirectoryId = resource.ActiveDirectories.First().ActiveDirectoryId;
var activeDirectories = new List<ActiveDirectory> { ResourceUtils.activeDirectory2 };
dict.Add("Tag3", "Value3");
// Now try and modify it
var netAppAccountPatch2 = new NetAppAccountPatch()
{
ActiveDirectories = activeDirectories,
Tags = dict
};
var resource2 = netAppMgmtClient.Accounts.Update(netAppAccountPatch2, ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.True(resource2.Tags.ContainsKey("Tag2"));
Assert.Equal("Value1", resource2.Tags["Tag2"]);
Assert.True(resource2.Tags.ContainsKey("Tag3"));
Assert.Equal("Value3", resource2.Tags["Tag3"]);
Assert.NotNull(resource2.ActiveDirectories);
Assert.Equal("sdkuser1", resource2.ActiveDirectories.First().Username);
// cleanup - remove the account
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
private static string GetSessionsDirectoryPath()
{
string executingAssemblyPath = typeof(NetApp.Tests.ResourceTests.AccountTests).GetTypeInfo().Assembly.Location;
return Path.Combine(Path.GetDirectoryName(executingAssemblyPath), "SessionRecords");
}
}
}
| |
/********************************************************************
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 TUVienna.CS_CUP
{
using System.Collections;
/** This class represents an LALR item. Each LALR item consists of
* a production, a "dot" at a position within that production, and
* a Set of lookahead symbols (terminal). (The first two of these parts
* are provide by the super class). An item is designed to represent a
* configuration that the parser may be in. For example, an item of the
* form: <pre>
* [A ::= B * C d E , {a,b,c}]
* </pre>
* indicates that the parser is in the middle of parsing the production <pre>
* A ::= B C d E
* </pre>
* that B has already been parsed, and that we will expect to see a lookahead
* of either a, b, or c once the complete RHS of this production has been
* found.<p>
*
* Items may initially be missing some items from their lookahead sets.
* Links are maintained from each item to the Set of items that would need
* to be updated if symbols are added to its lookahead Set. During
* "lookahead propagation", we add symbols to various lookahead sets and
* propagate these changes across these dependency links as needed.
*
* @see java_cup.lalr_item_set
* @see java_cup.lalr_state
* @version last updated: 11/25/95
* @author Scott Hudson
* translated to C# 08.09.2003 by Samuel Imriska
*/
public class lalr_item : lr_item_core
{
/*-----------------------------------------------------------*/
/*--- Constructor(s) ----------------------------------------*/
/*-----------------------------------------------------------*/
/** Full constructor.
* @param prod the production for the item.
* @param pos the position of the "dot" within the production.
* @param look the Set of lookahead symbols.
*/
public lalr_item(production prod, int pos, terminal_set look):base(prod,pos)
{
_lookahead = look;
_propagate_items = new Stack();
needs_propagation = true;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Constructor with default position (dot at start).
* @param prod the production for the item.
* @param look the Set of lookahead symbols.
*/
public lalr_item(production prod, terminal_set look) : this(prod,0,look)
{
// this(prod,0,look);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Constructor with default position and empty lookahead Set.
* @param prod the production for the item.
*/
public lalr_item(production prod) : this (prod,0,new terminal_set()){}
/*-----------------------------------------------------------*/
/*--- (Access to) Instance Variables ------------------------*/
/*-----------------------------------------------------------*/
/** The lookahead symbols of the item. */
protected terminal_set _lookahead;
/** The lookahead symbols of the item. */
public terminal_set lookahead() {return _lookahead;}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Links to items that the lookahead needs to be propagated to. */
protected Stack _propagate_items;
/** Links to items that the lookahead needs to be propagated to */
public Stack propagate_items() {return _propagate_items;}
//in C# added to emulate Stack.setElementAt
public void set_propagate_item(object obj,int index)
{
object[] tmp=_propagate_items.ToArray();
tmp[index]=obj;
_propagate_items= new Stack(tmp);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Flag to indicate that this item needs to propagate its lookahead
* (whether it has changed or not).
*/
protected bool needs_propagation;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Add a new item to the Set of items we propagate to. */
public void add_propagate(lalr_item prop_to)
{
_propagate_items.Push(prop_to);
needs_propagation = true;
}
/*-----------------------------------------------------------*/
/*--- General Methods ---------------------------------------*/
/*-----------------------------------------------------------*/
/** Propagate incoming lookaheads through this item to others need to
* be changed.
* @params incoming symbols to potentially be added to lookahead of this item.
*/
public void propagate_lookaheads(terminal_set incoming)
{
bool change = false;
/* if we don't need to propagate, then bail out now */
if (!needs_propagation && (incoming == null || incoming.empty()))
return;
/* if we have null incoming, treat as an empty Set */
if (incoming != null)
{
/* add the incoming to the lookahead of this item */
change = lookahead().add(incoming);
}
/* if we changed or need it anyway, propagate across our links */
if (change || needs_propagation)
{
/* don't need to propagate again */
needs_propagation = false;
/* propagate our lookahead into each item we are linked to */
IEnumerator myEnum= propagate_items().GetEnumerator();
while (myEnum.MoveNext())
((lalr_item)myEnum.Current).propagate_lookaheads(lookahead());
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Produce the new lalr_item that results from shifting the dot one position
* to the right.
*/
public lalr_item shift()
{
lalr_item result;
/* can't shift if we have dot already at the end */
if (dot_at_end())
throw new internal_error("Attempt to shift past end of an lalr_item");
/* create the new item w/ the dot shifted by one */
result = new lalr_item(the_production(), dot_pos()+1,
new terminal_set(lookahead()));
/* change in our lookahead needs to be propagated to this item */
add_propagate(result);
return result;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Calculate lookahead representing symbols that could appear after the
* symbol that the dot is currently in front of. Note: this routine must
* not be invoked before first sets and nullability has been calculated
* for all non terminals.
*/
public terminal_set calc_lookahead(terminal_set lookahead_after)
{
terminal_set result;
int pos;
production_part part;
symbol sym;
/* sanity check */
if (dot_at_end())
throw new internal_error(
"Attempt to calculate a lookahead Set with a completed item");
/* start with an empty result */
result = new terminal_set();
/* consider all nullable symbols after the one to the right of the dot */
for (pos = dot_pos()+1; pos < the_production().rhs_length(); pos++)
{
part = the_production().rhs(pos);
/* consider what kind of production part it is -- skip actions */
if (!part.is_action())
{
sym = ((symbol_part)part).the_symbol();
/* if its a terminal add it in and we are done */
if (!sym.is_non_term())
{
result.add((terminal)sym);
return result;
}
else
{
/* otherwise add in first Set of the non terminal */
result.add(((non_terminal)sym).first_set());
/* if its nullable we continue adding, if not, we are done */
if (!((non_terminal)sym).nullable())
return result;
}
}
}
/* if we get here everything past the dot was nullable
we add in the lookahead for after the production and we are done */
result.add(lookahead_after);
return result;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Determine if everything from the symbol one beyond the dot all the
* way to the end of the right hand side is nullable. This would indicate
* that the lookahead of this item must be included in the lookaheads of
* all items produced as a closure of this item. Note: this routine should
* not be invoked until after first sets and nullability have been
* calculated for all non terminals.
*/
public bool lookahead_visible()
{
production_part part;
symbol sym;
/* if the dot is at the end, we have a problem, but the cleanest thing
to do is just return true. */
if (dot_at_end()) return true;
/* walk down the rhs and bail if we get a non-nullable symbol */
for (int pos = dot_pos() + 1; pos < the_production().rhs_length(); pos++)
{
part = the_production().rhs(pos);
/* skip actions */
if (!part.is_action())
{
sym = ((symbol_part)part).the_symbol();
/* if its a terminal we fail */
if (!sym.is_non_term()) return false;
/* if its not nullable we fail */
if (!((non_terminal)sym).nullable()) return false;
}
}
/* if we get here its all nullable */
return true;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Equality comparison -- here we only require the cores to be equal since
* we need to do sets of items based only on core equality (ignoring
* lookahead sets).
*/
public bool Equals(lalr_item other)
{
if (other == null) return false;
return base.Equals(other);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Generic equality comparison. */
public override bool Equals(object other)
{
if (other.GetType()!=typeof(lalr_item))
return false;
else
return Equals((lalr_item)other);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Return a hash code -- here we only hash the core since we only test core
* matching in LALR items.
*/
public override int GetHashCode()
{
return base.GetHashCode();
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Convert to string. */
public override string ToString()
{
string result = "";
// additional output for debugging:
// result += "(" + obj_hash() + ")";
result += "[";
result += base.ToString();
result += ", ";
if (lookahead() != null)
{
result += "{";
for (int t = 0; t < terminal.number(); t++)
if (lookahead().contains(t))
result += terminal.find(t).name() + " ";
result += "}";
}
else
result += "NULL LOOKAHEAD!!";
result += "]";
// additional output for debugging:
// result += " -> ";
// for (int i = 0; i<propagate_items().size(); i++)
// result+=((lalr_item)(propagate_items().elementAt(i))).obj_hash()+" ";
//
// if (needs_propagation) result += " NP";
return result;
}
/*-----------------------------------------------------------*/
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData.Query
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.Data.Edm;
using Microsoft.Data.Edm.Library;
using Microsoft.Data.OData.Metadata;
#endregion Namespaces
/// <summary>
/// Class which translates semantic tree fragments (QueryNode) into LINQ Expression.
/// </summary>
#if INTERNAL_DROP
internal abstract class QueryExpressionTranslator
#else
public abstract class QueryExpressionTranslator
#endif
{
/// <summary>
/// The name of the method to call on Queryable or Enumerable to perform Where operation.
/// </summary>
private const string WhereMethodName = "Where";
/// <summary>
/// The name of the method to call on Queryable or Enumerable to perform Skip operation.
/// </summary>
private const string SkipMethodName = "Skip";
/// <summary>
/// The name of the method to call on Queryable or Enumerable to perform Take operation.
/// </summary>
private const string TakeMethodName = "Take";
/// <summary>
/// The name of the method to call on Queryable or Enumerable to perform OrderBy operation.
/// </summary>
private const string OrderByMethodName = "OrderBy";
/// <summary>
/// The name of the method to call on Queryable or Enumerable to perform OrderByDescending operation.
/// </summary>
private const string OrderByDescendingMethodName = "OrderByDescending";
/// <summary>
/// The name of the method to call on Queryable or Enumerable to perform ThenBy operation.
/// </summary>
private const string ThenByMethodName = "ThenBy";
/// <summary>
/// The name of the method to call on Queryable or Enumerable to perform ThenByDescending operation.
/// </summary>
private const string ThenByDescendingMethodName = "ThenByDescending";
/// <summary>
/// Constant expression representing the (untyped) null literal.
/// </summary>
private static readonly Expression nullLiteralExpression = Expression.Constant(null);
/// <summary>
/// Literal constant true expression.
/// </summary>
private static readonly Expression trueLiteralExpression = Expression.Constant(true, typeof(bool));
/// <summary>
/// Literal constant false expression.
/// </summary>
private static readonly ConstantExpression falseLiteralExpression = Expression.Constant(false);
/// <summary>
/// Set to true if null propagation should be injected into the resulting expression tree.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Temporary until the field is actually used.")]
private readonly bool nullPropagationRequired;
/// <summary>
/// Model containing annotations.
/// </summary>
private readonly IEdmModel model;
/// <summary>
/// Stack which holds definitions for parameter nodes.
/// </summary>
/// <remarks>The top of the stack contains the current parameter query node and its respective expression it should be translated to.</remarks>
private Stack<KeyValuePair<ParameterQueryNode, Expression>> parameterNodeDefinitions;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="nullPropagationRequired">true if null propagation should be injected or false otherwise.</param>
/// <param name="model">Model containing annotations.</param>
protected QueryExpressionTranslator(bool nullPropagationRequired, IEdmModel model)
{
ExceptionUtils.CheckArgumentNotNull(model, "model");
this.nullPropagationRequired = nullPropagationRequired;
this.model = model;
this.parameterNodeDefinitions = new Stack<KeyValuePair<ParameterQueryNode, Expression>>();
}
/// <summary>
/// Translates a semantic node and all its children into a LINQ expression.
/// </summary>
/// <param name="node">The query node to translate.</param>
/// <returns>The translated LINQ expression.</returns>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "One place to switch on all the node types.")]
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "One place to switch on all the node types.")]
public Expression Translate(QueryNode node)
{
ExceptionUtils.CheckArgumentNotNull(node, "node");
Expression result = null;
Type requiredExpressionType = null;
CollectionQueryNode collectionNode = node as CollectionQueryNode;
SingleValueQueryNode singleValueNode = node as SingleValueQueryNode;
if (collectionNode != null)
{
if (collectionNode.ItemType == null)
{
throw new ODataException(Strings.QueryExpressionTranslator_CollectionQueryNodeWithoutItemType(node.Kind));
}
bool requiresIQueryable = false;
switch (node.Kind)
{
case QueryNodeKind.Extension:
result = this.TranslateExtension(node);
break;
case QueryNodeKind.EntitySet:
requiresIQueryable = true;
result = this.TranslateEntitySet((EntitySetQueryNode)node);
break;
case QueryNodeKind.CollectionServiceOperation:
requiresIQueryable = true;
result = this.TranslateCollectionServiceOperation((CollectionServiceOperationQueryNode)node);
break;
case QueryNodeKind.Skip:
// TODO: eventually we will have to support this on IEnumerable as well (as it can happen on expansions)
requiresIQueryable = true;
result = this.TranslateSkip((SkipQueryNode)node);
break;
case QueryNodeKind.Top:
// TODO: eventually we will have to support this on IEnumerable as well (as it can happen on expansions)
requiresIQueryable = true;
result = this.TranslateTop((TopQueryNode)node);
break;
case QueryNodeKind.Filter:
// TODO: eventually we will have to support this on IEnumerable as well (as it can happen on expansions)
requiresIQueryable = true;
result = this.TranslateFilter((FilterQueryNode)node);
break;
case QueryNodeKind.OrderBy:
// TODO: eventually we will have to support this on IEnumerable as well (as it can happen on expansions)
requiresIQueryable = true;
result = this.TranslateOrderBy((OrderByQueryNode)node);
break;
default:
throw new ODataException(Strings.QueryExpressionTranslator_UnsupportedQueryNodeKind(node.Kind));
}
if (requiresIQueryable)
{
requiredExpressionType = typeof(IQueryable<>).MakeGenericType(collectionNode.ItemType.GetInstanceType(this.model));
}
else
{
requiredExpressionType = typeof(IEnumerable<>).MakeGenericType(collectionNode.ItemType.GetInstanceType(this.model));
}
}
else if (singleValueNode != null)
{
// we allow null types for the nodes that can take literal null values and
// the operators combining them. We have separate checks in the corresponding translate methods
// to ensure that a null type is only allowed if the result is statically known to be null
IEdmTypeReference typeReference = singleValueNode.TypeReference;
if (typeReference == null &&
singleValueNode.Kind != QueryNodeKind.Constant &&
singleValueNode.Kind != QueryNodeKind.UnaryOperator &&
singleValueNode.Kind != QueryNodeKind.BinaryOperator)
{
throw new ODataException(Strings.QueryExpressionTranslator_SingleValueQueryNodeWithoutTypeReference(node.Kind));
}
// TODO: Note that we don't always set the requiredExpressionType
// The reason is that in some cases it can be IQueryable<T> and in other cases just T.
// When we translate the query path, we need to keep everything IQueryable<T> (even if we know it should be a single value)
// so that the LINQ providers can recognize the query as a join. Outside of the query path (in filters, expansions and so on)
// we keep single values as simple T instead.
switch (node.Kind)
{
case QueryNodeKind.Extension:
Debug.Assert(typeReference != null, "typeReference != null");
result = this.TranslateExtension(node);
break;
case QueryNodeKind.SingleValueServiceOperation:
Debug.Assert(typeReference != null, "typeReference != null");
result = this.TranslateSingleValueServiceOperation((SingleValueServiceOperationQueryNode)node);
break;
case QueryNodeKind.Constant:
result = this.TranslateConstant((ConstantQueryNode)node);
requiredExpressionType = typeReference == null ? null : typeReference.GetInstanceType(this.model);
break;
case QueryNodeKind.Convert:
Debug.Assert(typeReference != null, "typeReference != null");
result = this.TranslateConvert((ConvertQueryNode)node);
requiredExpressionType = typeReference.GetInstanceType(this.model);
break;
case QueryNodeKind.KeyLookup:
Debug.Assert(typeReference != null, "typeReference != null");
result = this.TranslateKeyLookup((KeyLookupQueryNode)node);
break;
case QueryNodeKind.BinaryOperator:
result = this.TranslateBinaryOperator((BinaryOperatorQueryNode)node);
requiredExpressionType = typeReference == null ? null : typeReference.GetInstanceType(this.model);
break;
case QueryNodeKind.UnaryOperator:
result = this.TranslateUnaryOperator((UnaryOperatorQueryNode)node);
requiredExpressionType = typeReference == null ? null : typeReference.GetInstanceType(this.model);
break;
case QueryNodeKind.PropertyAccess:
Debug.Assert(typeReference != null, "typeReference != null");
result = this.TranslatePropertyAccess((PropertyAccessQueryNode)node);
requiredExpressionType = typeReference.GetInstanceType(this.model);
break;
case QueryNodeKind.Parameter:
Debug.Assert(typeReference != null, "typeReference != null");
result = this.TranslateParameter((ParameterQueryNode)node);
requiredExpressionType = typeReference.GetInstanceType(this.model);
break;
case QueryNodeKind.SingleValueFunctionCall:
result = this.TranslateSingleValueFunctionCall((SingleValueFunctionCallQueryNode)node);
requiredExpressionType = singleValueNode.TypeReference.GetInstanceType(this.model);
break;
default:
throw new ODataException(Strings.QueryExpressionTranslator_UnsupportedQueryNodeKind(node.Kind));
}
}
else
{
switch (node.Kind)
{
case QueryNodeKind.Extension:
result = this.TranslateExtension(node);
break;
default:
throw new ODataException(Strings.QueryExpressionTranslator_UnsupportedQueryNodeKind(node.Kind));
}
}
if (result == null)
{
throw new ODataException(Strings.QueryExpressionTranslator_NodeTranslatedToNull(node.Kind));
}
// Check if the result type matches the required type. Note that we do allow to return nullable version of the required type
// if null propagation is turned on, since null propagation may turn otherwise non-nullable expressions to nullable ones.
if (requiredExpressionType != null && !requiredExpressionType.IsAssignableFrom(result.Type))
{
if (!this.nullPropagationRequired || !TypeUtils.AreTypesEquivalent(TypeUtils.GetNonNullableType(result.Type), requiredExpressionType))
{
throw new ODataException(Strings.QueryExpressionTranslator_NodeTranslatedToWrongType(node.Kind, result.Type, requiredExpressionType));
}
}
return result;
}
/// <summary>
/// Translates an extension node.
/// </summary>
/// <param name="extensionNode">The extension node to translate.</param>
/// <returns>The expression the node was translated to.</returns>
protected virtual Expression TranslateExtension(QueryNode extensionNode)
{
ExceptionUtils.CheckArgumentNotNull(extensionNode, "extensionNode");
throw new ODataException(Strings.QueryExpressionTranslator_UnsupportedExtensionNode);
}
/// <summary>
/// Translates an entity set node.
/// </summary>
/// <param name="entitySetNode">The entity set query node to translate.</param>
/// <returns>Expression which evaluates to IQueryable<T> where T is the InstanceType of the type of the entity set.</returns>
protected abstract Expression TranslateEntitySet(EntitySetQueryNode entitySetNode);
/// <summary>
/// Translates a service operation node which returns a collection of entities.
/// </summary>
/// <param name="serviceOperationNode">The collection service operation node to translate.</param>
/// <returns>Expression which evaluates to IQueryable<T> where T is the InstanceType of the ResultType of the service operation.</returns>
protected abstract Expression TranslateCollectionServiceOperation(CollectionServiceOperationQueryNode serviceOperationNode);
/// <summary>
/// Translates a service operation node which returns a single value.
/// </summary>
/// <param name="serviceOperationNode">The single value service operation node to translate.</param>
/// <returns>Expression which evaluates to type which is the InstanceType of the ResultType of the service operation.</returns>
protected abstract Expression TranslateSingleValueServiceOperation(SingleValueServiceOperationQueryNode serviceOperationNode);
/// <summary>
/// Translates a constant node.
/// </summary>
/// <param name="constantNode">The constant node to translate.</param>
/// <returns>The translated expression which evaluates to the constant value.</returns>
protected virtual Expression TranslateConstant(ConstantQueryNode constantNode)
{
ExceptionUtils.CheckArgumentNotNull(constantNode, "constantNode");
if (constantNode.TypeReference == null)
{
Debug.Assert(constantNode.Value == null, "constantNode.Value == null");
return nullLiteralExpression;
}
else
{
if (!constantNode.TypeReference.IsODataPrimitiveTypeKind())
{
throw new ODataException(Strings.QueryExpressionTranslator_ConstantNonPrimitive(constantNode.TypeReference.ODataFullName()));
}
return Expression.Constant(constantNode.Value, constantNode.TypeReference.GetInstanceType(this.model));
}
}
/// <summary>
/// Translates a convert node.
/// </summary>
/// <param name="convertNode">The convert node to translate.</param>
/// <returns>The translated expression which evaluates to the converted value.</returns>
protected virtual Expression TranslateConvert(ConvertQueryNode convertNode)
{
ExceptionUtils.CheckArgumentNotNull(convertNode, "convertNode");
ExceptionUtils.CheckArgumentNotNull(convertNode.TypeReference, "convertNode.Type");
// TODO: Should we verify that the Source doesn't translate to a wrong type?
// In theory if it's a KeyLookup for example it might translate to IQueryable<T> instead of T in which case the Convert should fail
// as it's not supported in the path.
if (convertNode.TypeReference.GetCanReflectOnInstanceType(this.model))
{
Expression sourceExpression = this.Translate(convertNode.Source);
// If we detect a null literal we replace the convert of the null literal with a typed null literal.
return sourceExpression == nullLiteralExpression
? (Expression)Expression.Constant(null, convertNode.TypeReference.GetInstanceType(this.model))
: (Expression)Expression.Convert(sourceExpression, convertNode.TypeReference.GetInstanceType(this.model));
}
else
{
// TODO: Support for types that are not strongly typed in convert
throw new NotImplementedException();
}
}
/// <summary>
/// Translates a key lookup.
/// </summary>
/// <param name="keyLookupNode">The key lookup node to translate.</param>
/// <returns>The translated expression which evaluates to the result of the key lookup.</returns>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Keeping key lookup in one place.")]
protected virtual Expression TranslateKeyLookup(KeyLookupQueryNode keyLookupNode)
{
ExceptionUtils.CheckArgumentNotNull(keyLookupNode, "keyLookupNode");
ExceptionUtils.CheckArgumentNotNull(keyLookupNode.Collection, "keyLookupNode.Collection");
ExceptionUtils.CheckArgumentNotNull(keyLookupNode.Collection.ItemType, "keyLookupNode.Collection.ItemType");
ExceptionUtils.CheckArgumentNotNull(keyLookupNode.KeyPropertyValues, "keyLookupNode.KeyPropertyValues");
IEdmTypeReference itemType = keyLookupNode.Collection.ItemType;
if (keyLookupNode.Collection.ItemType.TypeKind() != EdmTypeKind.Entity)
{
throw new ODataException(Strings.QueryExpressionTranslator_KeyLookupOnlyOnEntities(keyLookupNode.Collection.ItemType.ODataFullName(), keyLookupNode.Collection.ItemType.TypeKind()));
}
IEdmEntityTypeReference itemEntityType = itemType.AsEntityOrNull();
Debug.Assert(itemEntityType != null, "itemEntityType != null");
Expression collectionExpression = this.Translate(keyLookupNode.Collection);
Type expectedCollectionExpressionType = typeof(IQueryable<>).MakeGenericType(itemType.GetInstanceType(this.model));
if (!expectedCollectionExpressionType.IsAssignableFrom(collectionExpression.Type))
{
throw new ODataException(Strings.QueryExpressionTranslator_KeyLookupOnlyOnQueryable(collectionExpression.Type, expectedCollectionExpressionType));
}
ParameterExpression parameter = Expression.Parameter(itemType.GetInstanceType(this.model), "it");
Expression body = null;
// We have to walk the key properties as declared on the type to get the declared order (rather than the order in the query)
// So we need to cache the key properties in a list so that we can look them up. This is necessary to avoid enumerating the IEnumerable
// specified on the Key lookup node multiple times (since we don't know how costly it is and if it's actually possible).
List<KeyPropertyValue> keyPropertyValuesCache = new List<KeyPropertyValue>(keyLookupNode.KeyPropertyValues);
foreach (IEdmStructuralProperty keyProperty in itemEntityType.Key())
{
// Find the value for the key property and verify that it's specified exactly once.
KeyPropertyValue keyPropertyValue = null;
foreach (KeyPropertyValue candidateKeyPropertyValue in keyPropertyValuesCache.Where(kpv => kpv.KeyProperty == keyProperty))
{
if (keyPropertyValue != null)
{
throw new ODataException(Strings.QueryExpressionTranslator_KeyLookupWithoutKeyProperty(keyProperty.Name, itemType.ODataFullName()));
}
keyPropertyValue = candidateKeyPropertyValue;
}
if (keyPropertyValue == null)
{
throw new ODataException(Strings.QueryExpressionTranslator_KeyLookupWithoutKeyProperty(keyProperty.Name, itemType.ODataFullName()));
}
// NOTE: using Any() instead of Contains() since Contains() does not exist on all platforms
if (keyPropertyValue.KeyProperty == null || !itemEntityType.Key().Any(k => k == keyPropertyValue.KeyProperty))
{
throw new ODataException(Strings.QueryExpressionTranslator_KeyPropertyValueWithoutProperty);
}
if (keyPropertyValue.KeyValue == null ||
keyPropertyValue.KeyValue.TypeReference == null ||
!keyPropertyValue.KeyValue.TypeReference.IsEquivalentTo(keyPropertyValue.KeyProperty.Type))
{
throw new ODataException(Strings.QueryExpressionTranslator_KeyPropertyValueWithWrongValue(keyPropertyValue.KeyProperty.Name));
}
Expression keyPropertyAccess = this.CreatePropertyAccessExpression(parameter, itemEntityType, keyPropertyValue.KeyProperty);
Expression keyValueExpression = this.Translate(keyPropertyValue.KeyValue);
#if DEBUG
Debug.Assert(
TypeUtils.AreTypesEquivalent(keyPropertyAccess.Type, keyValueExpression.Type),
"The types of the expression should have been checked against the metadata types which are equal.");
#endif
Expression keyPredicate = Expression.Equal(
keyPropertyAccess,
keyValueExpression);
if (body == null)
{
body = keyPredicate;
}
else
{
body = Expression.AndAlso(body, keyPredicate);
}
}
if (body == null)
{
throw new ODataException(Strings.QueryExpressionTranslator_KeyLookupWithNoKeyValues);
}
return Expression.Call(
typeof(Queryable),
WhereMethodName,
new Type[] { itemType.GetInstanceType(this.model) },
collectionExpression,
Expression.Quote(Expression.Lambda(body, parameter)));
}
/// <summary>
/// Translates a skip operation.
/// </summary>
/// <param name="skipNode">The skip node to translate.</param>
/// <returns>The translated expression which evaluates to the result of the skip operation.</returns>
protected virtual Expression TranslateSkip(SkipQueryNode skipNode)
{
ExceptionUtils.CheckArgumentNotNull(skipNode, "skipNode");
ExceptionUtils.CheckArgumentNotNull(skipNode.Amount, "skipNode.Amount");
Expression collectionExpression = this.Translate(skipNode.Collection);
Expression amountExpression = this.Translate(skipNode.Amount);
// TODO: eventually we will have to support this on Enumerable as well (as it can happen on expansions)
return Expression.Call(
typeof(Queryable),
SkipMethodName,
new Type[] { skipNode.Collection.ItemType.GetInstanceType(this.model) },
collectionExpression,
amountExpression);
}
/// <summary>
/// Translates a top/take operation.
/// </summary>
/// <param name="topNode">The top node to translate.</param>
/// <returns>The translated expression which evaluates to the result of the top operation.</returns>
protected virtual Expression TranslateTop(TopQueryNode topNode)
{
ExceptionUtils.CheckArgumentNotNull(topNode, "topNode");
ExceptionUtils.CheckArgumentNotNull(topNode.Amount, "topNode.Amount");
Expression collectionExpression = this.Translate(topNode.Collection);
Expression amountExpression = this.Translate(topNode.Amount);
// TODO: eventually we will have to support this on Enumerable as well (as it can happen on expansions)
return Expression.Call(
typeof(Queryable),
TakeMethodName,
new Type[] { topNode.Collection.ItemType.GetInstanceType(this.model) },
collectionExpression,
amountExpression);
}
/// <summary>
/// Translates a filter node.
/// </summary>
/// <param name="filterNode">The filter node to translate.</param>
/// <returns>Expression which evaluates to the result after the filter operation.</returns>
protected virtual Expression TranslateFilter(FilterQueryNode filterNode)
{
ExceptionUtils.CheckArgumentNotNull(filterNode, "filterNode");
ExceptionUtils.CheckArgumentNotNull(filterNode.ItemType, "filterNode.ItemType");
ExceptionUtils.CheckArgumentNotNull(filterNode.Collection, "filterNode.Collection");
ExceptionUtils.CheckArgumentNotNull(filterNode.Collection.ItemType, "filterNode.Collection.ItemType");
ExceptionUtils.CheckArgumentNotNull(filterNode.Expression, "filterNode.Expression");
ExceptionUtils.CheckArgumentNotNull(filterNode.Parameter, "filterNode.Parameter");
ExceptionUtils.CheckArgumentNotNull(filterNode.Parameter.TypeReference, "filterNode.Parameter.Type");
ParameterExpression parameter = Expression.Parameter(filterNode.Parameter.TypeReference.GetInstanceType(this.model), "it");
Expression collectionExpression = this.Translate(filterNode.Collection);
// TODO: If we should support Filter on IEnumerable, then we need to add support here
Type expectedCollectionType = typeof(IQueryable<>).MakeGenericType(parameter.Type);
if (!expectedCollectionType.IsAssignableFrom(collectionExpression.Type))
{
throw new ODataException(Strings.QueryExpressionTranslator_FilterCollectionOfWrongType(collectionExpression.Type, expectedCollectionType));
}
this.parameterNodeDefinitions.Push(new KeyValuePair<ParameterQueryNode, Expression>(filterNode.Parameter, parameter));
Expression body = this.Translate(filterNode.Expression);
Debug.Assert(this.parameterNodeDefinitions.Peek().Key == filterNode.Parameter, "The parameter definition stack was not balanced correctly.");
Debug.Assert(this.parameterNodeDefinitions.Peek().Value == parameter, "The parameter definition stack was not balanced correctly.");
this.parameterNodeDefinitions.Pop();
// TODO: Deal with open expressions
if (body == nullLiteralExpression)
{
// lifting rules say that a null literal is interpreted as 'false' when treated as boolean.
body = falseLiteralExpression;
}
else if (body.Type == typeof(bool?))
{
Expression test = Expression.Equal(body, Expression.Constant(null, typeof(bool?)));
body = Expression.Condition(test, falseLiteralExpression, Expression.Property(body, "Value"));
}
if (body.Type != typeof(bool))
{
throw new ODataException(Strings.QueryExpressionTranslator_FilterExpressionOfWrongType(body.Type));
}
return Expression.Call(
typeof(Queryable),
WhereMethodName,
new Type[] { parameter.Type },
collectionExpression,
Expression.Quote(Expression.Lambda(body, parameter)));
}
/// <summary>
/// Translates a binary operator node.
/// </summary>
/// <param name="binaryOperatorNode">The binary operator node to translate.</param>
/// <returns>Expression which evaluates to the result of the binary operator.</returns>
protected virtual Expression TranslateBinaryOperator(BinaryOperatorQueryNode binaryOperatorNode)
{
ExceptionUtils.CheckArgumentNotNull(binaryOperatorNode, "binaryOperatorNode");
ExceptionUtils.CheckArgumentNotNull(binaryOperatorNode.Left, "binaryOperatorNode.Left");
ExceptionUtils.CheckArgumentNotNull(binaryOperatorNode.Right, "binaryOperatorNode.Right");
Expression left = this.Translate(binaryOperatorNode.Left);
Expression right = this.Translate(binaryOperatorNode.Right);
// If the operands both statically are null literals we optimize the operator to result in the
// null literal as well (per specification) because we otherwise cannot execute such an expression tree
if (left == nullLiteralExpression && right == nullLiteralExpression)
{
// Equality operators have special rules if one (or both) operands are null
if (binaryOperatorNode.OperatorKind == BinaryOperatorKind.Equal)
{
return trueLiteralExpression;
}
else if (binaryOperatorNode.OperatorKind == BinaryOperatorKind.NotEqual)
{
return falseLiteralExpression;
}
return nullLiteralExpression;
}
Debug.Assert(left != nullLiteralExpression && right != nullLiteralExpression, "None of the operands should be the untyped literal null expression at this point.");
// throw if no type is available
if (binaryOperatorNode.TypeReference == null)
{
throw new ODataException(Strings.QueryExpressionTranslator_SingleValueQueryNodeWithoutTypeReference(binaryOperatorNode.Kind));
}
// Deal with null propagation; after translating the operands to expressions one (or both) can have changed from a non-nullable type to a
// nullable type if null propagation is enabled; compensate for that.
if (this.nullPropagationRequired)
{
HandleBinaryOperatorNullPropagation(ref left, ref right);
}
else
{
Debug.Assert(left.Type == right.Type, "left.Type == right.Type");
}
// TODO: Deal with open properties
// See RequestQueryParser.ExpressionParser.GenerateComparisonExpression for the actual complexity required for comparison operators
switch (binaryOperatorNode.OperatorKind)
{
case BinaryOperatorKind.Or:
return Expression.OrElse(left, right);
case BinaryOperatorKind.And:
return Expression.AndAlso(left, right);
case BinaryOperatorKind.Equal:
if (left.Type == typeof(byte[]))
{
return Expression.Equal(left, right, false, DataServiceProviderMethods.AreByteArraysEqualMethodInfo);
}
else
{
return Expression.Equal(left, right);
}
case BinaryOperatorKind.NotEqual:
if (left.Type == typeof(byte[]))
{
return Expression.NotEqual(left, right, false, DataServiceProviderMethods.AreByteArraysNotEqualMethodInfo);
}
else
{
return Expression.NotEqual(left, right);
}
case BinaryOperatorKind.GreaterThan:
return CreateGreaterThanExpression(left, right);
case BinaryOperatorKind.GreaterThanOrEqual:
return CreateGreaterThanOrEqualExpression(left, right);
case BinaryOperatorKind.LessThan:
return CreateLessThanExpression(left, right);
case BinaryOperatorKind.LessThanOrEqual:
return CreateLessThanOrEqualExpression(left, right);
case BinaryOperatorKind.Add:
return Expression.Add(left, right);
case BinaryOperatorKind.Subtract:
return Expression.Subtract(left, right);
case BinaryOperatorKind.Multiply:
return Expression.Multiply(left, right);
case BinaryOperatorKind.Divide:
return Expression.Divide(left, right);
case BinaryOperatorKind.Modulo:
return Expression.Modulo(left, right);
default:
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.QueryExpressionTranslator_TranslateBinaryOperator_UnreachableCodepath));
}
}
/// <summary>
/// Translates a unary operator node.
/// </summary>
/// <param name="unaryOperatorNode">The unary operator node to translate.</param>
/// <returns>Expression which evaluates to the result of the unary operator.</returns>
protected virtual Expression TranslateUnaryOperator(UnaryOperatorQueryNode unaryOperatorNode)
{
ExceptionUtils.CheckArgumentNotNull(unaryOperatorNode, "unaryOperatorNode");
ExceptionUtils.CheckArgumentNotNull(unaryOperatorNode.Operand, "unaryOperatorNode.Operand");
Expression operand = this.Translate(unaryOperatorNode.Operand);
// If the operand statically is the null literal we optimize the operator to result in the
// null literal as well (per specification) because we otherwise cannot execute such an expression tree
if (operand == nullLiteralExpression)
{
return nullLiteralExpression;
}
// throw if no type is available
if (unaryOperatorNode.TypeReference == null)
{
throw new ODataException(Strings.QueryExpressionTranslator_SingleValueQueryNodeWithoutTypeReference(unaryOperatorNode.Kind));
}
// TODO: deal with null propagation if necessary
// TODO: deal with open types
switch (unaryOperatorNode.OperatorKind)
{
case UnaryOperatorKind.Negate:
return Expression.Negate(operand);
case UnaryOperatorKind.Not:
if (operand.Type == typeof(bool) || operand.Type == typeof(bool?))
{
// Expression.Not will take numerics and apply '~' to them, thus the extra check here.
return Expression.Not(operand);
}
else
{
throw new ODataException(Strings.QueryExpressionTranslator_UnaryNotOperandNotBoolean(operand.Type));
}
default:
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.QueryExpressionTranslator_TranslateUnaryOperator_UnreachableCodepath));
}
}
/// <summary>
/// Translates a property access node.
/// </summary>
/// <param name="propertyAccessNode">The property access node to translate.</param>
/// <returns>Expression which evaluates to the result of the property access.</returns>
protected virtual Expression TranslatePropertyAccess(PropertyAccessQueryNode propertyAccessNode)
{
ExceptionUtils.CheckArgumentNotNull(propertyAccessNode, "propertyAccessNode");
ExceptionUtils.CheckArgumentNotNull(propertyAccessNode.Source, "propertyAccessNode.Source");
ExceptionUtils.CheckArgumentNotNull(propertyAccessNode.Source.TypeReference, "propertyAccessNode.Source.TypeReference");
ExceptionUtils.CheckArgumentNotNull(propertyAccessNode.Property, "propertyAccessNode.Property");
Expression source = this.Translate(propertyAccessNode.Source);
if (!propertyAccessNode.Source.TypeReference.GetInstanceType(this.model).IsAssignableFrom(source.Type))
{
throw new ODataException(Strings.QueryExpressionTranslator_PropertyAccessSourceWrongType(source.Type, propertyAccessNode.Source.TypeReference.GetInstanceType(this.model)));
}
if (propertyAccessNode.Property.GetCanReflectOnInstanceTypeProperty(this.model))
{
Debug.Assert(source != nullLiteralExpression, "source != nullLiteralExpression");
IEdmTypeReference sourceType = propertyAccessNode.Source.TypeReference;
IEdmStructuredTypeReference structuredSourceTypeReference = sourceType.AsStructuredOrNull();
if (structuredSourceTypeReference == null)
{
throw new ODataException(Strings.QueryExpressionTranslator_PropertyAccessSourceNotStructured(sourceType.TypeKind()));
}
Expression propertyAccessExpression = Expression.Property(source, structuredSourceTypeReference.GetPropertyInfo(propertyAccessNode.Property, this.model));
// Add null propagation code if the parent is not the parameter node (which will never be null) and is nullable
if (this.nullPropagationRequired && source.NodeType != ExpressionType.Parameter && TypeUtils.TypeAllowsNull(source.Type))
{
Expression test = Expression.Equal(source, Expression.Constant(null, source.Type));
Type propagatedType = TypeUtils.GetNullableType(propertyAccessExpression.Type);
if (propagatedType != propertyAccessExpression.Type)
{
// we need to convert the property access result to the propagated type
propertyAccessExpression = Expression.Convert(propertyAccessExpression, propagatedType);
}
propertyAccessExpression = Expression.Condition(test, Expression.Constant(null, propagatedType), propertyAccessExpression);
}
return propertyAccessExpression;
}
else
{
// TODO: support for untyped and open properties
throw new NotImplementedException();
}
}
/// <summary>
/// Translates a parameter node.
/// </summary>
/// <param name="parameterNode">The parameter node to translate.</param>
/// <returns>Expression which evaluates to the result of the parameter.</returns>
protected virtual Expression TranslateParameter(ParameterQueryNode parameterNode)
{
ExceptionUtils.CheckArgumentNotNull(parameterNode, "parameterNode");
if (this.parameterNodeDefinitions.Count == 0)
{
throw new ODataException(Strings.QueryExpressionTranslator_ParameterNotDefinedInScope);
}
KeyValuePair<ParameterQueryNode, Expression> currentParameter = this.parameterNodeDefinitions.Peek();
if (!object.ReferenceEquals(currentParameter.Key, parameterNode))
{
throw new ODataException(Strings.QueryExpressionTranslator_ParameterNotDefinedInScope);
}
return currentParameter.Value;
}
/// <summary>
/// Translates an orderby node.
/// </summary>
/// <param name="orderByNode">The orderby node to translate.</param>
/// <returns>Expression which evaluates to the result after the order operation.</returns>
protected virtual Expression TranslateOrderBy(OrderByQueryNode orderByNode)
{
ExceptionUtils.CheckArgumentNotNull(orderByNode, "orderByNode");
ExceptionUtils.CheckArgumentNotNull(orderByNode.ItemType, "orderByNode.ItemType");
ExceptionUtils.CheckArgumentNotNull(orderByNode.Collection, "orderByNode.Collection");
ExceptionUtils.CheckArgumentNotNull(orderByNode.Collection.ItemType, "orderByNode.Collection.ItemType");
ExceptionUtils.CheckArgumentNotNull(orderByNode.Expression, "orderByNode.Expression");
ExceptionUtils.CheckArgumentNotNull(orderByNode.Parameter, "orderByNode.Parameter");
ExceptionUtils.CheckArgumentNotNull(orderByNode.Parameter.TypeReference, "orderByNode.Parameter.Type");
ParameterExpression parameter = Expression.Parameter(orderByNode.Parameter.TypeReference.GetInstanceType(this.model), "element");
Expression collectionExpression = this.Translate(orderByNode.Collection);
// TODO: If we should support OrderBy on IEnumerable, then we need to add support here
Type expectedCollectionType = typeof(IQueryable<>).MakeGenericType(parameter.Type);
if (!expectedCollectionType.IsAssignableFrom(collectionExpression.Type))
{
throw new ODataException(Strings.QueryExpressionTranslator_OrderByCollectionOfWrongType(collectionExpression.Type, expectedCollectionType));
}
this.parameterNodeDefinitions.Push(new KeyValuePair<ParameterQueryNode, Expression>(orderByNode.Parameter, parameter));
Expression body = this.Translate(orderByNode.Expression);
Debug.Assert(this.parameterNodeDefinitions.Peek().Key == orderByNode.Parameter, "The parameter definition stack was not balanced correctly.");
Debug.Assert(this.parameterNodeDefinitions.Peek().Value == parameter, "The parameter definition stack was not balanced correctly.");
this.parameterNodeDefinitions.Pop();
// If the collectionExpression is already another OrderBy or ThenBy we need to use a ThenBy
string methodName = orderByNode.Direction == OrderByDirection.Ascending ? OrderByMethodName : OrderByDescendingMethodName;
if (collectionExpression.NodeType == ExpressionType.Call)
{
MethodCallExpression collectionMethodCallExpression = (MethodCallExpression)collectionExpression;
if (collectionMethodCallExpression.Method.DeclaringType == typeof(Queryable) &&
collectionMethodCallExpression.Method.Name == OrderByMethodName ||
collectionMethodCallExpression.Method.Name == OrderByDescendingMethodName ||
collectionMethodCallExpression.Method.Name == ThenByMethodName ||
collectionMethodCallExpression.Method.Name == ThenByDescendingMethodName)
{
methodName = orderByNode.Direction == OrderByDirection.Ascending ? ThenByMethodName : ThenByDescendingMethodName;
}
}
return Expression.Call(
typeof(Queryable),
methodName,
new Type[] { parameter.Type, body.Type },
collectionExpression,
Expression.Quote(Expression.Lambda(body, parameter)));
}
/// <summary>
/// Translates a function call which returns a single value.
/// </summary>
/// <param name="functionCallNode">The function call node to translate.</param>
/// <returns>The translated expression which evaluates to the result of the function call.</returns>
protected virtual Expression TranslateSingleValueFunctionCall(SingleValueFunctionCallQueryNode functionCallNode)
{
ExceptionUtils.CheckArgumentNotNull(functionCallNode, "functionCallNode");
ExceptionUtils.CheckArgumentNotNull(functionCallNode.Name, "functionCallNode.Name");
// First check that all arguments are single nodes and build a list so that we can go over them more than once.
List<SingleValueQueryNode> argumentNodes = new List<SingleValueQueryNode>();
if (functionCallNode.Arguments != null)
{
foreach (QueryNode argumentNode in functionCallNode.Arguments)
{
SingleValueQueryNode singleValueArgumentNode = argumentNode as SingleValueQueryNode;
if (singleValueArgumentNode == null)
{
throw new ODataException(Strings.QueryExpressionTranslator_FunctionArgumentNotSingleValue(functionCallNode.Name));
}
argumentNodes.Add(singleValueArgumentNode);
}
}
// Find the exact matching signature
BuiltInFunctionSignature[] signatures;
if (!BuiltInFunctions.TryGetBuiltInFunction(functionCallNode.Name, out signatures))
{
throw new ODataException(Strings.QueryExpressionTranslator_UnknownFunction(functionCallNode.Name));
}
BuiltInFunctionSignature signature =
(BuiltInFunctionSignature)TypePromotionUtils.FindExactFunctionSignature(
signatures,
argumentNodes.Select(argumentNode => argumentNode.TypeReference).ToArray());
if (signature == null)
{
throw new ODataException(
Strings.QueryExpressionTranslator_NoApplicableFunctionFound(
functionCallNode.Name,
BuiltInFunctions.BuildFunctionSignatureListDescription(functionCallNode.Name, signatures)));
}
// Translate all arguments into expressions
Expression[] argumentExpressions = new Expression[argumentNodes.Count];
Expression[] nonNullableArgumentExpression = new Expression[argumentNodes.Count];
for (int argumentIndex = 0; argumentIndex < argumentNodes.Count; argumentIndex++)
{
SingleValueQueryNode argumentNode = argumentNodes[argumentIndex];
Expression argumentExpression = this.Translate(argumentNode);
argumentExpressions[argumentIndex] = argumentExpression;
// The below code relies on the fact that all built-in functions do not take nullable parameters (in CLR space)
// so if we do see a nullable as one of the parameters, we cast it down to non-nullable
// If null propagation is on, we may deal with the nullable aspect later on by injecting conditionals around the function call
// which handle the null, or if null propagation is of, passing the potential null is OK since the LINQ provider is expected
// to handle such cases then.
if (TypeUtils.IsNullableType(argumentExpression.Type))
{
nonNullableArgumentExpression[argumentIndex] = Expression.Convert(argumentExpression, TypeUtils.GetNonNullableType(argumentExpression.Type));
}
else
{
nonNullableArgumentExpression[argumentIndex] = argumentExpression;
}
}
// Build the function call expression (as if null propagation is not required and nulls can be handled anywhere)
Expression functionCallExpression = signature.BuildExpression(nonNullableArgumentExpression);
// Apply the null propagation
// Note that we inject null propagation on all arguments, which means we assume that if any of the arguments passed to function
// is null, the entire function is null. This is true for all the built-in functions for now. If this would be to change we would have to review
// the following code.
if (this.nullPropagationRequired)
{
for (int argumentIndex = 0; argumentIndex < argumentExpressions.Length; argumentIndex++)
{
Expression argumentExpression = argumentExpressions[argumentIndex];
// Don't null propagate the lambda parameter since it will never be null
// or if the argument expression can't be null due to its type.
if (argumentExpression == this.parameterNodeDefinitions.Peek().Value || !TypeUtils.TypeAllowsNull(argumentExpression.Type))
{
continue;
}
// Tiny optimization: remove the check on constants which are known not to be null.
// Otherwise every string literal propagates out, which is correct but unnecessarily messy.
ConstantExpression constantExpression = argumentExpression as ConstantExpression;
if (constantExpression != null && constantExpression.Value != null)
{
continue;
}
Expression test = Expression.Equal(argumentExpression, Expression.Constant(null, argumentExpression.Type));
Expression falseBranch = functionCallExpression;
if (!TypeUtils.TypeAllowsNull(falseBranch.Type))
{
falseBranch = Expression.Convert(falseBranch, typeof(Nullable<>).MakeGenericType(falseBranch.Type));
}
Expression trueBranch = Expression.Constant(null, falseBranch.Type);
functionCallExpression = Expression.Condition(test, trueBranch, falseBranch);
}
}
return functionCallExpression;
}
/// <summary>
/// Creates a greater then expression.
/// </summary>
/// <param name="left">The left operand expression.</param>
/// <param name="right">The right operand expression.</param>
/// <returns>The result expression.</returns>
private static Expression CreateGreaterThanExpression(Expression left, Expression right)
{
Debug.Assert(left != null, "left != null");
Debug.Assert(right != null, "right != null");
// TODO: Deal with open types
MethodInfo comparisonMethodInfo = GetComparisonMethodInfo(left.Type);
if (comparisonMethodInfo != null)
{
left = Expression.Call(null, comparisonMethodInfo, left, right);
right = Expression.Constant(0, typeof(int));
}
return Expression.GreaterThan(left, right);
}
/// <summary>
/// Creates a greater then or equal expression.
/// </summary>
/// <param name="left">The left operand expression.</param>
/// <param name="right">The right operand expression.</param>
/// <returns>The result expression.</returns>
private static Expression CreateGreaterThanOrEqualExpression(Expression left, Expression right)
{
Debug.Assert(left != null, "left != null");
Debug.Assert(right != null, "right != null");
// TODO: Deal with open types
MethodInfo comparisonMethodInfo = GetComparisonMethodInfo(left.Type);
if (comparisonMethodInfo != null)
{
left = Expression.Call(null, comparisonMethodInfo, left, right);
right = Expression.Constant(0, typeof(int));
}
return Expression.GreaterThanOrEqual(left, right);
}
/// <summary>
/// Creates a less then expression.
/// </summary>
/// <param name="left">The left operand expression.</param>
/// <param name="right">The right operand expression.</param>
/// <returns>The result expression.</returns>
private static Expression CreateLessThanExpression(Expression left, Expression right)
{
Debug.Assert(left != null, "left != null");
Debug.Assert(right != null, "right != null");
// TODO: Deal with open types
MethodInfo comparisonMethodInfo = GetComparisonMethodInfo(left.Type);
if (comparisonMethodInfo != null)
{
left = Expression.Call(null, comparisonMethodInfo, left, right);
right = Expression.Constant(0, typeof(int));
}
return Expression.LessThan(left, right);
}
/// <summary>
/// Creates a less then or equal expression.
/// </summary>
/// <param name="left">The left operand expression.</param>
/// <param name="right">The right operand expression.</param>
/// <returns>The result expression.</returns>
private static Expression CreateLessThanOrEqualExpression(Expression left, Expression right)
{
Debug.Assert(left != null, "left != null");
Debug.Assert(right != null, "right != null");
// TODO: Deal with open types
MethodInfo comparisonMethodInfo = GetComparisonMethodInfo(left.Type);
if (comparisonMethodInfo != null)
{
left = Expression.Call(null, comparisonMethodInfo, left, right);
right = Expression.Constant(0, typeof(int));
}
return Expression.LessThanOrEqual(left, right);
}
/// <summary>
/// Determine which method to use as the implementation for a comparison operator on a given type.
/// </summary>
/// <param name="type">The type the comparison is working on. This should be a primitive type.</param>
/// <returns>A method info for the method to use as the implementation method for the comparison operator.</returns>
private static MethodInfo GetComparisonMethodInfo(Type type)
{
Debug.Assert(type != null, "type != null");
if (type == typeof(string))
{
return DataServiceProviderMethods.StringCompareMethodInfo;
}
else if (type == typeof(bool))
{
return DataServiceProviderMethods.BoolCompareMethodInfo;
}
else if (type == typeof(bool?))
{
return DataServiceProviderMethods.BoolCompareMethodInfoNullable;
}
else if (type == typeof(Guid))
{
return DataServiceProviderMethods.GuidCompareMethodInfo;
}
else if (type == typeof(Guid?))
{
return DataServiceProviderMethods.GuidCompareMethodInfoNullable;
}
else
{
return null;
}
}
/// <summary>
/// After processing the operands of a binary operator, one or both of them may have changed their
/// type from a non-nullable type to a nullable type because of null propagation.
/// This method lifts the operands to the nullable type as required.
/// </summary>
/// <param name="left">The left operand of the binary operator.</param>
/// <param name="right">The right operand of the binary operator.</param>
private static void HandleBinaryOperatorNullPropagation(ref Expression left, ref Expression right)
{
Debug.Assert(left != null, "left != null");
Debug.Assert(right != null, "right != null");
if (left.Type != right.Type)
{
if (TypeUtils.IsNullableType(left.Type))
{
right = Expression.Convert(right, TypeUtils.GetNullableType(right.Type));
}
else if (TypeUtils.IsNullableType(right.Type))
{
left = Expression.Convert(left, TypeUtils.GetNullableType(left.Type));
}
else
{
Debug.Assert(!TypeUtils.IsNullableType(right.Type) && !TypeUtils.IsNullableType(left.Type), "None of the operands is expected to be nullable.");
}
}
}
/// <summary>
/// Creates an expression to access a property.
/// </summary>
/// <param name="source">The source expression which evaluates to the instance to access the property on.</param>
/// <param name="sourceStructuredType">The type of the source expression.</param>
/// <param name="property">The property to access.</param>
/// <returns>An expression which evaluates to the property value.</returns>
private Expression CreatePropertyAccessExpression(Expression source, IEdmStructuredTypeReference sourceStructuredType, IEdmProperty property)
{
Debug.Assert(source != null, "source != null");
Debug.Assert(sourceStructuredType != null, "sourceStructuredType != null");
Debug.Assert(property != null, "property != null");
Debug.Assert(TypeUtils.AreTypesEquivalent(source.Type, sourceStructuredType.GetInstanceType(this.model)), "source.Type != sourceStructuredType.GetInstanceType()");
#if DEBUG
Debug.Assert(sourceStructuredType.ContainsProperty(property), "property is not declared on sourceStructuredType");
#endif
// TODO: Deal with null propagation???
if (property.GetCanReflectOnInstanceTypeProperty(this.model))
{
return Expression.Property(source, sourceStructuredType.GetPropertyInfo(property, this.model));
}
else
{
// TODO: Support for untyped and open properties
throw new NotImplementedException();
}
}
}
}
| |
using System;
using System.Xml.Xsl;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Text;
using System.CodeDom.Compiler;
namespace Hydra.Framework.XmlSerialization.Exslt
{
//
// **********************************************************************
/// <summary>
/// Enumeration used to indicate an EXSLT function namespace.
/// </summary>
// **********************************************************************
//
[Flags]
public enum ExsltFunctionNamespace
{
//
// **********************************************************************
/// <summary>Nothing</summary>
// **********************************************************************
//
None = 0,
/// <summary>Dates and Times module</summary>
DatesAndTimes = 1,
//
// **********************************************************************
/// <summary>Math module</summary>
// **********************************************************************
//
Math = 2,
/// <summary>RegExp module</summary>
RegularExpressions = 4,
//
// **********************************************************************
/// <summary>Sets module</summary>
// **********************************************************************
//
Sets = 8,
/// <summary>Strings module</summary>
Strings = 16,
//
// **********************************************************************
/// <summary>GotDotNet Dates and Times module</summary>
// **********************************************************************
//
GDNDatesAndTimes = 32,
/// <summary>GotDotNet Sets module</summary>
GDNSets = 64,
//
// **********************************************************************
/// <summary>GotDotNet Math module</summary>
// **********************************************************************
//
GDNMath = 128,
/// <summary>GotDotNet RegExp module</summary>
GDNRegularExpressions = 256,
//
// **********************************************************************
/// <summary>GotDotNet Strings module</summary>
// **********************************************************************
//
GDNStrings = 512,
/// <summary>Random module</summary>
Random = 1024,
//
// **********************************************************************
/// <summary>GotDotNet Dynamic module</summary>
// **********************************************************************
//
GDNDynamic = 2056,
/// <summary>All EXSLT modules</summary>
AllExslt = DatesAndTimes | Math | Random | RegularExpressions | Sets | Strings,
//
// **********************************************************************
/// <summary>All modules</summary>
// **********************************************************************
//
All = DatesAndTimes | Math | Random | RegularExpressions | Sets | Strings |
GDNDatesAndTimes | GDNSets | GDNMath | GDNRegularExpressions | GDNStrings | GDNDynamic
}
//
// **********************************************************************
/// <summary>
/// Transforms XML data using an XSLT stylesheet. Supports a number of EXSLT as
/// defined at http://www.exslt.org
/// </summary>
/// <remarks>
/// XslCompiledTransform supports the XSLT 1.0 syntax. The XSLT stylesheet must use the
/// namespace http://www.w3.org/1999/XSL/Transform. Additional arguments can also be
/// added to the stylesheet using the XsltArgumentList class.
/// This class contains input parameters for the stylesheet and extension objects which can be called from the stylesheet.
/// This class also recognizes functions from the following namespaces:<br/>
/// * http://exslt.org/common<br/>
/// * http://exslt.org/dates-and-times<br/>
/// * http://exslt.org/math<br/>
/// * http://exslt.org/random<br/>
/// * http://exslt.org/regular-expressions<br/>
/// * http://exslt.org/sets<br/>
/// * http://exslt.org/strings<br/>
/// * http://gotdotnet.com/exslt/dates-and-times<br/>
/// * http://gotdotnet.com/exslt/math<br/>
/// * http://gotdotnet.com/exslt/regular-expressions<br/>
/// * http://gotdotnet.com/exslt/sets<br/>
/// * http://gotdotnet.com/exslt/strings<br/>
/// * http://gotdotnet.com/exslt/dynamic<br/>
/// </remarks>
// **********************************************************************
//
[Obsolete("This class has been deprecated. Please use Hydra.Framework.XmlSerialization.Common.Xsl.MvpXslTransform instead.")]
public class ExsltTransform
{
#region Private Fields and Properties
//
// **********************************************************************
/// <summary>
/// Sync object.
/// </summary>
// **********************************************************************
//
private object sync = new object();
//
// **********************************************************************
/// <summary>
/// The XslTransform object wrapped by this class.
/// </summary>
// **********************************************************************
//
private XslCompiledTransform xslTransform;
//
// **********************************************************************
/// <summary>
/// Bitwise enumeration used to specify which EXSLT functions should be accessible to
/// the ExsltTransform object. The default value is ExsltFunctionNamespace.All
/// </summary>
// **********************************************************************
//
private ExsltFunctionNamespace _supportedFunctions = ExsltFunctionNamespace.All;
//
// **********************************************************************
/// <summary>
/// Extension object which implements the functions in the http://exslt.org/math namespace
/// </summary>
// **********************************************************************
//
private ExsltMath exsltMath = new ExsltMath();
//
// **********************************************************************
/// <summary>
/// Extension object which implements the functions in the http://exslt.org/random namespace
/// </summary>
// **********************************************************************
//
private ExsltRandom exsltRandom = new ExsltRandom();
//
// **********************************************************************
/// <summary>
/// Extension object which implements the functions in the http://exslt.org/dates-and-times namespace
/// </summary>
// **********************************************************************
//
private ExsltDatesAndTimes exsltDatesAndTimes = new ExsltDatesAndTimes();
//
// **********************************************************************
/// <summary>
/// Extension object which implements the functions in the http://exslt.org/regular-expressions namespace
/// </summary>
// **********************************************************************
//
private ExsltRegularExpressions exsltRegularExpressions = new ExsltRegularExpressions();
//
// **********************************************************************
/// <summary>
/// Extension object which implements the functions in the http://exslt.org/strings namespace
/// </summary>
// **********************************************************************
//
private ExsltStrings exsltStrings = new ExsltStrings();
//
// **********************************************************************
/// <summary>
/// Extension object which implements the functions in the http://exslt.org/sets namespace
/// </summary>
// **********************************************************************
//
private ExsltSets exsltSets = new ExsltSets();
//
// **********************************************************************
/// <summary>
/// Extension object which implements the functions in the http://gotdotnet.com/exslt/dates-and-times namespace
/// </summary>
// **********************************************************************
//
private GDNDatesAndTimes gdnDatesAndTimes = new GDNDatesAndTimes();
//
// **********************************************************************
/// <summary>
/// Extension object which implements the functions in the http://gotdotnet.com/exslt/regular-expressions namespace
/// </summary>
// **********************************************************************
//
private GDNRegularExpressions gdnRegularExpressions = new GDNRegularExpressions();
//
// **********************************************************************
/// <summary>
/// Extension object which implements the functions in the http://gotdotnet.com/exslt/math namespace
/// </summary>
// **********************************************************************
//
private GDNMath gdnMath = new GDNMath();
//
// **********************************************************************
/// <summary>
/// Extension object which implements the functions in the http://gotdotnet.com/exslt/sets namespace
/// </summary>
// **********************************************************************
//
private GDNSets gdnSets = new GDNSets();
//
// **********************************************************************
/// <summary>
/// Extension object which implements the functions in the http://gotdotnet.com/exslt/strings namespace
/// </summary>
// **********************************************************************
//
private GDNStrings gdnStrings = new GDNStrings();
//
// **********************************************************************
/// <summary>
/// Extension object which implements the functions in the http://gotdotnet.com/exslt/dynamic namespace
/// </summary>
// **********************************************************************
//
private GDNDynamic gdnDynamic = new GDNDynamic();
//
// **********************************************************************
/// <summary>
/// Boolean flag used to specify whether multiple output is supported.
/// </summary>
// **********************************************************************
//
private bool _multiOutput = false;
#endregion
#region Public Fields and Properties
//
// **********************************************************************
/// <summary>
/// Bitwise enumeration used to specify which EXSLT functions should be accessible to
/// the ExsltTransform object. The default value is ExsltFunctionNamespace.All
/// </summary>
// **********************************************************************
//
public ExsltFunctionNamespace SupportedFunctions
{
set
{
if (Enum.IsDefined(typeof(ExsltFunctionNamespace), value))
this._supportedFunctions = value;
}
get { return this._supportedFunctions; }
}
//
// **********************************************************************
/// <summary>
/// Boolean flag used to specify whether multiple output (via exsl:document) is
/// supported.
/// Note: This property is ignored (hence multiple output is not supported) when
/// transformation is done to XmlReader or XmlWriter (use overloaded method,
/// which transforms to MultiXmlTextWriter instead).
/// Note: Because of some restrictions and slight overhead this feature is
/// disabled by default. If you need multiple output support, set this property to
/// true before the Transform() call.
/// </summary>
// **********************************************************************
//
public bool MultiOutput
{
get { return _multiOutput; }
set { _multiOutput = value; }
}
//
// **********************************************************************
/// <summary>
/// Gets an <see cref="XmlWriterSettings"/> object that contains the output
/// information derived from the xsl:output element of the style sheet.
/// </summary>
// **********************************************************************
//
public XmlWriterSettings OutputSettings
{
get { return xslTransform.OutputSettings; }
}
//
// **********************************************************************
/// <summary>
/// Gets the TempFileCollection that contains the temporary files generated
/// on disk after a successful call to the Load method.
/// </summary>
// **********************************************************************
//
public TempFileCollection TemporaryFiles
{
get { return xslTransform.TemporaryFiles; }
}
#endregion
#region Constructors
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the ExsltTransform class.
/// </summary>
// **********************************************************************
//
public ExsltTransform()
{
this.xslTransform = new XslCompiledTransform();
}
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the ExsltTransform
/// class with the specified debug setting.
/// </summary>
// **********************************************************************
//
public ExsltTransform(bool debug)
{
this.xslTransform = new XslCompiledTransform(debug);
}
#endregion
#region Load() method Overloads
//
// **********************************************************************
/// <summary>
/// Loads and compiles the style sheet contained in the <see cref="IXPathNavigable"/> object.
/// See also <see cref="XslCompiledTransform.Load(IXPathNavigable)"/>.
/// </summary>
/// <param name="stylesheet">An object implementing the <see cref="IXPathNavigable"/> interface.
/// In the Microsoft .NET Framework, this can be either an <see cref="XmlNode"/> (typically an <see cref="XmlDocument"/>),
/// or an <see cref="XPathDocument"/> containing the style sheet.</param>
// **********************************************************************
//
public void Load(IXPathNavigable stylesheet) { this.xslTransform.Load(stylesheet); }
//
// **********************************************************************
/// <summary>
/// Loads and compiles the style sheet located at the specified URI.
/// See also <see cref="XslCompiledTransform.Load(String)"/>.
/// </summary>
/// <param name="stylesheetUri">The URI of the style sheet.</param>
// **********************************************************************
//
public void Load(string stylesheetUri) { this.xslTransform.Load(stylesheetUri); }
//
// **********************************************************************
/// <summary>
/// Compiles the style sheet contained in the <see cref="XmlReader"/>.
/// See also <see cref="XslCompiledTransform.Load(XmlReader)"/>.
/// </summary>
/// <param name="stylesheet">An <see cref="XmlReader"/> containing the style sheet.</param>
// **********************************************************************
//
public void Load(XmlReader stylesheet) { this.xslTransform.Load(stylesheet); }
//
// **********************************************************************
/// <summary>
/// Compiles the XSLT style sheet contained in the <see cref="IXPathNavigable"/>.
/// The <see cref="XmlResolver"/> resolves any XSLT <c>import</c> or <c>include</c> elements and the
/// XSLT settings determine the permissions for the style sheet.
/// See also <see cref="XslCompiledTransform.Load(IXPathNavigable, XsltSettings, XmlResolver)"/>.
/// </summary>
/// <param name="stylesheet">An object implementing the <see cref="IXPathNavigable"/> interface.
/// In the Microsoft .NET Framework, this can be either an <see cref="XmlNode"/> (typically an <see cref="XmlDocument"/>),
/// or an <see cref="XPathDocument"/> containing the style sheet.</param>
/// <param name="settings">The <see cref="XsltSettings"/> to apply to the style sheet.
/// If this is a null reference (Nothing in Visual Basic), the <see cref="XsltSettings.Default"/> setting is applied.</param>
/// <param name="stylesheetResolver">The <see cref="XmlResolver"/> used to resolve any
/// style sheets referenced in XSLT <c>import</c> and <c>include</c> elements. If this is a
/// null reference (Nothing in Visual Basic), external resources are not resolved.</param>
// **********************************************************************
//
public void Load(IXPathNavigable stylesheet, XsltSettings settings, XmlResolver stylesheetResolver)
{
this.xslTransform.Load(stylesheet, settings, stylesheetResolver);
}
//
// **********************************************************************
/// <summary>
/// Loads and compiles the XSLT style sheet specified by the URI.
/// The <see cref="XmlResolver"/> resolves any XSLT <c>import</c> or <c>include</c> elements and the
/// XSLT settings determine the permissions for the style sheet.
/// See also <see cref="XslCompiledTransform.Load(string, XsltSettings, XmlResolver)"/>.
/// </summary>
/// <param name="stylesheetUri">The URI of the style sheet.</param>
/// <param name="settings">The <see cref="XsltSettings"/> to apply to the style sheet.
/// If this is a null reference (Nothing in Visual Basic), the <see cref="XsltSettings.Default"/> setting is applied.</param>
/// <param name="stylesheetResolver">The <see cref="XmlResolver"/> used to resolve any
/// style sheets referenced in XSLT <c>import</c> and <c>include</c> elements. If this is a
/// null reference (Nothing in Visual Basic), external resources are not resolved.</param>
// **********************************************************************
//
public void Load(string stylesheetUri, XsltSettings settings, XmlResolver stylesheetResolver)
{
this.xslTransform.Load(stylesheetUri, settings, stylesheetResolver);
}
//
// **********************************************************************
/// <summary>
/// Compiles the XSLT style sheet contained in the <see cref="XmlReader"/>.
/// The <see cref="XmlResolver"/> resolves any XSLT <c>import</c> or <c>include</c> elements and the
/// XSLT settings determine the permissions for the style sheet.
/// See also <see cref="XslCompiledTransform.Load(XmlReader, XsltSettings, XmlResolver)"/>.
/// </summary>
/// <param name="stylesheet">The <see cref="XmlReader"/> containing the style sheet.</param>
/// <param name="settings">The <see cref="XsltSettings"/> to apply to the style sheet.
/// If this is a null reference (Nothing in Visual Basic), the <see cref="XsltSettings.Default"/> setting is applied.</param>
/// <param name="stylesheetResolver">The <see cref="XmlResolver"/> used to resolve any
/// style sheets referenced in XSLT <c>import</c> and <c>include</c> elements. If this is a
/// null reference (Nothing in Visual Basic), external resources are not resolved.</param>
// **********************************************************************
//
public void Load(XmlReader stylesheet, XsltSettings settings, XmlResolver stylesheetResolver)
{
this.xslTransform.Load(stylesheet, settings, stylesheetResolver);
}
#endregion
#region Transform() method Overloads
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the
/// IXPathNavigable object and outputs the results to an XmlWriter.
/// </summary>
// **********************************************************************
//
public void Transform(IXPathNavigable input, XmlWriter results)
{
this.xslTransform.Transform(input, AddExsltExtensionObjects(null), results);
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the URI
/// and outputs the results to a file.
/// </summary>
// **********************************************************************
//
public void Transform(string inputUri, string resultsFile)
{
//
// Use using so that the file is not held open after the call
//
using (FileStream outStream = File.OpenWrite(resultsFile))
{
if (_multiOutput)
{
this.xslTransform.Transform(new XPathDocument(inputUri),
this.AddExsltExtensionObjects(null),
new MultiXmlTextWriter(outStream, this.OutputSettings.Encoding));
}
else
{
this.xslTransform.Transform(new XPathDocument(inputUri),
this.AddExsltExtensionObjects(null),
outStream);
}
}
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the URI
/// and outputs the results to an XmlWriter.
/// </summary>
// **********************************************************************
//
public void Transform(string inputUri, XmlWriter results)
{
this.xslTransform.Transform(inputUri,
this.AddExsltExtensionObjects(null), results);
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the
/// XmlReader object and outputs the results to an XmlWriter.
/// </summary>
// **********************************************************************
//
public void Transform(XmlReader input, XmlWriter results)
{
this.xslTransform.Transform(input,
this.AddExsltExtensionObjects(null), results);
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the
/// IXPathNavigable object and outputs the results to a stream.
/// The XsltArgumentList provides additional runtime arguments.
/// </summary>
// **********************************************************************
//
public void Transform(IXPathNavigable input, XsltArgumentList arguments, Stream results)
{
if (_multiOutput)
{
this.xslTransform.Transform(input,
this.AddExsltExtensionObjects(arguments),
new MultiXmlTextWriter(results, this.OutputSettings.Encoding));
}
else
{
this.xslTransform.Transform(input,
this.AddExsltExtensionObjects(arguments), results);
}
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the
/// IXPathNavigable object and outputs the results to an TextWriter.
/// The XsltArgumentList provides additional run-time arguments.
/// </summary>
// **********************************************************************
//
public void Transform(IXPathNavigable input, XsltArgumentList arguments, TextWriter results)
{
if (_multiOutput)
{
this.xslTransform.Transform(input,
this.AddExsltExtensionObjects(arguments),
new MultiXmlTextWriter(results));
}
else
{
this.xslTransform.Transform(input,
this.AddExsltExtensionObjects(arguments), results);
}
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the
/// IXPathNavigable object and outputs the results to an XmlWriter.
/// The XsltArgumentList provides additional run-time arguments.
/// </summary>
// **********************************************************************
//
public void Transform(IXPathNavigable input, XsltArgumentList arguments, XmlWriter results)
{
this.xslTransform.Transform(input,
this.AddExsltExtensionObjects(arguments), results);
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the URI
/// and outputs the results to stream.
/// The XsltArgumentList provides additional run-time arguments.
/// </summary>
// **********************************************************************
//
public void Transform(string inputUri, XsltArgumentList arguments, Stream results)
{
if (_multiOutput)
{
this.xslTransform.Transform(inputUri,
this.AddExsltExtensionObjects(arguments),
new MultiXmlTextWriter(results, this.OutputSettings.Encoding));
}
else
{
this.xslTransform.Transform(inputUri,
this.AddExsltExtensionObjects(arguments), results);
}
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the URI and
/// outputs the results to a TextWriter.
/// </summary>
// **********************************************************************
//
public void Transform(string inputUri, XsltArgumentList arguments, TextWriter results)
{
if (_multiOutput)
{
this.xslTransform.Transform(inputUri,
this.AddExsltExtensionObjects(arguments),
new MultiXmlTextWriter(results));
}
else
{
this.xslTransform.Transform(inputUri,
this.AddExsltExtensionObjects(arguments), results);
}
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the URI
/// and outputs the results to an XmlWriter.
/// The XsltArgumentList provides additional run-time arguments.
/// </summary>
// **********************************************************************
//
public void Transform(string inputUri, XsltArgumentList arguments, XmlWriter results)
{
this.xslTransform.Transform(inputUri,
this.AddExsltExtensionObjects(arguments), results);
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the XmlReader
/// object and outputs the results to a stream.
/// The XsltArgumentList provides additional run-time arguments.
/// </summary>
// **********************************************************************
//
public void Transform(XmlReader input, XsltArgumentList arguments, Stream results)
{
if (_multiOutput)
{
this.xslTransform.Transform(input,
this.AddExsltExtensionObjects(arguments),
new MultiXmlTextWriter(results, this.OutputSettings.Encoding));
}
else
{
this.xslTransform.Transform(input,
this.AddExsltExtensionObjects(arguments), results);
}
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the XmlReader
/// object and outputs the results to a TextWriter.
/// The XsltArgumentList provides additional run-time arguments.
/// </summary>
// **********************************************************************
//
public void Transform(XmlReader input, XsltArgumentList arguments, TextWriter results)
{
if (_multiOutput)
{
this.xslTransform.Transform(input,
this.AddExsltExtensionObjects(arguments),
new MultiXmlTextWriter(results));
}
else
{
this.xslTransform.Transform(input,
this.AddExsltExtensionObjects(arguments), results);
}
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the XmlReader
/// object and outputs the results to an XmlWriter.
/// The XsltArgumentList provides additional run-time arguments.
/// </summary>
// **********************************************************************
//
public void Transform(XmlReader input, XsltArgumentList arguments, XmlWriter results)
{
this.xslTransform.Transform(input,
this.AddExsltExtensionObjects(arguments), results);
}
//
// **********************************************************************
/// <summary>
/// Executes the transform using the input document specified by the XmlReader
/// object and outputs the results to an XmlWriter.
/// The XsltArgumentList provides additional run-time arguments and the
/// XmlResolver resolves the XSLT document() function.
/// </summary>
// **********************************************************************
//
public void Transform(XmlReader input, XsltArgumentList arguments,
XmlWriter results, XmlResolver documentResolver)
{
this.xslTransform.Transform(input,
this.AddExsltExtensionObjects(arguments), results, documentResolver);
}
#endregion
#region Private Methods
//
// **********************************************************************
/// <summary>
/// Adds the objects that implement the EXSLT extensions to the provided argument
/// list. The extension objects added depend on the value of the SupportedFunctions
/// property.
/// </summary>
/// <param name="list">The argument list</param>
/// <returns>An XsltArgumentList containing the contents of the list passed in
/// and objects that implement the EXSLT. </returns>
/// <remarks>If null is passed in then a new XsltArgumentList is constructed. </remarks>
// **********************************************************************
//
private XsltArgumentList AddExsltExtensionObjects(XsltArgumentList list)
{
if (list == null)
{
list = new XsltArgumentList();
}
lock (sync)
{
//remove all our extension objects in case the XSLT argument list is being reused
list.RemoveExtensionObject(ExsltNamespaces.Math);
list.RemoveExtensionObject(ExsltNamespaces.Random);
list.RemoveExtensionObject(ExsltNamespaces.DatesAndTimes);
list.RemoveExtensionObject(ExsltNamespaces.RegularExpressions);
list.RemoveExtensionObject(ExsltNamespaces.Strings);
list.RemoveExtensionObject(ExsltNamespaces.Sets);
list.RemoveExtensionObject(ExsltNamespaces.GDNDatesAndTimes);
list.RemoveExtensionObject(ExsltNamespaces.GDNMath);
list.RemoveExtensionObject(ExsltNamespaces.GDNRegularExpressions);
list.RemoveExtensionObject(ExsltNamespaces.GDNSets);
list.RemoveExtensionObject(ExsltNamespaces.GDNStrings);
list.RemoveExtensionObject(ExsltNamespaces.GDNDynamic);
//add extension objects as specified by SupportedFunctions
if ((this.SupportedFunctions & ExsltFunctionNamespace.Math) > 0)
{
list.AddExtensionObject(ExsltNamespaces.Math, this.exsltMath);
}
if ((this.SupportedFunctions & ExsltFunctionNamespace.Random) > 0)
{
list.AddExtensionObject(ExsltNamespaces.Random, this.exsltRandom);
}
if ((this.SupportedFunctions & ExsltFunctionNamespace.DatesAndTimes) > 0)
{
list.AddExtensionObject(ExsltNamespaces.DatesAndTimes, this.exsltDatesAndTimes);
}
if ((this.SupportedFunctions & ExsltFunctionNamespace.RegularExpressions) > 0)
{
list.AddExtensionObject(ExsltNamespaces.RegularExpressions, this.exsltRegularExpressions);
}
if ((this.SupportedFunctions & ExsltFunctionNamespace.Strings) > 0)
{
list.AddExtensionObject(ExsltNamespaces.Strings, this.exsltStrings);
}
if ((this.SupportedFunctions & ExsltFunctionNamespace.Sets) > 0)
{
list.AddExtensionObject(ExsltNamespaces.Sets, this.exsltSets);
}
if ((this.SupportedFunctions & ExsltFunctionNamespace.GDNDatesAndTimes) > 0)
{
list.AddExtensionObject(ExsltNamespaces.GDNDatesAndTimes, this.gdnDatesAndTimes);
}
if ((this.SupportedFunctions & ExsltFunctionNamespace.GDNMath) > 0)
{
list.AddExtensionObject(ExsltNamespaces.GDNMath, this.gdnMath);
}
if ((this.SupportedFunctions & ExsltFunctionNamespace.GDNRegularExpressions) > 0)
{
list.AddExtensionObject(ExsltNamespaces.GDNRegularExpressions, this.gdnRegularExpressions);
}
if ((this.SupportedFunctions & ExsltFunctionNamespace.GDNSets) > 0)
{
list.AddExtensionObject(ExsltNamespaces.GDNSets, this.gdnSets);
}
if ((this.SupportedFunctions & ExsltFunctionNamespace.GDNStrings) > 0)
{
list.AddExtensionObject(ExsltNamespaces.GDNStrings, this.gdnStrings);
}
if ((this.SupportedFunctions & ExsltFunctionNamespace.GDNDynamic) > 0)
{
list.AddExtensionObject(ExsltNamespaces.GDNDynamic, this.gdnDynamic);
}
}
return list;
}
#endregion
}
}
| |
using CapnpNet.Rpc;
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace CapnpNet
{
// consider struct Message<TRoot> wrapper?
public partial class Message : IDisposable
{
private ISegmentFactory _segmentFactory;
// go back to List? pooled arrays?
private Segment _firstSegment, _lastSegment;
public Message()
{
}
public ISegmentFactory SegmentFactory => _segmentFactory;
public SegmentList Segments => new SegmentList(_firstSegment);
public long WordsToLive { get; set; }
public int TotalAllocated
{
get
{
int sum = 0;
foreach (var seg in this.Segments)
{
sum += seg.AllocationIndex;
}
return sum;
}
}
public int TotalCapcity
{
get
{
int sum = 0;
foreach (var seg in this.Segments)
{
sum += seg.WordCapacity;
}
return sum;
}
}
public Struct Root
{
get
{
// TOOD: follow far pointer?
var rootPointer = Unsafe.As<ulong, Pointer>(ref _firstSegment.GetWord(0));
return new Struct(_firstSegment, 1, (StructPointer)rootPointer);
}
set
{
new Struct(_firstSegment, 0, 0, 1).WritePointer(0, value);
}
}
internal RefList<CapEntry> LocalCaps { get; set; }
public T GetRoot<T>() where T : struct, IStruct => this.Root.As<T>();
public void SetRoot<T>(T @struct) where T : struct, IStruct => this.Root = @struct.Struct;
public int CalculateSize() => this.Root.CalculateSize();
public Message Init(ISegmentFactory segmentFactory, bool allocateRootPointer)
{
Check.NotNull(segmentFactory, nameof(segmentFactory));
_segmentFactory = segmentFactory;
this.WordsToLive = 64 * 1024 * 1024 / 8; // 64MB
if (allocateRootPointer) this.Allocate(1); // root pointer
return this;
}
public Struct Allocate(ushort dataWords, ushort pointerWords)
{
this.Allocate(dataWords + pointerWords, out int offset, out Segment segment);
return new Struct(segment, offset, dataWords, pointerWords);
}
public void Allocate(int words, out int offset, out Segment segment)
{
if (_lastSegment != null && _lastSegment.TryAllocate(words, out offset))
{
segment = _lastSegment;
return;
}
segment = _segmentFactory.TryCreatePrompt(this, words);
if (segment == null)
{
// TODO: different exception type
throw new InvalidOperationException("Temporary allocation failure");
}
if (segment.TryAllocate(words, out offset) == false)
{
throw new InvalidOperationException("Newly created segment was not big enough");
}
}
public AllocationContext Allocate(int words)
{
this.Allocate(words, out int offset, out var segment);
return new AllocationContext(segment, offset, words);
}
public Pointer GetCapPointer(ICapability cap)
{
uint index;
for (index = 0; index < this.LocalCaps.Count; index++)
{
ref CapEntry entry = ref this.LocalCaps[index];
if (entry.Capability == cap)
{
entry.RefCount++;
return new OtherPointer
{
Type = PointerType.Other,
OtherPointerType = OtherPointerType.Capability,
CapabilityId = index
};
}
}
this.LocalCaps.Add(out index) = new CapEntry
{
Capability = cap,
RefCount = 1
};
return new OtherPointer
{
Type = PointerType.Other,
OtherPointerType = OtherPointerType.Capability,
CapabilityId = index
};
}
public void DecrementCapRefCount(uint capId)
{
// TODO: safety checks
this.LocalCaps[capId].RefCount--;
}
public async Task CreateAndAddSegmentAsync(
int? sizeHint,
CancellationToken cancellationToken = default)
{
await _segmentFactory.CreateAsync(this, sizeHint, cancellationToken);
}
public void AddSegment(Segment segment)
{
var seg = _firstSegment;
while (seg != null)
{
if (seg == segment) throw new ArgumentException("Segment already added");
seg = seg.Next;
}
var prevSegment = _lastSegment;
_lastSegment = segment;
segment.SegmentIndex = (prevSegment?.SegmentIndex + 1) ?? 0;
#if TRACE && UNSAFE
unsafe { Trace.WriteLine($"Adding segment {(long)Unsafe.AsPointer(ref segment.GetByte(0)):X8}"); }
#endif
if (prevSegment == null)
{
_firstSegment = _lastSegment;
}
else
{
prevSegment.Next = _lastSegment;
}
}
public void PreAllocate(int words)
{
if (_lastSegment == null || _lastSegment.WordCapacity - _lastSegment.AllocationIndex < words)
{
var segment = _segmentFactory.TryCreatePrompt(this, words);
if (segment == null) throw new InvalidOperationException("Temporary allocation failure"); // TODO: different type
}
}
public async Task PreAllocateAsync(int words)
{
if (_lastSegment == null || _lastSegment.WordCapacity - _lastSegment.AllocationIndex < words)
{
await _segmentFactory.CreateAsync(this, words);
}
}
public long CheckTraversalLimit(Pointer pointer)
{
long words = 1;
if (pointer.Type == PointerType.Struct)
{
words = Math.Min(1, pointer.DataWords + pointer.PointerWords);
}
else if (pointer.Type == PointerType.List)
{
switch (pointer.ElementSize)
{
case ElementSize.OneBit:
words = (pointer.ElementCount + 63) / 64;
break;
case ElementSize.OneByte:
words = (pointer.ElementCount + 7) / 8;
break;
case ElementSize.TwoBytes:
words = (pointer.ElementCount + 3) / 4;
break;
case ElementSize.FourBytes:
words = (pointer.ElementCount + 1) / 2;
break;
case ElementSize.EightBytesNonPointer:
case ElementSize.EightBytesPointer:
case ElementSize.Composite:
words = pointer.ElementCount;
break;
}
}
this.WordsToLive -= words;
if (this.WordsToLive < 0) // TODO: option to disable exception
{
throw new InvalidOperationException("Traversal limit exceeded");
}
return words;
}
public bool Traverse(ref Pointer pointer, ref Segment segment, out int baseOffset)
{
if (pointer.Type != PointerType.Far)
{
this.CheckTraversalLimit(pointer);
baseOffset = default;
return false;
}
var farPointer = (FarPointer)pointer;
segment = this.Segments[(int)farPointer.TargetSegmentId];
var landingPadOffset = (int)farPointer.LandingPadOffset;
var landingPadPointer = Unsafe.As<ulong, Pointer>(ref segment.GetWord(landingPadOffset));
if (pointer.IsDoubleFar)
{
// the pointer is in another castle
var padFarPointer = (FarPointer)landingPadPointer;
Debug.Assert(padFarPointer.IsDoubleFar == false);
pointer = Unsafe.As<ulong, Pointer>(ref segment.GetWord(landingPadOffset));
segment = this.Segments[(int)padFarPointer.TargetSegmentId];
baseOffset = (int)padFarPointer.LandingPadOffset;
Debug.Assert(pointer.WordOffset == 0);
}
else
{
baseOffset = landingPadOffset + 1;
pointer = landingPadPointer;
}
this.CheckTraversalLimit(pointer);
return true;
}
public void Dispose()
{
var segment = _firstSegment;
while (segment != null)
{
var nextSegment = segment.Next;
segment.Dispose();
segment = nextSegment;
}
_firstSegment = null;
_lastSegment = null;
_segmentFactory = null;
this.LocalCaps = null;
}
internal struct CapEntry
{
public ICapability Capability;
public int RefCount;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Forms.dll Alpha
// Description: The basic module for DotSpatial.Forms version 6.0
// ********************************************************************************************************
//
// The Original Code is from DotSpatial.Forms.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 5/18/2009 9:06:46 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// Initial dialog for selecting a predefined line symbol
/// </summary>
public class LineSymbolDialog : Form
{
#region Events
/// <summary>
/// Fires an event indicating that changes should be applied.
/// </summary>
public event EventHandler ChangesApplied;
#endregion
#region Private Variables
private List<string> _categories;
private ILineSymbolizer _original;
private ILineSymbolizer _symbolizer;
private ILineSymbolizer _symbolizer2;
private Button btnSymbolDetails;
private ComboBox cmbCategories;
/// <summary>
/// Required designer variable.
/// </summary>
private IContainer components = null;
private DialogButtons dialogButtons1;
private Label lblPredefinedSymbol;
private Label lblSymbolPreview;
private Label lblSymbologyType;
private PredefinedLineSymbolControl predefinedLineSymbolControl1;
private SymbolPreview symbolPreview1;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of DetailedLineSymbolDialog
/// </summary>
public LineSymbolDialog()
{
InitializeComponent();
_original = new LineSymbolizer();
_symbolizer = new LineSymbolizer();
_symbolizer2 = new LineSymbolizer();
Configure();
}
/// <summary>
/// Creates a new Detailed Line Symbol Dialog
/// </summary>
/// <param name="symbolizer"></param>
public LineSymbolDialog(ILineSymbolizer symbolizer)
{
InitializeComponent();
_original = symbolizer;
_symbolizer = symbolizer.Copy();
Configure();
}
private void Configure()
{
dialogButtons1.OkClicked += btnOK_Click;
dialogButtons1.CancelClicked += btnCancel_Click;
dialogButtons1.ApplyClicked += btnApply_Click;
LoadDefaultSymbols();
UpdatePreview();
predefinedLineSymbolControl1.IsSelected = false;
predefinedLineSymbolControl1.SymbolSelected += predefinedSymbolControl_SymbolSelected;
predefinedLineSymbolControl1.DoubleClick += predefinedLineSymbolControl1_DoubleClick;
symbolPreview1.DoubleClick += SymbolPreview_DoubleClick;
}
#endregion
#region Windows Form Designer generated code
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LineSymbolDialog));
this.lblSymbologyType = new System.Windows.Forms.Label();
this.lblPredefinedSymbol = new System.Windows.Forms.Label();
this.lblSymbolPreview = new System.Windows.Forms.Label();
this.btnSymbolDetails = new System.Windows.Forms.Button();
this.cmbCategories = new System.Windows.Forms.ComboBox();
this.predefinedLineSymbolControl1 = new DotSpatial.Symbology.Forms.PredefinedLineSymbolControl();
this.symbolPreview1 = new DotSpatial.Symbology.Forms.SymbolPreview();
this.dialogButtons1 = new DotSpatial.Symbology.Forms.DialogButtons();
this.SuspendLayout();
//
// lblSymbologyType
//
resources.ApplyResources(this.lblSymbologyType, "lblSymbologyType");
this.lblSymbologyType.Name = "lblSymbologyType";
//
// lblPredefinedSymbol
//
resources.ApplyResources(this.lblPredefinedSymbol, "lblPredefinedSymbol");
this.lblPredefinedSymbol.Name = "lblPredefinedSymbol";
//
// lblSymbolPreview
//
resources.ApplyResources(this.lblSymbolPreview, "lblSymbolPreview");
this.lblSymbolPreview.Name = "lblSymbolPreview";
//
// btnSymbolDetails
//
resources.ApplyResources(this.btnSymbolDetails, "btnSymbolDetails");
this.btnSymbolDetails.Name = "btnSymbolDetails";
this.btnSymbolDetails.UseVisualStyleBackColor = true;
this.btnSymbolDetails.Click += new System.EventHandler(this.btnSymbolDetails_Click);
//
// cmbCategories
//
resources.ApplyResources(this.cmbCategories, "cmbCategories");
this.cmbCategories.FormattingEnabled = true;
this.cmbCategories.Name = "cmbCategories";
this.cmbCategories.SelectedIndexChanged += new System.EventHandler(this.cmbCategories_SelectedIndexChanged);
//
// predefinedLineSymbolControl1
//
resources.ApplyResources(this.predefinedLineSymbolControl1, "predefinedLineSymbolControl1");
this.predefinedLineSymbolControl1.BackColor = System.Drawing.Color.White;
this.predefinedLineSymbolControl1.CategoryFilter = String.Empty;
this.predefinedLineSymbolControl1.CellMargin = 8;
this.predefinedLineSymbolControl1.CellSize = new System.Drawing.Size(62, 62);
this.predefinedLineSymbolControl1.ControlRectangle = new System.Drawing.Rectangle(0, 0, 272, 253);
this.predefinedLineSymbolControl1.DefaultCategoryFilter = "All";
this.predefinedLineSymbolControl1.DynamicColumns = true;
this.predefinedLineSymbolControl1.IsInitialized = false;
this.predefinedLineSymbolControl1.IsSelected = true;
this.predefinedLineSymbolControl1.Name = "predefinedLineSymbolControl1";
this.predefinedLineSymbolControl1.SelectedIndex = -1;
this.predefinedLineSymbolControl1.SelectionBackColor = System.Drawing.Color.LightGray;
this.predefinedLineSymbolControl1.SelectionForeColor = System.Drawing.Color.White;
this.predefinedLineSymbolControl1.ShowSymbolNames = true;
this.predefinedLineSymbolControl1.TextFont = new System.Drawing.Font("Arial", 8F);
this.predefinedLineSymbolControl1.VerticalScrollEnabled = true;
//
// symbolPreview1
//
resources.ApplyResources(this.symbolPreview1, "symbolPreview1");
this.symbolPreview1.BackColor = System.Drawing.Color.White;
this.symbolPreview1.Name = "symbolPreview1";
//
// dialogButtons1
//
resources.ApplyResources(this.dialogButtons1, "dialogButtons1");
this.dialogButtons1.Name = "dialogButtons1";
//
// LineSymbolDialog
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.dialogButtons1);
this.Controls.Add(this.predefinedLineSymbolControl1);
this.Controls.Add(this.cmbCategories);
this.Controls.Add(this.symbolPreview1);
this.Controls.Add(this.btnSymbolDetails);
this.Controls.Add(this.lblSymbolPreview);
this.Controls.Add(this.lblPredefinedSymbol);
this.Controls.Add(this.lblSymbologyType);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.HelpButton = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "LineSymbolDialog";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
#region Event Handlers
private void predefinedSymbolControl_SymbolSelected(object sender, EventArgs e)
{
CustomLineSymbolizer customSymbol = predefinedLineSymbolControl1.SelectedSymbolizer;
if (customSymbol != null)
{
_symbolizer = customSymbol.Symbolizer;
UpdatePreview();
}
}
private void SymbolPreview_DoubleClick(object sender, EventArgs e)
{
if (_symbolizer != null && _original != null)
{
ShowDetailsDialog();
}
}
private void predefinedLineSymbolControl1_DoubleClick(object sender, EventArgs e)
{
OnApplyChanges();
DialogResult = DialogResult.OK;
Close();
}
private void btnSymbolDetails_Click(object sender, EventArgs e)
{
if (_symbolizer != null && _original != null)
{
ShowDetailsDialog();
}
}
private void btnApply_Click(object sender, EventArgs e)
{
OnApplyChanges();
}
private void btnOK_Click(object sender, EventArgs e)
{
OnApplyChanges();
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
private void cmbCategories_SelectedIndexChanged(object sender, EventArgs e)
{
predefinedLineSymbolControl1.CategoryFilter = cmbCategories.SelectedItem.ToString();
}
//when the user clicks 'Add to custom symbols' on the details dialog
private void detailsDialog_AddToCustomSymbols(object sender, LineSymbolizerEventArgs e)
{
// Here a dialog is displayed. The user can enter the custom symbol name and category
// in the dialog.
AddCustomSymbolDialog dlg = new AddCustomSymbolDialog(_categories, e.Symbolizer);
dlg.ShowDialog();
CustomLineSymbolizer newSym = dlg.CustomSymbolizer as CustomLineSymbolizer;
if (newSym != null)
{
//check if user added a new category
if (!_categories.Contains(newSym.Category))
{
_categories.Add(newSym.Category);
}
UpdateCategories();
predefinedLineSymbolControl1.SymbolizerList.Insert(0, newSym);
predefinedLineSymbolControl1.Invalidate();
}
//TODO: save the custom symbolizer to xml / serialized file.
//predefinedLineSymbolControl1.SaveToXml("test.xml");
}
private void detailsDialog_ChangesApplied(object sender, EventArgs e)
{
//unselect any symbolizers in the control
predefinedLineSymbolControl1.IsSelected = false;
UpdatePreview(_symbolizer2);
}
#endregion
#region Methods
private void UpdatePreview()
{
symbolPreview1.UpdatePreview(_symbolizer);
}
private void UpdatePreview(IFeatureSymbolizer symbolizer)
{
symbolPreview1.UpdatePreview(symbolizer);
}
/// <summary>
/// Shows the 'Symbol Details' dialog
/// </summary>
private void ShowDetailsDialog()
{
DetailedLineSymbolDialog detailsDialog = new DetailedLineSymbolDialog(_original);
detailsDialog.ChangesApplied += detailsDialog_ChangesApplied;
detailsDialog.ShowDialog();
}
//this loads the default symbols and initializes the control
//as well as the available categories
private void LoadDefaultSymbols()
{
CustomLineSymbolProvider prov = new CustomLineSymbolProvider();
_categories = prov.GetAvailableCategories();
UpdateCategories();
}
private void UpdateCategories()
{
cmbCategories.SuspendLayout();
cmbCategories.Items.Clear();
cmbCategories.Items.Add("All");
foreach (string cat in _categories)
{
cmbCategories.Items.Add(cat);
}
cmbCategories.SelectedIndex = 0;
cmbCategories.ResumeLayout();
}
#endregion
#region Properties
#endregion
#region Protected Methods
/// <summary>
/// Fires the ChangesApplied event
/// </summary>
protected void OnApplyChanges()
{
UpdatePreview();
_original.CopyProperties(_symbolizer);
if (ChangesApplied != null) ChangesApplied(this, EventArgs.Empty);
}
/// <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);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace AnagramMaker.Lib
{
/// <summary>
/// Implementation of trie data structure.
/// </summary>
/// <typeparam name="TValue">The type of values in the trie.</typeparam>
public class Trie<TValue> : IDictionary<string, TValue>
{
private readonly TrieNode root;
private int count;
/// <summary>
/// Initializes a new instance of the <see cref="Trie{TValue}"/>.
/// </summary>
/// <param name="comparer">Comparer.</param>
public Trie(IEqualityComparer<char> comparer)
{
root = new TrieNode(char.MinValue, comparer);
}
/// <summary>
/// Initializes a new instance of the <see cref="Trie{TValue}"/>.
/// </summary>
public Trie()
: this(EqualityComparer<char>.Default)
{
}
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
public int Count
{
get { return count; }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
public ICollection<string> Keys
{
get { return GetAllNodes().Select(n => n.Key).ToArray(); }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
public ICollection<TValue> Values
{
get { return GetAllNodes().Select(n => n.Value).ToArray(); }
}
bool ICollection<KeyValuePair<string, TValue>>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <returns>
/// The element with the specified key.
/// </returns>
/// <param name="key">The key of the element to get or set.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.</exception>
public TValue this[string key]
{
get
{
TValue value;
if (!TryGetValue(key, out value))
{
throw new KeyNotFoundException("The given charKey was not present in the trie.");
}
return value;
}
set
{
TrieNode node;
if (TryGetNode(key, out node))
{
SetTerminalNode(node, value);
}
else
{
Add(key, value);
}
}
}
/// <summary>
/// Adds an element with the provided charKey and value to the <see cref="Trie{TValue}"/>.
/// </summary>
/// <param name="key">The object to use as the charKey of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
/// <exception cref="T:System.ArgumentException">An element with the same charKey already exists in the <see cref="Trie{TValue}"/>.</exception>
public void Add(string key, TValue value)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
var node = root;
foreach (var c in key)
{
node = node.Add(c);
}
if (node.IsTerminal)
{
throw new ArgumentException(
string.Format("An element with the same charKey already exists: '{0}'", key), "key");
}
SetTerminalNode(node, value);
count++;
}
/// <summary>
/// Adds an item to the <see cref="Trie{TValue}"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="Trie{TValue}"/>.</param>
/// <exception cref="T:System.ArgumentException">An element with the same charKey already exists in the <see cref="Trie{TValue}"/>.</exception>
public void Add(TrieEntry<TValue> item)
{
Add(item.Key, item.Value);
}
/// <summary>
/// Adds the elements of the specified collection to the <see cref="Trie{TValue}"/>.
/// </summary>
/// <param name="collection">The collection whose elements should be added to the <see cref="Trie{TValue}"/>. The items should have unique keys.</param>
/// <exception cref="T:System.ArgumentException">An element with the same charKey already exists in the <see cref="Trie{TValue}"/>.</exception>
public void AddRange(IEnumerable<TrieEntry<TValue>> collection)
{
foreach (var item in collection)
{
Add(item.Key, item.Value);
}
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception>
public void Clear()
{
root.Clear();
count = 0;
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified charKey.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the charKey; otherwise, false.
/// </returns>
/// <param name="key">The charKey to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
public bool ContainsKey(string key)
{
TValue value;
return TryGetValue(key, out value);
}
/// <summary>
/// Gets items by key prefix.
/// </summary>
/// <param name="prefix">Key prefix.</param>
/// <returns>Collection of <see cref="TrieEntry{TValue}"/> items which have key with specified key.</returns>
public IEnumerable<TrieEntry<TValue>> GetByPrefix(string prefix)
{
var node = root;
foreach (var item in prefix)
{
if (!node.TryGetNode(item, out node))
{
return Enumerable.Empty<TrieEntry<TValue>>();
}
}
return node.GetByPrefix();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>1</filterpriority>
public IEnumerator<KeyValuePair<string, TValue>> GetEnumerator()
{
return GetAllNodes().Select(n => new KeyValuePair<string, TValue>(n.Key, n.Value)).GetEnumerator();
}
/// <summary>
/// Removes the element with the specified charKey from the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
/// <param name="key">The charKey of the element to remove.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception>
public bool Remove(string key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
TrieNode node;
if (!TryGetNode(key, out node))
{
return false;
}
if (!node.IsTerminal)
{
return false;
}
RemoveNode(node);
return true;
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <returns>
/// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false.
/// </returns>
/// <param name="key">The key whose value to get.</param>
/// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
public bool TryGetValue(string key, out TValue value)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
TrieNode node;
value = default(TValue);
if (!TryGetNode(key, out node))
{
return false;
}
if (!node.IsTerminal)
{
return false;
}
value = node.Value;
return true;
}
void ICollection<KeyValuePair<string, TValue>>.Add(KeyValuePair<string, TValue> item)
{
Add(item.Key, item.Value);
}
bool ICollection<KeyValuePair<string, TValue>>.Contains(KeyValuePair<string, TValue> item)
{
TrieNode node;
if (!TryGetNode(item.Key, out node))
{
return false;
}
return node.IsTerminal && EqualityComparer<TValue>.Default.Equals(node.Value, item.Value);
}
void ICollection<KeyValuePair<string, TValue>>.CopyTo(KeyValuePair<string, TValue>[] array, int arrayIndex)
{
Array.Copy(GetAllNodes().Select(n => new KeyValuePair<string, TValue>(n.Key, n.Value)).ToArray(), 0, array,
arrayIndex, Count);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
bool ICollection<KeyValuePair<string, TValue>>.Remove(KeyValuePair<string, TValue> item)
{
TrieNode node;
if (!TryGetNode(item.Key, out node))
{
return false;
}
if (!node.IsTerminal)
{
return false;
}
if (!EqualityComparer<TValue>.Default.Equals(node.Value, item.Value))
{
return false;
}
RemoveNode(node);
return true;
}
private static void SetTerminalNode(TrieNode node, TValue value)
{
node.IsTerminal = true;
node.Value = value;
}
private IEnumerable<TrieNode> GetAllNodes()
{
return root.GetAllNodes();
}
private void RemoveNode(TrieNode node)
{
node.Remove();
count--;
}
private bool TryGetNode(string key, out TrieNode node)
{
node = root;
foreach (var c in key)
{
if (!node.TryGetNode(c, out node))
{
return false;
}
}
return true;
}
/// <summary>
/// <see cref="Trie{TValue}"/>'s node.
/// </summary>
private sealed class TrieNode
{
private readonly Dictionary<char, TrieNode> children;
private readonly IEqualityComparer<char> comparer;
private readonly char keyChar;
internal TrieNode(char keyChar, IEqualityComparer<char> comparer)
{
this.keyChar = keyChar;
this.comparer = comparer;
children = new Dictionary<char, TrieNode>(comparer);
}
internal bool IsTerminal { get; set; }
internal string Key
{
get
{
////var result = new StringBuilder().Append(keyChar);
////TrieNode node = this;
////while ((node = node.Parent).Parent != null)
////{
//// result.Insert(0, node.keyChar);
////}
////return result.ToString();
var stack = new Stack<char>();
stack.Push(keyChar);
TrieNode node = this;
while ((node = node.Parent).Parent != null)
{
stack.Push(node.keyChar);
}
return new string(stack.ToArray());
}
}
internal TValue Value { get; set; }
private TrieNode Parent { get; set; }
internal TrieNode Add(char key)
{
TrieNode childNode;
if (!children.TryGetValue(key, out childNode))
{
childNode = new TrieNode(key, comparer)
{
Parent = this
};
children.Add(key, childNode);
}
return childNode;
}
internal void Clear()
{
children.Clear();
}
internal IEnumerable<TrieNode> GetAllNodes()
{
foreach (var child in children)
{
if (child.Value.IsTerminal)
{
yield return child.Value;
}
foreach (var item in child.Value.GetAllNodes())
{
if (item.IsTerminal)
{
yield return item;
}
}
}
}
internal IEnumerable<TrieEntry<TValue>> GetByPrefix()
{
if (IsTerminal)
{
yield return new TrieEntry<TValue>(Key, Value);
}
foreach (var item in children)
{
foreach (var element in item.Value.GetByPrefix())
{
yield return element;
}
}
}
internal void Remove()
{
IsTerminal = false;
if (children.Count == 0 && Parent != null)
{
Parent.children.Remove(keyChar);
if (!Parent.IsTerminal)
{
Parent.Remove();
}
}
}
internal bool TryGetNode(char key, out TrieNode node)
{
return children.TryGetValue(key, out node);
}
}
}
/// <summary>
/// Defines a key/value pair that can be set or retrieved from <see cref="Trie{TValue}"/>.
/// </summary>
public struct TrieEntry<TValue>
{
/// <summary>
/// Initializes a new instance of the <see cref="TrieEntry{TValue}"/> structure with the specified key and value.
/// </summary>
/// <param name="key">The <see cref="string"/> object defined in each key/value pair.</param>
/// <param name="value">The definition associated with key.</param>
public TrieEntry(string key, TValue value)
: this()
{
Key = key;
Value = value;
}
/// <summary>
/// Gets the key in the key/value pair.
/// </summary>
public string Key { get; private set; }
/// <summary>
/// Gets the value in the key/value pair.
/// </summary>
public TValue Value { get; private set; }
/// <summary>
/// Returns the fully qualified type name of this instance.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> containing a fully qualified type name.
/// </returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
return string.Format("[{0}, {1}]", Key, Value);
}
}
}
| |
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 SignalR.MongoRabbit.Example.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;
}
}
}
| |
// 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.Reflection.Runtime.TypeInfos;
namespace System.Reflection.TypeLoading
{
internal static class Assignability
{
public static bool IsAssignableFrom(Type toTypeInfo, Type fromTypeInfo, CoreTypes coreTypes)
{
if (toTypeInfo == null)
throw new NullReferenceException();
if (fromTypeInfo == null)
return false; // It would be more appropriate to throw ArgumentNullException here, but returning "false" is the desktop-compat behavior.
if (fromTypeInfo.Equals(toTypeInfo))
return true;
if (toTypeInfo.IsGenericTypeDefinition)
{
// Asking whether something can cast to a generic type definition is arguably meaningless. The desktop CLR Reflection layer converts all
// generic type definitions to generic type instantiations closed over the formal generic type parameters. The .NET Native framework
// keeps the two separate. Fortunately, under either interpretation, returning "false" unless the two types are identical is still a
// defensible behavior. To avoid having the rest of the code deal with the differing interpretations, we'll short-circuit this now.
return false;
}
if (fromTypeInfo.IsGenericTypeDefinition)
{
// The desktop CLR Reflection layer converts all generic type definitions to generic type instantiations closed over the formal
// generic type parameters. The .NET Native framework keeps the two separate. For the purpose of IsAssignableFrom(),
// it makes sense to unify the two for the sake of backward compat. We'll just make the transform here so that the rest of code
// doesn't need to know about this quirk.
fromTypeInfo = fromTypeInfo.GetGenericTypeDefinition().MakeGenericType(fromTypeInfo.GetGenericTypeParameters());
}
if (fromTypeInfo.CanCastTo(toTypeInfo, coreTypes))
return true;
// Desktop compat: IsAssignableFrom() considers T as assignable to Nullable<T> (but does not check if T is a generic parameter.)
if (!fromTypeInfo.IsGenericParameter)
{
if (toTypeInfo.IsConstructedGenericType && toTypeInfo.GetGenericTypeDefinition() == coreTypes[CoreType.NullableT])
{
Type nullableUnderlyingType = toTypeInfo.GenericTypeArguments[0];
if (nullableUnderlyingType.Equals(fromTypeInfo))
return true;
}
}
return false;
}
private static bool CanCastTo(this Type fromTypeInfo, Type toTypeInfo, CoreTypes coreTypes)
{
if (fromTypeInfo.Equals(toTypeInfo))
return true;
if (fromTypeInfo.IsArray)
{
if (toTypeInfo.IsInterface)
return fromTypeInfo.CanCastArrayToInterface(toTypeInfo, coreTypes);
if (fromTypeInfo.IsSubclassOf(toTypeInfo))
return true; // T[] is castable to Array or Object.
if (!toTypeInfo.IsArray)
return false;
int rank = fromTypeInfo.GetArrayRank();
if (rank != toTypeInfo.GetArrayRank())
return false;
bool fromTypeIsSzArray = fromTypeInfo.IsSZArray();
bool toTypeIsSzArray = toTypeInfo.IsSZArray();
if (fromTypeIsSzArray != toTypeIsSzArray)
{
// T[] is assignable to T[*] but not vice-versa.
if (!(rank == 1 && !toTypeIsSzArray))
{
return false; // T[*] is not castable to T[]
}
}
Type toElementTypeInfo = toTypeInfo.GetElementType();
Type fromElementTypeInfo = fromTypeInfo.GetElementType();
return fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes);
}
if (fromTypeInfo.IsByRef)
{
if (!toTypeInfo.IsByRef)
return false;
Type toElementTypeInfo = toTypeInfo.GetElementType();
Type fromElementTypeInfo = fromTypeInfo.GetElementType();
return fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes);
}
if (fromTypeInfo.IsPointer)
{
if (toTypeInfo.Equals(coreTypes[CoreType.Object]))
return true; // T* is castable to Object.
if (toTypeInfo.Equals(coreTypes[CoreType.UIntPtr]))
return true; // T* is castable to UIntPtr (but not IntPtr)
if (!toTypeInfo.IsPointer)
return false;
Type toElementTypeInfo = toTypeInfo.GetElementType();
Type fromElementTypeInfo = fromTypeInfo.GetElementType();
return fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes);
}
if (fromTypeInfo.IsGenericParameter)
{
//
// A generic parameter can be cast to any of its constraints, or object, if none are specified, or ValueType if the "struct" constraint is
// specified.
//
// This has to be coded as its own case as TypeInfo.BaseType on a generic parameter doesn't always return what you'd expect.
//
if (toTypeInfo.Equals(coreTypes[CoreType.Object]))
return true;
if (toTypeInfo.Equals(coreTypes[CoreType.ValueType]))
{
GenericParameterAttributes attributes = fromTypeInfo.GenericParameterAttributes;
if ((attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
return true;
}
foreach (Type constraintType in fromTypeInfo.GetGenericParameterConstraints())
{
if (constraintType.CanCastTo(toTypeInfo, coreTypes))
return true;
}
return false;
}
if (toTypeInfo.IsArray || toTypeInfo.IsByRef || toTypeInfo.IsPointer || toTypeInfo.IsGenericParameter)
return false;
if (fromTypeInfo.MatchesWithVariance(toTypeInfo, coreTypes))
return true;
if (toTypeInfo.IsInterface)
{
foreach (Type ifc in fromTypeInfo.GetInterfaces())
{
if (ifc.MatchesWithVariance(toTypeInfo, coreTypes))
return true;
}
return false;
}
else
{
// Interfaces are always castable to System.Object. The code below will not catch this as interfaces report their BaseType as null.
if (toTypeInfo.Equals(coreTypes[CoreType.Object]) && fromTypeInfo.IsInterface)
return true;
Type walk = fromTypeInfo;
for (;;)
{
Type baseType = walk.BaseType;
if (baseType == null)
return false;
walk = baseType;
if (walk.MatchesWithVariance(toTypeInfo, coreTypes))
return true;
}
}
}
//
// Check a base type or implemented interface type for equivalence (taking into account variance for generic instantiations.)
// Does not check ancestors recursively.
//
private static bool MatchesWithVariance(this Type fromTypeInfo, Type toTypeInfo, CoreTypes coreTypes)
{
Debug.Assert(!(fromTypeInfo.IsArray || fromTypeInfo.IsByRef || fromTypeInfo.IsPointer || fromTypeInfo.IsGenericParameter));
Debug.Assert(!(toTypeInfo.IsArray || toTypeInfo.IsByRef || toTypeInfo.IsPointer || toTypeInfo.IsGenericParameter));
if (fromTypeInfo.Equals(toTypeInfo))
return true;
if (!(fromTypeInfo.IsConstructedGenericType && toTypeInfo.IsConstructedGenericType))
return false;
Type genericTypeDefinition = fromTypeInfo.GetGenericTypeDefinition();
if (!genericTypeDefinition.Equals(toTypeInfo.GetGenericTypeDefinition()))
return false;
Type[] fromTypeArguments = fromTypeInfo.GenericTypeArguments;
Type[] toTypeArguments = toTypeInfo.GenericTypeArguments;
Type[] genericTypeParameters = genericTypeDefinition.GetGenericTypeParameters();
for (int i = 0; i < genericTypeParameters.Length; i++)
{
Type fromTypeArgumentInfo = fromTypeArguments[i];
Type toTypeArgumentInfo = toTypeArguments[i];
GenericParameterAttributes attributes = genericTypeParameters[i].GenericParameterAttributes;
switch (attributes & GenericParameterAttributes.VarianceMask)
{
case GenericParameterAttributes.Covariant:
if (!(fromTypeArgumentInfo.IsGcReferenceTypeAndCastableTo(toTypeArgumentInfo, coreTypes)))
return false;
break;
case GenericParameterAttributes.Contravariant:
if (!(toTypeArgumentInfo.IsGcReferenceTypeAndCastableTo(fromTypeArgumentInfo, coreTypes)))
return false;
break;
case GenericParameterAttributes.None:
if (!(fromTypeArgumentInfo.Equals(toTypeArgumentInfo)))
return false;
break;
default:
throw new BadImageFormatException(); // Unexpected variance value in metadata.
}
}
return true;
}
//
// A[] can cast to B[] if one of the following are true:
//
// A can cast to B under variance rules.
//
// A and B are both integers or enums and have the same reduced type (i.e. represent the same-sized integer, ignoring signed/unsigned differences.)
// "char" is not interchangable with short/ushort. "bool" is not interchangable with byte/sbyte.
//
// For desktop compat, A& and A* follow the same rules.
//
private static bool IsElementTypeCompatibleWith(this Type fromTypeInfo, Type toTypeInfo, CoreTypes coreTypes)
{
if (fromTypeInfo.IsGcReferenceTypeAndCastableTo(toTypeInfo, coreTypes))
return true;
Type reducedFromType = fromTypeInfo.ReducedType(coreTypes);
Type reducedToType = toTypeInfo.ReducedType(coreTypes);
if (reducedFromType.Equals(reducedToType))
return true;
return false;
}
private static Type ReducedType(this Type t, CoreTypes coreTypes)
{
if (t.IsEnum)
t = t.GetEnumUnderlyingType();
if (t.Equals(coreTypes[CoreType.Byte]))
return coreTypes[CoreType.SByte] ?? throw new TypeLoadException(SR.Format(SR.CoreTypeNotFound, "System.SByte"));
if (t.Equals(coreTypes[CoreType.UInt16]))
return coreTypes[CoreType.Int16] ?? throw new TypeLoadException(SR.Format(SR.CoreTypeNotFound, "System.Int16"));
if (t.Equals(coreTypes[CoreType.UInt32]))
return coreTypes[CoreType.Int32] ?? throw new TypeLoadException(SR.Format(SR.CoreTypeNotFound, "System.Int32"));
if (t.Equals(coreTypes[CoreType.UInt64]))
return coreTypes[CoreType.Int64] ?? throw new TypeLoadException(SR.Format(SR.CoreTypeNotFound, "System.Int64"));
return t;
}
//
// Contra/CoVariance.
//
// IEnumerable<D> can cast to IEnumerable<B> if D can cast to B and if there's no possibility that D is a value type.
//
private static bool IsGcReferenceTypeAndCastableTo(this Type fromTypeInfo, Type toTypeInfo, CoreTypes coreTypes)
{
if (fromTypeInfo.Equals(toTypeInfo))
return true;
if (fromTypeInfo.ProvablyAGcReferenceType(coreTypes))
return fromTypeInfo.CanCastTo(toTypeInfo, coreTypes);
return false;
}
//
// A true result indicates that a type can never be a value type. This is important when testing variance-compatibility.
//
private static bool ProvablyAGcReferenceType(this Type t, CoreTypes coreTypes)
{
if (t.IsGenericParameter)
{
GenericParameterAttributes attributes = t.GenericParameterAttributes;
if ((attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0)
return true; // generic parameter with a "class" constraint.
}
return t.ProvablyAGcReferenceTypeHelper(coreTypes);
}
private static bool ProvablyAGcReferenceTypeHelper(this Type t, CoreTypes coreTypes)
{
if (t.IsArray)
return true;
if (t.IsByRef || t.IsPointer)
return false;
if (t.IsGenericParameter)
{
// We intentionally do not check for a "class" constraint on generic parameter ancestors.
// That's because this property does not propagate up the constraining hierarchy.
// (e.g. "class A<S, T> where S : T, where T : class" does not guarantee that S is a class.)
foreach (Type constraintType in t.GetGenericParameterConstraints())
{
if (constraintType.ProvablyAGcReferenceTypeHelper(coreTypes))
return true;
}
return false;
}
return t.IsClass && !t.Equals(coreTypes[CoreType.Object]) && !t.Equals(coreTypes[CoreType.ValueType]) && !t.Equals(coreTypes[CoreType.Enum]);
}
//
// T[] casts to IList<T>. This could be handled by the normal ancestor-walking code
// but for one complication: T[] also casts to IList<U> if T[] casts to U[].
//
private static bool CanCastArrayToInterface(this Type fromTypeInfo, Type toTypeInfo, CoreTypes coreTypes)
{
Debug.Assert(fromTypeInfo.IsArray);
Debug.Assert(toTypeInfo.IsInterface);
if (toTypeInfo.IsConstructedGenericType)
{
Type[] toTypeGenericTypeArguments = toTypeInfo.GenericTypeArguments;
if (toTypeGenericTypeArguments.Length != 1)
return false;
Type toElementTypeInfo = toTypeGenericTypeArguments[0];
Type toTypeGenericTypeDefinition = toTypeInfo.GetGenericTypeDefinition();
Type fromElementTypeInfo = fromTypeInfo.GetElementType();
foreach (Type ifc in fromTypeInfo.GetInterfaces())
{
if (ifc.IsConstructedGenericType)
{
Type ifcGenericTypeDefinition = ifc.GetGenericTypeDefinition();
if (ifcGenericTypeDefinition.Equals(toTypeGenericTypeDefinition))
{
if (fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes))
return true;
}
}
}
return false;
}
else
{
foreach (Type ifc in fromTypeInfo.GetInterfaces())
{
if (ifc.Equals(toTypeInfo))
return true;
}
return false;
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TableViewSection_T.cs" company="sgmunn">
// (c) sgmunn 2012
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of
// the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace MonoKit.UI
{
using System;
using System.Collections;
using MonoTouch.UIKit;
using System.Collections.Generic;
using MonoTouch.Foundation;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using MonoKit.DataBinding;
using MonoKit.Interactivity;
public class TableViewSection<TItem> : TableViewSectionBase, IEnumerable<TItem>, INotifyCollectionChanged where TItem : IDisposable
{
private int notifyCollectionChanges;
private readonly List<TItem> items;
public TableViewSection(TableViewSource source) : base(source)
{
this.items = new List<TItem>();
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoKit.UI.TableViewSection`1"/> class.
/// </summary>
/// <param name='viewDefinitions'>
/// View declarations. more specific definitions should be before more general ones
/// </param>
public TableViewSection(TableViewSource source, params IViewDefinition[] viewDefinitions) : base(source, viewDefinitions)
{
this.items = new List<TItem>();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
private List<TItem> Items
{
get
{
return this.items;
}
}
public void BeginUpdate()
{
this.notifyCollectionChanges++;
}
public void EndUpdate()
{
this.notifyCollectionChanges--;
if (this.notifyCollectionChanges <= 0)
{
this.notifyCollectionChanges = 0;
var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
this.OnCollectionChanged(args);
}
}
public override void Clear()
{
foreach (var item in this.Items)
{
item.Dispose();
}
this.Items.Clear();
var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
this.OnCollectionChanged(args);
}
public void Add(TItem item)
{
this.Items.Add(item);
var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item,this.Items.Count -1);
this.OnCollectionChanged(args);
}
public void AddRange(IEnumerable<TItem> items)
{
var index = this.Items.Count;
var newItems = new List<TItem>(items);
this.Items.AddRange(newItems);
var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newItems, index);
this.OnCollectionChanged(args);
}
public int IndexOf(TItem item)
{
return this.Items.IndexOf(item);
}
public void Insert(int index, TItem item)
{
this.Items.Insert(index, item);
var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index);
this.OnCollectionChanged(args);
}
public void Remove(TItem item)
{
var index = this.Items.IndexOf(item);
this.Items.Remove(item);
var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index);
this.OnCollectionChanged(args);
}
public void RemoveAt(int index)
{
var item = this.Items[index];
this.Items.RemoveAt(index);
var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index);
this.OnCollectionChanged(args);
}
public void RemoveRange(int index, int count)
{
var items = this.Items.GetRange(index, count);
this.Items.RemoveRange(index, count);
var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, items, index);
this.OnCollectionChanged(args);
}
public override UITableViewCell GetCell(int row)
{
return this.GetViewForObject(this.Items[row]);
}
public override void RowSelected(NSIndexPath indexPath)
{
this.Source.TableView.DeselectRow(indexPath, true);
var item = this.Items[indexPath.Row];
var command = item as ICommand;
if (command != null && command.GetCanExecute())
{
command.Execute();
}
}
public override bool CanEditRow(NSIndexPath indexPath)
{
var item = this.Items[indexPath.Row];
var edit = item as IEdit;
if (edit != null)
{
return edit.GetCanEdit();
}
return true;
}
public override void EditRow(UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
{
var item = this.Items[indexPath.Row];
var edit = item as IEdit;
if (edit != null)
{
edit.ExecuteEdit();
}
switch (editingStyle)
{
case UITableViewCellEditingStyle.Delete:
this.notifyCollectionChanges++;
this.Items.Remove(item);
this.notifyCollectionChanges--;
break;
}
}
public override void MoveRow(NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath)
{
var item = this.Items[sourceIndexPath.Row];
// tell item that it has new index
}
public override float GetHeightForRow(NSIndexPath indexPath)
{
// todo: get the height for a given item in a more efficient manner
//var item = this.GetElementAtIndex(indexPath.Row);
//var info = this.GetViewInfoForElement(item);
//if (info != null)
//{
// return info.RowHeight;
//}
return -1;
}
public override IEnumerator GetEnumerator()
{
return this.Items.GetEnumerator();
}
protected override int GetCount()
{
return this.Items.Count;
}
protected void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
{
if (this.notifyCollectionChanges == 0)
{
var ev = this.CollectionChanged;
if (ev != null)
{
ev(this, args);
}
}
}
IEnumerator<TItem> System.Collections.Generic.IEnumerable<TItem>.GetEnumerator()
{
return this.Items.GetEnumerator();
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.UserModel
{
using System;
using TestCases.HSSF;
using NPOI.HSSF.Model;
using NUnit.Framework;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
/**
* Class TestHSSFDateUtil
*
*
* @author Dan Sherman (dsherman at isisph.com)
* @author Hack Kampbjorn (hak at 2mba.dk)
* @author Pavel Krupets (pkrupets at palmtreebusiness dot com)
* @author Alex Jacoby (ajacoby at gmail.com)
* @version %I%, %G%
*/
[TestFixture]
public class TestHSSFDateUtil
{
public static int CALENDAR_JANUARY = 1;
public static int CALENDAR_FEBRUARY = 2;
public static int CALENDAR_MARCH = 3;
public static int CALENDAR_APRIL = 4;
public static int CALENDAR_JULY = 7;
public static int CALENDAR_OCTOBER = 10;
/**
* Checks the date conversion functions in the DateUtil class.
*/
[Test]
public void TestDateConversion()
{
// Iteratating over the hours exposes any rounding issues.
for (int hour = 1; hour < 24; hour++)
{
DateTime date = new DateTime(2002, 1, 1,
hour, 1, 1);
double excelDate =
DateUtil.GetExcelDate(date, false);
Assert.AreEqual(date,DateUtil.GetJavaDate(excelDate, false), "Checking hour = " + hour);
}
// Check 1900 and 1904 date windowing conversions
double excelDate2 = 36526.0;
// with 1900 windowing, excelDate is Jan. 1, 2000
// with 1904 windowing, excelDate is Jan. 2, 2004
DateTime dateIf1900 = new DateTime(2000, 1, 1); // Jan. 1, 2000
DateTime dateIf1904 = dateIf1900.AddYears(4); // now Jan. 1, 2004
dateIf1904 = dateIf1904.AddDays(1); // now Jan. 2, 2004
// 1900 windowing
Assert.AreEqual(dateIf1900,
DateUtil.GetJavaDate(excelDate2, false), "Checking 1900 Date Windowing");
// 1904 windowing
Assert.AreEqual(
dateIf1904,DateUtil.GetJavaDate(excelDate2, true),"Checking 1904 Date Windowing");
}
/**
* Checks the conversion of a java.util.date to Excel on a day when
* Daylight Saving Time starts.
*/
public void TestExcelConversionOnDSTStart()
{
//TODO:: change time zone
DateTime cal = new DateTime(2004, CALENDAR_MARCH, 28);
for (int hour = 0; hour < 24; hour++)
{
// Skip 02:00 CET as that is the Daylight change time
// and Java converts it automatically to 03:00 CEST
if (hour == 2)
{
continue;
}
cal.AddHours(hour);
DateTime javaDate = cal;
double excelDate = DateUtil.GetExcelDate(javaDate, false);
double difference = excelDate - Math.Floor(excelDate);
int differenceInHours = (int)(difference * 24 * 60 + 0.5) / 60;
Assert.AreEqual(
hour,
differenceInHours, "Checking " + hour + " hour on Daylight Saving Time start date");
Assert.AreEqual(
javaDate,
DateUtil.GetJavaDate(excelDate, false),
"Checking " + hour + " hour on Daylight Saving Time start date");
}
}
/**
* Checks the conversion of an Excel date to a java.util.date on a day when
* Daylight Saving Time starts.
*/
public void TestJavaConversionOnDSTStart()
{
//TODO:: change time zone
DateTime cal = new DateTime(2004, CALENDAR_MARCH, 28);
double excelDate = DateUtil.GetExcelDate(cal, false);
double oneHour = 1.0 / 24;
double oneMinute = oneHour / 60;
for (int hour = 0; hour < 24; hour++, excelDate += oneHour)
{
// Skip 02:00 CET as that is the Daylight change time
// and Java converts it automatically to 03:00 CEST
if (hour == 2)
{
continue;
}
cal.AddHours(hour);
DateTime javaDate = DateUtil.GetJavaDate(excelDate, false);
Assert.AreEqual(
excelDate,
DateUtil.GetExcelDate(javaDate, false),0.001);
}
}
/**
* Checks the conversion of a java.util.Date to Excel on a day when
* Daylight Saving Time ends.
*/
public void TestExcelConversionOnDSTEnd()
{
//TODO:: change time zone
DateTime cal = new DateTime(2004, CALENDAR_OCTOBER, 31);
for (int hour = 0; hour < 24; hour++)
{
cal.AddDays(hour);
DateTime javaDate = cal;
double excelDate = DateUtil.GetExcelDate(javaDate, false);
double difference = excelDate - Math.Floor(excelDate);
int differenceInHours = (int)(difference * 24 * 60 + 0.5) / 60;
Assert.AreEqual(
hour,
differenceInHours, "Checking " + hour + " hour on Daylight Saving Time end date");
Assert.AreEqual(
javaDate,
DateUtil.GetJavaDate(excelDate, false),
"Checking " + hour + " hour on Daylight Saving Time start date");
}
}
/**
* Checks the conversion of an Excel date to java.util.Date on a day when
* Daylight Saving Time ends.
*/
[Test]
public void TestJavaConversionOnDSTEnd()
{
//TODO:: change time zone
DateTime cal = new DateTime(2004, CALENDAR_OCTOBER, 31);
double excelDate = DateUtil.GetExcelDate(cal, false);
double oneHour = 1.0 / 24;
double oneMinute = oneHour / 60;
for (int hour = 0; hour < 24; hour++, excelDate += oneHour)
{
cal.AddHours( hour);
DateTime javaDate = DateUtil.GetJavaDate(excelDate, false);
Assert.AreEqual(
excelDate,
DateUtil.GetExcelDate(javaDate, false),0.1);
}
}
/**
* Tests that we deal with time-zones properly
*/
[Ignore("")]
public void TestCalendarConversion()
{
DateTime date = new DateTime(2002, 1, 1, 12, 1, 1);
DateTime expected = date;
// Iterating over the hours exposes any rounding issues.
for (int hour = -12; hour <= 12; hour++)
{
String id = "GMT" + (hour < 0 ? "" : "+") + hour + ":00";
//TODO:: change time zone
//date.SetTimeZone(TimeZone.GetTimeZone(id));
//date.AddDays(12);
double excelDate = DateUtil.GetExcelDate(date, false);
DateTime javaDate = DateUtil.GetJavaDate(excelDate);
// Should Match despite time-zone
Assert.AreEqual(expected, javaDate, "Checking timezone " + id);
}
//// Check that the timezone aware getter works correctly
//TimeZone cet = TimeZone.getTimeZone("Europe/Copenhagen");
//TimeZone ldn = TimeZone.getTimeZone("Europe/London");
//TimeZone.setDefault(cet);
//// 12:45 on 27th April 2012
//double excelDate = 41026.53125;
//// Same, no change
//assertEquals(
// HSSFDateUtil.getJavaDate(excelDate, false).getTime(),
// HSSFDateUtil.getJavaDate(excelDate, false, cet).getTime()
//);
//// London vs Copenhagen, should differ by an hour
//Date cetDate = HSSFDateUtil.getJavaDate(excelDate, false);
//Date ldnDate = HSSFDateUtil.getJavaDate(excelDate, false, ldn);
//assertEquals(ldnDate.getTime() - cetDate.getTime(), 60 * 60 * 1000);
}
/**
* Tests that we correctly detect date formats as such
*/
[Test]
public void TestIdentifyDateFormats()
{
// First up, try with a few built in date formats
short[] builtins = new short[] { 0x0e, 0x0f, 0x10, 0x16, 0x2d, 0x2e };
for (int i = 0; i < builtins.Length; i++)
{
String formatStr = HSSFDataFormat.GetBuiltinFormat(builtins[i]);
Assert.IsTrue(DateUtil.IsInternalDateFormat(builtins[i]));
Assert.IsTrue(DateUtil.IsADateFormat(builtins[i], formatStr));
}
// Now try a few built-in non date formats
builtins = new short[] { 0x01, 0x02, 0x17, 0x1f, 0x30 };
for (int i = 0; i < builtins.Length; i++)
{
String formatStr = HSSFDataFormat.GetBuiltinFormat(builtins[i]);
Assert.IsFalse(DateUtil.IsInternalDateFormat(builtins[i]));
Assert.IsFalse(DateUtil.IsADateFormat(builtins[i], formatStr));
}
// Now for some non-internal ones
// These come after the real ones
int numBuiltins = HSSFDataFormat.NumberOfBuiltinBuiltinFormats;
Assert.IsTrue(numBuiltins < 60);
short formatId = 60;
Assert.IsFalse(DateUtil.IsInternalDateFormat(formatId));
// Valid ones first
String[] formats = new String[] {
"yyyy-mm-dd", "yyyy/mm/dd", "yy/mm/dd", "yy/mmm/dd",
"dd/mm/yy", "dd/mm/yyyy", "dd/mmm/yy",
"dd-mm-yy", "dd-mm-yyyy",
"DD-MM-YY", "DD-mm-YYYY",
"dd\\-mm\\-yy", // Sometimes escaped
"dd.mm.yyyy", "dd\\.mm\\.yyyy",
"dd\\ mm\\.yyyy AM", "dd\\ mm\\.yyyy pm",
"dd\\ mm\\.yyyy\\-dd", "[h]:mm:ss",
//"mm/dd/yy", "\"mm\"/\"dd\"/\"yy\"",
"mm/dd/yy",
"\\\"mm\\\"/\\\"dd\\\"/\\\"yy\\\"",
"mm/dd/yy \"\\\"some\\\" string\"",
"m\\/d\\/yyyy",
// These crazy ones are valid
"yyyy-mm-dd;@", "yyyy/mm/dd;@",
"dd-mm-yy;@", "dd-mm-yyyy;@",
// These even crazier ones are also valid
// (who knows what they mean though...)
"[$-F800]dddd\\,\\ mmm\\ dd\\,\\ yyyy",
"[$-F900]ddd/mm/yyy",
// These ones specify colours, who knew that was allowed?
"[BLACK]dddd/mm/yy",
"[yeLLow]yyyy-mm-dd"
};
for (int i = 0; i < formats.Length; i++)
{
Assert.IsTrue(
DateUtil.IsADateFormat(formatId, formats[i])
,formats[i] + " is a date format"
);
}
// Then time based ones too
formats = new String[] {
"yyyy-mm-dd hh:mm:ss", "yyyy/mm/dd HH:MM:SS",
"mm/dd HH:MM", "yy/mmm/dd SS",
"mm/dd HH:MM AM", "mm/dd HH:MM am",
"mm/dd HH:MM PM", "mm/dd HH:MM pm"
//"m/d/yy h:mm AM/PM"
};
for (int i = 0; i < formats.Length; i++)
{
Assert.IsTrue(
DateUtil.IsADateFormat(formatId, formats[i]),
formats[i] + " is a datetime format"
);
}
// Then invalid ones
formats = new String[] {
"yyyy*mm*dd",
"0.0", "0.000",
"0%", "0.0%",
"[]Foo", "[BLACK]0.00%",
"", null
};
for (int i = 0; i < formats.Length; i++)
{
Assert.IsFalse(
DateUtil.IsADateFormat(formatId, formats[i]),
formats[i] + " is not a date or datetime format"
);
}
// And these are ones we probably shouldn't allow,
// but would need a better regexp
formats = new String[] {
//"yyyy:mm:dd",
"yyyy:mm:dd", "\"mm\"/\"dd\"/\"yy\"",
};
for (int i = 0; i < formats.Length; i++)
{
// Assert.IsFalse( DateUtil.IsADateFormat(formatId, formats[i]) );
}
}
/**
* Test that against a real, Test file, we still do everything
* correctly
*/
[Test]
public void TestOnARealFile()
{
HSSFWorkbook workbook = HSSFTestDataSamples.OpenSampleWorkbook("DateFormats.xls");
NPOI.SS.UserModel.ISheet sheet = workbook.GetSheetAt(0);
InternalWorkbook wb = workbook.Workbook;
IRow row;
ICell cell;
NPOI.SS.UserModel.ICellStyle style;
double aug_10_2007 = 39304.0;
// Should have dates in 2nd column
// All of them are the 10th of August
// 2 US dates, 3 UK dates
row = sheet.GetRow(0);
cell = row.GetCell(1);
style = cell.CellStyle;
Assert.AreEqual(aug_10_2007, cell.NumericCellValue, 0.0001);
Assert.AreEqual("d-mmm-yy", style.GetDataFormatString());
Assert.IsTrue(DateUtil.IsInternalDateFormat(style.DataFormat));
Assert.IsTrue(DateUtil.IsADateFormat(style.DataFormat, style.GetDataFormatString()));
Assert.IsTrue(DateUtil.IsCellDateFormatted(cell));
row = sheet.GetRow(1);
cell = row.GetCell(1);
style = cell.CellStyle;
Assert.AreEqual(aug_10_2007, cell.NumericCellValue, 0.0001);
Assert.IsFalse(DateUtil.IsInternalDateFormat(cell.CellStyle.DataFormat));
Assert.IsTrue(DateUtil.IsADateFormat(style.DataFormat, style.GetDataFormatString()));
Assert.IsTrue(DateUtil.IsCellDateFormatted(cell));
row = sheet.GetRow(2);
cell = row.GetCell(1);
style = cell.CellStyle;
Assert.AreEqual(aug_10_2007, cell.NumericCellValue, 0.0001);
Assert.IsTrue(DateUtil.IsInternalDateFormat(cell.CellStyle.DataFormat));
Assert.IsTrue(DateUtil.IsADateFormat(style.DataFormat, style.GetDataFormatString()));
Assert.IsTrue(DateUtil.IsCellDateFormatted(cell));
row = sheet.GetRow(3);
cell = row.GetCell(1);
style = cell.CellStyle;
Assert.AreEqual(aug_10_2007, cell.NumericCellValue, 0.0001);
Assert.IsFalse(DateUtil.IsInternalDateFormat(cell.CellStyle.DataFormat));
Assert.IsTrue(DateUtil.IsADateFormat(style.DataFormat, style.GetDataFormatString()));
Assert.IsTrue(DateUtil.IsCellDateFormatted(cell));
row = sheet.GetRow(4);
cell = row.GetCell(1);
style = cell.CellStyle;
Assert.AreEqual(aug_10_2007, cell.NumericCellValue, 0.0001);
Assert.IsFalse(DateUtil.IsInternalDateFormat(cell.CellStyle.DataFormat));
Assert.IsTrue(DateUtil.IsADateFormat(style.DataFormat, style.GetDataFormatString()));
Assert.IsTrue(DateUtil.IsCellDateFormatted(cell));
}
[Test]
public void ExcelDateBorderCases()
{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Assert.AreEqual(1.0, DateUtil.GetExcelDate(df.Parse("1900-01-01")), 0.00001);
Assert.AreEqual(31.0, DateUtil.GetExcelDate(df.Parse("1900-01-31")), 0.00001);
Assert.AreEqual(32.0, DateUtil.GetExcelDate(df.Parse("1900-02-01")), 0.00001);
Assert.AreEqual(/* BAD_DATE! */ -1.0, DateUtil.GetExcelDate(df.Parse("1899-12-31")), 0.00001);
}
[Test]
public void TestDateBug_2Excel()
{
Assert.AreEqual(59.0, DateUtil.GetExcelDate(new DateTime(1900, CALENDAR_FEBRUARY, 28), false), 1);
Assert.AreEqual(61.0, DateUtil.GetExcelDate(new DateTime(1900, CALENDAR_MARCH, 1), false), 1);
Assert.AreEqual(37315.00, DateUtil.GetExcelDate(new DateTime(2002, CALENDAR_FEBRUARY, 28), false), 1);
Assert.AreEqual(37316.00, DateUtil.GetExcelDate(new DateTime(2002, CALENDAR_MARCH, 1), false), 1);
Assert.AreEqual(37257.00, DateUtil.GetExcelDate(new DateTime(2002, CALENDAR_JANUARY, 1), false), 1);
Assert.AreEqual(38074.00, DateUtil.GetExcelDate(new DateTime(2004, CALENDAR_MARCH, 28), false), 1);
}
[Test]
public void TestDateBug_2Java()
{
Assert.AreEqual(new DateTime(1900, CALENDAR_FEBRUARY, 28), DateUtil.GetJavaDate(59.0, false));
Assert.AreEqual(new DateTime(1900, CALENDAR_MARCH, 1), DateUtil.GetJavaDate(61.0, false));
Assert.AreEqual(new DateTime(2002, CALENDAR_FEBRUARY, 28), DateUtil.GetJavaDate(37315.00, false));
Assert.AreEqual(new DateTime(2002, CALENDAR_MARCH, 1), DateUtil.GetJavaDate(37316.00, false));
Assert.AreEqual(new DateTime(2002, CALENDAR_JANUARY, 1), DateUtil.GetJavaDate(37257.00, false));
Assert.AreEqual(new DateTime(2004, CALENDAR_MARCH, 28), DateUtil.GetJavaDate(38074.00, false));
}
[Test]
public void TestDate1904()
{
Assert.AreEqual(new DateTime(1904, CALENDAR_JANUARY, 2), DateUtil.GetJavaDate(1.0, true));
Assert.AreEqual(new DateTime(1904, CALENDAR_JANUARY, 1), DateUtil.GetJavaDate(0.0, true));
Assert.AreEqual(0.0, DateUtil.GetExcelDate(new DateTime(1904, CALENDAR_JANUARY, 1), true), 0.00001);
Assert.AreEqual(1.0, DateUtil.GetExcelDate(new DateTime(1904, CALENDAR_JANUARY, 2), true), 0.00001);
Assert.AreEqual(new DateTime(1998, CALENDAR_JULY, 5), DateUtil.GetJavaDate(35981, false));
Assert.AreEqual(new DateTime(1998, CALENDAR_JULY, 5), DateUtil.GetJavaDate(34519, true));
Assert.AreEqual(35981.0, DateUtil.GetExcelDate(new DateTime(1998, CALENDAR_JULY, 5), false), 0.00001);
Assert.AreEqual(34519.0, DateUtil.GetExcelDate(new DateTime(1998, CALENDAR_JULY, 5), true), 0.00001);
}
/**
* Check if DateUtil.GetAbsoluteDay works as advertised.
*/
[Test]
public void TestAbsoluteDay()
{
// 1 Jan 1900 is 1 day after 31 Dec 1899
DateTime calendar = new DateTime(1900, 1, 1);
Assert.AreEqual(1, DateUtil.AbsoluteDay(calendar, false), "Checking absolute day (1 Jan 1900)");
// 1 Jan 1901 is 366 days after 31 Dec 1899
calendar = new DateTime(1901, 1, 1);
Assert.AreEqual(366, DateUtil.AbsoluteDay(calendar, false), "Checking absolute day (1 Jan 1901)");
}
[Test]
public void TestConvertTime()
{
double delta = 1E-7; // a couple of digits more accuracy than strictly required
Assert.AreEqual(0.5, DateUtil.ConvertTime("12:00"), delta);
Assert.AreEqual(2.0 / 3, DateUtil.ConvertTime("16:00"), delta);
Assert.AreEqual(0.0000116, DateUtil.ConvertTime("0:00:01"), delta);
Assert.AreEqual(0.7330440, DateUtil.ConvertTime("17:35:35"), delta);
}
[Test]
public void TestParseDate()
{
Assert.AreEqual(new DateTime(2008, 8, 3), DateUtil.ParseYYYYMMDDDate("2008/08/03"));
Assert.AreEqual(new DateTime(1994, 5, 1), DateUtil.ParseYYYYMMDDDate("1994/05/01"));
}
/**
* Ensure that date values *with* a fractional portion get the right time of day
*/
[Test]
public void TestConvertDateTime()
{
// Excel day 30000 is date 18-Feb-1982
// 0.7 corresponds to time 16:48:00
DateTime actual = DateUtil.GetJavaDate(30000.7);
DateTime expected = new DateTime(1982, 2, 18, 16, 48, 0);
Assert.AreEqual(expected, actual);
}
/**
* User reported a datetime issue in POI-2.5:
* Setting Cell's value to Jan 1, 1900 without a time doesn't return the same value Set to
*/
[Test]
public void TestBug19172()
{
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet();
ICell cell = sheet.CreateRow(0).CreateCell(0);
DateTime valueToTest = new DateTime(1900, 1, 1);
cell.SetCellValue(valueToTest);
DateTime returnedValue = cell.DateCellValue;
Assert.AreEqual(valueToTest.TimeOfDay, returnedValue.TimeOfDay);
}
/**
* DateUtil.isCellFormatted(Cell) should not true for a numeric cell
* that's formatted as ".0000"
*/
[Test]
public void TestBug54557()
{
string format = ".0000";
bool isDateFormat = HSSFDateUtil.IsADateFormat(165, format);
Assert.AreEqual(false, isDateFormat);
}
[Test]
public void Bug56269()
{
double excelFraction = 41642.45833321759d;
DateTime calNoRound = HSSFDateUtil.GetJavaCalendar(excelFraction, false);
Assert.AreEqual(10, calNoRound.Hour);
Assert.AreEqual(59, calNoRound.Minute);
Assert.AreEqual(59, calNoRound.Second);
DateTime calRound = HSSFDateUtil.GetJavaCalendar(excelFraction, false, true);
Assert.AreEqual(11, calRound.Hour);
Assert.AreEqual(0, calRound.Minute);
Assert.AreEqual(0, calRound.Second);
}
}
}
| |
// 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;
namespace Microsoft.Scripting.Utils {
/// <summary>
/// Allows wrapping of proxy types (like COM RCWs) to expose their IEnumerable functionality
/// which is supported after casting to IEnumerable, even though Reflection will not indicate
/// IEnumerable as a supported interface
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1010:CollectionsShouldImplementGenericInterface")] // TODO
public class EnumerableWrapper : IEnumerable {
private IEnumerable _wrappedObject;
public EnumerableWrapper(IEnumerable o) {
_wrappedObject = o;
}
public IEnumerator GetEnumerator() {
return _wrappedObject.GetEnumerator();
}
}
public static class CollectionUtils {
public static IEnumerable<T> Cast<S, T>(this IEnumerable<S> sequence) where S : T {
return (IEnumerable<T>)sequence;
}
public static IEnumerable<TSuper> ToCovariant<T, TSuper>(IEnumerable<T> enumerable)
where T : TSuper {
return (IEnumerable<TSuper>)enumerable;
}
public static void AddRange<T>(ICollection<T> collection, IEnumerable<T> items) {
ContractUtils.RequiresNotNull(collection, nameof(collection));
ContractUtils.RequiresNotNull(items, nameof(items));
if (collection is List<T> list) {
list.AddRange(items);
} else {
foreach (T item in items) {
collection.Add(item);
}
}
}
public static void AddRange<T>(this IList<T> list, IEnumerable<T> items) {
foreach (var item in items) {
list.Add(item);
}
}
public static IEnumerable<T> ToEnumerable<T>(IEnumerable enumerable) {
foreach (T item in enumerable) {
yield return item;
}
}
public static IEnumerator<TSuper> ToCovariant<T, TSuper>(IEnumerator<T> enumerator)
where T : TSuper {
ContractUtils.RequiresNotNull(enumerator, nameof(enumerator));
while (enumerator.MoveNext()) {
yield return enumerator.Current;
}
}
private class CovariantConvertor<T, TSuper> : IEnumerable<TSuper> where T : TSuper {
private IEnumerable<T> _enumerable;
public CovariantConvertor(IEnumerable<T> enumerable) {
ContractUtils.RequiresNotNull(enumerable, nameof(enumerable));
_enumerable = enumerable;
}
public IEnumerator<TSuper> GetEnumerator() {
return ToCovariant<T, TSuper>(_enumerable.GetEnumerator());
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
public static IDictionaryEnumerator ToDictionaryEnumerator(IEnumerator<KeyValuePair<object, object>> enumerator) {
return new DictionaryEnumerator(enumerator);
}
private sealed class DictionaryEnumerator : IDictionaryEnumerator {
private readonly IEnumerator<KeyValuePair<object, object>> _enumerator;
public DictionaryEnumerator(IEnumerator<KeyValuePair<object, object>> enumerator) {
_enumerator = enumerator;
}
public DictionaryEntry Entry {
get { return new DictionaryEntry(_enumerator.Current.Key, _enumerator.Current.Value); }
}
public object Key {
get { return _enumerator.Current.Key; }
}
public object Value {
get { return _enumerator.Current.Value; }
}
public object Current {
get { return Entry; }
}
public bool MoveNext() {
return _enumerator.MoveNext();
}
public void Reset() {
_enumerator.Reset();
}
}
public static List<T> MakeList<T>(T item) {
List<T> result = new List<T>();
result.Add(item);
return result;
}
public static int CountOf<T>(IList<T> list, T item) where T : IEquatable<T> {
if (list == null) return 0;
int result = 0;
for (int i = 0; i < list.Count; i++) {
if (list[i].Equals(item)) {
result++;
}
}
return result;
}
public static int Max(this IEnumerable<int> values) {
ContractUtils.RequiresNotNull(values, nameof(values));
int result = Int32.MinValue;
foreach (var value in values) {
if (value > result) {
result = value;
}
}
return result;
}
public static bool TrueForAll<T>(IEnumerable<T> collection, Predicate<T> predicate) {
ContractUtils.RequiresNotNull(collection, nameof(collection));
ContractUtils.RequiresNotNull(predicate, nameof(predicate));
foreach (T item in collection) {
if (!predicate(item)) return false;
}
return true;
}
public static IList<TRet> ConvertAll<T, TRet>(IList<T> collection, Func<T, TRet> predicate) {
ContractUtils.RequiresNotNull(collection, nameof(collection));
ContractUtils.RequiresNotNull(predicate, nameof(predicate));
List<TRet> res = new List<TRet>(collection.Count);
foreach (T item in collection) {
res.Add(predicate(item));
}
return res;
}
public static IEnumerable<TRet> Select<TRet>(this IEnumerable enumerable, Func<object, TRet> selector) {
ContractUtils.RequiresNotNull(enumerable, nameof(enumerable));
ContractUtils.RequiresNotNull(selector, nameof(selector));
foreach (object item in enumerable) {
yield return selector(item);
}
}
public static List<T> GetRange<T>(IList<T> list, int index, int count) {
ContractUtils.RequiresNotNull(list, nameof(list));
ContractUtils.RequiresArrayRange(list, index, count, nameof(index), nameof(count));
List<T> result = new List<T>(count);
int stop = index + count;
for (int i = index; i < stop; i++) {
result.Add(list[i]);
}
return result;
}
public static void InsertRange<T>(IList<T> collection, int index, IEnumerable<T> items) {
ContractUtils.RequiresNotNull(collection, nameof(collection));
ContractUtils.RequiresNotNull(items, nameof(items));
ContractUtils.RequiresArrayInsertIndex(collection, index, nameof(index));
if (collection is List<T> list) {
list.InsertRange(index, items);
} else {
int i = index;
foreach (T obj in items) {
collection.Insert(i++, obj);
}
}
}
public static void RemoveRange<T>(IList<T> collection, int index, int count) {
ContractUtils.RequiresNotNull(collection, nameof(collection));
ContractUtils.RequiresArrayRange(collection, index, count, nameof(index), nameof(count));
if (collection is List<T> list) {
list.RemoveRange(index, count);
} else {
for (int i = index + count - 1; i >= index; i--) {
collection.RemoveAt(i);
}
}
}
public static int FindIndex<T>(this IList<T> collection, Predicate<T> predicate) {
ContractUtils.RequiresNotNull(collection, nameof(collection));
ContractUtils.RequiresNotNull(predicate, nameof(predicate));
for (int i = 0; i < collection.Count; i++) {
if (predicate(collection[i])) {
return i;
}
}
return -1;
}
public static IList<T> ToSortedList<T>(this ICollection<T> collection, Comparison<T> comparison) {
ContractUtils.RequiresNotNull(collection, nameof(collection));
ContractUtils.RequiresNotNull(comparison, nameof(comparison));
var array = new T[collection.Count];
collection.CopyTo(array, 0);
Array.Sort(array, comparison);
return array;
}
public static T[] ToReverseArray<T>(this IList<T> list) {
ContractUtils.RequiresNotNull(list, nameof(list));
T[] result = new T[list.Count];
for (int i = 0; i < result.Length; i++) {
result[i] = list[result.Length - 1 - i];
}
return result;
}
public static IEqualityComparer<HashSet<T>> CreateSetComparer<T>() {
return HashSet<T>.CreateSetComparer();
}
}
}
| |
using System;
using System.Collections.Generic;
using Knowledge.Prospector.Morphology.Grammar;
namespace Knowledge.Prospector.Morphology
{
[Serializable]
public class FlexiaModel
{
/// <summary>
/// Reserved.
/// </summary>
private string Comments;
public Dictionary<string, MorphologicForm> Flexia;
private MorphologicForm firstMF;
private const string FlexiaModelCommDelim = "q//q";
public MorphologicForm FindMorphologicFormByFlex(string flex)
{
return Flexia[flex];
}
public int Count
{
get
{
return Flexia.Keys.Count;
}
}
public string[] GetAllPrefixes()
{
List<string> temp = new List<string>();
foreach (MorphologicForm mf in Flexia.Values)
{
if (mf.PrefixStr != string.Empty)
temp.Add(mf.PrefixStr);
}
return temp.ToArray();
}
public string[] GetAllPrefixesIncludeEmpty()
{
List<string> temp = new List<string>();
temp.Add(string.Empty);
foreach (MorphologicForm mf in Flexia.Values)
{
if (mf.PrefixStr != string.Empty)
temp.Add(mf.PrefixStr);
}
return temp.ToArray();
}
public string[] GetAllFlexes()
{
string[] temp = new string[Flexia.Keys.Count];
Flexia.Keys.CopyTo(temp, 0);
return temp;
}
public bool HasFlex(string flex)
{
return Flexia.ContainsKey(flex);
}
/// <summary>
/// METHOD POTENTIALLY WRONG
/// </summary>
/// <param name="word"></param>
/// <returns></returns>
public MorphologicForm FindMorphologicFormByWord(string word)
{
foreach (MorphologicForm mf in Flexia.Values)
{
if (word.EndsWith(mf.FlexiaStr))
return mf;
}
return new MorphologicForm();
}
#region Equivalence operators and functions
public static bool operator ==(FlexiaModel x, FlexiaModel y)
{
return x.Flexia == y.Flexia;
}
public static bool operator !=(FlexiaModel x, FlexiaModel y)
{
return !(x == y);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(Object obj)
{
// If parameter is null, or cannot be cast to FlexiaModel,
// return false.
if (obj == null) return false;
if (!(obj is FlexiaModel)) return false;
// Return true if the fields match:
return this == (FlexiaModel)obj;
}
public bool Equals(FlexiaModel fm)
{
// If parameter is null, return false:
if ((object)fm == null) return false;
// Return true if the fields match:
return this == fm;
}
#endregion
public bool ReadFromString(string s)
{
Flexia = new Dictionary<string, MorphologicForm>();
int comm = s.IndexOf(FlexiaModelCommDelim);
if (comm != -1)
{
Comments = s.Substring(comm + FlexiaModelCommDelim.Length).Trim();
s.Trim();
}
else
Comments = string.Empty;
string[] forms = s.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i < forms.Length; i++)
{
int ast = forms[i].IndexOf('*');
if (ast == -1) return false;
int last_ast = forms[i].LastIndexOf('*');
MorphologicForm mf;
if (last_ast != ast)
{
string Prefix = forms[i].Substring(last_ast + 1);
mf = new MorphologicForm(forms[i].Substring(ast + 1, last_ast - ast - 1), forms[i].Substring(0, ast), Prefix);
}
else
{
mf = new MorphologicForm(forms[i].Substring(ast + 1), forms[i].Substring(0, ast), string.Empty);
}
if (i==0)
firstMF = mf;
Flexia[mf.FlexiaStr] = mf;
}
return true;
}
public override string ToString()
{
string Result = string.Empty;
foreach(MorphologicForm mf in Flexia.Values)
{
if (mf.PrefixStr != string.Empty)
Result = string.Format("{0}%{1}*{2}*{3}", Result, mf.FlexiaStr, mf.Gramcode, mf.PrefixStr);
else
Result = string.Format("{0}%{1}*{2}", Result, mf.FlexiaStr, mf.Gramcode);
}
if (Comments != string.Empty)
Result += FlexiaModelCommDelim + Comments;
return Result;
}
public string FirstFlex
{
get
{
return firstMF.FlexiaStr;
}
}
public string FirstCode
{
get
{
return firstMF.Gramcode.ToString();
}
}
public MorphologicForm FirstMF
{
get
{
return firstMF;
}
}
public bool HasAncode(AnCode searchedAncode)
{
if (Flexia == null || Flexia.Count == 0)
return false;
foreach(MorphologicForm mf in Flexia.Values)
{
if (mf.Gramcode == searchedAncode)
return true;
}
return false;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography;
using AutoyaFramework;
using AutoyaFramework.AssetBundles;
using AutoyaFramework.Connections.IP;
using AutoyaFramework.Connections.Udp;
using AutoyaFramework.Settings.AssetBundles;
using Miyamasu;
using UnityEngine;
/**
tests for Autoya Udp feature.
*/
public class UdpTests : MiyamasuTestRunner
{
private UdpReceiver udpReceiver;
private UdpSender udpSender;
[MSetup]
public void Setup()
{
}
[MTeardown]
public IEnumerator Teardown()
{
udpReceiver.Close();
udpSender.Close();
yield return new WaitForSeconds(1);
}
[MTest]
public IEnumerator SetReceiverThenSend()
{
var received = false;
var port = 8888;
try
{
udpReceiver = new UdpReceiver(
IP.LocalIPAddressSync(),
port,
bytes =>
{
True(bytes.Length == 4);
received = true;
}
);
// send udp data.
udpSender = new UdpSender(IP.LocalIPAddressSync(), port);
udpSender.Send(new byte[] { 1, 2, 3, 4 });
}
catch (Exception e)
{
Fail("fail, " + e.ToString());
}
yield return WaitUntil(
() => received,
() => { throw new TimeoutException("failed."); }
);
}
[MTest]
public IEnumerator SetReceiverThenSendTwice()
{
var count = 2;
var receivedCount = 0;
var port = 8888;
try
{
udpReceiver = new UdpReceiver(
IP.LocalIPAddressSync(),
port,
bytes =>
{
True(bytes.Length == 4);
receivedCount++;
}
);
// send udp data.
udpSender = new UdpSender(IP.LocalIPAddressSync(), port);
udpSender.Send(new byte[] { 1, 2, 3, 4 });
udpSender.Send(new byte[] { 1, 2, 3, 4 });
}
catch (Exception e)
{
Fail("fail, " + e.ToString());
}
yield return WaitUntil(
() => count == receivedCount,
() => { throw new TimeoutException("failed."); }
);
}
[MTest]
public IEnumerator SetReceiverThenSendManyTimes()
{
var count = 10;
var receivedCount = 0;
var port = 8888;
try
{
udpReceiver = new UdpReceiver(
IP.LocalIPAddressSync(),
port,
bytes =>
{
True(bytes.Length == 4);
receivedCount++;
}
);
// send udp data.
udpSender = new UdpSender(IP.LocalIPAddressSync(), port);
for (var i = 0; i < count; i++)
{
udpSender.Send(new byte[] { 1, 2, 3, 4 });
}
}
catch (Exception e)
{
Fail("fail, " + e.ToString());
}
yield return WaitUntil(
() => count == receivedCount,
() => { throw new TimeoutException("failed. receivedCount:" + receivedCount); }
);
}
[MTest]
public IEnumerator SetReceiverThenSendManyTimesWithValidation()
{
var count = 10;
var receivedCount = 0;
var port = 8888;
try
{
var data = new byte[100];
for (var i = 0; i < data.Length; i++)
{
data[i] = (byte)UnityEngine.Random.Range(byte.MinValue, byte.MaxValue);
}
// validate by hash. checking send data == received data or not.
var md5 = MD5.Create();
var origin = md5.ComputeHash(data);
var hashLen = origin.Length;
// add hash data to head of new data.
var newData = new byte[data.Length + hashLen];
for (var i = 0; i < newData.Length; i++)
{
if (i < hashLen)
{
newData[i] = origin[i];
}
else
{
newData[i] = data[i - hashLen];
}
}
udpReceiver = new UdpReceiver(
IP.LocalIPAddressSync(),
port,
bytes =>
{
True(bytes.Length == newData.Length);
var hash = md5.ComputeHash(bytes, hashLen, bytes.Length - hashLen);
for (var i = 0; i < hash.Length; i++)
{
True(hash[i] == bytes[i]);
}
receivedCount++;
}
);
// send udp data.
udpSender = new UdpSender(IP.LocalIPAddressSync(), port);
for (var i = 0; i < count; i++)
{
udpSender.Send(newData);
}
}
catch (Exception e)
{
Fail(e.ToString());
}
yield return WaitUntil(
() => count == receivedCount,
() => { throw new TimeoutException("failed. receivedCount:" + receivedCount); }
);
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2013 Jacob Dufault
//
// 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 Forge.Utilities;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Forge.Collections {
/// <summary>
/// Interface for objects which are monitoring a specific region within a QuadTree.
/// </summary>
[JsonObject(MemberSerialization.OptIn, IsReference = true)]
public interface IQuadTreeMonitor<T> {
/// <summary>
/// Called when the given item has entered the region.
/// </summary>
void OnEnter(T item);
/// <summary>
/// Called when an item has left the region.
/// </summary>
void OnExit(T item);
}
[JsonObject(MemberSerialization.OptIn)]
internal struct Rect {
[JsonProperty("X0")]
public int X0;
[JsonProperty("Z0")]
public int Z0;
[JsonProperty("X1")]
public int X1;
[JsonProperty("Z1")]
public int Z1;
public Rect(int x0, int z0, int x1, int z1) {
X0 = x0;
Z0 = z0;
X1 = x1;
Z1 = z1;
}
public Rect(Bound bound) {
X0 = (bound.X - bound.Radius).AsInt;
Z0 = (bound.Z - bound.Radius).AsInt;
X1 = (bound.X + bound.Radius).AsInt;
Z1 = (bound.Z + bound.Radius).AsInt;
}
public static Rect Merge(Rect a, Rect b) {
int x0 = Math.Min(a.X0, b.X0);
int z0 = Math.Min(a.Z0, b.Z0);
int x1 = Math.Max(a.X1, b.X1);
int z1 = Math.Max(a.Z1, b.Z1);
return new Rect(x0, z0, x1, z1);
}
/// <summary>
/// Returns true if this rect is either intersecting with or fully contains the parameter
/// rect.
/// </summary>
public bool Colliding(Rect rect) {
bool xCollides =
(InRange(rect.X0, X0, X1)) ||
(InRange(rect.X1, X0, X1));
bool zCollides =
(InRange(rect.Z0, Z0, Z1)) ||
(InRange(rect.Z1, Z0, Z1));
return xCollides && zCollides;
}
/// <summary>
/// Returns true if v is between [min, max).
/// </summary>
private static bool InRange(int v, int min, int max) {
return v >= min && v < max;
}
}
// TODO: the linear searches in this class can be removed by using metadata
[JsonObject(MemberSerialization.OptIn)]
internal class Node<T> {
[JsonObject(MemberSerialization.OptIn)]
private class StoredMonitor {
[JsonProperty("Monitor")]
public IQuadTreeMonitor<T> Monitor;
[JsonProperty("Region")]
public Bound Region;
public StoredMonitor(IQuadTreeMonitor<T> monitor, Bound region) {
Monitor = monitor;
Region = region;
}
}
[JsonObject(MemberSerialization.OptIn)]
private class StoredItem {
[JsonProperty("Item")]
public T Item;
[JsonProperty("Position")]
public Vector2r Position;
public StoredItem(T item, Vector2r position) {
Item = item;
Position = position;
}
}
/// <summary>
/// The items that the node contains
/// </summary>
[JsonProperty("Items")]
private Bag<StoredItem> _items;
/// <summary>
/// The monitors that watch for adds/removes in this node
/// </summary>
[JsonProperty("Monitors")]
private Bag<StoredMonitor> _monitors;
/// <summary>
/// Returns all of the items that are stored in this node.
/// </summary>
public IEnumerable<T> Items {
get {
return from item in _items
select item.Item;
}
}
/// <summary>
/// Returns all of the monitors that are stored in this node.
/// </summary>
public IEnumerable<IQuadTreeMonitor<T>> Monitors {
get {
return from monitor in _monitors
select monitor.Monitor;
}
}
/// <summary>
/// The area that this node is monitoring
/// </summary>
[JsonProperty("MonitoredRegion")]
public Rect MonitoredRegion {
get;
private set;
}
public Node(Rect monitoredRegion) {
MonitoredRegion = monitoredRegion;
_items = new Bag<StoredItem>();
_monitors = new Bag<StoredMonitor>();
}
public void Add(T item, Vector2r position) {
_items.Add(new StoredItem(item, position));
// call OnEnter for all monitors that are interested in the item
for (int i = 0; i < _monitors.Length; ++i) {
StoredMonitor monitor = _monitors[i];
if (monitor.Region.Contains(position)) {
monitor.Monitor.OnEnter(item);
}
}
}
public void Update(T item, Vector2r previous, Vector2r current) {
// update the stored item
for (int i = 0; i < _items.Length; ++i) {
if (ReferenceEquals(_items[i].Item, item)) {
_items[i].Position = current;
break;
}
}
// update the monitors
for (int i = 0; i < _monitors.Length; ++i) {
StoredMonitor monitor = _monitors[i];
bool containedPrevious = monitor.Region.Contains(previous);
bool containedCurrent = monitor.Region.Contains(current);
// the monitor was previously interested but no longer is
if (containedPrevious && containedCurrent == false) {
monitor.Monitor.OnExit(item);
}
// the monitor was not previous interested but now is
else if (containedPrevious == false && containedCurrent) {
monitor.Monitor.OnEnter(item);
}
}
}
public void Remove(T item, Vector2r position) {
// remove the stored item
for (int i = 0; i < _items.Length; ++i) {
if (ReferenceEquals(_items[i].Item, item)) {
_items.Remove(i);
break;
}
}
// call OnExit for all monitors that were previously interested in the item
for (int i = 0; i < _monitors.Length; ++i) {
StoredMonitor monitor = _monitors[i];
if (monitor.Region.Contains(position)) {
monitor.Monitor.OnExit(item);
}
}
}
public void Add(IQuadTreeMonitor<T> monitor, Bound monitoredRegion) {
_monitors.Add(new StoredMonitor(monitor, monitoredRegion));
// check to see if the monitor is interested in any of our stored items
for (int i = 0; i < _items.Length; ++i) {
StoredItem item = _items[i];
if (monitoredRegion.Contains(item.Position)) {
monitor.OnEnter(item.Item);
}
}
}
/// <summary>
/// Adds all of the items inside of this node that are contained within the given region to
/// the given collection.
/// </summary>
/// <param name="region">The area to collect objects from.</param>
/// <param name="storage">Where to store the collected objects.</param>
public void CollectInto(Bound region, ICollection<T> storage) {
for (int i = 0; i < _items.Length; ++i) {
StoredItem item = _items[i];
if (region.Contains(item.Position)) {
storage.Add(item.Item);
}
}
}
public void Update(IQuadTreeMonitor<T> monitor, Bound previousRegion, Bound currentRegion) {
// update the stored monitor
for (int i = 0; i < _monitors.Length; ++i) {
if (ReferenceEquals(_monitors[i].Monitor, monitor)) {
_monitors[i].Region = currentRegion;
break;
}
}
// update the monitor
for (int i = 0; i < _items.Length; ++i) {
StoredItem item = _items[i];
bool containedPrevious = previousRegion.Contains(item.Position);
bool containedCurrent = currentRegion.Contains(item.Position);
// the monitor was previously interested but no longer is
if (containedPrevious && containedCurrent == false) {
monitor.OnExit(item.Item);
}
// the monitor was not previous interested but now is
else if (containedPrevious == false && containedCurrent) {
monitor.OnEnter(item.Item);
}
}
}
public void Remove(IQuadTreeMonitor<T> monitor, Bound monitoredRegion) {
// remove the stored monitor
for (int i = 0; i < _monitors.Length; ++i) {
if (ReferenceEquals(_monitors[i].Monitor, monitor)) {
_monitors.Remove(i);
break;
}
}
// remove all stored items from the monitor
for (int i = 0; i < _items.Length; ++i) {
StoredItem item = _items[i];
if (monitoredRegion.Contains(item.Position)) {
monitor.OnExit(item.Item);
}
}
}
}
/// <summary>
/// Implements a QuadTree, which supports spatial monitoring and spatial querying of
/// positionable objects. The objects can be positioned anywhere, even at negative coordinates.
/// </summary>
/// <remarks>
/// In regards to implementation details, this is not currently a recursive QuadTree. Instead,
/// the world is divided into a set of chunks which can be queried directly. The size of these
/// chunks can be controlled by the constructor parameter.
/// </remarks>
/// <typeparam name="T">The type of object stored in the QuadTree</typeparam>
[JsonObject(MemberSerialization.OptIn)]
public class QuadTree<TItem> {
/// <summary>
/// The width/height of each chunk
/// </summary>
[JsonProperty("WorldScale")]
private int _worldScale;
/// <summary>
/// All of the chunks
/// </summary>
[JsonProperty("Chunks")]
private Node<TItem>[,] _chunks;
/// <summary>
/// Constructs a new QuadTree that is empty.
/// </summary>
/// <param name="worldScale">The size of each node inside of the tree. A larger value will
/// result in faster queries over large areas, but a smaller value will result in faster
/// queries over a smaller area. In general, this should be close to your typical query
/// size.</param>
public QuadTree(int worldScale = 100) {
_worldScale = worldScale;
_chunks = new Node<TItem>[0, 0];
}
#region Query APIs
/// <summary>
/// Returns all monitors that are stored in the tree.
/// </summary>
public IEnumerable<IQuadTreeMonitor<TItem>> Monitors {
get {
var monitors = new HashSet<IQuadTreeMonitor<TItem>>();
foreach (var chunk in _chunks) {
foreach (var monitor in chunk.Monitors) {
monitors.Add(monitor);
}
}
return monitors;
}
}
/// <summary>
/// Returns all items that are stored in the tree.
/// </summary>
public IEnumerable<TItem> Items {
get {
var items = new HashSet<TItem>();
foreach (var chunk in _chunks) {
foreach (var item in chunk.Items) {
items.Add(item);
}
}
return items;
}
}
#endregion
#region Item API
/// <summary>
/// Add a new item to the QuadTree at the given position.
/// </summary>
/// <param name="item">The item to add.</param>
/// <param name="position">The position of the item.</param>
public void AddItem(TItem item, Vector2r position) {
var chunk = GetChunk(position.X.AsInt, position.Z.AsInt);
chunk.Add(item, position);
}
/// <summary>
/// Update the position of an item. This will notify monitors of position updates.
/// </summary>
/// <param name="item">The item to update the position of.</param>
/// <param name="previous">The old position of the item.</param>
/// <param name="current">The updated position of the item.</param>
public void UpdateItem(TItem item, Vector2r previous, Vector2r current) {
var previousChunk = GetChunk(previous.X.AsInt, previous.Z.AsInt);
var currentChunk = GetChunk(current.X.AsInt, current.Z.AsInt);
if (ReferenceEquals(previousChunk, currentChunk)) {
previousChunk.Update(item, previous, current);
}
else {
previousChunk.Remove(item, previous);
currentChunk.Add(item, current);
}
}
/// <summary>
/// Remove an item from the QuadTree.
/// </summary>
/// <param name="item">The item to remove.</param>
/// <param name="position">The position of the item.</param>
public void RemoveItem(TItem item, Vector2r position) {
var chunk = GetChunk(position.X.AsInt, position.Z.AsInt);
chunk.Remove(item, position);
}
/// <summary>
/// Collect all items that are stored inside of the given region.
/// </summary>
/// <param name="region">The area to collect entities from.</param>
/// <param name="storage">Where to store the collected entities.</param>
/// <typeparam name="TCollection">The type of collection to store items in.</typeparam>
/// <returns>All entities that are contained in or intersecting with the given
/// region.</returns>
public TCollection CollectItems<TCollection>(Bound region, TCollection storage = null)
where TCollection : class, ICollection<TItem>, new() {
if (storage == null) {
storage = new TCollection();
}
IterateChunks(region, node => {
node.CollectInto(region, storage);
});
return storage;
}
#endregion
#region Monitor API
/// <summary>
/// Inserts the given monitor into the QuadTree. The monitor will be notified of any
/// entities that enter or leave it. The monitor can be updated or removed.
/// </summary>
/// <param name="monitor">The monitor.</param>
/// <param name="monitoredRegion">The area that the monitor is viewing.</param>
public void AddMonitor(IQuadTreeMonitor<TItem> monitor, Bound monitoredRegion) {
IterateChunks(monitoredRegion, node => {
node.Add(monitor, monitoredRegion);
});
}
/// <summary>
/// Removes the given monitor from the quad tree. It will receive a series of OnExit calls
/// during this Remove call.
/// </summary>
/// <param name="monitor">The monitor to remove.</param>
/// <param name="monitoredRegion">The region that the monitor was monitoring.</param>
public void RemoveMonitor(IQuadTreeMonitor<TItem> monitor, Bound monitoredRegion) {
IterateChunks(monitoredRegion, node => {
node.Remove(monitor, monitoredRegion);
});
}
/// <summary>
/// Update the position of a monitor.
/// </summary>
/// <param name="monitor">The monitor whose position has changed.</param>
/// <param name="previousRegion">The previous area that the monitor was watching.</param>
/// <param name="currentRegion">The new area that the monitor is watching.</param>
public void UpdateMonitor(IQuadTreeMonitor<TItem> monitor, Bound previousRegion, Bound currentRegion) {
// convert the bounds to rectangles
Rect previousRect = new Rect(previousRegion);
Rect currentRect = new Rect(currentRegion);
Rect merged = Rect.Merge(previousRect, currentRect);
IterateChunks(merged, node => {
bool previousContains = previousRect.Colliding(node.MonitoredRegion);
bool currentContains = currentRect.Colliding(node.MonitoredRegion);
// the monitor is no longer interested in this chunk
if (previousContains && currentContains == false) {
node.Remove(monitor, previousRegion);
}
// the monitor is still interested in this chunk
else if (previousContains && currentContains) {
node.Update(monitor, previousRegion, currentRegion);
}
// the monitor is now interested in this chunk, but was not before
else if (previousContains == false && currentContains) {
node.Add(monitor, currentRegion);
}
});
}
#endregion
#region Chunk Management
/// <summary>
/// Helper function to iterate all of the chunks that are contained within the given world
/// region.
/// </summary>
private void IterateChunks(Bound region, Action<Node<TItem>> onChunk) {
IterateChunks(new Rect(region), onChunk);
}
/// <summary>
/// Helper function to iterate all of the chunks that are contained within the given world
/// region.
/// </summary>
private void IterateChunks(Rect region, Action<Node<TItem>> onChunk) {
for (int x = region.X0; x < (region.X1 + _worldScale); x += _worldScale) {
for (int z = region.Z0; z < (region.Z1 + _worldScale); z += _worldScale) {
onChunk(GetChunk(x, z));
}
}
}
/// <summary>
/// Returns the chunk located at the given x and z world coordinates.
/// </summary>
private Node<TItem> GetChunk(int xWorld, int zWorld) {
int xIndex, zIndex;
WorldIndexCoordinateTransform.ConvertWorldToIndex(_worldScale,
xWorld, zWorld, out xIndex, out zIndex);
if (xIndex >= _chunks.GetLength(0) || zIndex >= _chunks.GetLength(1)) {
_chunks = GrowArray(_chunks, xIndex + 1, zIndex + 1, GenerateChunk);
}
return _chunks[xIndex, zIndex];
}
/// <summary>
/// Creates a new chunk located at the given x and z index coordinates.
/// </summary>
private Node<TItem> GenerateChunk(int xIndex, int zIndex) {
int xWorld, zWorld;
WorldIndexCoordinateTransform.ConvertIndexToWorld(_worldScale,
xIndex, zIndex, out xWorld, out zWorld);
Rect rect = new Rect(xWorld, zWorld, xWorld + _worldScale, zWorld + _worldScale);
return new Node<TItem>(rect);
}
/// <summary>
/// Helper method that grows a 2D array and populates new elements with values created from
/// the generator.
/// </summary>
private static T[,] GrowArray<T>(T[,] original, int newLengthX, int newLengthZ, Func<int, int, T> generator) {
var newArray = new T[newLengthX, newLengthZ];
int originalLengthX = original.GetLength(0);
int originalLengthZ = original.GetLength(1);
for (int x = 0; x < newLengthX; x++) {
for (int z = 0; z < newLengthZ; z++) {
T stored;
if (x >= originalLengthX || z >= originalLengthZ) {
stored = generator(x, z);
}
else {
stored = original[x, z];
}
newArray[x, z] = stored;
}
}
return newArray;
}
#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.
// Don't entity encode high chars (160 to 256)
#define ENTITY_ENCODE_HIGH_ASCII_CHARS
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.Net
{
public static class WebUtility
{
// some consts copied from Char / CharUnicodeInfo since we don't have friend access to those types
private const char HIGH_SURROGATE_START = '\uD800';
private const char LOW_SURROGATE_START = '\uDC00';
private const char LOW_SURROGATE_END = '\uDFFF';
private const int UNICODE_PLANE00_END = 0x00FFFF;
private const int UNICODE_PLANE01_START = 0x10000;
private const int UNICODE_PLANE16_END = 0x10FFFF;
private const int UnicodeReplacementChar = '\uFFFD';
#region HtmlEncode / HtmlDecode methods
private static readonly char[] s_htmlEntityEndingChars = new char[] { ';', '&' };
public static string HtmlEncode(string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
// Don't create StringBuilder if we don't have anything to encode
int index = IndexOfHtmlEncodingChars(value, 0);
if (index == -1)
{
return value;
}
StringBuilder sb = StringBuilderCache.Acquire(value.Length);
HtmlEncode(value, index, sb);
return StringBuilderCache.GetStringAndRelease(sb);
}
public static void HtmlEncode(string value, TextWriter output)
{
output.Write(HtmlEncode(value));
}
private static unsafe void HtmlEncode(string value, int index, StringBuilder output)
{
Debug.Assert(value != null);
Debug.Assert(output != null);
Debug.Assert(0 <= index && index <= value.Length, "0 <= index && index <= value.Length");
int cch = value.Length - index;
fixed (char* str = value)
{
char* pch = str;
while (index-- > 0)
{
output.Append(*pch++);
}
for (; cch > 0; cch--, pch++)
{
char ch = *pch;
if (ch <= '>')
{
switch (ch)
{
case '<':
output.Append("<");
break;
case '>':
output.Append(">");
break;
case '"':
output.Append(""");
break;
case '\'':
output.Append("'");
break;
case '&':
output.Append("&");
break;
default:
output.Append(ch);
break;
}
}
else
{
int valueToEncode = -1; // set to >= 0 if needs to be encoded
#if ENTITY_ENCODE_HIGH_ASCII_CHARS
if (ch >= 160 && ch < 256)
{
// The seemingly arbitrary 160 comes from RFC
valueToEncode = ch;
}
else
#endif // ENTITY_ENCODE_HIGH_ASCII_CHARS
if (Char.IsSurrogate(ch))
{
int scalarValue = GetNextUnicodeScalarValueFromUtf16Surrogate(ref pch, ref cch);
if (scalarValue >= UNICODE_PLANE01_START)
{
valueToEncode = scalarValue;
}
else
{
// Don't encode BMP characters (like U+FFFD) since they wouldn't have
// been encoded if explicitly present in the string anyway.
ch = (char)scalarValue;
}
}
if (valueToEncode >= 0)
{
// value needs to be encoded
output.Append("&#");
output.Append(valueToEncode.ToString(CultureInfo.InvariantCulture));
output.Append(';');
}
else
{
// write out the character directly
output.Append(ch);
}
}
}
}
}
public static string HtmlDecode(string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
// Don't create StringBuilder if we don't have anything to encode
if (!StringRequiresHtmlDecoding(value))
{
return value;
}
StringBuilder sb = StringBuilderCache.Acquire(value.Length);
HtmlDecode(value, sb);
return StringBuilderCache.GetStringAndRelease(sb);
}
public static void HtmlDecode(string value, TextWriter output)
{
output.Write(HtmlDecode(value));
}
[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.UInt16.TryParse(System.String,System.Globalization.NumberStyles,System.IFormatProvider,System.UInt16@)", Justification = "UInt16.TryParse guarantees that result is zero if the parse fails.")]
private static void HtmlDecode(string value, StringBuilder output)
{
Debug.Assert(output != null);
int l = value.Length;
for (int i = 0; i < l; i++)
{
char ch = value[i];
if (ch == '&')
{
// We found a '&'. Now look for the next ';' or '&'. The idea is that
// if we find another '&' before finding a ';', then this is not an entity,
// and the next '&' might start a real entity (VSWhidbey 275184)
int index = value.IndexOfAny(s_htmlEntityEndingChars, i + 1);
if (index > 0 && value[index] == ';')
{
int entityOffset = i + 1;
int entityLength = index - entityOffset;
if (entityLength > 1 && value[entityOffset] == '#')
{
// The # syntax can be in decimal or hex, e.g.
// å --> decimal
// å --> same char in hex
// See http://www.w3.org/TR/REC-html40/charset.html#entities
bool parsedSuccessfully;
uint parsedValue;
if (value[entityOffset + 1] == 'x' || value[entityOffset + 1] == 'X')
{
parsedSuccessfully = uint.TryParse(value.Substring(entityOffset + 2, entityLength - 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out parsedValue);
}
else
{
parsedSuccessfully = uint.TryParse(value.Substring(entityOffset + 1, entityLength - 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedValue);
}
if (parsedSuccessfully)
{
// decoded character must be U+0000 .. U+10FFFF, excluding surrogates
parsedSuccessfully = ((parsedValue < HIGH_SURROGATE_START) || (LOW_SURROGATE_END < parsedValue && parsedValue <= UNICODE_PLANE16_END));
}
if (parsedSuccessfully)
{
if (parsedValue <= UNICODE_PLANE00_END)
{
// single character
output.Append((char)parsedValue);
}
else
{
// multi-character
char leadingSurrogate, trailingSurrogate;
ConvertSmpToUtf16(parsedValue, out leadingSurrogate, out trailingSurrogate);
output.Append(leadingSurrogate);
output.Append(trailingSurrogate);
}
i = index; // already looked at everything until semicolon
continue;
}
}
else
{
string entity = value.Substring(entityOffset, entityLength);
i = index; // already looked at everything until semicolon
char entityChar = HtmlEntities.Lookup(entity);
if (entityChar != (char)0)
{
ch = entityChar;
}
else
{
output.Append('&');
output.Append(entity);
output.Append(';');
continue;
}
}
}
}
output.Append(ch);
}
}
private static unsafe int IndexOfHtmlEncodingChars(string s, int startPos)
{
Debug.Assert(0 <= startPos && startPos <= s.Length, "0 <= startPos && startPos <= s.Length");
int cch = s.Length - startPos;
fixed (char* str = s)
{
for (char* pch = &str[startPos]; cch > 0; pch++, cch--)
{
char ch = *pch;
if (ch <= '>')
{
switch (ch)
{
case '<':
case '>':
case '"':
case '\'':
case '&':
return s.Length - cch;
}
}
#if ENTITY_ENCODE_HIGH_ASCII_CHARS
else if (ch >= 160 && ch < 256)
{
return s.Length - cch;
}
#endif // ENTITY_ENCODE_HIGH_ASCII_CHARS
else if (Char.IsSurrogate(ch))
{
return s.Length - cch;
}
}
}
return -1;
}
#endregion
#region UrlEncode implementation
private static void GetEncodedBytes(byte[] originalBytes, int offset, int count, byte[] expandedBytes)
{
int pos = 0;
int end = offset + count;
Debug.Assert(offset < end && end <= originalBytes.Length);
for (int i = offset; i < end; i++)
{
#if DEBUG
// Make sure we never overwrite any bytes if originalBytes and
// expandedBytes refer to the same array
if (originalBytes == expandedBytes)
{
Debug.Assert(i >= pos);
}
#endif
byte b = originalBytes[i];
char ch = (char)b;
if (IsUrlSafeChar(ch))
{
expandedBytes[pos++] = b;
}
else if (ch == ' ')
{
expandedBytes[pos++] = (byte)'+';
}
else
{
expandedBytes[pos++] = (byte)'%';
expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf);
expandedBytes[pos++] = (byte)IntToHex(b & 0x0f);
}
}
}
#endregion
#region UrlEncode public methods
[SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Already shipped public API; code moved here as part of API consolidation")]
public static string UrlEncode(string value)
{
if (string.IsNullOrEmpty(value))
return value;
int safeCount = 0;
int spaceCount = 0;
for (int i = 0; i < value.Length; i++)
{
char ch = value[i];
if (IsUrlSafeChar(ch))
{
safeCount++;
}
else if (ch == ' ')
{
spaceCount++;
}
}
int unexpandedCount = safeCount + spaceCount;
if (unexpandedCount == value.Length)
{
if (spaceCount != 0)
{
// Only spaces to encode
return value.Replace(' ', '+');
}
// Nothing to expand
return value;
}
int byteCount = Encoding.UTF8.GetByteCount(value);
int unsafeByteCount = byteCount - unexpandedCount;
int byteIndex = unsafeByteCount * 2;
// Instead of allocating one array of length `byteCount` to store
// the UTF-8 encoded bytes, and then a second array of length
// `3 * byteCount - 2 * unexpandedCount`
// to store the URL-encoded UTF-8 bytes, we allocate a single array of
// the latter and encode the data in place, saving the first allocation.
// We store the UTF-8 bytes to the end of this array, and then URL encode to the
// beginning of the array.
byte[] newBytes = new byte[byteCount + byteIndex];
Encoding.UTF8.GetBytes(value, 0, value.Length, newBytes, byteIndex);
GetEncodedBytes(newBytes, byteIndex, byteCount, newBytes);
return Encoding.UTF8.GetString(newBytes);
}
public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count)
{
if (!ValidateUrlEncodingParameters(value, offset, count))
{
return null;
}
bool foundSpaces = false;
int unsafeCount = 0;
// count them first
for (int i = 0; i < count; i++)
{
char ch = (char)value[offset + i];
if (ch == ' ')
foundSpaces = true;
else if (!IsUrlSafeChar(ch))
unsafeCount++;
}
// nothing to expand?
if (!foundSpaces && unsafeCount == 0)
{
var subarray = new byte[count];
Buffer.BlockCopy(value, offset, subarray, 0, count);
return subarray;
}
// expand not 'safe' characters into %XX, spaces to +s
byte[] expandedBytes = new byte[count + unsafeCount * 2];
GetEncodedBytes(value, offset, count, expandedBytes);
return expandedBytes;
}
#endregion
#region UrlDecode implementation
private static string UrlDecodeInternal(string value, Encoding encoding)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
int count = value.Length;
UrlDecoder helper = new UrlDecoder(count, encoding);
// go through the string's chars collapsing %XX and
// appending each char as char, with exception of %XX constructs
// that are appended as bytes
bool needsDecodingUnsafe = false;
bool needsDecodingSpaces = false;
for (int pos = 0; pos < count; pos++)
{
char ch = value[pos];
if (ch == '+')
{
needsDecodingSpaces = true;
ch = ' ';
}
else if (ch == '%' && pos < count - 2)
{
int h1 = HexToInt(value[pos + 1]);
int h2 = HexToInt(value[pos + 2]);
if (h1 >= 0 && h2 >= 0)
{ // valid 2 hex chars
byte b = (byte)((h1 << 4) | h2);
pos += 2;
// don't add as char
helper.AddByte(b);
needsDecodingUnsafe = true;
continue;
}
}
if ((ch & 0xFF80) == 0)
helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode
else
helper.AddChar(ch);
}
if (!needsDecodingUnsafe)
{
if (needsDecodingSpaces)
{
// Only spaces to decode
return value.Replace('+', ' ');
}
// Nothing to decode
return value;
}
return helper.GetString();
}
private static byte[] UrlDecodeInternal(byte[] bytes, int offset, int count)
{
if (!ValidateUrlEncodingParameters(bytes, offset, count))
{
return null;
}
int decodedBytesCount = 0;
byte[] decodedBytes = new byte[count];
for (int i = 0; i < count; i++)
{
int pos = offset + i;
byte b = bytes[pos];
if (b == '+')
{
b = (byte)' ';
}
else if (b == '%' && i < count - 2)
{
int h1 = HexToInt((char)bytes[pos + 1]);
int h2 = HexToInt((char)bytes[pos + 2]);
if (h1 >= 0 && h2 >= 0)
{ // valid 2 hex chars
b = (byte)((h1 << 4) | h2);
i += 2;
}
}
decodedBytes[decodedBytesCount++] = b;
}
if (decodedBytesCount < decodedBytes.Length)
{
Array.Resize(ref decodedBytes, decodedBytesCount);
}
return decodedBytes;
}
#endregion
#region UrlDecode public methods
[SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Already shipped public API; code moved here as part of API consolidation")]
public static string UrlDecode(string encodedValue)
{
return UrlDecodeInternal(encodedValue, Encoding.UTF8);
}
public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count)
{
return UrlDecodeInternal(encodedValue, offset, count);
}
#endregion
#region Helper methods
// similar to Char.ConvertFromUtf32, but doesn't check arguments or generate strings
// input is assumed to be an SMP character
private static void ConvertSmpToUtf16(uint smpChar, out char leadingSurrogate, out char trailingSurrogate)
{
Debug.Assert(UNICODE_PLANE01_START <= smpChar && smpChar <= UNICODE_PLANE16_END);
int utf32 = (int)(smpChar - UNICODE_PLANE01_START);
leadingSurrogate = (char)((utf32 / 0x400) + HIGH_SURROGATE_START);
trailingSurrogate = (char)((utf32 % 0x400) + LOW_SURROGATE_START);
}
private static unsafe int GetNextUnicodeScalarValueFromUtf16Surrogate(ref char* pch, ref int charsRemaining)
{
// invariants
Debug.Assert(charsRemaining >= 1);
Debug.Assert(Char.IsSurrogate(*pch));
if (charsRemaining <= 1)
{
// not enough characters remaining to resurrect the original scalar value
return UnicodeReplacementChar;
}
char leadingSurrogate = pch[0];
char trailingSurrogate = pch[1];
if (Char.IsSurrogatePair(leadingSurrogate, trailingSurrogate))
{
// we're going to consume an extra char
pch++;
charsRemaining--;
// below code is from Char.ConvertToUtf32, but without the checks (since we just performed them)
return (((leadingSurrogate - HIGH_SURROGATE_START) * 0x400) + (trailingSurrogate - LOW_SURROGATE_START) + UNICODE_PLANE01_START);
}
else
{
// unmatched surrogate
return UnicodeReplacementChar;
}
}
private static int HexToInt(char h)
{
return (h >= '0' && h <= '9') ? h - '0' :
(h >= 'a' && h <= 'f') ? h - 'a' + 10 :
(h >= 'A' && h <= 'F') ? h - 'A' + 10 :
-1;
}
private static char IntToHex(int n)
{
Debug.Assert(n < 0x10);
if (n <= 9)
return (char)(n + (int)'0');
else
return (char)(n - 10 + (int)'A');
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsUrlSafeChar(char ch)
{
// Set of safe chars, from RFC 1738.4 minus '+'
/*
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9')
return true;
switch (ch)
{
case '-':
case '_':
case '.':
case '!':
case '*':
case '(':
case ')':
return true;
}
return false;
*/
// Optimized version of the above:
int code = (int)ch;
const int safeSpecialCharMask = 0x03FF0000 | // 0..9
1 << ((int)'!' - 0x20) | // 0x21
1 << ((int)'(' - 0x20) | // 0x28
1 << ((int)')' - 0x20) | // 0x29
1 << ((int)'*' - 0x20) | // 0x2A
1 << ((int)'-' - 0x20) | // 0x2D
1 << ((int)'.' - 0x20); // 0x2E
unchecked
{
return ((uint)(code - 'a') <= (uint)('z' - 'a')) ||
((uint)(code - 'A') <= (uint)('Z' - 'A')) ||
((uint)(code - 0x20) <= (uint)('9' - 0x20) && ((1 << (code - 0x20)) & safeSpecialCharMask) != 0) ||
(code == (int)'_');
}
}
private static bool ValidateUrlEncodingParameters(byte[] bytes, int offset, int count)
{
if (bytes == null && count == 0)
return false;
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes));
}
if (offset < 0 || offset > bytes.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || offset + count > bytes.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
return true;
}
private static bool StringRequiresHtmlDecoding(string s)
{
// this string requires html decoding if it contains '&' or a surrogate character
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (c == '&' || Char.IsSurrogate(c))
{
return true;
}
}
return false;
}
#endregion
// Internal struct to facilitate URL decoding -- keeps char buffer and byte buffer, allows appending of either chars or bytes
private struct UrlDecoder
{
private int _bufferSize;
// Accumulate characters in a special array
private int _numChars;
private char[] _charBuffer;
// Accumulate bytes for decoding into characters in a special array
private int _numBytes;
private byte[] _byteBuffer;
// Encoding to convert chars to bytes
private Encoding _encoding;
private void FlushBytes()
{
Debug.Assert(_numBytes > 0);
if (_charBuffer == null)
_charBuffer = new char[_bufferSize];
_numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars);
_numBytes = 0;
}
internal UrlDecoder(int bufferSize, Encoding encoding)
{
_bufferSize = bufferSize;
_encoding = encoding;
_charBuffer = null; // char buffer created on demand
_numChars = 0;
_numBytes = 0;
_byteBuffer = null; // byte buffer created on demand
}
internal void AddChar(char ch)
{
if (_numBytes > 0)
FlushBytes();
if (_charBuffer == null)
_charBuffer = new char[_bufferSize];
_charBuffer[_numChars++] = ch;
}
internal void AddByte(byte b)
{
if (_byteBuffer == null)
_byteBuffer = new byte[_bufferSize];
_byteBuffer[_numBytes++] = b;
}
internal String GetString()
{
if (_numBytes > 0)
FlushBytes();
Debug.Assert(_numChars > 0);
return new string(_charBuffer, 0, _numChars);
}
}
// helper class for lookup of HTML encoding entities
private static class HtmlEntities
{
#if DEBUG
static HtmlEntities()
{
// Make sure the initial capacity for s_lookupTable is correct
Debug.Assert(s_lookupTable.Count == Count, $"There should be {Count} HTML entities, but {nameof(s_lookupTable)} has {s_lookupTable.Count} of them.");
}
#endif
// The list is from http://www.w3.org/TR/REC-html40/sgml/entities.html, except for ', which
// is defined in http://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent.
private const int Count = 253;
// maps entity strings => unicode chars
private static readonly LowLevelDictionary<string, char> s_lookupTable =
new LowLevelDictionary<string, char>(Count, StringComparer.Ordinal)
{
["quot"] = '\x0022',
["amp"] = '\x0026',
["apos"] = '\x0027',
["lt"] = '\x003c',
["gt"] = '\x003e',
["nbsp"] = '\x00a0',
["iexcl"] = '\x00a1',
["cent"] = '\x00a2',
["pound"] = '\x00a3',
["curren"] = '\x00a4',
["yen"] = '\x00a5',
["brvbar"] = '\x00a6',
["sect"] = '\x00a7',
["uml"] = '\x00a8',
["copy"] = '\x00a9',
["ordf"] = '\x00aa',
["laquo"] = '\x00ab',
["not"] = '\x00ac',
["shy"] = '\x00ad',
["reg"] = '\x00ae',
["macr"] = '\x00af',
["deg"] = '\x00b0',
["plusmn"] = '\x00b1',
["sup2"] = '\x00b2',
["sup3"] = '\x00b3',
["acute"] = '\x00b4',
["micro"] = '\x00b5',
["para"] = '\x00b6',
["middot"] = '\x00b7',
["cedil"] = '\x00b8',
["sup1"] = '\x00b9',
["ordm"] = '\x00ba',
["raquo"] = '\x00bb',
["frac14"] = '\x00bc',
["frac12"] = '\x00bd',
["frac34"] = '\x00be',
["iquest"] = '\x00bf',
["Agrave"] = '\x00c0',
["Aacute"] = '\x00c1',
["Acirc"] = '\x00c2',
["Atilde"] = '\x00c3',
["Auml"] = '\x00c4',
["Aring"] = '\x00c5',
["AElig"] = '\x00c6',
["Ccedil"] = '\x00c7',
["Egrave"] = '\x00c8',
["Eacute"] = '\x00c9',
["Ecirc"] = '\x00ca',
["Euml"] = '\x00cb',
["Igrave"] = '\x00cc',
["Iacute"] = '\x00cd',
["Icirc"] = '\x00ce',
["Iuml"] = '\x00cf',
["ETH"] = '\x00d0',
["Ntilde"] = '\x00d1',
["Ograve"] = '\x00d2',
["Oacute"] = '\x00d3',
["Ocirc"] = '\x00d4',
["Otilde"] = '\x00d5',
["Ouml"] = '\x00d6',
["times"] = '\x00d7',
["Oslash"] = '\x00d8',
["Ugrave"] = '\x00d9',
["Uacute"] = '\x00da',
["Ucirc"] = '\x00db',
["Uuml"] = '\x00dc',
["Yacute"] = '\x00dd',
["THORN"] = '\x00de',
["szlig"] = '\x00df',
["agrave"] = '\x00e0',
["aacute"] = '\x00e1',
["acirc"] = '\x00e2',
["atilde"] = '\x00e3',
["auml"] = '\x00e4',
["aring"] = '\x00e5',
["aelig"] = '\x00e6',
["ccedil"] = '\x00e7',
["egrave"] = '\x00e8',
["eacute"] = '\x00e9',
["ecirc"] = '\x00ea',
["euml"] = '\x00eb',
["igrave"] = '\x00ec',
["iacute"] = '\x00ed',
["icirc"] = '\x00ee',
["iuml"] = '\x00ef',
["eth"] = '\x00f0',
["ntilde"] = '\x00f1',
["ograve"] = '\x00f2',
["oacute"] = '\x00f3',
["ocirc"] = '\x00f4',
["otilde"] = '\x00f5',
["ouml"] = '\x00f6',
["divide"] = '\x00f7',
["oslash"] = '\x00f8',
["ugrave"] = '\x00f9',
["uacute"] = '\x00fa',
["ucirc"] = '\x00fb',
["uuml"] = '\x00fc',
["yacute"] = '\x00fd',
["thorn"] = '\x00fe',
["yuml"] = '\x00ff',
["OElig"] = '\x0152',
["oelig"] = '\x0153',
["Scaron"] = '\x0160',
["scaron"] = '\x0161',
["Yuml"] = '\x0178',
["fnof"] = '\x0192',
["circ"] = '\x02c6',
["tilde"] = '\x02dc',
["Alpha"] = '\x0391',
["Beta"] = '\x0392',
["Gamma"] = '\x0393',
["Delta"] = '\x0394',
["Epsilon"] = '\x0395',
["Zeta"] = '\x0396',
["Eta"] = '\x0397',
["Theta"] = '\x0398',
["Iota"] = '\x0399',
["Kappa"] = '\x039a',
["Lambda"] = '\x039b',
["Mu"] = '\x039c',
["Nu"] = '\x039d',
["Xi"] = '\x039e',
["Omicron"] = '\x039f',
["Pi"] = '\x03a0',
["Rho"] = '\x03a1',
["Sigma"] = '\x03a3',
["Tau"] = '\x03a4',
["Upsilon"] = '\x03a5',
["Phi"] = '\x03a6',
["Chi"] = '\x03a7',
["Psi"] = '\x03a8',
["Omega"] = '\x03a9',
["alpha"] = '\x03b1',
["beta"] = '\x03b2',
["gamma"] = '\x03b3',
["delta"] = '\x03b4',
["epsilon"] = '\x03b5',
["zeta"] = '\x03b6',
["eta"] = '\x03b7',
["theta"] = '\x03b8',
["iota"] = '\x03b9',
["kappa"] = '\x03ba',
["lambda"] = '\x03bb',
["mu"] = '\x03bc',
["nu"] = '\x03bd',
["xi"] = '\x03be',
["omicron"] = '\x03bf',
["pi"] = '\x03c0',
["rho"] = '\x03c1',
["sigmaf"] = '\x03c2',
["sigma"] = '\x03c3',
["tau"] = '\x03c4',
["upsilon"] = '\x03c5',
["phi"] = '\x03c6',
["chi"] = '\x03c7',
["psi"] = '\x03c8',
["omega"] = '\x03c9',
["thetasym"] = '\x03d1',
["upsih"] = '\x03d2',
["piv"] = '\x03d6',
["ensp"] = '\x2002',
["emsp"] = '\x2003',
["thinsp"] = '\x2009',
["zwnj"] = '\x200c',
["zwj"] = '\x200d',
["lrm"] = '\x200e',
["rlm"] = '\x200f',
["ndash"] = '\x2013',
["mdash"] = '\x2014',
["lsquo"] = '\x2018',
["rsquo"] = '\x2019',
["sbquo"] = '\x201a',
["ldquo"] = '\x201c',
["rdquo"] = '\x201d',
["bdquo"] = '\x201e',
["dagger"] = '\x2020',
["Dagger"] = '\x2021',
["bull"] = '\x2022',
["hellip"] = '\x2026',
["permil"] = '\x2030',
["prime"] = '\x2032',
["Prime"] = '\x2033',
["lsaquo"] = '\x2039',
["rsaquo"] = '\x203a',
["oline"] = '\x203e',
["frasl"] = '\x2044',
["euro"] = '\x20ac',
["image"] = '\x2111',
["weierp"] = '\x2118',
["real"] = '\x211c',
["trade"] = '\x2122',
["alefsym"] = '\x2135',
["larr"] = '\x2190',
["uarr"] = '\x2191',
["rarr"] = '\x2192',
["darr"] = '\x2193',
["harr"] = '\x2194',
["crarr"] = '\x21b5',
["lArr"] = '\x21d0',
["uArr"] = '\x21d1',
["rArr"] = '\x21d2',
["dArr"] = '\x21d3',
["hArr"] = '\x21d4',
["forall"] = '\x2200',
["part"] = '\x2202',
["exist"] = '\x2203',
["empty"] = '\x2205',
["nabla"] = '\x2207',
["isin"] = '\x2208',
["notin"] = '\x2209',
["ni"] = '\x220b',
["prod"] = '\x220f',
["sum"] = '\x2211',
["minus"] = '\x2212',
["lowast"] = '\x2217',
["radic"] = '\x221a',
["prop"] = '\x221d',
["infin"] = '\x221e',
["ang"] = '\x2220',
["and"] = '\x2227',
["or"] = '\x2228',
["cap"] = '\x2229',
["cup"] = '\x222a',
["int"] = '\x222b',
["there4"] = '\x2234',
["sim"] = '\x223c',
["cong"] = '\x2245',
["asymp"] = '\x2248',
["ne"] = '\x2260',
["equiv"] = '\x2261',
["le"] = '\x2264',
["ge"] = '\x2265',
["sub"] = '\x2282',
["sup"] = '\x2283',
["nsub"] = '\x2284',
["sube"] = '\x2286',
["supe"] = '\x2287',
["oplus"] = '\x2295',
["otimes"] = '\x2297',
["perp"] = '\x22a5',
["sdot"] = '\x22c5',
["lceil"] = '\x2308',
["rceil"] = '\x2309',
["lfloor"] = '\x230a',
["rfloor"] = '\x230b',
["lang"] = '\x2329',
["rang"] = '\x232a',
["loz"] = '\x25ca',
["spades"] = '\x2660',
["clubs"] = '\x2663',
["hearts"] = '\x2665',
["diams"] = '\x2666',
};
public static char Lookup(string entity)
{
char theChar;
s_lookupTable.TryGetValue(entity, out theChar);
return theChar;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.QTKit;
using System.IO;
using MonoMac.CoreImage;
using System.Text;
namespace QTRecorder
{
public partial class QTRDocument : MonoMac.AppKit.NSDocument
{
QTCaptureSession session;
QTCaptureDeviceInput videoDeviceInput, audioDeviceInput;
QTCaptureMovieFileOutput movieFileOutput;
QTCaptureAudioPreviewOutput audioPreviewOutput;
public QTRDocument ()
{
}
[Export("initWithCoder:")]
public QTRDocument (NSCoder coder) : base(coder)
{
}
public override void WindowControllerDidLoadNib (NSWindowController windowController)
{
NSError error;
base.WindowControllerDidLoadNib (windowController);
// Create session
session = new QTCaptureSession ();
// Attach preview to session
captureView.CaptureSession = session;
captureView.WillDisplayImage = (view, image) => {
if (videoPreviewFilterDescription == null)
return image;
var selectedFilter = (NSString) videoPreviewFilterDescription [filterNameKey];
var filter = CIFilter.FromName (selectedFilter);
filter.SetDefaults ();
filter.SetValueForKey (image, CIFilter.InputImageKey);
return (CIImage) filter.ValueForKey (CIFilter.OutputImageKey);
};
// Attach outputs to session
movieFileOutput = new QTCaptureMovieFileOutput ();
movieFileOutput.WillStartRecording += delegate {
Console.WriteLine ("Will start recording");
};
movieFileOutput.DidStartRecording += delegate {
Console.WriteLine ("Started Recording");
};
movieFileOutput.ShouldChangeOutputFile = (output, url, connections, reason) => {
// Should change the file on error
Console.WriteLine (reason.LocalizedDescription);
return false;
};
movieFileOutput.MustChangeOutputFile += delegate(object sender, QTCaptureFileErrorEventArgs e) {
Console.WriteLine ("Must change file due to error");
};
// These ones we care about, some notifications
movieFileOutput.WillFinishRecording += delegate(object sender, QTCaptureFileErrorEventArgs e) {
Console.WriteLine ("Will finish recording");
InvokeOnMainThread (delegate {
WillChangeValue ("Recording");
});
};
movieFileOutput.DidFinishRecording += delegate(object sender, QTCaptureFileErrorEventArgs e) {
Console.WriteLine ("Recorded {0} bytes duration {1}", movieFileOutput.RecordedFileSize, movieFileOutput.RecordedDuration);
DidChangeValue ("Recording");
if (e.Reason != null){
NSAlert.WithError (e.Reason).BeginSheet (Window, delegate {});
return;
}
var save = NSSavePanel.SavePanel;
save.RequiredFileType = "mov";
save.CanSelectHiddenExtension = true;
save.Begin (code => {
NSError err2;
if (code == (int) NSPanelButtonType.Ok){
var filename = save.Filename;
NSFileManager.DefaultManager.Move (e.OutputFileURL.Path, filename, out err2);
} else {
NSFileManager.DefaultManager.Remove (e.OutputFileURL.Path, out err2);
}
});
};
session.AddOutput (movieFileOutput, out error);
audioPreviewOutput = new QTCaptureAudioPreviewOutput ();
session.AddOutput (audioPreviewOutput, out error);
if (VideoDevices.Length > 0)
SelectedVideoDevice = VideoDevices [0];
if (AudioDevices.Length > 0)
SelectedAudioDevice = AudioDevices [0];
session.StartRunning ();
// events: devices added/removed
AddObserver (QTCaptureDevice.WasConnectedNotification, DevicesDidChange);
AddObserver (QTCaptureDevice.WasDisconnectedNotification, DevicesDidChange);
// events: connection format changes
AddObserver (QTCaptureConnection.FormatDescriptionDidChangeNotification, FormatDidChange);
AddObserver (QTCaptureConnection.FormatDescriptionWillChangeNotification, FormatWillChange);
AddObserver (QTCaptureDevice.AttributeDidChangeNotification, AttributeDidChange);
AddObserver (QTCaptureDevice.AttributeWillChangeNotification, AttributeWillChange);
}
List<NSObject> notifications = new List<NSObject> ();
void AddObserver (NSString key, Action<NSNotification> notification)
{
notifications.Add (NSNotificationCenter.DefaultCenter.AddObserver (key, notification));
}
NSWindow Window {
get {
return WindowControllers [0].Window;
}
}
protected override void Dispose (bool disposing)
{
if (disposing){
NSNotificationCenter.DefaultCenter.RemoveObservers (notifications);
notifications = null;
}
base.Dispose (disposing);
}
//
// Save support:
// Override one of GetAsData, GetAsFileWrapper, or WriteToUrl.
//
// This method should store the contents of the document using the given typeName
// on the return NSData value.
public override NSData GetAsData (string documentType, out NSError outError)
{
outError = NSError.FromDomain (NSError.OsStatusErrorDomain, -4);
return null;
}
//
// Load support:
// Override one of ReadFromData, ReadFromFileWrapper or ReadFromUrl
//
public override bool ReadFromData (NSData data, string typeName, out NSError outError)
{
outError = NSError.FromDomain (NSError.OsStatusErrorDomain, -4);
return false;
}
// Not available until we bind CIFilter
string [] filterNames = new string [] {
"CIKaleidoscope", "CIGaussianBlur", "CIZoomBlur",
"CIColorInvert", "CISepiaTone", "CIBumpDistortion",
"CICircularWrap", "CIHoleDistortion", "CITorusLensDistortion",
"CITwirlDistortion", "CIVortexDistortion", "CICMYKHalftone",
"CIColorPosterize", "CIDotScreen", "CIHatchedScreen",
"CIBloom", "CICrystallize", "CIEdges",
"CIEdgeWork", "CIGloom", "CIPixellate",
};
static NSString filterNameKey = new NSString ("filterName");
static NSString localizedFilterKey = new NSString ("localizedName");
// Creates descriptions that can be accessed with Key/Values
NSString [] videoPreviewFilterDescriptions;
[Export]
NSDictionary [] VideoPreviewFilterDescriptions {
get {
return (from name in filterNames
select NSDictionary.FromObjectsAndKeys (
new NSObject [] { new NSString (name), new NSString (CIFilter.FilterLocalizedName (name)) },
new NSObject [] { filterNameKey, localizedFilterKey })).ToArray ();
}
}
NSDictionary videoPreviewFilterDescription;
[Export]
NSDictionary VideoPreviewFilterDescription {
get {
return videoPreviewFilterDescription;
}
set {
if (value == videoPreviewFilterDescription)
return;
videoPreviewFilterDescription = value;
captureView.NeedsDisplay = true;
}
}
QTCaptureDevice [] videoDevices, audioDevices;
void RefreshDevices ()
{
WillChangeValue ("VideoDevices");
videoDevices = QTCaptureDevice.GetInputDevices (QTMediaType.Video).Concat (QTCaptureDevice.GetInputDevices (QTMediaType.Muxed)).ToArray ();
DidChangeValue ("VideoDevices");
WillChangeValue ("AudioDevices");
audioDevices = QTCaptureDevice.GetInputDevices (QTMediaType.Sound);
DidChangeValue ("AudioDevices");
if (!videoDevices.Contains (SelectedVideoDevice))
SelectedVideoDevice = null;
if (!audioDevices.Contains (SelectedAudioDevice))
SelectedAudioDevice = null;
}
void DevicesDidChange (NSNotification notification)
{
RefreshDevices ();
}
//
// Binding support
//
[Export]
public QTCaptureAudioPreviewOutput AudioPreviewOutput {
get {
return audioPreviewOutput;
}
}
[Export]
public QTCaptureDevice [] VideoDevices {
get {
if (videoDevices == null)
RefreshDevices ();
return videoDevices;
}
set {
videoDevices = value;
}
}
[Export]
public QTCaptureDevice SelectedVideoDevice {
get {
return videoDeviceInput == null ? null : videoDeviceInput.Device;
}
set {
if (videoDeviceInput != null){
session.RemoveInput (videoDeviceInput);
videoDeviceInput.Device.Close ();
videoDeviceInput.Dispose ();
videoDeviceInput = null;
}
if (value != null){
NSError err;
if (!value.Open (out err)){
NSAlert.WithError (err).BeginSheet (Window, delegate {});
return;
}
videoDeviceInput = new QTCaptureDeviceInput (value);
if (!session.AddInput (videoDeviceInput, out err)){
NSAlert.WithError (err).BeginSheet (Window, delegate {});
videoDeviceInput.Dispose ();
videoDeviceInput = null;
value.Close ();
return;
}
}
// If the video device provides audio, do not use a new audio device
if (SelectedVideoDeviceProvidesAudio)
SelectedAudioDevice = null;
}
}
[Export]
public QTCaptureDevice [] AudioDevices {
get {
if (audioDevices == null)
RefreshDevices ();
return audioDevices;
}
}
[Export]
public QTCaptureDevice SelectedAudioDevice {
get {
if (audioDeviceInput == null)
return null;
return audioDeviceInput.Device;
}
set {
if (audioDeviceInput != null){
session.RemoveInput (audioDeviceInput);
audioDeviceInput.Device.Close ();
audioDeviceInput.Dispose ();
audioDeviceInput = null;
}
if (value == null || SelectedVideoDeviceProvidesAudio)
return;
NSError err;
// try to open
if (!value.Open (out err)){
NSAlert.WithError (err).BeginSheet (Window, delegate {});
return;
}
audioDeviceInput = new QTCaptureDeviceInput (value);
if (session.AddInput (audioDeviceInput, out err))
return;
NSAlert.WithError (err).BeginSheet (Window, delegate {});
audioDeviceInput.Dispose ();
audioDeviceInput = null;
value.Close ();
}
}
[Export]
public string MediaFormatSummary {
get {
var sb = new StringBuilder ();
if (videoDeviceInput != null)
foreach (var c in videoDeviceInput.Connections)
sb.AppendFormat ("{0}\n", c.FormatDescription.LocalizedFormatSummary);
if (audioDeviceInput != null)
foreach (var c in videoDeviceInput.Connections)
sb.AppendFormat ("{0}\n", c.FormatDescription.LocalizedFormatSummary);
return sb.ToString ();
}
}
bool SelectedVideoDeviceProvidesAudio {
get {
var x = SelectedVideoDevice;
if (x == null)
return false;
return x.HasMediaType (QTMediaType.Muxed) || x.HasMediaType (QTMediaType.Sound);
}
}
[Export]
public bool HasRecordingDevice {
get {
return videoDeviceInput != null || audioDeviceInput != null;
}
}
[Export]
public bool Recording {
get {
if (movieFileOutput == null) return false;
return movieFileOutput.OutputFileUrl != null;
}
set {
if (value == Recording)
return;
if (value){
movieFileOutput.RecordToOutputFile (NSUrl.FromFilename (Path.GetTempFileName () + ".mov"));
Path.GetTempPath ();
} else {
movieFileOutput.RecordToOutputFile (null);
}
}
}
// UI controls
[Export]
public QTCaptureDevice ControllableDevice {
get {
if (SelectedVideoDevice == null)
return null;
if (SelectedVideoDevice.AvcTransportControl == null)
return null;
if (SelectedVideoDevice.IsAvcTransportControlReadOnly)
return null;
return SelectedVideoDevice;
}
}
[Export]
public bool DevicePlaying {
get {
var device = ControllableDevice;
if (device == null)
return false;
var controls = device.AvcTransportControl;
if (controls == null)
return false;
return controls.Speed == QTCaptureDeviceControlsSpeed.NormalForward && controls.PlaybackMode == QTCaptureDevicePlaybackMode.Playing;
}
set {
var device = ControllableDevice;
if (device == null)
return;
device.AvcTransportControl = new QTCaptureDeviceTransportControl () {
Speed = value ? QTCaptureDeviceControlsSpeed.NormalForward : QTCaptureDeviceControlsSpeed.Stopped,
PlaybackMode = QTCaptureDevicePlaybackMode.Playing
};
}
}
partial void StopDevice (NSObject sender)
{
var device = ControllableDevice;
if (device == null)
return;
device.AvcTransportControl = new QTCaptureDeviceTransportControl () {
Speed = QTCaptureDeviceControlsSpeed.Stopped,
PlaybackMode = QTCaptureDevicePlaybackMode.NotPlaying
};
}
bool GetDeviceSpeed (Func<QTCaptureDeviceControlsSpeed?,bool> g)
{
var device = ControllableDevice;
if (device == null)
return false;
var control = device.AvcTransportControl;
if (control == null)
return false;
return g (control.Speed);
}
void SetDeviceSpeed (bool value, QTCaptureDeviceControlsSpeed speed)
{
var device = ControllableDevice;
if (device == null)
return;
var control = device.AvcTransportControl;
if (control == null)
return;
control.Speed = value ? speed : QTCaptureDeviceControlsSpeed.Stopped;
device.AvcTransportControl = control;
}
[Export]
public bool DeviceRewinding {
get {
return GetDeviceSpeed (x => x < QTCaptureDeviceControlsSpeed.Stopped);
}
set {
SetDeviceSpeed (value, QTCaptureDeviceControlsSpeed.FastReverse);
}
}
[Export]
public bool DeviceFastForwarding {
get {
return GetDeviceSpeed (x => x > QTCaptureDeviceControlsSpeed.Stopped);
}
set {
SetDeviceSpeed (value, QTCaptureDeviceControlsSpeed.FastForward);
}
}
// Link any co-dependent keys
[Export]
public static NSSet keyPathsForValuesAffectingHasRecordingDevice ()
{
// With MonoMac 0.4:
return new NSSet (new string [] {"SelectedVideoDevice", "SelectedAudioDevice" });
// With the new MonoMac:
//return new NSSet ("SelectedVideoDevice", "SelectedAudioDevice");
}
[Export]
public static NSSet keyPathsForValuesAffectingControllableDevice ()
{
// With MonoMac 0.4:
return new NSSet (new string [] { "SelectedVideoDevice" });
// With the new MonoMac:
//return new NSSet ("SelectedVideoDevice");
}
[Export]
public static NSSet keyPathsForValuesAffectingSelectedVideoDeviceProvidesAudio ()
{
// With MonoMac 0.4:
return new NSSet (new string [] { "SelectedVideoDevice" });
// With the new MonoMac:
//return new NSSet ("SelectedVideoDevice");
}
//
// Notifications
//
void AttributeWillChange (NSNotification n)
{
}
void AttributeDidChange (NSNotification n)
{
}
void FormatWillChange (NSNotification n)
{
var owner = ((QTCaptureConnection)n.Object).Owner;
Console.WriteLine (owner);
if (owner == videoDeviceInput || owner == audioDeviceInput)
WillChangeValue ("mediaFormatSummary");
}
void FormatDidChange (NSNotification n)
{
var owner = ((QTCaptureConnection)n.Object).Owner;
Console.WriteLine (owner);
if (owner == videoDeviceInput || owner == audioDeviceInput)
DidChangeValue ("mediaFormatSummary");
}
public override string WindowNibName {
get {
return "QTRDocument";
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the es-2015-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.Elasticsearch.Model;
namespace Amazon.Elasticsearch
{
/// <summary>
/// Interface for accessing Elasticsearch
///
/// Amazon Elasticsearch Configuration Service
/// <para>
/// Use the Amazon Elasticsearch configuration API to create, configure, and manage Elasticsearch
/// domains.
/// </para>
///
/// <para>
/// The endpoint for configuration service requests is region-specific: es.<i>region</i>.amazonaws.com.
/// For example, es.us-east-1.amazonaws.com. For a current list of supported regions and
/// endpoints, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html#cloudsearch_region"
/// target="_blank">Regions and Endpoints</a>.
/// </para>
/// </summary>
public partial interface IAmazonElasticsearch : IDisposable
{
#region AddTags
/// <summary>
/// Attaches tags to an existing Elasticsearch domain. Tags are a set of case-sensitive
/// key value pairs. An Elasticsearch domain may have up to 10 tags. See <a href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-managedomains.html#es-managedomains-awsresorcetagging"
/// target="_blank"> Tagging Amazon Elasticsearch Service Domains for more information.</a>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AddTags service method.</param>
///
/// <returns>The response from the AddTags service method, as returned by Elasticsearch.</returns>
/// <exception cref="Amazon.Elasticsearch.Model.BaseException">
/// An error occurred while processing the request.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.InternalException">
/// The request processing has failed because of an unknown error, exception or failure
/// (the failure is internal to the service) . Gives http status code of 500.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.LimitExceededException">
/// An exception for trying to create more than allowed resources or sub-resources. Gives
/// http status code of 409.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ValidationException">
/// An exception for missing / invalid input fields. Gives http status code of 400.
/// </exception>
AddTagsResponse AddTags(AddTagsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the AddTags operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AddTags operation on AmazonElasticsearchClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndAddTags
/// operation.</returns>
IAsyncResult BeginAddTags(AddTagsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the AddTags operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginAddTags.</param>
///
/// <returns>Returns a AddTagsResult from Elasticsearch.</returns>
AddTagsResponse EndAddTags(IAsyncResult asyncResult);
#endregion
#region CreateElasticsearchDomain
/// <summary>
/// Creates a new Elasticsearch domain. For more information, see <a href="http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomains"
/// target="_blank">Creating Elasticsearch Domains</a> in the <i>Amazon Elasticsearch
/// Service Developer Guide</i>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateElasticsearchDomain service method.</param>
///
/// <returns>The response from the CreateElasticsearchDomain service method, as returned by Elasticsearch.</returns>
/// <exception cref="Amazon.Elasticsearch.Model.BaseException">
/// An error occurred while processing the request.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.DisabledOperationException">
/// An error occured because the client wanted to access a not supported operation. Gives
/// http status code of 409.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.InternalException">
/// The request processing has failed because of an unknown error, exception or failure
/// (the failure is internal to the service) . Gives http status code of 500.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.InvalidTypeException">
/// An exception for trying to create or access sub-resource that is either invalid or
/// not supported. Gives http status code of 409.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.LimitExceededException">
/// An exception for trying to create more than allowed resources or sub-resources. Gives
/// http status code of 409.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ResourceAlreadyExistsException">
/// An exception for creating a resource that already exists. Gives http status code of
/// 400.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ValidationException">
/// An exception for missing / invalid input fields. Gives http status code of 400.
/// </exception>
CreateElasticsearchDomainResponse CreateElasticsearchDomain(CreateElasticsearchDomainRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateElasticsearchDomain operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateElasticsearchDomain operation on AmazonElasticsearchClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateElasticsearchDomain
/// operation.</returns>
IAsyncResult BeginCreateElasticsearchDomain(CreateElasticsearchDomainRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateElasticsearchDomain operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateElasticsearchDomain.</param>
///
/// <returns>Returns a CreateElasticsearchDomainResult from Elasticsearch.</returns>
CreateElasticsearchDomainResponse EndCreateElasticsearchDomain(IAsyncResult asyncResult);
#endregion
#region DeleteElasticsearchDomain
/// <summary>
/// Permanently deletes the specified Elasticsearch domain and all of its data. Once a
/// domain is deleted, it cannot be recovered.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteElasticsearchDomain service method.</param>
///
/// <returns>The response from the DeleteElasticsearchDomain service method, as returned by Elasticsearch.</returns>
/// <exception cref="Amazon.Elasticsearch.Model.BaseException">
/// An error occurred while processing the request.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.InternalException">
/// The request processing has failed because of an unknown error, exception or failure
/// (the failure is internal to the service) . Gives http status code of 500.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ResourceNotFoundException">
/// An exception for accessing or deleting a resource that does not exist. Gives http
/// status code of 400.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ValidationException">
/// An exception for missing / invalid input fields. Gives http status code of 400.
/// </exception>
DeleteElasticsearchDomainResponse DeleteElasticsearchDomain(DeleteElasticsearchDomainRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteElasticsearchDomain operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteElasticsearchDomain operation on AmazonElasticsearchClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteElasticsearchDomain
/// operation.</returns>
IAsyncResult BeginDeleteElasticsearchDomain(DeleteElasticsearchDomainRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteElasticsearchDomain operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteElasticsearchDomain.</param>
///
/// <returns>Returns a DeleteElasticsearchDomainResult from Elasticsearch.</returns>
DeleteElasticsearchDomainResponse EndDeleteElasticsearchDomain(IAsyncResult asyncResult);
#endregion
#region DescribeElasticsearchDomain
/// <summary>
/// Returns domain configuration information about the specified Elasticsearch domain,
/// including the domain ID, domain endpoint, and domain ARN.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeElasticsearchDomain service method.</param>
///
/// <returns>The response from the DescribeElasticsearchDomain service method, as returned by Elasticsearch.</returns>
/// <exception cref="Amazon.Elasticsearch.Model.BaseException">
/// An error occurred while processing the request.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.InternalException">
/// The request processing has failed because of an unknown error, exception or failure
/// (the failure is internal to the service) . Gives http status code of 500.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ResourceNotFoundException">
/// An exception for accessing or deleting a resource that does not exist. Gives http
/// status code of 400.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ValidationException">
/// An exception for missing / invalid input fields. Gives http status code of 400.
/// </exception>
DescribeElasticsearchDomainResponse DescribeElasticsearchDomain(DescribeElasticsearchDomainRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeElasticsearchDomain operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeElasticsearchDomain operation on AmazonElasticsearchClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeElasticsearchDomain
/// operation.</returns>
IAsyncResult BeginDescribeElasticsearchDomain(DescribeElasticsearchDomainRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeElasticsearchDomain operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeElasticsearchDomain.</param>
///
/// <returns>Returns a DescribeElasticsearchDomainResult from Elasticsearch.</returns>
DescribeElasticsearchDomainResponse EndDescribeElasticsearchDomain(IAsyncResult asyncResult);
#endregion
#region DescribeElasticsearchDomainConfig
/// <summary>
/// Provides cluster configuration information about the specified Elasticsearch domain,
/// such as the state, creation date, update version, and update date for cluster options.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeElasticsearchDomainConfig service method.</param>
///
/// <returns>The response from the DescribeElasticsearchDomainConfig service method, as returned by Elasticsearch.</returns>
/// <exception cref="Amazon.Elasticsearch.Model.BaseException">
/// An error occurred while processing the request.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.InternalException">
/// The request processing has failed because of an unknown error, exception or failure
/// (the failure is internal to the service) . Gives http status code of 500.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ResourceNotFoundException">
/// An exception for accessing or deleting a resource that does not exist. Gives http
/// status code of 400.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ValidationException">
/// An exception for missing / invalid input fields. Gives http status code of 400.
/// </exception>
DescribeElasticsearchDomainConfigResponse DescribeElasticsearchDomainConfig(DescribeElasticsearchDomainConfigRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeElasticsearchDomainConfig operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeElasticsearchDomainConfig operation on AmazonElasticsearchClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeElasticsearchDomainConfig
/// operation.</returns>
IAsyncResult BeginDescribeElasticsearchDomainConfig(DescribeElasticsearchDomainConfigRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeElasticsearchDomainConfig operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeElasticsearchDomainConfig.</param>
///
/// <returns>Returns a DescribeElasticsearchDomainConfigResult from Elasticsearch.</returns>
DescribeElasticsearchDomainConfigResponse EndDescribeElasticsearchDomainConfig(IAsyncResult asyncResult);
#endregion
#region DescribeElasticsearchDomains
/// <summary>
/// Returns domain configuration information about the specified Elasticsearch domains,
/// including the domain ID, domain endpoint, and domain ARN.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeElasticsearchDomains service method.</param>
///
/// <returns>The response from the DescribeElasticsearchDomains service method, as returned by Elasticsearch.</returns>
/// <exception cref="Amazon.Elasticsearch.Model.BaseException">
/// An error occurred while processing the request.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.InternalException">
/// The request processing has failed because of an unknown error, exception or failure
/// (the failure is internal to the service) . Gives http status code of 500.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ValidationException">
/// An exception for missing / invalid input fields. Gives http status code of 400.
/// </exception>
DescribeElasticsearchDomainsResponse DescribeElasticsearchDomains(DescribeElasticsearchDomainsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeElasticsearchDomains operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeElasticsearchDomains operation on AmazonElasticsearchClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeElasticsearchDomains
/// operation.</returns>
IAsyncResult BeginDescribeElasticsearchDomains(DescribeElasticsearchDomainsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeElasticsearchDomains operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeElasticsearchDomains.</param>
///
/// <returns>Returns a DescribeElasticsearchDomainsResult from Elasticsearch.</returns>
DescribeElasticsearchDomainsResponse EndDescribeElasticsearchDomains(IAsyncResult asyncResult);
#endregion
#region ListDomainNames
/// <summary>
/// Returns the name of all Elasticsearch domains owned by the current user's account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListDomainNames service method.</param>
///
/// <returns>The response from the ListDomainNames service method, as returned by Elasticsearch.</returns>
/// <exception cref="Amazon.Elasticsearch.Model.BaseException">
/// An error occurred while processing the request.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ValidationException">
/// An exception for missing / invalid input fields. Gives http status code of 400.
/// </exception>
ListDomainNamesResponse ListDomainNames(ListDomainNamesRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListDomainNames operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListDomainNames operation on AmazonElasticsearchClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListDomainNames
/// operation.</returns>
IAsyncResult BeginListDomainNames(ListDomainNamesRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListDomainNames operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListDomainNames.</param>
///
/// <returns>Returns a ListDomainNamesResult from Elasticsearch.</returns>
ListDomainNamesResponse EndListDomainNames(IAsyncResult asyncResult);
#endregion
#region ListTags
/// <summary>
/// Returns all tags for the given Elasticsearch domain.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTags service method.</param>
///
/// <returns>The response from the ListTags service method, as returned by Elasticsearch.</returns>
/// <exception cref="Amazon.Elasticsearch.Model.BaseException">
/// An error occurred while processing the request.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.InternalException">
/// The request processing has failed because of an unknown error, exception or failure
/// (the failure is internal to the service) . Gives http status code of 500.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ResourceNotFoundException">
/// An exception for accessing or deleting a resource that does not exist. Gives http
/// status code of 400.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ValidationException">
/// An exception for missing / invalid input fields. Gives http status code of 400.
/// </exception>
ListTagsResponse ListTags(ListTagsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListTags operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTags operation on AmazonElasticsearchClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTags
/// operation.</returns>
IAsyncResult BeginListTags(ListTagsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListTags operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTags.</param>
///
/// <returns>Returns a ListTagsResult from Elasticsearch.</returns>
ListTagsResponse EndListTags(IAsyncResult asyncResult);
#endregion
#region RemoveTags
/// <summary>
/// Removes the specified set of tags from the specified Elasticsearch domain.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RemoveTags service method.</param>
///
/// <returns>The response from the RemoveTags service method, as returned by Elasticsearch.</returns>
/// <exception cref="Amazon.Elasticsearch.Model.BaseException">
/// An error occurred while processing the request.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.InternalException">
/// The request processing has failed because of an unknown error, exception or failure
/// (the failure is internal to the service) . Gives http status code of 500.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ValidationException">
/// An exception for missing / invalid input fields. Gives http status code of 400.
/// </exception>
RemoveTagsResponse RemoveTags(RemoveTagsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the RemoveTags operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RemoveTags operation on AmazonElasticsearchClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRemoveTags
/// operation.</returns>
IAsyncResult BeginRemoveTags(RemoveTagsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the RemoveTags operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRemoveTags.</param>
///
/// <returns>Returns a RemoveTagsResult from Elasticsearch.</returns>
RemoveTagsResponse EndRemoveTags(IAsyncResult asyncResult);
#endregion
#region UpdateElasticsearchDomainConfig
/// <summary>
/// Modifies the cluster configuration of the specified Elasticsearch domain, setting
/// as setting the instance type and the number of instances.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateElasticsearchDomainConfig service method.</param>
///
/// <returns>The response from the UpdateElasticsearchDomainConfig service method, as returned by Elasticsearch.</returns>
/// <exception cref="Amazon.Elasticsearch.Model.BaseException">
/// An error occurred while processing the request.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.InternalException">
/// The request processing has failed because of an unknown error, exception or failure
/// (the failure is internal to the service) . Gives http status code of 500.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.InvalidTypeException">
/// An exception for trying to create or access sub-resource that is either invalid or
/// not supported. Gives http status code of 409.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.LimitExceededException">
/// An exception for trying to create more than allowed resources or sub-resources. Gives
/// http status code of 409.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ResourceNotFoundException">
/// An exception for accessing or deleting a resource that does not exist. Gives http
/// status code of 400.
/// </exception>
/// <exception cref="Amazon.Elasticsearch.Model.ValidationException">
/// An exception for missing / invalid input fields. Gives http status code of 400.
/// </exception>
UpdateElasticsearchDomainConfigResponse UpdateElasticsearchDomainConfig(UpdateElasticsearchDomainConfigRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateElasticsearchDomainConfig operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateElasticsearchDomainConfig operation on AmazonElasticsearchClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateElasticsearchDomainConfig
/// operation.</returns>
IAsyncResult BeginUpdateElasticsearchDomainConfig(UpdateElasticsearchDomainConfigRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateElasticsearchDomainConfig operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateElasticsearchDomainConfig.</param>
///
/// <returns>Returns a UpdateElasticsearchDomainConfigResult from Elasticsearch.</returns>
UpdateElasticsearchDomainConfigResponse EndUpdateElasticsearchDomainConfig(IAsyncResult asyncResult);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NLog;
using TcpRequestHandler;
namespace eMailServer {
public class SmtpServer : SmtpRequestHandler {
protected new static Logger logger = LogManager.GetCurrentClassLogger();
private User _user = new User();
private Dictionary<string, string> _temporaryVariables = new Dictionary<string, string>();
public SmtpServer() : base() {
}
public SmtpServer(TcpClient client, int sslPort) : base(client, sslPort) {
bool dataStarted = false;
string mailMessage = String.Empty;
eMail mail = new eMail();
this.Connected += (object sender, TcpRequestEventArgs e) => {
if (this.Verbose && e.RemoteEndPoint != null && e.LocalEndPoint != null) {
logger.Debug("connected from remote [{0}:{1}] to local [{2}:{3}]",
e.RemoteEndPoint.Address.ToString(),
e.RemoteEndPoint.Port,
e.LocalEndPoint.Address.ToString(),
e.LocalEndPoint.Port
);
}
this.SendMessage("service ready", 220);
};
this.Disconnected += (object sender, TcpRequestEventArgs e) => {
if (this.Verbose && e.RemoteEndPoint != null && e.LocalEndPoint != null) {
logger.Debug("disconnected from remote [{0}:{1}] to local [{2}:{3}]",
e.RemoteEndPoint.Address.ToString(),
e.RemoteEndPoint.Port,
e.LocalEndPoint.Address.ToString(),
e.LocalEndPoint.Port
);
}
};
this.LineReceived += (object sender, TcpLineReceivedEventArgs e) => {
logger.Info(String.Format("[{0}:{1}] to [{2}:{3}] Received Line: \"{4}\"", this._remoteEndPoint.Address.ToString(), this._remoteEndPoint.Port, this._localEndPoint.Address.ToString(), this._localEndPoint.Port, e.Line));
switch(this._state) {
case State.AuthenticateLoginUsername:
this._temporaryVariables["username"] = Encoding.UTF8.GetString(Convert.FromBase64String(e.Line)).Trim();
if (this._temporaryVariables["username"] != String.Empty) {
this._state = State.AuthenticateLoginPassword;
if (User.NameExists(this._temporaryVariables["username"]) || User.EMailExists(this._temporaryVariables["username"])) {
this.SendMessage(Convert.ToBase64String(Encoding.UTF8.GetBytes("Password:")), 334);
} else {
this.SendMessage("5.7.8 Authentication credentials invalid", 535);
}
} else {
this._temporaryVariables.Remove("username");
this._state = State.Default;
this.SendMessage("5.7.8 Authentication credentials invalid", 535);
}
break;
case State.AuthenticateLoginPassword:
this._temporaryVariables["password"] = Encoding.UTF8.GetString(Convert.FromBase64String(e.Line)).Trim();
this._state = State.Default;
if (this._temporaryVariables["password"] != String.Empty) {
string username = this._temporaryVariables["username"];
string password = this._temporaryVariables["password"];
this._temporaryVariables.Remove("username");
this._temporaryVariables.Remove("password");
if (this._user.RefreshByUsernamePassword(username, password) || this._user.RefreshByEMailPassword(username, password)) {
this.SendMessage("2.7.0 Authentication Succeeded", 235);
} else {
this.SendMessage("5.7.8 Authentication credentials invalid", 535);
}
} else {
this.SendMessage("5.7.8 Authentication credentials invalid", 535);
}
break;
case State.AuthenticateCramMD5:
List<string> wordsCramMD5 = this.GetWordsFromBase64EncodedLine(e.Line);
this._state = State.Default;
if (wordsCramMD5.Count == 1) {
string[] splittedWords = wordsCramMD5[0].Split(new char[] {' '});
if (splittedWords.Length == 2) {
bool nameExists = User.NameExists(splittedWords[0]);
bool eMailExists = User.EMailExists(splittedWords[0]);
if (nameExists || eMailExists) {
string userId = (nameExists) ? User.GetIdByName(splittedWords[0]) : User.GetIdByEMail(splittedWords[0]);
User tmpUser = new User();
if (tmpUser.RefreshById(userId)) {
string calculatedDigest = this.CalculateCramMD5Digest(tmpUser.Password, this._currentCramMD5Challenge);
if (calculatedDigest == splittedWords[1]) {
this._user = tmpUser;
this.SendMessage("2.7.0 Authentication Succeeded", 235);
} else {
this.SendMessage("5.7.8 Authentication credentials invalid", 535);
}
} else {
this.SendMessage("4.7.0 Temporary authentication failure", 454);
}
} else {
this.SendMessage("5.7.8 Authentication credentials invalid", 535);
}
} else {
this.SendMessage("5.7.8 Authentication credentials invalid", 535);
}
} else {
this.SendMessage("5.7.8 Authentication credentials invalid", 535);
}
this._currentCramMD5Challenge = String.Empty;
break;
case State.Default:
default:
if (!dataStarted) {
if (e.Line.StartsWith("HELO ")) {
mail.SetClientName(e.Line.Substring(5));
this.SendMessage("OK", 250);
} else if (e.Line.StartsWith("EHLO ")) {
mail.SetClientName(e.Line.Substring(5));
this.SendMessage("Hello " + mail.ClientName + " [" + this._remoteEndPoint.Address.ToString() + "]", "250-localhost");
if (!this.SslIsActive) {
string capabilities = "LOGIN";
capabilities += " PLAIN CRAM-MD5";
this.SendMessage(capabilities, "250-AUTH");
this.SendMessage("STARTTLS", 250);
} else {
string capabilities = "AUTH LOGIN";
capabilities += " PLAIN CRAM-MD5";
this.SendMessage(capabilities, 250);
}
} else if (e.Line.StartsWith("AUTH ")) {
Match authMatch = Regex.Match(e.Line, @"^AUTH\s+(PLAIN|CRAM-MD5|LOGIN)(.*)?", RegexOptions.IgnoreCase);
if (authMatch.Success) {
switch(authMatch.Groups[1].Value.ToUpper()) {
case "PLAIN":
List<string> words = new List<string>();
try {
words = this.GetWordsFromBase64EncodedLine(authMatch.Groups[2].Value);
} catch(Exception) {
}
this._state = State.Default;
if (words.Count == 2) {
if (words[0] != String.Empty && words[1] != String.Empty) {
if (this._user.RefreshByUsernamePassword(words[0], words[1]) || this._user.RefreshByEMailPassword(words[0], words[1])) {
this.SendMessage("2.7.0 Authentication Succeeded", 235);
} else {
this.SendMessage("5.7.8 Authentication credentials invalid", 535);
}
} else {
this.SendMessage("5.7.8 Authentication credentials invalid", 535);
}
} else {
this.SendMessage("5.7.8 Authentication credentials invalid", 535);
}
break;
case "LOGIN":
this._state = State.AuthenticateLoginUsername;
this.SendMessage(Convert.ToBase64String(Encoding.UTF8.GetBytes("Username:")), 334);
break;
case "CRAM-MD5":
this._state = State.AuthenticateCramMD5;
string base64EncodedCramMD5Challenge = this.CalculateOneTimeBase64Challenge("localhost.de");
this._currentCramMD5Challenge = Encoding.UTF8.GetString(Convert.FromBase64String(base64EncodedCramMD5Challenge));
this.SendMessage(base64EncodedCramMD5Challenge, 334);
break;
default:
this.SendMessage("Unrecognized authentication type", 504);
break;
}
}
} else if (e.Line.StartsWith("MAIL FROM:")) {
string email = e.Line.Substring(10);
try {
mail.SetFrom(email);
this.SendMessage("OK", 250);
} catch(FormatException) {
this.SendMessage("BAD <" + email + ">... Denied due to invalid email-format", 555);
}
} else if (e.Line.StartsWith("RCPT TO:")) {
mail.SetRecipient(e.Line.Substring(8));
this.SendMessage("OK", 250);
} else if (e.Line.StartsWith("STARTTLS")) {
if (e.Line.Trim() == "STARTTLS") {
this.SendMessage("Ready to start TLS", 220);
if (!this.StartTls()) {
this.SendMessage("TLS not available due to temporary reason", 454);
}
} else {
this.SendMessage("Syntax error (no parameters allowed)", 501);
}
} else if (e.Line == "DATA") {
this.SendMessage("start mail input", 354);
dataStarted = true;
} else if (e.Line == "QUIT") {
if (eMailServer.Options.Verbose) {
logger.Debug("[{0}:{1}] to [{2}:{3}] quit connection", this._localEndPoint.Address.ToString(), this._localEndPoint.Port, this._remoteEndPoint.Address.ToString(), this._remoteEndPoint.Port);
}
this.Close();
return;
} else {
this.SendMessage("Syntax error, command unrecognized", 500);
if (eMailServer.Options.Verbose) {
logger.Debug("[{0}:{1}] to [{2}:{3}] unknown command: {2}", this._remoteEndPoint.Address.ToString(), this._remoteEndPoint.Port, this._localEndPoint.Address.ToString(), this._localEndPoint.Port, e.Line);
}
}
} else {
if (e.Line == ".") {
mailMessage = mailMessage.Trim();
logger.Info("[{0}:{1}] to [{2}:{3}] eMail data received: {2}", this._remoteEndPoint.Address.ToString(), this._remoteEndPoint.Port, mailMessage, this._localEndPoint.Address.ToString(), this._localEndPoint.Port);
dataStarted = false;
mail.ParseData(mailMessage);
if (mail.IsValid) {
if (this._user.IsLoggedIn && User.EMailExists(mail.MailFrom)) {
mail.SetUser(this._user);
mail.SetFolder("SENT");
} else {
mail.SetFolder("INBOX");
}
mail.SaveToMongoDB();
} else {
logger.Error("received message is invalid for saving to database.");
}
this.SendMessage("OK", 250);
} else {
mailMessage += e.Line + "\r\n";
}
}
break;
}
};
}
}
}
| |
//#define PROFILE
//#define DBG
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
/*
* New serializer idea:
- FLEXIBLE (not rigid - can easily adapt to new types)
- EASY TO DEBUG
- uses reflection (the fast one)
- no more IL (except for reflection, that's fine...)
- binary, no parsing
- fast, robust, simple
- customizable (custom serialization logic/attributes etc)
- optional runtimetypeinfo/cycle handling
*/
namespace BX20Serializer
{
public delegate void StrongReader<T>(Stream stream, ref T value);
public delegate void StrongWriter<T>(Stream stream, T value);
public delegate bool FieldPredicate(FieldInfo field);
public delegate bool PropertyPredicate(PropertyInfo property);
public class BinaryX20
{
public static Action<string> Log = delegate { };
private delegate void SerializeFunction(Stream stream, Type type, object value);
private delegate void DeserializeFunction(Stream stream, Type type, ref object instance);
private readonly List<BaseSerializer> _Serializers;
private readonly Dictionary<Type, BaseSerializer> _CachedSerializers;
private readonly SerializationContext _Ctx;
private readonly ReferenceMarker _Marker;
private SerializeFunction _Serialize;
private DeserializeFunction _Deserialize;
private int _CurrentRefId;
/// <summary>
/// 1: runtime type info (polymorphic serialization), cycle/serialize by reference, string cache
/// 0: string cache
/// </summary>
public void SetMode(int value)
{
if (value == 0)
{
_Serialize = Serialize_Minimal;
_Deserialize = Deserialize_Minimal;
}
else
{
_Serialize = Serialize_Standard;
_Deserialize = Deserialize_Standard;
}
}
public BinaryX20()
{
_Serializers = new List<BaseSerializer>()
{
PrimitiveSerializer.Instance,
new V2Serializer(),
new V3Serializer(),
new V4Serializer(),
new BoundsSerializer(),
new LayerMaskSerializer(),
new RectSerializer(),
new ArraySerializer(),
new DictionarySerializer(),
new EnumSerializer(),
new CollectionSerializer(),
new TypeSerializer(),
new ReflectiveSerializer(),
};
_Ctx = new SerializationContext(this);
_Marker = new ReferenceMarker();
_CachedSerializers = new Dictionary<Type, BaseSerializer>();
SetMode(1);
}
public BinaryX20 AddSerializer(BaseSerializer serializer)
{
_Serializers.Insert(0, serializer);
return this;
}
public BinaryX20 AddStrongReflective<TTarget, TMember0>(string member0, StrongWriter<TMember0> writer, StrongReader<TMember0> reader)
{
_Serializers.Insert(0, new StrongReflectiveSerializer<TTarget, TMember0>(member0, writer, reader));
return this;
}
public BinaryX20 AddStrongArray<T>(StrongWriter<T> write, StrongReader<T> read)
{
_Serializers.Insert(0, new ArraySerializer<T>(write, read));
return this;
}
public BinaryX20 AddStrongList<T>(StrongWriter<T> write, StrongReader<T> read)
{
_Serializers.Insert(0, new ListSerializer<T>(write, read));
return this;
}
public BinaryX20 AddStrongDictionary<TK, TV>(StrongWriter<TK> keyWriter, StrongReader<TK> keyReader, StrongWriter<TV> valueWriter, StrongReader<TV> valueReader)
{
_Serializers.Insert(0, new DictionarySerializer<TK, TV>(keyWriter, keyReader, valueWriter, valueReader));
return this;
}
public void ClearSerializersCache()
{
_CachedSerializers.Clear();
}
private BaseSerializer GetSerializer(Type type)
{
BaseSerializer result;
if (!_CachedSerializers.TryGetValue(type, out result))
{
for (int i = 0; i < _Serializers.Count; i++)
{
var serializer = _Serializers[i];
if (serializer.Handles(type))
{
_CachedSerializers[type] = serializer;
#if DBG
Log("Cached serializer for type: " + type.Name + " is: " + serializer.GetType().Name);
#endif
result = serializer;
result.ctx = _Ctx;
break;
}
}
}
return result;
}
public void Serialize(Stream stream, Type type, object value)
{
Serialize(stream, type, value, null);
}
public void Serialize(Stream stream, Type type, object value, object ctx)
{
_Ctx.Context = ctx;
{
#if PROFILE
Profiler.BeginSample("Binary: Serializing " + type.Name);
#endif
Serialize_Main(stream, type, value);
#if PROFILE
Profiler.EndSample();
#endif
}
_Marker.Clear();
Basic.ClearMarkedStrings();
}
public void Serialize_Main(Stream stream, Type type, object value)
{
_Serialize(stream, type, value);
}
private void Serialize_Minimal(Stream stream, Type type, object value)
{
if (type.IsValueType)
{
// Primitives
{
if (type.IsPrimitive || type == typeof(DateTime))
{
#if DBG
Log("Writing primitive: " + value + " (" + type.Name + ")");
#endif
PrimitiveSerializer.Instance.Serialize(stream, type, value);
return;
}
}
// Structs
{
#if DBG
Log("Writing struct: " + value + " (" + type.Name + ")");
#endif
var serializer = GetSerializer(type);
serializer.Serialize(stream, type, value);
return;
}
}
// Reference-types
{
#if DBG
Log("Writing reference type: " + type.Name);
#endif
if (type == typeof(string))
{
#if DBG
Log("Writing string: " + value);
#endif
Basic.WriteString(stream, value as string);
return;
}
if (value == null)
{
// set null flag
#if DBG
Log("Setting null flag");
#endif
Basic.WriteByte(stream, 1);
return;
}
#if DBG
Log("Clearing null flag");
#endif
Basic.WriteByte(stream, 0); // clear null flag
var serializer = GetSerializer(type);
serializer.Serialize(stream, type, value);
}
}
private void Serialize_Standard(Stream stream, Type type, object value)
{
if (type.IsValueType)
{
// Primitives
{
if (type.IsPrimitive || type == typeof(DateTime))
{
#if DBG
Log("Writing primitive: " + type.Name);
#endif
PrimitiveSerializer.Instance.Serialize(stream, type, value);
return;
}
}
// Structs
{
#if DBG
Log("Writing struct: " + type.Name);
#endif
var serializer = GetSerializer(type);
serializer.Serialize(stream, type, value);
return;
}
}
if (type == typeof(string))
{
#if DBG
Log("Writing string: " + value);
#endif
Basic.WriteString(stream, value as string);
return;
}
// Reference-types
{
#if DBG
Log("Writing refernece type: " + type.Name);
#endif
if (value == null)
{
#if DBG
Log("Setting null flag");
#endif
// set null flag
Basic.WriteByte(stream, 1);
return;
}
#if DBG
Log("Clearing null flag");
#endif
Basic.WriteByte(stream, 0); // clear null flag
int id = _Marker.GetRefId(value);
#if DBG
Log("Writing reference id");
#endif
Basic.WriteInt(stream, id);
if (_Marker.IsReference(id))
{
// set isref flag
#if DBG
Log("Setting isref flag");
#endif
Basic.WriteByte(stream, 1);
return;
}
#if DBG
Log("Clearing isref flag");
#endif
Basic.WriteByte(stream, 0); // clear isref flag
_Marker.Mark(value, id);
var runtimeType = value.GetType();
if (runtimeType != type)
{
// set rti flag
#if DBG
Log("Setting rti flag. And writing runtime type: " + runtimeType);
#endif
Basic.WriteByte(stream, 1);
TypeSerializer.Write(stream, runtimeType);
}
else // clear rti flag
{
#if DBG
Log("Clearing rti flag");
#endif
Basic.WriteByte(stream, 0);
}
var serializer = GetSerializer(runtimeType);
#if DBG
Log("Serializing with: " + serializer.GetType().Name);
#endif
serializer.Serialize(stream, runtimeType, value);
}
}
public void Deserialize<T>(Stream stream, Type type, ref T instance)
{
object obj = instance;
Deserialize(stream, type, ref obj);
instance = (T) obj;
}
public T Deserialize<T>(Stream stream)
{
T obj = default(T);
Deserialize(stream, typeof(T), ref obj);
return obj;
}
public void Deserialize(Stream stream, Type type, ref object instance)
{
Deserialize(stream, type, ref instance, null);
}
public void Deserialize(Stream stream, Type type, ref object instance, object ctx)
{
_Ctx.Context = ctx;
{
Deserialize_Main(stream, type, ref instance);
}
_Marker.Clear();
Basic.ClearMarkedStrings();
}
public void Deserialize_Main(Stream stream, Type type, ref object instance)
{
_Deserialize(stream, type, ref instance);
}
private void Deserialize_Minimal(Stream stream, Type type, ref object instance)
{
if (type.IsValueType)
{
// Primitives
{
if (type.IsPrimitive || type == typeof(DateTime))
{
PrimitiveSerializer.Instance.Deserialize(stream, type, ref instance);
#if DBG
Log("Read primitive: " + instance);
#endif
return;
}
}
// Structs
{
var serializer = GetSerializer(type);
if (instance == null)
instance = serializer.GetInstance(stream, type);
serializer.Deserialize(stream, type, ref instance);
#if DBG
Log("Read struct: " + instance);
#endif
return;
}
}
// Reference-types
{
if (type == typeof(string))
{
instance = stream.ReadString();
#if DBG
Log("Read string: " + instance);
#endif
return;
}
bool nullFlag = stream.ReadBool();
#if DBG
Log("Read null flag: " + nullFlag);
#endif
if (nullFlag)
{
instance = null;
return;
}
var serializer = GetSerializer(type);
if (instance == null)
instance = serializer.GetInstance(stream, type);
serializer.Deserialize(stream, type, ref instance);
}
}
private void Deserialize_Standard(Stream stream, Type type, ref object instance)
{
if (type.IsValueType)
{
// Primitives
{
if (type.IsPrimitive || type == typeof(DateTime))
{
PrimitiveSerializer.Instance.Deserialize(stream, type, ref instance);
#if DBG
Log("Read primitive: " + instance + " (" + type.Name + ")");
#endif
return;
}
}
// Structs
{
var serializer = GetSerializer(type);
if (instance == null)
instance = serializer.GetInstance(stream, type);
#if DBG
Log("Reading struct: " + type.Name + " with: " + serializer.GetType().Name);
#endif
serializer.Deserialize(stream, type, ref instance);
#if DBG
Log("struct value: " + instance);
#endif
return;
}
}
if (type == typeof(string))
{
instance = stream.ReadString();
#if DBG
Log("Read string: " + instance);
#endif
return;
}
// Reference-types
{
#if DBG
Log("Reading reference type: " + type.Name);
#endif
bool nullFlag = stream.ReadBool();
#if DBG
Log("Read null flag: " + nullFlag);
#endif
if (nullFlag)
{
instance = null;
return;
}
int id = stream.ReadInt();
#if DBG
Log("Read ref id (int): " + id);
#endif
bool refFlag = stream.ReadBool();
#if DBG
Log("Read ref flag (bool/byte): " + refFlag);
#endif
if (refFlag)
{
instance = _Marker.GetRef(id);
return;
}
Type runtimeType;
bool typeInfoFlag = stream.ReadBool();
#if DBG
Log("Read rti flag: " + typeInfoFlag);
#endif
if (typeInfoFlag)
runtimeType = TypeSerializer.Read(stream);
else
runtimeType = type;
var serializer = GetSerializer(runtimeType);
if (instance == null)
{
#if DBG
Log("instance == null - Creating new instance (" + runtimeType + ")");
#endif
instance = serializer.GetInstance(stream, runtimeType);
}
#if DBG
Log("Marked instance: " + instance + " with id: " + id);
#endif
_Marker.Mark(instance, id);
_CurrentRefId = id;
serializer.Deserialize(stream, runtimeType, ref instance);
}
}
internal void ReMark(object instance)
{
_Marker.Mark(instance, _CurrentRefId);
}
public string SerializeToString(object value)
{
using (var ms = new MemoryStream())
{
Serialize(ms, value.GetType(), value, null);
var bytes = ms.ToArray();
var result = Convert.ToBase64String(bytes);
return result;
}
}
public T DeserializeFromString<T>(string serializedState)
{
var bytes = Convert.FromBase64String(serializedState);
using (var ms = new MemoryStream(bytes))
{
T instance = default(T);
Deserialize<T>(ms, typeof(T), ref instance);
return instance;
}
}
private class ReferenceMarker
{
private int _NextRefId;
private readonly Dictionary<int, object> _Marked = new Dictionary<int, object>();
private readonly Dictionary<object, int> _Ids = new Dictionary<object, int>(RefComparer.Instance);
public object GetRef(int id)
{
return _Marked[id];
}
public bool IsReference(int objId)
{
return _Marked.ContainsKey(objId);
}
public void Mark(object obj, int id)
{
_Marked[id] = obj;
}
public int GetRefId(object obj)
{
int id;
if (!_Ids.TryGetValue(obj, out id))
{
id = _NextRefId++;
_Ids[obj] = id;
}
return id;
}
public void Clear()
{
_Marked.Clear();
_Ids.Clear();
_NextRefId = 0;
}
private class RefComparer : IEqualityComparer<object>
{
public static readonly RefComparer Instance = new RefComparer();
private RefComparer()
{
}
new public bool Equals(object x, object y)
{
return x == y;
}
public int GetHashCode(object obj)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}
}
}
public class SerializationContext
{
public readonly BinaryX20 Serializer;
public object Context;
public SerializationContext(BinaryX20 serializer)
{
this.Serializer = serializer;
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Orleans.CodeGeneration;
namespace Orleans.Runtime
{
/// <summary>
/// A collection of utility functions for dealing with Type information.
/// </summary>
internal static class TypeUtils
{
/// <summary>
/// The assembly name of the core Orleans assembly.
/// </summary>
private static readonly AssemblyName OrleansCoreAssembly = typeof(IGrain).GetTypeInfo().Assembly.GetName();
private static readonly ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string> ParseableNameCache = new ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string>();
private static readonly ConcurrentDictionary<Tuple<Type, bool>, List<Type>> ReferencedTypes = new ConcurrentDictionary<Tuple<Type, bool>, List<Type>>();
public static string GetSimpleTypeName(Type t, Predicate<Type> fullName = null)
{
return GetSimpleTypeName(t.GetTypeInfo(), fullName);
}
public static string GetSimpleTypeName(TypeInfo typeInfo, Predicate<Type> fullName = null)
{
if (typeInfo.IsNestedPublic || typeInfo.IsNestedPrivate)
{
if (typeInfo.DeclaringType.GetTypeInfo().IsGenericType)
{
return GetTemplatedName(
GetUntemplatedTypeName(typeInfo.DeclaringType.Name),
typeInfo.DeclaringType,
typeInfo.GetGenericArguments(),
_ => true) + "." + GetUntemplatedTypeName(typeInfo.Name);
}
return GetTemplatedName(typeInfo.DeclaringType) + "." + GetUntemplatedTypeName(typeInfo.Name);
}
var type = typeInfo.AsType();
if (typeInfo.IsGenericType) return GetSimpleTypeName(fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name);
return fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name;
}
public static string GetUntemplatedTypeName(string typeName)
{
int i = typeName.IndexOf('`');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('<');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
return typeName;
}
public static string GetSimpleTypeName(string typeName)
{
int i = typeName.IndexOf('`');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('[');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('<');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
return typeName;
}
public static bool IsConcreteTemplateType(Type t)
{
if (t.GetTypeInfo().IsGenericType) return true;
return t.IsArray && IsConcreteTemplateType(t.GetElementType());
}
public static string GetTemplatedName(Type t, Predicate<Type> fullName = null)
{
if (fullName == null)
fullName = _ => true; // default to full type names
var typeInfo = t.GetTypeInfo();
if (typeInfo.IsGenericType) return GetTemplatedName(GetSimpleTypeName(typeInfo, fullName), t, typeInfo.GetGenericArguments(), fullName);
if (t.IsArray)
{
return GetTemplatedName(t.GetElementType(), fullName)
+ "["
+ new string(',', t.GetArrayRank() - 1)
+ "]";
}
return GetSimpleTypeName(typeInfo, fullName);
}
public static bool IsConstructedGenericType(this TypeInfo typeInfo)
{
// is there an API that returns this info without converting back to type already?
return typeInfo.AsType().IsConstructedGenericType;
}
internal static IEnumerable<TypeInfo> GetTypeInfos(this Type[] types)
{
return types.Select(t => t.GetTypeInfo());
}
public static string GetTemplatedName(string baseName, Type t, Type[] genericArguments, Predicate<Type> fullName)
{
var typeInfo = t.GetTypeInfo();
if (!typeInfo.IsGenericType || (t.DeclaringType != null && t.DeclaringType.GetTypeInfo().IsGenericType)) return baseName;
string s = baseName;
s += "<";
s += GetGenericTypeArgs(genericArguments, fullName);
s += ">";
return s;
}
public static string GetGenericTypeArgs(IEnumerable<Type> args, Predicate<Type> fullName)
{
string s = string.Empty;
bool first = true;
foreach (var genericParameter in args)
{
if (!first)
{
s += ",";
}
if (!genericParameter.GetTypeInfo().IsGenericType)
{
s += GetSimpleTypeName(genericParameter, fullName);
}
else
{
s += GetTemplatedName(genericParameter, fullName);
}
first = false;
}
return s;
}
public static string GetParameterizedTemplateName(TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null)
{
if (fullName == null)
fullName = tt => true;
return GetParameterizedTemplateName(typeInfo, fullName, applyRecursively);
}
public static string GetParameterizedTemplateName(TypeInfo typeInfo, Predicate<Type> fullName, bool applyRecursively = false)
{
if (typeInfo.IsGenericType)
{
return GetParameterizedTemplateName(GetSimpleTypeName(typeInfo, fullName), typeInfo, applyRecursively, fullName);
}
var t = typeInfo.AsType();
if (fullName != null && fullName(t) == true)
{
return t.FullName;
}
return t.Name;
}
public static string GetParameterizedTemplateName(string baseName, TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null)
{
if (fullName == null)
fullName = tt => false;
if (!typeInfo.IsGenericType) return baseName;
string s = baseName;
s += "<";
bool first = true;
foreach (var genericParameter in typeInfo.GetGenericArguments())
{
if (!first)
{
s += ",";
}
var genericParameterTypeInfo = genericParameter.GetTypeInfo();
if (applyRecursively && genericParameterTypeInfo.IsGenericType)
{
s += GetParameterizedTemplateName(genericParameterTypeInfo, applyRecursively);
}
else
{
s += genericParameter.FullName == null || !fullName(genericParameter)
? genericParameter.Name
: genericParameter.FullName;
}
first = false;
}
s += ">";
return s;
}
public static string GetRawClassName(string baseName, Type t)
{
var typeInfo = t.GetTypeInfo();
return typeInfo.IsGenericType ? baseName + '`' + typeInfo.GetGenericArguments().Length : baseName;
}
public static string GetRawClassName(string typeName)
{
int i = typeName.IndexOf('[');
return i <= 0 ? typeName : typeName.Substring(0, i);
}
public static Type[] GenericTypeArgsFromClassName(string className)
{
return GenericTypeArgsFromArgsString(GenericTypeArgsString(className));
}
public static Type[] GenericTypeArgsFromArgsString(string genericArgs)
{
if (string.IsNullOrEmpty(genericArgs)) return new Type[] { };
var genericTypeDef = genericArgs.Replace("[]", "##"); // protect array arguments
return InnerGenericTypeArgs(genericTypeDef);
}
private static Type[] InnerGenericTypeArgs(string className)
{
var typeArgs = new List<Type>();
var innerTypes = GetInnerTypes(className);
foreach (var innerType in innerTypes)
{
if (innerType.StartsWith("[[")) // Resolve and load generic types recursively
{
InnerGenericTypeArgs(GenericTypeArgsString(innerType));
string genericTypeArg = className.Trim('[', ']');
typeArgs.Add(Type.GetType(genericTypeArg.Replace("##", "[]")));
}
else
{
string nonGenericTypeArg = innerType.Trim('[', ']');
typeArgs.Add(Type.GetType(nonGenericTypeArg.Replace("##", "[]")));
}
}
return typeArgs.ToArray();
}
private static string[] GetInnerTypes(string input)
{
// Iterate over strings of length 2 positionwise.
var charsWithPositions = input.Zip(Enumerable.Range(0, input.Length), (c, i) => new { Ch = c, Pos = i });
var candidatesWithPositions = charsWithPositions.Zip(charsWithPositions.Skip(1), (c1, c2) => new { Str = c1.Ch.ToString() + c2.Ch, Pos = c1.Pos });
var results = new List<string>();
int startPos = -1;
int endPos = -1;
int endTokensNeeded = 0;
string curStartToken = "";
string curEndToken = "";
var tokenPairs = new[] { new { Start = "[[", End = "]]" }, new { Start = "[", End = "]" } }; // Longer tokens need to come before shorter ones
foreach (var candidate in candidatesWithPositions)
{
if (startPos == -1)
{
foreach (var token in tokenPairs)
{
if (candidate.Str.StartsWith(token.Start))
{
curStartToken = token.Start;
curEndToken = token.End;
startPos = candidate.Pos;
break;
}
}
}
if (curStartToken != "" && candidate.Str.StartsWith(curStartToken))
endTokensNeeded++;
if (curEndToken != "" && candidate.Str.EndsWith(curEndToken))
{
endPos = candidate.Pos;
endTokensNeeded--;
}
if (endTokensNeeded == 0 && startPos != -1)
{
results.Add(input.Substring(startPos, endPos - startPos + 2));
startPos = -1;
curStartToken = "";
}
}
return results.ToArray();
}
public static string GenericTypeArgsString(string className)
{
int startIndex = className.IndexOf('[');
int endIndex = className.LastIndexOf(']');
return className.Substring(startIndex + 1, endIndex - startIndex - 1);
}
public static bool IsGenericClass(string name)
{
return name.Contains("`") || name.Contains("[");
}
public static string GetFullName(TypeInfo typeInfo)
{
if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo));
return GetFullName(typeInfo.AsType());
}
public static string GetFullName(Type t)
{
if (t == null) throw new ArgumentNullException(nameof(t));
if (t.IsNested && !t.IsGenericParameter)
{
return t.Namespace + "." + t.DeclaringType.Name + "." + t.Name;
}
if (t.IsArray)
{
return GetFullName(t.GetElementType())
+ "["
+ new string(',', t.GetArrayRank() - 1)
+ "]";
}
return t.FullName ?? (t.IsGenericParameter ? t.Name : t.Namespace + "." + t.Name);
}
/// <summary>
/// Returns all fields of the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>All fields of the specified type.</returns>
public static IEnumerable<FieldInfo> GetAllFields(this Type type)
{
const BindingFlags AllFields =
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
var current = type;
while ((current != typeof(object)) && (current != null))
{
var fields = current.GetFields(AllFields);
foreach (var field in fields)
{
yield return field;
}
current = current.GetTypeInfo().BaseType;
}
}
/// <summary>
/// decide whether the class is derived from Grain
/// </summary>
public static bool IsGrainClass(Type type)
{
var grainType = typeof(Grain);
var grainChevronType = typeof(Grain<>);
#if !NETSTANDARD
if (type.Assembly.ReflectionOnly)
{
grainType = ToReflectionOnlyType(grainType);
grainChevronType = ToReflectionOnlyType(grainChevronType);
}
#endif
if (grainType == type || grainChevronType == type) return false;
if (!grainType.IsAssignableFrom(type)) return false;
// exclude generated classes.
return !IsGeneratedType(type);
}
public static bool IsSystemTargetClass(Type type)
{
Type systemTargetType;
if (!TryResolveType("Orleans.Runtime.SystemTarget", out systemTargetType)) return false;
var systemTargetInterfaceType = typeof(ISystemTarget);
var systemTargetBaseInterfaceType = typeof(ISystemTargetBase);
#if !NETSTANDARD
if (type.Assembly.ReflectionOnly)
{
systemTargetType = ToReflectionOnlyType(systemTargetType);
systemTargetInterfaceType = ToReflectionOnlyType(systemTargetInterfaceType);
systemTargetBaseInterfaceType = ToReflectionOnlyType(systemTargetBaseInterfaceType);
}
#endif
if (!systemTargetInterfaceType.IsAssignableFrom(type) ||
!systemTargetBaseInterfaceType.IsAssignableFrom(type) ||
!systemTargetType.IsAssignableFrom(type)) return false;
// exclude generated classes.
return !IsGeneratedType(type);
}
public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints, bool complain)
{
complaints = null;
if (!IsGrainClass(type)) return false;
if (!type.GetTypeInfo().IsAbstract) return true;
complaints = complain ? new[] { string.Format("Grain type {0} is abstract and cannot be instantiated.", type.FullName) } : null;
return false;
}
public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints)
{
return IsConcreteGrainClass(type, out complaints, complain: true);
}
public static bool IsConcreteGrainClass(Type type)
{
IEnumerable<string> complaints;
return IsConcreteGrainClass(type, out complaints, complain: false);
}
public static bool IsGeneratedType(Type type)
{
return TypeHasAttribute(type, typeof(GeneratedAttribute));
}
/// <summary>
/// Returns true if the provided <paramref name="type"/> is in any of the provided
/// <paramref name="namespaces"/>, false otherwise.
/// </summary>
/// <param name="type">The type to check.</param>
/// <param name="namespaces"></param>
/// <returns>
/// true if the provided <paramref name="type"/> is in any of the provided <paramref name="namespaces"/>, false
/// otherwise.
/// </returns>
public static bool IsInNamespace(Type type, List<string> namespaces)
{
if (type.Namespace == null)
{
return false;
}
foreach (var ns in namespaces)
{
if (ns.Length > type.Namespace.Length)
{
continue;
}
// If the candidate namespace is a prefix of the type's namespace, return true.
if (type.Namespace.StartsWith(ns, StringComparison.Ordinal)
&& (type.Namespace.Length == ns.Length || type.Namespace[ns.Length] == '.'))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns true if <paramref name="type"/> has implementations of all serialization methods, false otherwise.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// true if <paramref name="type"/> has implementations of all serialization methods, false otherwise.
/// </returns>
public static bool HasAllSerializationMethods(Type type)
{
// Check if the type has any of the serialization methods.
var hasCopier = false;
var hasSerializer = false;
var hasDeserializer = false;
foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
{
hasSerializer |= method.GetCustomAttribute<SerializerMethodAttribute>(false) != null;
hasDeserializer |= method.GetCustomAttribute<DeserializerMethodAttribute>(false) != null;
hasCopier |= method.GetCustomAttribute<CopierMethodAttribute>(false) != null;
}
var hasAllSerializationMethods = hasCopier && hasSerializer && hasDeserializer;
return hasAllSerializationMethods;
}
public static bool IsGrainMethodInvokerType(Type type)
{
var generalType = typeof(IGrainMethodInvoker);
#if !NETSTANDARD
if (type.Assembly.ReflectionOnly)
{
generalType = ToReflectionOnlyType(generalType);
}
#endif
return generalType.IsAssignableFrom(type) && TypeHasAttribute(type, typeof(MethodInvokerAttribute));
}
#if NETSTANDARD_TODO
public static Type ResolveType(string fullName)
{
return Type.GetType(fullName, true);
}
public static bool TryResolveType(string fullName, out Type type)
{
type = Type.GetType(fullName, false);
return type != null;
}
#else
public static Type ResolveType(string fullName)
{
return CachedTypeResolver.Instance.ResolveType(fullName);
}
public static bool TryResolveType(string fullName, out Type type)
{
return CachedTypeResolver.Instance.TryResolveType(fullName, out type);
}
public static Type ResolveReflectionOnlyType(string assemblyQualifiedName)
{
return CachedReflectionOnlyTypeResolver.Instance.ResolveType(assemblyQualifiedName);
}
public static Type ToReflectionOnlyType(Type type)
{
return type.Assembly.ReflectionOnly ? type : ResolveReflectionOnlyType(type.AssemblyQualifiedName);
}
#endif
public static IEnumerable<Type> GetTypes(Assembly assembly, Predicate<Type> whereFunc, Logger logger)
{
return assembly.IsDynamic ? Enumerable.Empty<Type>() : GetDefinedTypes(assembly, logger).Select(t => t.AsType()).Where(type => !type.GetTypeInfo().IsNestedPrivate && whereFunc(type));
}
public static IEnumerable<TypeInfo> GetDefinedTypes(Assembly assembly, Logger logger)
{
try
{
return assembly.DefinedTypes;
}
catch (Exception exception)
{
if (logger != null && logger.IsWarning)
{
var message = $"AssemblyLoader encountered an exception loading types from assembly '{assembly.FullName}': {exception}";
logger.Warn(ErrorCode.Loader_TypeLoadError_5, message, exception);
}
var typeLoadException = exception as ReflectionTypeLoadException;
if (typeLoadException != null)
{
return typeLoadException.Types?.Where(type => type != null).Select(type => type.GetTypeInfo()) ??
Enumerable.Empty<TypeInfo>();
}
return Enumerable.Empty<TypeInfo>();
}
}
public static IEnumerable<Type> GetTypes(Predicate<Type> whereFunc, Logger logger)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var result = new List<Type>();
foreach (var assembly in assemblies)
{
// there's no point in evaluating nested private types-- one of them fails to coerce to a reflection-only type anyhow.
var types = GetTypes(assembly, whereFunc, logger);
result.AddRange(types);
}
return result;
}
public static IEnumerable<Type> GetTypes(List<string> assemblies, Predicate<Type> whereFunc, Logger logger)
{
var currentAssemblies = AppDomain.CurrentDomain.GetAssemblies();
var result = new List<Type>();
foreach (var assembly in currentAssemblies.Where(loaded => !loaded.IsDynamic && assemblies.Contains(loaded.Location)))
{
// there's no point in evaluating nested private types-- one of them fails to coerce to a reflection-only type anyhow.
var types = GetTypes(assembly, whereFunc, logger);
result.AddRange(types);
}
return result;
}
/// <summary>
/// Returns a value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.
/// </summary>
/// <param name="methodInfo">The method.</param>
/// <returns>A value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.</returns>
public static bool IsGrainMethod(MethodInfo methodInfo)
{
if (methodInfo == null) throw new ArgumentNullException("methodInfo", "Cannot inspect null method info");
if (methodInfo.IsStatic || methodInfo.IsSpecialName || methodInfo.DeclaringType == null)
{
return false;
}
return methodInfo.DeclaringType.GetTypeInfo().IsInterface
&& typeof(IAddressable).IsAssignableFrom(methodInfo.DeclaringType);
}
public static bool TypeHasAttribute(Type type, Type attribType)
{
#if !NETSTANDARD
if (type.Assembly.ReflectionOnly || attribType.Assembly.ReflectionOnly)
{
type = ToReflectionOnlyType(type);
attribType = ToReflectionOnlyType(attribType);
// we can't use Type.GetCustomAttributes here because we could potentially be working with a reflection-only type.
return CustomAttributeData.GetCustomAttributes(type).Any(
attrib => attribType.IsAssignableFrom(attrib.AttributeType));
}
#endif
return TypeHasAttribute(type.GetTypeInfo(), attribType);
}
public static bool TypeHasAttribute(TypeInfo typeInfo, Type attribType)
{
return typeInfo.GetCustomAttributes(attribType, true).Any();
}
/// <summary>
/// Returns a sanitized version of <paramref name="type"/>s name which is suitable for use as a class name.
/// </summary>
/// <param name="type">
/// The grain type.
/// </param>
/// <returns>
/// A sanitized version of <paramref name="type"/>s name which is suitable for use as a class name.
/// </returns>
public static string GetSuitableClassName(Type type)
{
return GetClassNameFromInterfaceName(type.GetUnadornedTypeName());
}
/// <summary>
/// Returns a class-like version of <paramref name="interfaceName"/>.
/// </summary>
/// <param name="interfaceName">
/// The interface name.
/// </param>
/// <returns>
/// A class-like version of <paramref name="interfaceName"/>.
/// </returns>
public static string GetClassNameFromInterfaceName(string interfaceName)
{
string cleanName;
if (interfaceName.StartsWith("i", StringComparison.OrdinalIgnoreCase))
{
cleanName = interfaceName.Substring(1);
}
else
{
cleanName = interfaceName;
}
return cleanName;
}
/// <summary>
/// Returns the non-generic type name without any special characters.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <returns>
/// The non-generic type name without any special characters.
/// </returns>
public static string GetUnadornedTypeName(this Type type)
{
var index = type.Name.IndexOf('`');
// An ampersand can appear as a suffix to a by-ref type.
return (index > 0 ? type.Name.Substring(0, index) : type.Name).TrimEnd('&');
}
/// <summary>
/// Returns the non-generic method name without any special characters.
/// </summary>
/// <param name="method">
/// The method.
/// </param>
/// <returns>
/// The non-generic method name without any special characters.
/// </returns>
public static string GetUnadornedMethodName(this MethodInfo method)
{
var index = method.Name.IndexOf('`');
return index > 0 ? method.Name.Substring(0, index) : method.Name;
}
/// <summary>Returns a string representation of <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="options">The type formatting options.</param>
/// <returns>A string representation of the <paramref name="type"/>.</returns>
public static string GetParseableName(this Type type, TypeFormattingOptions options = null)
{
options = options ?? new TypeFormattingOptions();
return ParseableNameCache.GetOrAdd(
Tuple.Create(type, options),
_ =>
{
var builder = new StringBuilder();
var typeInfo = type.GetTypeInfo();
GetParseableName(
type,
builder,
new Queue<Type>(
typeInfo.IsGenericTypeDefinition
? typeInfo.GetGenericArguments()
: typeInfo.GenericTypeArguments),
options);
return builder.ToString();
});
}
/// <summary>Returns a string representation of <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="builder">The <see cref="StringBuilder"/> to append results to.</param>
/// <param name="typeArguments">The type arguments of <paramref name="type"/>.</param>
/// <param name="options">The type formatting options.</param>
private static void GetParseableName(
Type type,
StringBuilder builder,
Queue<Type> typeArguments,
TypeFormattingOptions options)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsArray)
{
builder.AppendFormat(
"{0}[{1}]",
typeInfo.GetElementType().GetParseableName(options),
string.Concat(Enumerable.Range(0, type.GetArrayRank() - 1).Select(_ => ',')));
return;
}
if (typeInfo.IsGenericParameter)
{
if (options.IncludeGenericTypeParameters)
{
builder.Append(type.GetUnadornedTypeName());
}
return;
}
if (typeInfo.DeclaringType != null)
{
// This is not the root type.
GetParseableName(typeInfo.DeclaringType, builder, typeArguments, options);
builder.Append(options.NestedTypeSeparator);
}
else if (!string.IsNullOrWhiteSpace(type.Namespace) && options.IncludeNamespace)
{
// This is the root type, so include the namespace.
var namespaceName = type.Namespace;
if (options.NestedTypeSeparator != '.')
{
namespaceName = namespaceName.Replace('.', options.NestedTypeSeparator);
}
if (options.IncludeGlobal)
{
builder.AppendFormat("global::");
}
builder.AppendFormat("{0}{1}", namespaceName, options.NestedTypeSeparator);
}
if (type.IsConstructedGenericType)
{
// Get the unadorned name, the generic parameters, and add them together.
var unadornedTypeName = type.GetUnadornedTypeName() + options.NameSuffix;
builder.Append(EscapeIdentifier(unadornedTypeName));
var generics =
Enumerable.Range(0, Math.Min(typeInfo.GetGenericArguments().Count(), typeArguments.Count))
.Select(_ => typeArguments.Dequeue())
.ToList();
if (generics.Count > 0 && options.IncludeTypeParameters)
{
var genericParameters = string.Join(
",",
generics.Select(generic => GetParseableName(generic, options)));
builder.AppendFormat("<{0}>", genericParameters);
}
}
else if (typeInfo.IsGenericTypeDefinition)
{
// Get the unadorned name, the generic parameters, and add them together.
var unadornedTypeName = type.GetUnadornedTypeName() + options.NameSuffix;
builder.Append(EscapeIdentifier(unadornedTypeName));
var generics =
Enumerable.Range(0, Math.Min(type.GetGenericArguments().Count(), typeArguments.Count))
.Select(_ => typeArguments.Dequeue())
.ToList();
if (generics.Count > 0 && options.IncludeTypeParameters)
{
var genericParameters = string.Join(
",",
generics.Select(_ => options.IncludeGenericTypeParameters ? _.ToString() : string.Empty));
builder.AppendFormat("<{0}>", genericParameters);
}
}
else
{
builder.Append(EscapeIdentifier(type.GetUnadornedTypeName() + options.NameSuffix));
}
}
/// <summary>
/// Returns the namespaces of the specified types.
/// </summary>
/// <param name="types">
/// The types to include.
/// </param>
/// <returns>
/// The namespaces of the specified types.
/// </returns>
public static IEnumerable<string> GetNamespaces(params Type[] types)
{
return types.Select(type => "global::" + type.Namespace).Distinct();
}
/// <summary>
/// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </returns>
public static MethodInfo Method<T, TResult>(Expression<Func<T, TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="PropertyInfo"/> for the simple member access in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the property.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the property.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="PropertyInfo"/> for the simple member access call in the provided <paramref name="expression"/>.
/// </returns>
public static PropertyInfo Property<T, TResult>(Expression<Func<T, TResult>> expression)
{
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member as PropertyInfo;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.
/// </returns>
public static MemberInfo Member<T, TResult>(Expression<Func<T, TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.</summary>
/// <typeparam name="TResult">The return type of the method.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.</returns>
public static MemberInfo Member<TResult>(Expression<Func<TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</summary>
/// <typeparam name="T">The containing type of the method.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns>
public static MethodInfo Method<T>(Expression<Func<T>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">The containing type of the method.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns>
public static MethodInfo Method<T>(Expression<Action<T>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </returns>
public static MethodInfo Method(Expression<Action> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</summary>
/// <param name="type">The type.</param>
/// <returns>The namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</returns>
public static string GetNamespaceOrEmpty(this Type type)
{
if (type == null || string.IsNullOrEmpty(type.Namespace))
{
return string.Empty;
}
return type.Namespace;
}
/// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param>
/// <returns>The types referenced by the provided <paramref name="type"/>.</returns>
public static IList<Type> GetTypes(this Type type, bool includeMethods = false)
{
List<Type> results;
var key = Tuple.Create(type, includeMethods);
if (!ReferencedTypes.TryGetValue(key, out results))
{
results = GetTypes(type, includeMethods, null).ToList();
ReferencedTypes.TryAdd(key, results);
}
return results;
}
/// <summary>
/// Get a public or non-public constructor that matches the constructor arguments signature
/// </summary>
/// <param name="type">The type to use.</param>
/// <param name="constructorArguments">The constructor argument types to match for the signature.</param>
/// <returns>A constructor that matches the signature or <see langword="null"/>.</returns>
public static ConstructorInfo GetConstructorThatMatches(Type type, Type[] constructorArguments)
{
#if NETSTANDARD
var candidates = type.GetTypeInfo().GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (ConstructorInfo candidate in candidates)
{
if (ConstructorMatches(candidate, constructorArguments))
{
return candidate;
}
}
return null;
#else
var constructorInfo = type.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
constructorArguments,
null);
return constructorInfo;
#endif
}
private static bool ConstructorMatches(ConstructorInfo candidate, Type[] constructorArguments)
{
ParameterInfo[] parameters = candidate.GetParameters();
if (parameters.Length == constructorArguments.Length)
{
for (int i = 0; i < constructorArguments.Length; i++)
{
if (parameters[i].ParameterType != constructorArguments[i])
{
return false;
}
}
return true;
}
return false;
}
/// <summary>
/// Returns a value indicating whether or not the provided assembly is the Orleans assembly or references it.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>A value indicating whether or not the provided assembly is the Orleans assembly or references it.</returns>
internal static bool IsOrleansOrReferencesOrleans(Assembly assembly)
{
// We want to be loosely coupled to the assembly version if an assembly depends on an older Orleans,
// but we want a strong assembly match for the Orleans binary itself
// (so we don't load 2 different versions of Orleans by mistake)
return DoReferencesContain(assembly.GetReferencedAssemblies(), OrleansCoreAssembly)
|| string.Equals(assembly.GetName().FullName, OrleansCoreAssembly.FullName, StringComparison.Ordinal);
}
/// <summary>
/// Returns a value indicating whether or not the specified references contain the provided assembly name.
/// </summary>
/// <param name="references">The references.</param>
/// <param name="assemblyName">The assembly name.</param>
/// <returns>A value indicating whether or not the specified references contain the provided assembly name.</returns>
private static bool DoReferencesContain(IReadOnlyCollection<AssemblyName> references, AssemblyName assemblyName)
{
if (references.Count == 0)
{
return false;
}
return references.Any(asm => string.Equals(asm.Name, assemblyName.Name, StringComparison.Ordinal));
}
/// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param>
/// <param name="exclude">Types to exclude</param>
/// <returns>The types referenced by the provided <paramref name="type"/>.</returns>
private static IEnumerable<Type> GetTypes(
this Type type,
bool includeMethods,
HashSet<Type> exclude)
{
exclude = exclude ?? new HashSet<Type>();
if (!exclude.Add(type))
{
yield break;
}
yield return type;
if (type.IsArray)
{
foreach (var elementType in type.GetElementType().GetTypes(false, exclude: exclude))
{
yield return elementType;
}
}
if (type.IsConstructedGenericType)
{
foreach (var genericTypeArgument in
type.GetGenericArguments().SelectMany(_ => GetTypes(_, false, exclude: exclude)))
{
yield return genericTypeArgument;
}
}
if (!includeMethods)
{
yield break;
}
foreach (var method in type.GetMethods())
{
foreach (var referencedType in GetTypes(method.ReturnType, false, exclude: exclude))
{
yield return referencedType;
}
foreach (var parameter in method.GetParameters())
{
foreach (var referencedType in GetTypes(parameter.ParameterType, false, exclude: exclude))
{
yield return referencedType;
}
}
}
}
private static string EscapeIdentifier(string identifier)
{
switch (identifier)
{
case "abstract":
case "add":
case "base":
case "bool":
case "break":
case "byte":
case "case":
case "catch":
case "char":
case "checked":
case "class":
case "const":
case "continue":
case "decimal":
case "default":
case "delegate":
case "do":
case "double":
case "else":
case "enum":
case "event":
case "explicit":
case "extern":
case "false":
case "finally":
case "fixed":
case "float":
case "for":
case "foreach":
case "get":
case "goto":
case "if":
case "implicit":
case "in":
case "int":
case "interface":
case "internal":
case "lock":
case "long":
case "namespace":
case "new":
case "null":
case "object":
case "operator":
case "out":
case "override":
case "params":
case "partial":
case "private":
case "protected":
case "public":
case "readonly":
case "ref":
case "remove":
case "return":
case "sbyte":
case "sealed":
case "set":
case "short":
case "sizeof":
case "static":
case "string":
case "struct":
case "switch":
case "this":
case "throw":
case "true":
case "try":
case "typeof":
case "uint":
case "ulong":
case "unsafe":
case "ushort":
case "using":
case "virtual":
case "where":
case "while":
return "@" + identifier;
default:
return identifier;
}
}
}
}
| |
#if ENABLE_PLAYFABSERVER_API
using System;
using System.Collections.Generic;
using PlayFab.SharedModels;
namespace PlayFab.MatchmakerModels
{
[Serializable]
public class AuthUserRequest : PlayFabRequestCommon
{
/// <summary>
/// Session Ticket provided by the client.
/// </summary>
public string AuthorizationTicket;
}
[Serializable]
public class AuthUserResponse : PlayFabResultCommon
{
/// <summary>
/// Boolean indicating if the user has been authorized to use the external match-making service.
/// </summary>
public bool Authorized;
/// <summary>
/// PlayFab unique identifier of the account that has been authorized.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// A unique instance of an item in a user's inventory. Note, to retrieve additional information for an item instance (such
/// as Tags, Description, or Custom Data that are set on the root catalog item), a call to GetCatalogItems is required. The
/// Item ID of the instance can then be matched to a catalog entry, which contains the additional information. Also note
/// that Custom Data is only set here from a call to UpdateUserInventoryItemCustomData.
/// </summary>
[Serializable]
public class ItemInstance
{
/// <summary>
/// Game specific comment associated with this instance when it was added to the user inventory.
/// </summary>
public string Annotation;
/// <summary>
/// Array of unique items that were awarded when this catalog item was purchased.
/// </summary>
public List<string> BundleContents;
/// <summary>
/// Unique identifier for the parent inventory item, as defined in the catalog, for object which were added from a bundle or
/// container.
/// </summary>
public string BundleParent;
/// <summary>
/// Catalog version for the inventory item, when this instance was created.
/// </summary>
public string CatalogVersion;
/// <summary>
/// A set of custom key-value pairs on the inventory item.
/// </summary>
public Dictionary<string,string> CustomData;
/// <summary>
/// CatalogItem.DisplayName at the time this item was purchased.
/// </summary>
public string DisplayName;
/// <summary>
/// Timestamp for when this instance will expire.
/// </summary>
public DateTime? Expiration;
/// <summary>
/// Class name for the inventory item, as defined in the catalog.
/// </summary>
public string ItemClass;
/// <summary>
/// Unique identifier for the inventory item, as defined in the catalog.
/// </summary>
public string ItemId;
/// <summary>
/// Unique item identifier for this specific instance of the item.
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Timestamp for when this instance was purchased.
/// </summary>
public DateTime? PurchaseDate;
/// <summary>
/// Total number of remaining uses, if this is a consumable item.
/// </summary>
public int? RemainingUses;
/// <summary>
/// Currency type for the cost of the catalog item.
/// </summary>
public string UnitCurrency;
/// <summary>
/// Cost of the catalog item in the given currency.
/// </summary>
public uint UnitPrice;
/// <summary>
/// The number of uses that were added or removed to this item in this call.
/// </summary>
public int? UsesIncrementedBy;
}
[Serializable]
public class PlayerJoinedRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the Game Server Instance the user is joining. This must be a Game Server Instance started with the
/// Matchmaker/StartGame API.
/// </summary>
public string LobbyId;
/// <summary>
/// PlayFab unique identifier for the player joining.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class PlayerJoinedResponse : PlayFabResultCommon
{
}
[Serializable]
public class PlayerLeftRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the Game Server Instance the user is leaving. This must be a Game Server Instance started with the
/// Matchmaker/StartGame API.
/// </summary>
public string LobbyId;
/// <summary>
/// PlayFab unique identifier for the player leaving.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class PlayerLeftResponse : PlayFabResultCommon
{
}
public enum Region
{
USCentral,
USEast,
EUWest,
Singapore,
Japan,
Brazil,
Australia
}
[Serializable]
public class StartGameRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the previously uploaded build executable which is to be started.
/// </summary>
public string Build;
/// <summary>
/// Custom command line argument when starting game server process.
/// </summary>
public string CustomCommandLineData;
/// <summary>
/// HTTP endpoint URL for receiving game status events, if using an external matchmaker. When the game ends, PlayFab will
/// make a POST request to this URL with the X-SecretKey header set to the value of the game's secret and an
/// application/json body of { "EventName": "game_ended", "GameID": "<gameid>" }.
/// </summary>
public string ExternalMatchmakerEventEndpoint;
/// <summary>
/// Game mode for this Game Server Instance.
/// </summary>
public string GameMode;
/// <summary>
/// Region with which to associate the server, for filtering.
/// </summary>
public Region Region;
}
[Serializable]
public class StartGameResponse : PlayFabResultCommon
{
/// <summary>
/// Unique identifier for the game/lobby in the new Game Server Instance.
/// </summary>
public string GameID;
/// <summary>
/// IPV4 address of the server
/// </summary>
public string ServerIPV4Address;
/// <summary>
/// IPV6 address of the new Game Server Instance.
/// </summary>
public string ServerIPV6Address;
/// <summary>
/// Port number for communication with the Game Server Instance.
/// </summary>
public uint ServerPort;
/// <summary>
/// Public DNS name (if any) of the server
/// </summary>
public string ServerPublicDNSName;
}
[Serializable]
public class UserInfoRequest : PlayFabRequestCommon
{
/// <summary>
/// Minimum catalog version for which data is requested (filters the results to only contain inventory items which have a
/// catalog version of this or higher).
/// </summary>
public int MinCatalogVersion;
/// <summary>
/// PlayFab unique identifier of the user whose information is being requested.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class UserInfoResponse : PlayFabResultCommon
{
/// <summary>
/// Array of inventory items in the user's current inventory.
/// </summary>
public List<ItemInstance> Inventory;
/// <summary>
/// Boolean indicating whether the user is a developer.
/// </summary>
public bool IsDeveloper;
/// <summary>
/// PlayFab unique identifier of the user whose information was requested.
/// </summary>
public string PlayFabId;
/// <summary>
/// Steam unique identifier, if the user has an associated Steam account.
/// </summary>
public string SteamId;
/// <summary>
/// Title specific display name, if set.
/// </summary>
public string TitleDisplayName;
/// <summary>
/// PlayFab unique user name.
/// </summary>
public string Username;
/// <summary>
/// Array of virtual currency balance(s) belonging to the user.
/// </summary>
public Dictionary<string,int> VirtualCurrency;
/// <summary>
/// Array of remaining times and timestamps for virtual currencies.
/// </summary>
public Dictionary<string,VirtualCurrencyRechargeTime> VirtualCurrencyRechargeTimes;
}
[Serializable]
public class VirtualCurrencyRechargeTime
{
/// <summary>
/// Maximum value to which the regenerating currency will automatically increment. Note that it can exceed this value
/// through use of the AddUserVirtualCurrency API call. However, it will not regenerate automatically until it has fallen
/// below this value.
/// </summary>
public int RechargeMax;
/// <summary>
/// Server timestamp in UTC indicating the next time the virtual currency will be incremented.
/// </summary>
public DateTime RechargeTime;
/// <summary>
/// Time remaining (in seconds) before the next recharge increment of the virtual currency.
/// </summary>
public int SecondsToRecharge;
}
}
#endif
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMarquee : MonoBehaviour {
public List<GameObject> SelectedUnits;
public Texture marqueeGraphics;
public GameObject movementRing;
public GameObject attackRing;
public LayerMask marqueeLayer;
public bool mouseIsBeingUsedByHUD;
public Camera minimapCam;
bool marqueeStarted;
Rect marqueeRect;
Rect backupRect;
Vector2 marqueeOrigin;
Vector2 marqueeSize;
HudController HUD;
void Start()
{
SelectedUnits = new List<GameObject>();
HUD = GameObject.Find ("HUD").GetComponent<HudController>();
}
private void OnGUI()
{
marqueeRect = new Rect(marqueeOrigin.x, marqueeOrigin.y, marqueeSize.x, marqueeSize.y);
GUI.color = new Color(0, 0, 0, .3f);
GUI.DrawTexture(marqueeRect, marqueeGraphics);
}
void Update()
{
// ignore all actions performed by the mouse when it is over the HUD
if (!mouseIsBeingUsedByHUD)
{
if (Input.GetMouseButtonDown(0))
MarqueeStart();
if (Input.GetMouseButtonUp(0))
MarqueeFinish();
if (Input.GetMouseButton(0))
MarqueeUpdate();
}
// Can use this without ignoring HUD
if (Input.GetMouseButtonDown(1))
RightMouseClick();
}
void MarqueeStart()
{
// clear previous selection if "shift" is not held down
if (!Input.GetKey(Keymap.select.Inclusive))
UnselectUnits();
//Check if the player just wants to add/remove an unit
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, marqueeLayer) &&
hit.collider.CompareTag("selectable"))
{
marqueeStarted = false;
if (Input.GetKey(Keymap.select.Alternative))
SelectedUnits.AddRange(FindSelectableUnits(hit.collider.name));
else
SelectedUnits.Add(hit.collider.gameObject);
SelectUnits();
}
else
{
marqueeStarted = true;
// initiate selection marquee
float _invertedY = Screen.height - Input.mousePosition.y;
marqueeOrigin = new Vector2(Input.mousePosition.x, _invertedY);
}
}
void MarqueeUpdate()
{
if (marqueeStarted)
{
float _invertedY = Screen.height - Input.mousePosition.y;
marqueeSize = new Vector2(Input.mousePosition.x - marqueeOrigin.x, (marqueeOrigin.y - _invertedY) * -1);
if (marqueeRect.width < 0)
backupRect = new Rect(marqueeRect.x - Mathf.Abs(marqueeRect.width), marqueeRect.y, Mathf.Abs(marqueeRect.width), marqueeRect.height);
else if (marqueeRect.height < 0)
backupRect = new Rect(marqueeRect.x, marqueeRect.y - Mathf.Abs(marqueeRect.height), marqueeRect.width, Mathf.Abs(marqueeRect.height));
if (marqueeRect.width < 0 && marqueeRect.height < 0)
backupRect = new Rect(marqueeRect.x - Mathf.Abs(marqueeRect.width), marqueeRect.y - Mathf.Abs(marqueeRect.height), Mathf.Abs(marqueeRect.width), Mathf.Abs(marqueeRect.height));
}
}
void MarqueeFinish()
{
if (marqueeStarted)
{
//Poppulate the selectableUnits array with all the selectable units that exist
foreach (GameObject unit in FindSelectableUnits())
{
//Convert the world position of the unit to a screen position and then to a GUI point
Vector3 _screenPos = Camera.main.WorldToScreenPoint(unit.transform.position);
Vector2 _screenPoint = new Vector2(_screenPos.x, Screen.height - _screenPos.y);
//Ensure that any units not within the marquee are currently unselected
if (marqueeRect.Contains(_screenPoint) || backupRect.Contains(_screenPoint))
SelectedUnits.Add(unit);
}
SelectUnits();
}
//Reset the marquee so it no longer appears on the screen.
marqueeStarted = false;
marqueeRect.width = 0;
marqueeRect.height = 0;
backupRect.width = 0;
backupRect.height = 0;
marqueeSize = Vector2.zero;
}
void RightMouseClick ()
{
RaycastHit hit;
// Clicking on NOT the HUD
if (!mouseIsBeingUsedByHUD) {
if (Physics.Raycast (
Camera.main.ScreenPointToRay (Input.mousePosition),
out hit,
Mathf.Infinity,
marqueeLayer
)) {
// right click over an enemy unit
if (hit.collider.CompareTag ("enemy")) {
AttackRing (hit.collider.transform.position);
AttackUnit (hit.collider.gameObject);
}
// right click over the ground
else {
MovementRing (hit.point);
MoveUnits (hit.point);
}
}
// Clicking on the HUD
} else {
if (Physics.Raycast (
minimapCam.ScreenPointToRay (Input.mousePosition),
out hit,
Mathf.Infinity,
marqueeLayer
)) {
// right click over an enemy unit
if (hit.collider.CompareTag ("enemy")) {
AttackRing (hit.collider.transform.position);
AttackUnit (hit.collider.gameObject);
}
// right click over the ground
else {
MovementRing (hit.point);
MoveUnits (hit.point);
}
}
}
}
List<GameObject> FindSelectableUnits(string name)
{
List<GameObject> selectable = FindSelectableUnits();
for (int i = 0; i < selectable.Count; i++)
if (selectable[i].name != name)
{
selectable.RemoveAt(i);
i--;
}
return selectable;
}
List<GameObject> FindSelectableUnits()
{
return new List<GameObject>(
GameObject.FindGameObjectsWithTag("selectable")
);
}
public void UnselectUnits ()
{
HUD.CleanAction();
AttackRing(false);
MovementRing(false);
// remove previous selection
foreach ( GameObject unit in SelectedUnits )
unit.SendMessage("OnUnselected", SendMessageOptions.DontRequireReceiver);
SelectedUnits.Clear();
}
public void SelectUnits (GameObject unit)
{
List<GameObject> units = new List<GameObject>();
units.Add(unit);
SelectUnits(units);
}
public void SelectUnits ( List<GameObject> _units )
{
if (_units != null && _units.Count > 0)
{
if (!Input.GetKey(Keymap.select.Inclusive))
UnselectUnits();
SelectedUnits.AddRange(_units);
SelectUnits();
}
}
void SelectUnits ()
{
// if at least on zombie is selected, make him to moan
if (SelectedUnits.Count > 0)
{
SelectedUnits[0]
.GetComponent<ZombieAudioController>()
.Moan();
// if zombie selected is moving, show its destination
if (SelectedUnits[0].GetComponent<UnitController>().State() == UnitState.moving)
MovementRing(SelectedUnits[0].GetComponent<NavMeshAgent>().destination);
// hide MovementRing otherwise
else
MovementRing(false);
}
// add new selection
foreach ( GameObject unit in SelectedUnits )
unit.SendMessage("OnSelected", SendMessageOptions.DontRequireReceiver);
}
public void AttackUnit ( GameObject _target )
{
// if at least on zombie is selected, make him scream
if (SelectedUnits.Count > 0)
{
SelectedUnits[0]
.GetComponent<ZombieAudioController>()
.Rage();
AttackRing(_target);
}
foreach ( GameObject unit in SelectedUnits )
unit
.GetComponent<UnitController>()
.MoveAndAttack(_target);
}
public void MoveUnits ( Vector3 _target )
{
int row = 0;
int column = 0;
foreach ( GameObject unit in SelectedUnits )
{
// offset from _target of units, when they move towards it
Vector3 target = _target;
target.x += ( column % 2 == 0 ? 2 : -2 ) * column;
target.z += -2 * row;
if ( ++ column == 5 )
{
column = 0;
row ++;
}
UnitController current = unit.GetComponent<UnitController>();
// Force movement to override attacking
current.hold = false;
unit.GetComponent<Mob>().Target = null;
current.Move( target );
}
}
public void HoldUnits ()
{
foreach ( GameObject unit in SelectedUnits )
unit.GetComponent<UnitController>().hold = true;
}
public void UnholdUnits ()
{
foreach ( GameObject unit in SelectedUnits )
unit.GetComponent<UnitController>().hold = false;
}
public void StopUnits ()
{
foreach ( GameObject unit in SelectedUnits )
unit
.GetComponent<UnitController>()
.Stop();
}
public void ResumeUnits ( )
{
foreach ( GameObject unit in SelectedUnits )
unit
.GetComponent<UnitController>()
.Resume();
}
void MovementRing( bool _active )
{
movementRing.SetActive(_active);
}
void MovementRing(Vector3 _position)
{
AttackRing(false);
movementRing.transform.position = _position + Vector3.up;
movementRing.SetActive(true);
}
void AttackRing(Vector3 _position)
{
MovementRing(false);
attackRing.transform.position = _position + Vector3.up;
attackRing.SetActive(true);
attackRing.GetComponent<Animator>().SetTrigger("active");
StartCoroutine(AttackRing(false));
}
IEnumerator AttackRing(bool _active)
{
yield return new WaitForSeconds(2.5f);
if (_active)
{
attackRing.SetActive(true);
attackRing.GetComponent<Animator>().SetTrigger("active");
}
else
{
attackRing.SetActive(false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
namespace Desharp.Core {
internal class Config {
internal const string APP_SETTINGS_ENABLED = "Desharp:Enabled"; // true | false | 1 | 0
internal const string APP_SETTINGS_EDITOR = "Desharp:Editor"; // MSVS2005 | MSVS2008 | MSVS2010 | MSVS2012 | MSVS2013 | MSVS2015 | MSVS2017
internal const string APP_SETTINGS_OUTPUT = "Desharp:Output"; // text | html
internal const string APP_SETTINGS_DEBUG_IPS = "Desharp:DebugIps"; // 127.0.0.1,88.31.45.67,...
internal const string APP_SETTINGS_LEVELS = "Desharp:Levels"; // exception,-debug,info,notice,warning,error,critical,alert,emergency,-javascript
internal const string APP_SETTINGS_PANELS = "Desharp:Panels"; // Desharp.Panels.Session,Desharp.Panels.Routing
internal const string APP_SETTINGS_DIRECTORY = "Desharp:Directory"; // ~/logs
internal const string APP_SETTINGS_WRITE_MILISECONDS = "Desharp:WriteMiliseconds"; // 0
internal const string APP_SETTINGS_ERROR_PAGE = "Desharp:ErrorPage"; // ~/path/to/custom/error-page-500.html
internal const string APP_SETTINGS_DEPTH = "Desharp:Depth"; // 3
internal const string APP_SETTINGS_MAX_LENGTH = "Desharp:MaxLength"; // 1024
internal const string APP_SETTINGS_SOURCE_LOC = "Desharp:SourceLocation"; // true | false | 1 | 0
internal const string APP_SETTINGS_NOTIFY_SETTINGS = "Desharp:NotifySettings"; // { host: 'smtp.mailbox.com', port: 587, ssl: true, user: 'username', password: '1234', from: 'desharp@app.com', to: 'username@mailbox.com', priority: 'high', timeout: 30000 }
internal const string APP_SETTINGS_DUMP_COMPILLER_GENERATED = "Desharp:DumpCompillerGenerated"; // false
private static Dictionary<string, string> _appSettings = new Dictionary<string, string>();
static Config () {
string itemKey;
string itemValue;
foreach (string key in ConfigurationManager.AppSettings) {
itemKey = key.Trim();
itemValue = ConfigurationManager.AppSettings[key].ToString();
if (itemKey.ToLower().IndexOf("desharp:") == 0) {
Config._appSettings[itemKey] = itemValue.Trim();
}
}
}
internal static bool? GetEnabled () {
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_ENABLED)) {
string rawValue = Config._appSettings[Config.APP_SETTINGS_ENABLED].Trim().ToLower();
return (rawValue == "false" || rawValue == "0" || rawValue == "") ? false : true;
} else {
return null;
}
}
internal static Type[] GetDebugPanels () {
List<Type> result = new List<Type>();
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_PANELS)) {
string rawValue = Config._appSettings[Config.APP_SETTINGS_PANELS].Trim();
Regex r = new Regex(@"[^a-zA-Z0-9_\,\.]");
rawValue = r.Replace(rawValue, "");
List<string> rawItems = rawValue.Split(',').ToList<string>();
Type value;
foreach (string rawItem in rawItems) {
try {
value = Type.GetType(rawItem, true);
if (value != null && !result.Contains(value)) {
result.Add(value);
}
} catch { }
}
}
return result.ToArray();
}
internal static string GetEditor () {
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_EDITOR)) {
return Config._appSettings[Config.APP_SETTINGS_EDITOR].Trim();
} else {
return null;
}
}
internal static string GetErrorPage () {
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_ERROR_PAGE)) {
return Config._appSettings[Config.APP_SETTINGS_ERROR_PAGE].Trim();
}
return "";
}
internal static LogFormat? GetLogFormat () {
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_OUTPUT)) {
string rawValue = Config._appSettings[Config.APP_SETTINGS_OUTPUT].Trim().ToLower();
if (rawValue == "html") return LogFormat.Html;
if (rawValue == "text") return LogFormat.Text;
}
return null;
}
internal static List<string> GetDebugIps () {
List<string> result = new List<string>();
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_DEBUG_IPS)) {
string rawValue = Config._appSettings[Config.APP_SETTINGS_DEBUG_IPS].Trim().ToLower();
Regex r = new Regex(@"[^a-f0-9\.\,:]");
rawValue = r.Replace(rawValue, "");
result = rawValue.Split(',').ToList<string>();
}
return result;
}
internal static Dictionary<string, int> GetLevels () {
Dictionary<string, int> result = new Dictionary<string, int>();
List<string> allPossiblelevels = LevelValues.Values.Values.ToList<string>();
allPossiblelevels.Add("exception");
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_LEVELS)) {
string rawValue = Config._appSettings[Config.APP_SETTINGS_LEVELS].Trim().ToLower();
Regex r = new Regex(@"[^a-z\,\-\+]");
rawValue = r.Replace(rawValue, "");
List<string> rawItems = rawValue.Split(',').ToList<string>();
string key;
int value;
foreach (string rawItem in rawItems) {
if (rawItem.Substring(0, 1) == "-") {
key = rawItem.Substring(1);
value = 0;
} else if (rawItem.Substring(0, 1) == "+") {
key = rawItem.Substring(1);
value = 2;
} else {
key = rawItem;
value = 1;
}
if (!result.ContainsKey(key))
result[key] = value;
}
}
int allLevelsDefaultValue = result.Count > 0 ? 0 : 1;
foreach (string levelKey in allPossiblelevels)
if (!result.ContainsKey(levelKey))
result.Add(levelKey, allLevelsDefaultValue);
return result;
}
internal static int GetLogWriteMilisecond () {
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_WRITE_MILISECONDS)) {
string rawValue = Config._appSettings[Config.APP_SETTINGS_WRITE_MILISECONDS].Trim();
rawValue = new Regex("[^0-9]").Replace(rawValue, "");
if (rawValue.Length > 0) {
return Int32.Parse(rawValue);
}
}
return 0;
}
internal static string GetDirectory () {
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_DIRECTORY)) {
return Config._appSettings[Config.APP_SETTINGS_DIRECTORY].Trim();
}
return "";
}
internal static int GetDepth () {
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_DEPTH)) {
string rawValue = Config._appSettings[Config.APP_SETTINGS_DEPTH].Trim();
rawValue = new Regex("[^0-9]").Replace(rawValue, "");
if (rawValue.Length > 0) {
return Int32.Parse(rawValue);
}
}
return 0;
}
internal static int GetMaxLength () {
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_MAX_LENGTH)) {
string rawValue = Config._appSettings[Config.APP_SETTINGS_MAX_LENGTH].Trim();
rawValue = new Regex("[^0-9]").Replace(rawValue, "");
if (rawValue.Length > 0) {
return Int32.Parse(rawValue);
}
}
return 0;
}
internal static bool? GetSourceLocation () {
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_SOURCE_LOC)) {
string rawValue = Config._appSettings[Config.APP_SETTINGS_SOURCE_LOC].Trim().ToLower();
return (rawValue == "false" || rawValue == "0" || rawValue == "") ? false : true;
} else {
return null;
}
}
internal static bool? GetDumpCompillerGenerated () {
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_DUMP_COMPILLER_GENERATED)) {
string rawValue = Config._appSettings[Config.APP_SETTINGS_DUMP_COMPILLER_GENERATED].Trim().ToLower();
return (rawValue == "false" || rawValue == "0" || rawValue == "") ? false : true;
} else {
return null;
}
}
internal static Dictionary<string, object> GetNotifySettings () {
Dictionary<string, object> result = new Dictionary<string, object>();
if (Config._appSettings.ContainsKey(Config.APP_SETTINGS_NOTIFY_SETTINGS)) {
string rawJson = Config._appSettings[Config.APP_SETTINGS_NOTIFY_SETTINGS].Trim();
try {
// remove all new lines and tabs
Regex r1 = new Regex("[\r\n\t]");
rawJson = r1.Replace(rawJson, "");
// fix all keys with missing begin and end double quotes
Regex r2 = new Regex(@"([^""])([a-zA-Z]+):");
rawJson = r2.Replace(rawJson, @"$1""$2"":");
// change all values with single quots to double quots
Regex r3 = new Regex(@"'([^']*)'");
rawJson = r3.Replace(rawJson, @"""$1""");
// remove all double dots with leading space to double dots only
Regex r4 = new Regex(@""":\s");
rawJson = r4.Replace(rawJson, @""":");
// remove all spaces between value and another key
Regex r5 = new Regex(@""",\s+""");
rawJson = r5.Replace(rawJson, @""",""");
Regex r6 = new Regex(@"""\s+\}");
rawJson = r6.Replace(rawJson, @"""}");
// so let's deserialize string data
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
result = jsonSerializer.Deserialize<Dictionary<string, object>>(rawJson);
} catch (Exception ex) {
result.Add("error", ex.Message);
}
}
if (result.ContainsKey("port")) {
string portStr = result["port"].ToString();
int port = 25;
Int32.TryParse(portStr, out port);
result["port"] = port;
}
if (result.ContainsKey("timeout")) {
string timeoutStr = result["timeout"].ToString();
int timeout = 10000;
Int32.TryParse(timeoutStr, out timeout);
result["timeout"] = timeout;
}
if (result.ContainsKey("ssl")) {
result["ssl"] = Boolean.Parse(result["ssl"].ToString().ToLower());
} else {
result["ssl"] = false;
}
if (result.ContainsKey("background")) {
result["background"] = Boolean.Parse(result["background"].ToString().ToLower());
} else {
result["background"] = false;
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace THNETII.TypeConverter.Serialization
{
/// <summary>
/// Helper class that provides Enum-String Conversions that honour the
/// <see cref="EnumMemberAttribute"/> applied to values of the enumeration
/// type.
/// </summary>
public static class EnumMemberStringConverter
{
private static class EnumValues<T> where T : struct, Enum
{
public static readonly Type TypeRef = typeof(T);
public static readonly IDictionary<string, T> StringToValue = InitializeStringToValueDictionary();
public static readonly IDictionary<T, string> ValueToString = InitializeValueToStringDictionary();
static void InitializeConversionDictionary(Action<string, T> dictionaryAddValueAction)
{
var ti = TypeRef.GetTypeInfo();
foreach (var fi in ti.DeclaredFields.Where(i => i.IsStatic))
{
var enumMemberAttr = fi.GetCustomAttribute<EnumMemberAttribute>();
if (enumMemberAttr is null)
continue;
T v = (T)fi.GetValue(null);
string s = enumMemberAttr.IsValueSetExplicitly ? enumMemberAttr.Value : fi.Name;
dictionaryAddValueAction(s, v);
}
}
static IDictionary<string, T> InitializeStringToValueDictionary()
{
var stringToValue = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
InitializeConversionDictionary((s, v) =>
{
if (s is null)
return;
if (!stringToValue.ContainsKey(s))
stringToValue[s] = v;
});
return stringToValue;
}
static IDictionary<T, string> InitializeValueToStringDictionary()
{
var valueToString = new Dictionary<T, string>();
InitializeConversionDictionary((s, v) =>
{
if (!valueToString.ContainsKey(v))
valueToString[v] = s;
});
return valueToString;
}
}
/// <summary>
/// Converts the string representation of the constant name, serialization name or the numeric value of one
/// or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>.
/// <para>This operation is always case-insensitive using ordinal string comparison.</para>
/// </summary>
/// <typeparam name="T">The enumeration type to convert to.</typeparam>
/// <param name="s">A string containing the name, serialization name or value to convert.</param>
/// <returns>The converted value as an instance of <typeparamref name="T"/>.</returns>
/// <remarks>
/// The serialization name refers to the value specified in for the <see cref="EnumMemberAttribute.Value"/> member of an
/// <see cref="EnumMemberAttribute"/> applied to one of the enumerated constants of the <typeparamref name="T"/> enumeration type.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1000")]
public static T Parse<T>(string s) where T : struct, Enum
{
if (!(s is null) && EnumValues<T>.StringToValue.TryGetValue(s, out T value))
return value;
return EnumStringConverter.Parse<T>(s!);
}
/// <summary>
/// Attempts to convert the string representation of the constant name, serialization name or numeric value of
/// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>.
/// <para>This operation is always case-insensitive using ordinal string comparison.</para>
/// <para>Returns the default value for <typeparamref name="T"/> in case the string cannot be converted.</para>
/// </summary>
/// <typeparam name="T">The enumeration type to convert to.</typeparam>
/// <param name="s">A string containing the name, serialization name or value to convert.</param>
/// <returns>
/// The converted value as an instance of <typeparamref name="T"/>, or the default value of <typeparamref name="T"/>
/// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1000")]
public static T ParseOrDefault<T>(string? s) where T : struct, Enum =>
ParseOrDefault<T>(s, @default: default);
/// <summary>
/// Attempts to convert the string representation of the constant name, serialization name or numeric value of
/// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>.
/// <para>This operation is always case-insensitive using ordinal string comparison.</para>
/// <para>Returns the specified alternate value in case the string cannot be converted.</para>
/// </summary>
/// <typeparam name="T">The enumeration type to convert to.</typeparam>
/// <param name="s">A string containing the name, serialization name or value to convert.</param>
/// <param name="default">The default value to return if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>.</param>
/// <returns>
/// The converted value as an instance of <typeparamref name="T"/>, or <paramref name="default"/>
/// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1000")]
public static T ParseOrDefault<T>(string? s, T @default) where T : struct, Enum
{
if (TryParse(s, out T value))
return value;
return @default;
}
/// <summary>
/// Attempts to convert the string representation of the constant name, serialization name or numeric value of
/// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>.
/// <para>This operation is always case-insensitive using ordinal string comparison.</para>
/// <para>Returns the specified alternate value in case the string cannot be converted.</para>
/// </summary>
/// <typeparam name="T">The enumeration type to convert to.</typeparam>
/// <param name="s">A string containing the name, serialization name or value to convert.</param>
/// <param name="defaultFactory">The factory that produces the value to return if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. Must not be <see langword="null"/>.</param>
/// <returns>
/// The converted value as an instance of <typeparamref name="T"/>, or the return value from <paramref name="defaultFactory"/>
/// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="defaultFactory"/> is <see langword="null"/>.</exception>
[SuppressMessage("Microsoft.Design", "CA1000")]
public static T ParseOrDefault<T>(string? s, Func<T> defaultFactory)
where T : struct, Enum
{
if (TryParse(s, out T value))
return value;
else if (defaultFactory is null)
throw new ArgumentNullException(nameof(defaultFactory));
return defaultFactory();
}
/// <summary>
/// Attempts to convert the string representation of the constant name, serialization name or numeric value of
/// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>.
/// <para>This operation is always case-insensitive using ordinal string comparison.</para>
/// <para>Returns the specified alternate value in case the string cannot be converted.</para>
/// </summary>
/// <typeparam name="T">The enumeration type to convert to.</typeparam>
/// <param name="s">A string containing the name, serialization name or value to convert.</param>
/// <param name="defaultFactory">The factory that produces the value to return if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. Must not be <see langword="null"/>.</param>
/// <returns>
/// The converted value as an instance of <typeparamref name="T"/>, or the return value from <paramref name="defaultFactory"/>
/// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="defaultFactory"/> is <see langword="null"/>.</exception>
[SuppressMessage("Microsoft.Design", "CA1000")]
public static T ParseOrDefault<T>(string? s, Func<string?, T> defaultFactory)
where T : struct, Enum
{
if (TryParse(s, out T value))
return value;
else if (defaultFactory is null)
throw new ArgumentNullException(nameof(defaultFactory));
return defaultFactory(s);
}
/// <summary>
/// Attempts to convert the string representation of the constant name, serialization name or numeric value of
/// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>.
/// <para>This operation is always case-insensitive using ordinal string comparison.</para>
/// <para>Returns <see langword="null"/> in case the string cannot be converted.</para>
/// </summary>
/// <typeparam name="T">The enumeration type to convert to.</typeparam>
/// <param name="s">A string containing the name, serialization name or value to convert.</param>
/// <returns>
/// The converted value as an instance of <typeparamref name="T"/>, or <see langword="null"/>
/// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1000")]
public static T? ParseOrNull<T>(string? s) where T : struct, Enum
{
if (TryParse(s, out T value))
return value;
return null;
}
/// <summary>
/// Attempts to convert the string representation of the constant name, serialization name or numeric value of
/// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>.
/// <para>This operation is always case-insensitive using ordinal string comparison.</para>
/// <para>Returns <see langword="null"/> in case the string cannot be converted.</para>
/// </summary>
/// <typeparam name="T">The enumeration type to convert to.</typeparam>
/// <param name="s">A string containing the name, serialization name or value to convert.</param>
/// <param name="value">The converted value of <paramref name="s"/> if the method returns <see langword="true"/>.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="s"/> was successfully converted to a value of <typeparamref name="T"/>; otherwise, <see langword="false"/>.
/// </returns>
/// <remarks>If this method returns <see langword="false"/>, the out-value of the <paramref name="value"/> parameter is not defined.</remarks>
[SuppressMessage("Microsoft.Design", "CA1000")]
public static bool TryParse<T>(string? s, out T value) where T : struct, Enum
{
if (!(s is null) && EnumValues<T>.StringToValue.TryGetValue(s, out value))
return true;
return EnumStringConverter.TryParse(s, out value);
}
/// <summary>
/// Returns the serialized name or the default string representation of the specified value.
/// </summary>
/// <typeparam name="T">The enumeration type to convert from.</typeparam>
/// <param name="value">The value of <typeparamref name="T"/> to serialize.</param>
/// <returns>
/// A string containing either the serialization name if the constant equal to <paramref name="value"/>
/// has an <see cref="EnumMemberAttribute"/> applied to it; otherwise, the return value of <see cref="Enum.ToString()"/> for
/// the specified value.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1000")]
public static string ToString<T>(T value) where T : struct, Enum
{
if (EnumValues<T>.ValueToString.TryGetValue(value, out string s))
return s;
return EnumStringConverter.ToString(value);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Microsoft.Build.Collections
{
/// <summary>
/// Lightweight, read-only IDictionary implementation using two arrays
/// and O(n) lookup.
/// Requires specifying capacity at construction and does not
/// support reallocation to increase capacity.
/// </summary>
/// <typeparam name="TKey">Type of keys</typeparam>
/// <typeparam name="TValue">Type of values</typeparam>
internal class ArrayDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary
{
private TKey[] keys;
private TValue[] values;
private int count;
public ArrayDictionary(int capacity)
{
keys = new TKey[capacity];
values = new TValue[capacity];
}
public static IDictionary<TKey, TValue> Create(int capacity)
{
return new ArrayDictionary<TKey, TValue>(capacity);
}
public TValue this[TKey key]
{
get
{
TryGetValue(key, out var value);
return value;
}
set
{
var comparer = KeyComparer;
for (int i = 0; i < count; i++)
{
if (comparer.Equals(key, keys[i]))
{
values[i] = value;
return;
}
}
Add(key, value);
}
}
object IDictionary.this[object key]
{
get => this[(TKey)key];
set => this[(TKey)key] = (TValue)value;
}
public TKey[] KeyArray => keys;
public TValue[] ValueArray => values;
public ICollection<TKey> Keys => keys;
ICollection IDictionary.Keys => keys;
public ICollection<TValue> Values => values;
ICollection IDictionary.Values => values;
private IEqualityComparer<TKey> KeyComparer => EqualityComparer<TKey>.Default;
private IEqualityComparer<TValue> ValueComparer => EqualityComparer<TValue>.Default;
public int Count => count;
public bool IsReadOnly => true;
bool IDictionary.IsFixedSize => true;
object ICollection.SyncRoot => this;
bool ICollection.IsSynchronized => false;
public void Add(TKey key, TValue value)
{
if (count < keys.Length)
{
keys[count] = key;
values[count] = value;
count += 1;
}
else
{
throw new InvalidOperationException($"ArrayDictionary is at capacity {keys.Length}");
}
}
public void Add(KeyValuePair<TKey, TValue> item)
{
Add(item.Key, item.Value);
}
public void Clear()
{
throw new System.NotImplementedException();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
var keyComparer = KeyComparer;
var valueComparer = ValueComparer;
for (int i = 0; i < count; i++)
{
if (keyComparer.Equals(item.Key, keys[i]) && valueComparer.Equals(item.Value, values[i]))
{
return true;
}
}
return false;
}
public bool ContainsKey(TKey key)
{
var comparer = KeyComparer;
for (int i = 0; i < count; i++)
{
if (comparer.Equals(key, keys[i]))
{
return true;
}
}
return false;
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
for (int i = 0; i < count; i++)
{
array[arrayIndex + i] = new KeyValuePair<TKey, TValue>(keys[i], values[i]);
}
}
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new Enumerator(this, emitDictionaryEntries: true);
}
public bool Remove(TKey key)
{
throw new System.NotImplementedException();
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new System.NotImplementedException();
}
public bool TryGetValue(TKey key, out TValue value)
{
var comparer = KeyComparer;
for (int i = 0; i < count; i++)
{
if (comparer.Equals(key, keys[i]))
{
value = values[i];
return true;
}
}
value = default;
return false;
}
bool IDictionary.Contains(object key)
{
if (key is not TKey typedKey)
{
return false;
}
return ContainsKey(typedKey);
}
void IDictionary.Add(object key, object value)
{
if (key is TKey typedKey && value is TValue typedValue)
{
Add(typedKey, typedValue);
}
throw new NotSupportedException();
}
void IDictionary.Remove(object key)
{
throw new NotImplementedException();
}
private struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator
{
private readonly ArrayDictionary<TKey, TValue> _dictionary;
private readonly bool _emitDictionaryEntries;
private int _position;
public Enumerator(ArrayDictionary<TKey, TValue> dictionary, bool emitDictionaryEntries = false)
{
this._dictionary = dictionary;
this._position = -1;
this._emitDictionaryEntries = emitDictionaryEntries;
}
public KeyValuePair<TKey, TValue> Current =>
new KeyValuePair<TKey, TValue>(
_dictionary.keys[_position],
_dictionary.values[_position]);
private DictionaryEntry CurrentDictionaryEntry => new DictionaryEntry(_dictionary.keys[_position], _dictionary.values[_position]);
object IEnumerator.Current => _emitDictionaryEntries ? CurrentDictionaryEntry : Current;
object IDictionaryEnumerator.Key => _dictionary.keys[_position];
object IDictionaryEnumerator.Value => _dictionary.values[_position];
DictionaryEntry IDictionaryEnumerator.Entry => CurrentDictionaryEntry;
public void Dispose()
{
}
public bool MoveNext()
{
_position += 1;
return _position < _dictionary.Count;
}
public void Reset()
{
throw new NotImplementedException();
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
namespace AnalysisTests {
public static class TestRunner {
static bool HELP, PERF, TRACE, VERBOSE, STDLIB, DJANGO, PATH;
static IEnumerable<PythonVersion> VERSIONS;
static HashSet<string> OTHER_ARGS;
public static int Main(string[] args) {
var argset = new HashSet<string>(args, StringComparer.InvariantCultureIgnoreCase);
HELP = argset.Count == 0 || (argset.Remove("H") | argset.Remove("HELP"));
PERF = argset.Remove("PERF");
VERBOSE = argset.Remove("VERBOSE") | argset.Remove("V");
TRACE = VERBOSE | (argset.Remove("TRACE") | argset.Remove("T"));
STDLIB = argset.Remove("STDLIB");
DJANGO = argset.Remove("DJANGO");
PATH = argset.Remove("PATH");
var versionSpecs = new HashSet<string>(argset.Where(arg => Regex.IsMatch(arg, "^V[23][0-9]$", RegexOptions.IgnoreCase)),
StringComparer.InvariantCultureIgnoreCase);
OTHER_ARGS = new HashSet<string>(argset.Except(versionSpecs), StringComparer.InvariantCultureIgnoreCase);
if (versionSpecs.Any()) {
VERSIONS = PythonPaths.Versions
.Where(v => versionSpecs.Contains(Enum.GetName(typeof(PythonLanguageVersion), v.Version)))
.Where(v => v.IsCPython)
.ToList();
} else {
VERSIONS = PythonPaths.Versions;
}
if (HELP) {
Console.WriteLine(@"AnalysisTest.exe [TRACE] [VERBOSE|V] [test names...]
Runs the specified tests. Test names are the short method name only.
AnalysisTest.exe [TRACE|VERBOSE|V] [test name ...]
AnalysisTest.exe [TRACE|VERBOSE|V] PERF
Runs all performance related tests.
AnalysisTest.exe [TRACE|VERBOSE|V] STDLIB [V## ...]
Runs standard library analyses against the specified versions.
Version numbers are V25, V26, V27, V30, V31, V32 or V33.
Specifying V27 will only include CPython. Omitting all specifiers
will include CPython 2.7 and IronPython 2.7 if installed.
AnalysisTest.exe [TRACE|VERBOSE|V] DJANGO [V## ...]
Runs Django analyses against the specified versions.
AnalysisTest.exe [TRACE|VERBOSE|V] PATH ""library path"" [V## ...]
Analyses the specified path with the specified versions.
Specifying TRACE will log messages to a file. Specifying VERBOSE or V implies
TRACE and will also log detailed analysis information to CSV file.
");
return 0;
}
if (TRACE) {
Stream traceOutput;
try {
traceOutput = new FileStream("AnalysisTests.Trace.txt", FileMode.Create, FileAccess.Write, FileShare.Read);
} catch (IOException) {
traceOutput = new FileStream(string.Format("AnalysisTests.Trace.{0}.txt", Process.GetCurrentProcess().Id), FileMode.Create, FileAccess.Write, FileShare.Read);
}
Trace.Listeners.Add(new TextWriterTraceListener(new StreamWriter(traceOutput, Encoding.UTF8)));
Trace.AutoFlush = true;
if (VERBOSE & !(STDLIB | DJANGO | PATH)) {
AnalysisLog.Output = new StreamWriter(new FileStream("AnalysisTests.Trace.csv", FileMode.Create, FileAccess.Write, FileShare.Read), Encoding.UTF8);
AnalysisLog.AsCSV = true;
}
} else {
Trace.Listeners.Add(new ConsoleTraceListener());
}
int res = 0;
if (STDLIB) {
res += RunStdLibTests();
}
if (DJANGO) {
res += RunDjangoTests();
}
if (PATH) {
res += RunPathTests();
}
if (!(STDLIB | DJANGO | PATH)) {
Type attrType = PERF ? typeof(PerfMethodAttribute) : typeof(TestMethodAttribute);
foreach (var type in typeof(AnalysisTest).Assembly.GetTypes()) {
if (type.IsDefined(typeof(TestClassAttribute), false)) {
res += RunTests(type, attrType);
}
}
}
return res;
}
private static bool RunOneTest(Action test, string name) {
if (Debugger.IsAttached) {
return RunOneTestWithoutEH(test, name);
}
var sw = new Stopwatch();
try {
sw.Start();
return RunOneTestWithoutEH(test, name);
} catch (Exception e) {
sw.Stop();
Console.ForegroundColor = ConsoleColor.Red;
#if TRACE
Trace.TraceError("Test failed: {0}, {1} ({2}ms)", name, sw.Elapsed, sw.ElapsedMilliseconds);
#endif
Console.WriteLine("Test failed: {0}, {1} ({2}ms)", name, sw.Elapsed, sw.ElapsedMilliseconds);
Console.WriteLine(e);
AnalysisLog.Flush();
return false;
}
}
private static bool RunOneTestWithoutEH(Action test, string name) {
var sw = new Stopwatch();
sw.Start();
test();
sw.Stop();
Console.ForegroundColor = ConsoleColor.Green;
#if TRACE
Trace.TraceInformation("Test passed: {0}, {1} ({2}ms)", name, sw.Elapsed, sw.ElapsedMilliseconds);
#endif
Console.WriteLine("Test passed: {0}, {1} ({2}ms)", name, sw.Elapsed, sw.ElapsedMilliseconds);
return true;
}
private static int RunStdLibTests() {
var fg = Console.ForegroundColor;
foreach (var ver in VERSIONS) {
if (VERBOSE) {
try {
if (File.Exists(string.Format("AnalysisTests.StdLib.{0}.csv", ver.Version))) {
File.Delete(string.Format("AnalysisTests.StdLib.{0}.csv", ver.Version));
}
} catch { }
}
}
int failures = 0;
foreach (var ver in VERSIONS) {
if (VERBOSE) {
AnalysisLog.ResetTime();
AnalysisLog.Output = new StreamWriter(new FileStream(string.Format("AnalysisTests.StdLib.{0}.csv", ver.Version), FileMode.Append, FileAccess.Write, FileShare.Read), Encoding.UTF8);
AnalysisLog.AsCSV = true;
AnalysisLog.Add("StdLib Start", ver.InterpreterPath, ver.Version, DateTime.Now);
}
if (!RunOneTest(() => {
new AnalysisTest().AnalyzeDir(Path.Combine(ver.PrefixPath, "Lib"), ver.Version, new[] { "site-packages" });
}, ver.InterpreterPath)) {
failures += 1;
}
Console.ForegroundColor = fg;
if (VERBOSE) {
AnalysisLog.Flush();
}
IdDispenser.Clear();
}
return failures;
}
private static int RunDjangoTests() {
var fg = Console.ForegroundColor;
foreach (var ver in VERSIONS) {
if (VERBOSE) {
try {
if (File.Exists(string.Format("AnalysisTests.Django.{0}.csv", ver.Version))) {
File.Delete(string.Format("AnalysisTests.Django.{0}.csv", ver.Version));
}
} catch { }
}
}
int failures = 0;
foreach (var ver in VERSIONS) {
var djangoPath = Path.Combine(ver.PrefixPath, "Lib", "site-packages", "django");
if (!Directory.Exists(djangoPath)) {
Trace.TraceInformation("Path {0} not found; skipping {1}", djangoPath, ver.Version);
continue;
}
if (VERBOSE) {
AnalysisLog.ResetTime();
AnalysisLog.Output = new StreamWriter(new FileStream(string.Format("AnalysisTests.Django.{0}.csv", ver.Version), FileMode.Append, FileAccess.Write, FileShare.Read), Encoding.UTF8);
AnalysisLog.AsCSV = true;
AnalysisLog.Add("Django Start", ver.InterpreterPath, ver.Version, DateTime.Now);
}
if (!RunOneTest(() => { new AnalysisTest().AnalyzeDir(djangoPath, ver.Version); }, ver.InterpreterPath)) {
failures += 1;
}
Console.ForegroundColor = fg;
if (VERBOSE) {
AnalysisLog.Flush();
}
IdDispenser.Clear();
}
return failures;
}
private static int RunPathTests() {
var fg = Console.ForegroundColor;
foreach (var ver in VERSIONS) {
if (VERBOSE) {
try {
if (File.Exists(string.Format("AnalysisTests.Path.{0}.csv", ver.Version))) {
File.Delete(string.Format("AnalysisTests.Path.{0}.csv", ver.Version));
}
} catch { }
}
}
int failures = 0;
foreach (var path in OTHER_ARGS) {
if (!Directory.Exists(path)) {
continue;
}
foreach (var ver in VERSIONS) {
if (VERBOSE) {
AnalysisLog.ResetTime();
AnalysisLog.Output = new StreamWriter(new FileStream(string.Format("AnalysisTests.Path.{0}.csv", ver.Version), FileMode.Append, FileAccess.Write, FileShare.Read), Encoding.UTF8);
AnalysisLog.AsCSV = true;
AnalysisLog.Add("Path Start", path, ver.Version, DateTime.Now);
}
if (!RunOneTest(() => { new AnalysisTest().AnalyzeDir(path, ver.Version); }, string.Format("{0}: {1}", ver.Version, path))) {
failures += 1;
}
Console.ForegroundColor = fg;
if (VERBOSE) {
AnalysisLog.Flush();
}
IdDispenser.Clear();
}
}
return failures;
}
private static int RunTests(Type instType, Type attrType) {
var fg = Console.ForegroundColor;
int failures = 0;
object inst = null;
foreach (var mi in instType.GetMethods()) {
if ((!OTHER_ARGS.Any() || OTHER_ARGS.Contains(mi.Name)) && mi.IsDefined(attrType, false)) {
if (inst == null) {
inst = Activator.CreateInstance(instType);
Console.WriteLine("Running tests against: {0}", instType.FullName);
}
if (!RunOneTest(() => { mi.Invoke(inst, new object[0]); }, mi.Name)) {
failures += 1;
}
Console.ForegroundColor = fg;
}
}
if (inst != null) {
Console.WriteLine();
if (failures == 0) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("No failures");
} else {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("{0} failures", failures);
}
Console.ForegroundColor = fg;
}
return failures;
}
}
}
| |
// Filename: ShapeFile.cs
// Description: Classes for reading ESRI shapefiles.
// Reference: ESRI Shapefile Technical Description, July 1998.
// http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf
// 2007-01-22 nschan Initial revision.
using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text;
using System.Windows;
namespace TestShapeFile
{
/// <summary>
/// Enumeration defining the various shape types. Each shapefile
/// contains only one type of shape (e.g., all polygons or all
/// polylines).
/// </summary>
public enum ShapeType
{
/// <summary>
/// Nullshape / placeholder record.
/// </summary>
NullShape = 0,
/// <summary>
/// Point record, for defining point locations such as a city.
/// </summary>
Point = 1,
/// <summary>
/// One or more sets of connected points. Used to represent roads,
/// hydrography, etc.
/// </summary>
PolyLine = 3,
/// <summary>
/// One or more sets of closed figures. Used to represent political
/// boundaries for countries, lakes, etc.
/// </summary>
Polygon = 5,
/// <summary>
/// A cluster of points represented by a single shape record.
/// </summary>
Multipoint = 8
// Unsupported types:
// PointZ = 11,
// PolyLineZ = 13,
// PolygonZ = 15,
// MultiPointZ = 18,
// PointM = 21,
// PolyLineM = 23,
// PolygonM = 25,
// MultiPointM = 28,
// MultiPatch = 31
}
/// <summary>
/// The ShapeFileHeader class represents the contents
/// of the fixed length, 100-byte file header at the
/// beginning of every shapefile.
/// </summary>
public class ShapeFileHeader
{
#region Private fields
private int fileCode;
private int fileLength;
private int version;
private int shapeType;
// Bounding box.
private double xMin;
private double yMin;
private double xMax;
private double yMax;
#endregion Private fields
#region Constructor
/// <summary>
/// Constructor for the ShapeFileHeader class.
/// </summary>
public ShapeFileHeader()
{
}
#endregion Constructor
#region Properties
/// <summary>
/// Indicate the fixed-length of this header in bytes.
/// </summary>
public static int Length
{
get { return 100; }
}
/// <summary>
/// Specifies the file code for an ESRI shapefile, which
/// should be the value, 9994.
/// </summary>
public int FileCode
{
get { return this.fileCode; }
set { this.fileCode = value; }
}
/// <summary>
/// Specifies the length of the shapefile, expressed
/// as the number of 16-bit words in the file.
/// </summary>
public int FileLength
{
get { return this.fileLength; }
set { this.fileLength = value; }
}
/// <summary>
/// Specifies the shapefile version number.
/// </summary>
public int Version
{
get { return this.version; }
set { this.version = value; }
}
/// <summary>
/// Specifies the shape type for the file. A shapefile
/// contains only one type of shape.
/// </summary>
public int ShapeType
{
get { return this.shapeType; }
set { this.shapeType = value; }
}
/// <summary>
/// Indicates the minimum x-position of the bounding
/// box for the shapefile (expressed in degrees longitude).
/// </summary>
public double XMin
{
get { return this.xMin; }
set { this.xMin = value; }
}
/// <summary>
/// Indicates the minimum y-position of the bounding
/// box for the shapefile (expressed in degrees latitude).
/// </summary>
public double YMin
{
get { return this.yMin; }
set { this.yMin = value; }
}
/// <summary>
/// Indicates the maximum x-position of the bounding
/// box for the shapefile (expressed in degrees longitude).
/// </summary>
public double XMax
{
get { return this.xMax; }
set { this.xMax = value; }
}
/// <summary>
/// Indicates the maximum y-position of the bounding
/// box for the shapefile (expressed in degrees latitude).
/// </summary>
public double YMax
{
get { return this.yMax; }
set { this.yMax = value; }
}
#endregion Properties
#region Public methods
/// <summary>
/// Output some of the fields of the file header.
/// </summary>
/// <returns>A string representation of the file header.</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("ShapeFileHeader: FileCode={0}, FileLength={1}, Version={2}, ShapeType={3}",
this.fileCode, this.fileLength, this.version, this.shapeType);
return sb.ToString();
}
#endregion Public methods
}
/// <summary>
/// The ShapeFileRecord class represents the contents of
/// a shape record, which is of variable length.
/// </summary>
public class ShapeFileRecord
{
#region Private fields
// Record Header.
private int recordNumber;
private int contentLength;
// Shape type.
private int shapeType;
// Bounding box for shape.
private double xMin;
private double yMin;
private double xMax;
private double yMax;
// Part indices and points array.
private Collection<int> parts = new Collection<int>();
private Collection<Point> points = new Collection<Point>();
// Shape attributes from a row in the dBASE file.
private DataRow attributes;
#endregion Private fields
#region Constructor
/// <summary>
/// Constructor for the ShapeFileRecord class.
/// </summary>
public ShapeFileRecord()
{
}
#endregion Constructor
#region Properties
/// <summary>
/// Indicates the record number (or index) which starts at 1.
/// </summary>
public int RecordNumber
{
get { return this.recordNumber; }
set { this.recordNumber = value; }
}
/// <summary>
/// Specifies the length of this shape record in 16-bit words.
/// </summary>
public int ContentLength
{
get { return this.contentLength; }
set { this.contentLength = value; }
}
/// <summary>
/// Specifies the shape type for this record.
/// </summary>
public int ShapeType
{
get { return this.shapeType; }
set { this.shapeType = value; }
}
/// <summary>
/// Indicates the minimum x-position of the bounding
/// box for the shape (expressed in degrees longitude).
/// </summary>
public double XMin
{
get { return this.xMin; }
set { this.xMin = value; }
}
/// <summary>
/// Indicates the minimum y-position of the bounding
/// box for the shape (expressed in degrees latitude).
/// </summary>
public double YMin
{
get { return this.yMin; }
set { this.yMin = value; }
}
/// <summary>
/// Indicates the maximum x-position of the bounding
/// box for the shape (expressed in degrees longitude).
/// </summary>
public double XMax
{
get { return this.xMax; }
set { this.xMax = value; }
}
/// <summary>
/// Indicates the maximum y-position of the bounding
/// box for the shape (expressed in degrees latitude).
/// </summary>
public double YMax
{
get { return this.yMax; }
set { this.yMax = value; }
}
/// <summary>
/// Indicates the number of parts for this shape.
/// A part is a connected set of points, analogous to
/// a PathFigure in WPF.
/// </summary>
public int NumberOfParts
{
get { return this.parts.Count; }
}
/// <summary>
/// Specifies the total number of points defining
/// this shape record.
/// </summary>
public int NumberOfPoints
{
get { return this.points.Count; }
}
/// <summary>
/// A collection of indices for the points array.
/// Each index identifies the starting point of the
/// corresponding part (or PathFigure using WPF
/// terminology).
/// </summary>
public Collection<int> Parts
{
get { return this.parts; }
}
/// <summary>
/// A collection of all of the points defining the
/// shape record.
/// </summary>
public Collection<Point> Points
{
get { return this.points; }
}
/// <summary>
/// Access the (dBASE) attribute values associated
/// with this shape record.
/// </summary>
public DataRow Attributes
{
get { return this.attributes; }
set { this.attributes = value; }
}
#endregion Properties
#region Public methods
/// <summary>
/// Output some of the fields of the shapefile record.
/// </summary>
/// <returns>A string representation of the record.</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("ShapeFileRecord: RecordNumber={0}, ContentLength={1}, ShapeType={2}",
this.recordNumber, this.contentLength, this.shapeType);
return sb.ToString();
}
#endregion Public methods
}
/// <summary>
/// The ShapeFileReadInfo class stores information about a shapefile
/// that can be used by external clients during a shapefile read.
/// </summary>
public class ShapeFileReadInfo
{
#region Private fields
private string fileName;
private ShapeFile shapeFile;
private Stream stream;
private int numBytesRead;
private int recordIndex;
#endregion Private fields
#region Constructor
/// <summary>
/// Constructor for the ShapeFileReadInfo class.
/// </summary>
public ShapeFileReadInfo()
{
}
#endregion Constructor
#region Properties
/// <summary>
/// The full pathname of the shapefile.
/// </summary>
public string FileName
{
get { return this.fileName; }
set { this.fileName = value; }
}
/// <summary>
/// A reference to the shapefile instance.
/// </summary>
public ShapeFile ShapeFile
{
get { return this.shapeFile; }
set { this.shapeFile = value; }
}
/// <summary>
/// An opened file stream for a shapefile.
/// </summary>
public Stream Stream
{
get { return this.stream; }
set { this.stream = value; }
}
/// <summary>
/// The number of bytes read from a shapefile so far.
/// Can be used to compute a progress value.
/// </summary>
public int NumberOfBytesRead
{
get { return this.numBytesRead; }
set { this.numBytesRead = value; }
}
/// <summary>
/// A general-purpose record index.
/// </summary>
public int RecordIndex
{
get { return this.recordIndex; }
set { this.recordIndex = value; }
}
#endregion Properties
#region Public methods
/// <summary>
/// Output some of the field values in the form of a string.
/// </summary>
/// <returns>A string representation of the field values.</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("ShapeFileReadInfo: FileName={0}, ", this.fileName);
sb.AppendFormat("NumberOfBytesRead={0}, RecordIndex={1}", this.numBytesRead, this.recordIndex);
return sb.ToString();
}
#endregion Public methods
}
/// <summary>
/// The ShapeFile class represents the contents of a single
/// ESRI shapefile. This is the class which contains functionality
/// for reading shapefiles and their corresponding dBASE attribute
/// files.
/// </summary>
/// <remarks>
/// You can call the Read() method to import both shapes and attributes
/// at once. Or, you can open the file stream yourself and read the file
/// header or individual records one at a time. The advantage of this is
/// that it allows you to implement your own progress reporting functionality,
/// for example.
/// </remarks>
public class ShapeFile
{
#region Constants
private const int expectedFileCode = 9994;
#endregion Constants
#region Private static fields
private static byte[] intBytes = new byte[4];
private static byte[] doubleBytes = new byte[8];
#endregion Private static fields
#region Private fields
// File Header.
private ShapeFileHeader fileHeader = new ShapeFileHeader();
// Collection of Shapefile Records.
private Collection<ShapeFileRecord> records = new Collection<ShapeFileRecord>();
#endregion Private fields
#region Constructor
/// <summary>
/// Constructor for the ShapeFile class.
/// </summary>
public ShapeFile()
{
}
#endregion Constructor
#region Properties
/// <summary>
/// Access the file header of this shapefile.
/// </summary>
public ShapeFileHeader FileHeader
{
get { return this.fileHeader; }
}
/// <summary>
/// Access the collection of records for this shapefile.
/// </summary>
public Collection<ShapeFileRecord> Records
{
get { return this.records; }
}
#endregion Properties
#region Public methods
/// <summary>
/// Read both shapes and attributes from the given
/// shapefile (and its corresponding dBASE file).
/// This is the top-level method for reading an ESRI
/// shapefile.
/// </summary>
/// <param name="fileName">Full pathname of the shapefile.</param>
public void Read(string fileName)
{
if (string.IsNullOrEmpty(fileName))
throw new ArgumentNullException("fileName");
// Read shapes first (geometry).
this.ReadShapes(fileName);
// Construct name and path of dBASE file. It's basically
// the same name as the shapefile except with a .dbf extension.
string dbaseFile = fileName.Replace(".shp", ".dbf");
dbaseFile = dbaseFile.Replace(".SHP", ".DBF");
// Read the attributes.
this.ReadAttributes(dbaseFile);
}
/// <summary>
/// Read shapes (geometry) from the given shapefile.
/// </summary>
/// <param name="fileName">Full pathname of the shapefile.</param>
public void ReadShapes(string fileName)
{
using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
this.ReadShapes(stream);
}
}
/// <summary>
/// Read shapes (geometry) from the given stream.
/// </summary>
/// <param name="stream">Input stream for a shapefile.</param>
public void ReadShapes(Stream stream)
{
// Read the File Header.
this.ReadShapeFileHeader(stream);
// Read the shape records.
this.records.Clear();
while (true)
{
try
{
this.ReadShapeFileRecord(stream);
}
catch (IOException)
{
// Stop reading when EOF exception occurs.
break;
}
}
}
/// <summary>
/// Read the file header of the shapefile.
/// </summary>
/// <param name="stream">Input stream.</param>
public void ReadShapeFileHeader(Stream stream)
{
// File Code.
this.fileHeader.FileCode = ShapeFile.ReadInt32_BE(stream);
if (this.fileHeader.FileCode != ShapeFile.expectedFileCode)
{
string msg = String.Format(System.Globalization.CultureInfo.InvariantCulture, "Invalid FileCode encountered. Expecting {0}.", ShapeFile.expectedFileCode);
throw new FileFormatException(msg);
}
// 5 unused values.
ShapeFile.ReadInt32_BE(stream);
ShapeFile.ReadInt32_BE(stream);
ShapeFile.ReadInt32_BE(stream);
ShapeFile.ReadInt32_BE(stream);
ShapeFile.ReadInt32_BE(stream);
// File Length.
this.fileHeader.FileLength = ShapeFile.ReadInt32_BE(stream);
// Version.
this.fileHeader.Version = ShapeFile.ReadInt32_LE(stream);
// Shape Type.
this.fileHeader.ShapeType = ShapeFile.ReadInt32_LE(stream);
// Bounding Box.
this.fileHeader.XMin = ShapeFile.ReadDouble64_LE(stream);
this.fileHeader.YMin = ShapeFile.ReadDouble64_LE(stream);
this.fileHeader.XMax = ShapeFile.ReadDouble64_LE(stream);
this.fileHeader.YMax = ShapeFile.ReadDouble64_LE(stream);
// Adjust the bounding box in case it is too small.
if (Math.Abs(this.fileHeader.XMax - this.fileHeader.XMin) < 1)
{
this.fileHeader.XMin -= 5;
this.fileHeader.XMax += 5;
}
if (Math.Abs(this.fileHeader.YMax - this.fileHeader.YMin) < 1)
{
this.fileHeader.YMin -= 5;
this.fileHeader.YMax += 5;
}
// Skip the rest of the file header.
stream.Seek(100, SeekOrigin.Begin);
}
/// <summary>
/// Read a shapefile record.
/// </summary>
/// <param name="stream">Input stream.</param>
public ShapeFileRecord ReadShapeFileRecord(Stream stream)
{
ShapeFileRecord record = new ShapeFileRecord();
// Record Header.
record.RecordNumber = ShapeFile.ReadInt32_BE(stream);
record.ContentLength = ShapeFile.ReadInt32_BE(stream);
// Shape Type.
record.ShapeType = ShapeFile.ReadInt32_LE(stream);
// Read the shape geometry, depending on its type.
switch (record.ShapeType)
{
case (int)ShapeType.NullShape:
// Do nothing.
break;
case (int)ShapeType.Point:
ShapeFile.ReadPoint(stream, record);
break;
case (int)ShapeType.PolyLine:
// PolyLine has exact same structure as Polygon in shapefile.
ShapeFile.ReadPolygon(stream, record);
break;
case (int)ShapeType.Polygon:
ShapeFile.ReadPolygon(stream, record);
break;
case (int)ShapeType.Multipoint:
ShapeFile.ReadMultipoint(stream, record);
break;
default:
{
string msg = String.Format(System.Globalization.CultureInfo.InvariantCulture, "ShapeType {0} is not supported.", (int)record.ShapeType);
throw new FileFormatException(msg);
}
}
// Add the record to our internal list.
this.records.Add(record);
return record;
}
/// <summary>
/// Read the table from specified dBASE (DBF) file and
/// merge the rows with shapefile records.
/// </summary>
/// <remarks>
/// The filename of the dBASE file is expected to follow 8.3 naming
/// conventions. If it doesn't follow the convention, we try to
/// determine the 8.3 short name ourselves (but the name we come up
/// with may not be correct in all cases).
/// </remarks>
/// <param name="dbaseFile">Full file path of the dBASE (DBF) file.</param>
public void ReadAttributes(string dbaseFile)
{
if (string.IsNullOrEmpty(dbaseFile))
throw new ArgumentNullException("dbaseFile");
// Check if the file exists. If it doesn't exist,
// this is not an error.
if (!File.Exists(dbaseFile))
return;
// Get the directory in which the dBASE (DBF) file resides.
FileInfo fi = new FileInfo(dbaseFile);
string directory = fi.DirectoryName;
// Get the filename minus the extension.
string fileNameNoExt = fi.Name.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
if (fileNameNoExt.EndsWith(".DBF"))
fileNameNoExt = fileNameNoExt.Substring(0, fileNameNoExt.Length - 4);
// Convert to a short filename (may not work in every case!).
if (fileNameNoExt.Length > 8)
{
if (fileNameNoExt.Contains(" "))
{
string noSpaces = fileNameNoExt.Replace(" ", "");
if (noSpaces.Length > 8)
fileNameNoExt = noSpaces;
}
fileNameNoExt = fileNameNoExt.Substring(0, 6) + "~1";
}
// Set the connection string.
string connectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" + directory + ";Extended Properties=dBASE 5.0";
// Set the select query.
string selectQuery = "SELECT * FROM [" + fileNameNoExt + "#DBF];";
// Create a database connection object using the connection string.
OleDbConnection connection = new OleDbConnection(connectionString);
// Create a database command on the connection using the select query.
OleDbCommand command = new OleDbCommand(selectQuery, connection);
try
{
// Open the connection.
connection.Open();
// Create a data adapter to fill a dataset.
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
dataAdapter.SelectCommand = command;
DataSet dataSet = new DataSet();
dataSet.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(dataSet);
// Merge attributes into the shape file.
if (dataSet.Tables.Count > 0)
this.MergeAttributes(dataSet.Tables[0]);
}
catch (OleDbException)
{
// Note: An exception will occur if the filename of the dBASE
// file does not follow 8.3 naming conventions. In this case,
// you must use its short (MS-DOS) filename.
// Rethrow the exception.
throw;
}
finally
{
// Dispose of connection.
((IDisposable)connection).Dispose();
}
}
/// <summary>
/// Output the File Header in the form of a string.
/// </summary>
/// <returns>A string representation of the file header.</returns>
public override string ToString()
{
return "ShapeFile: " + this.fileHeader.ToString();
}
#endregion Public methods
#region Private methods
/// <summary>
/// Read a 4-byte integer using little endian (Intel)
/// byte ordering.
/// </summary>
/// <param name="stream">Input stream to read.</param>
/// <returns>The integer value.</returns>
private static int ReadInt32_LE(Stream stream)
{
for (int i = 0; i < 4; i++)
{
int b = stream.ReadByte();
if (b == -1)
throw new EndOfStreamException();
intBytes[i] = (byte)b;
}
return BitConverter.ToInt32(intBytes, 0);
}
/// <summary>
/// Read a 4-byte integer using big endian
/// byte ordering.
/// </summary>
/// <param name="stream">Input stream to read.</param>
/// <returns>The integer value.</returns>
private static int ReadInt32_BE(Stream stream)
{
for (int i = 3; i >= 0; i--)
{
int b = stream.ReadByte();
if (b == -1)
throw new EndOfStreamException();
intBytes[i] = (byte)b;
}
return BitConverter.ToInt32(intBytes, 0);
}
/// <summary>
/// Read an 8-byte double using little endian (Intel)
/// byte ordering.
/// </summary>
/// <param name="stream">Input stream to read.</param>
/// <returns>The double value.</returns>
private static double ReadDouble64_LE(Stream stream)
{
for (int i = 0; i < 8; i++)
{
int b = stream.ReadByte();
if (b == -1)
throw new EndOfStreamException();
doubleBytes[i] = (byte)b;
}
return BitConverter.ToDouble(doubleBytes, 0);
}
/// <summary>
/// Read a shapefile Point record.
/// </summary>
/// <param name="stream">Input stream.</param>
/// <param name="record">Shapefile record to be updated.</param>
private static void ReadPoint(Stream stream, ShapeFileRecord record)
{
// Points - add a single point.
Point p = new System.Windows.Point();
p.X = ShapeFile.ReadDouble64_LE(stream);
p.Y = ShapeFile.ReadDouble64_LE(stream);
record.Points.Add(p);
// Bounding Box.
record.XMin = p.X;
record.YMin = p.Y;
record.XMax = record.XMin;
record.YMax = record.YMin;
}
/// <summary>
/// Read a shapefile MultiPoint record.
/// </summary>
/// <param name="stream">Input stream.</param>
/// <param name="record">Shapefile record to be updated.</param>
private static void ReadMultipoint(Stream stream, ShapeFileRecord record)
{
// Bounding Box.
record.XMin = ShapeFile.ReadDouble64_LE(stream);
record.YMin = ShapeFile.ReadDouble64_LE(stream);
record.XMax = ShapeFile.ReadDouble64_LE(stream);
record.YMax = ShapeFile.ReadDouble64_LE(stream);
// Num Points.
int numPoints = ShapeFile.ReadInt32_LE(stream);
// Points.
for (int i = 0; i < numPoints; i++)
{
Point p = new Point();
p.X = ShapeFile.ReadDouble64_LE(stream);
p.Y = ShapeFile.ReadDouble64_LE(stream);
record.Points.Add(p);
}
}
/// <summary>
/// Read a shapefile Polygon record.
/// </summary>
/// <param name="stream">Input stream.</param>
/// <param name="record">Shapefile record to be updated.</param>
private static void ReadPolygon(Stream stream, ShapeFileRecord record)
{
// Bounding Box.
record.XMin = ShapeFile.ReadDouble64_LE(stream);
record.YMin = ShapeFile.ReadDouble64_LE(stream);
record.XMax = ShapeFile.ReadDouble64_LE(stream);
record.YMax = ShapeFile.ReadDouble64_LE(stream);
// Num Parts and Points.
int numParts = ShapeFile.ReadInt32_LE(stream);
int numPoints = ShapeFile.ReadInt32_LE(stream);
// Parts.
for (int i = 0; i < numParts; i++)
{
record.Parts.Add(ShapeFile.ReadInt32_LE(stream));
}
// Points.
for (int i = 0; i < numPoints; i++)
{
Point p = new Point();
p.X = ShapeFile.ReadDouble64_LE(stream);
p.Y = ShapeFile.ReadDouble64_LE(stream);
record.Points.Add(p);
}
}
/// <summary>
/// Merge data rows from the given table with
/// the shapefile records.
/// </summary>
/// <param name="table">Attributes table.</param>
private void MergeAttributes(DataTable table)
{
// For each data row, assign it to a shapefile record.
int index = 0;
foreach (DataRow row in table.Rows)
{
if (index >= this.records.Count)
break;
this.records[index].Attributes = row;
++index;
}
}
#endregion Private methods
}
}
// END
| |
// Copyright Structured Solutions
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
using BVSoftware.Bvc5.Core.Catalog;
using BVSoftware.Bvc5.Core.Contacts;
using BVSoftware.Bvc5.Core.Content;
using BVSoftware.Bvc5.Core.Shipping;
using StructuredSolutions.Bvc5.Shipping.Providers.Controls;
using StructuredSolutions.Bvc5.Shipping.Providers.Settings;
using ASPNET = System.Web.UI.WebControls;
using ListItem = System.Web.UI.WebControls.ListItem;
public partial class BVModules_Shipping_Order_Rules_PackageMatchEditor : UserControl
{
#region Properties
public object DataSource
{
get { return ViewState["DataSource"]; }
set { ViewState["DataSource"] = value; }
}
public ShippingMethod ShippingMethod
{
get { return ((BVShippingModule) NamingContainer.NamingContainer.NamingContainer.NamingContainer).ShippingMethod; }
}
public string Prompt
{
get
{
object value = ViewState["Prompt"];
if (value == null)
return string.Empty;
else
return (string) value;
}
set { ViewState["Prompt"] = value; }
}
public string RuleId
{
get
{
object value = ViewState["RuleId"];
if (value == null)
return string.Empty;
else
return (string) value;
}
set { ViewState["RuleId"] = value; }
}
#endregion
#region Event Handlers
protected void LimitItemPropertyField_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender != null)
{
DropDownList itemPropertyField = (DropDownList) sender;
ItemProperties itemProperty =
(ItemProperties) Enum.Parse(typeof (ItemProperties), itemPropertyField.SelectedValue);
DropDownList customPropertyField =
(DropDownList) itemPropertyField.NamingContainer.FindControl("LimitCustomPropertyField");
HelpLabel customPropertyLabel =
(HelpLabel) itemPropertyField.NamingContainer.FindControl("LimitCustomPropertyLabel");
Label multiplierLabel = (Label) itemPropertyField.NamingContainer.FindControl("LimitMultiplierLabel");
HelpLabel limitLabel = (HelpLabel) itemPropertyField.NamingContainer.FindControl("LimitLabel");
TextBox limitField = (TextBox) itemPropertyField.NamingContainer.FindControl("LimitField");
BaseValidator limitRequired = (BaseValidator) itemPropertyField.NamingContainer.FindControl("LimitRequired");
BaseValidator limitNumeric = (BaseValidator) itemPropertyField.NamingContainer.FindControl("LimitNumeric");
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, itemProperty);
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, itemProperty);
}
}
protected void LimitPackagePropertyField_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender != null)
{
DropDownList propertyField = (DropDownList) sender;
PackageProperties packageProperty =
(PackageProperties) Enum.Parse(typeof (PackageProperties), propertyField.SelectedValue);
DropDownList itemPropertyField =
(DropDownList) propertyField.NamingContainer.FindControl("LimitItemPropertyField");
ItemProperties itemProperty =
(ItemProperties) Enum.Parse(typeof (ItemProperties), itemPropertyField.SelectedValue);
DropDownList customPropertyField =
(DropDownList) propertyField.NamingContainer.FindControl("LimitCustomPropertyField");
HelpLabel customPropertyLabel =
(HelpLabel) propertyField.NamingContainer.FindControl("LimitCustomPropertyLabel");
Label multiplierLabel = (Label) propertyField.NamingContainer.FindControl("LimitMultiplierLabel");
HelpLabel limitLabel = (HelpLabel) propertyField.NamingContainer.FindControl("LimitLabel");
TextBox limitField = (TextBox) propertyField.NamingContainer.FindControl("LimitField");
BaseValidator limitRequired = (BaseValidator) propertyField.NamingContainer.FindControl("LimitRequired");
BaseValidator limitNumeric = (BaseValidator) propertyField.NamingContainer.FindControl("LimitNumeric");
if (packageProperty == PackageProperties.ItemProperty)
{
itemPropertyField.Visible = true;
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, itemProperty);
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, itemProperty);
}
else
{
itemPropertyField.Visible = false;
customPropertyField.Visible = false;
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric, packageProperty);
Page.Validate("RuleGroup");
if (Page.IsValid)
{
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, packageProperty);
}
}
}
}
protected void LimitValidator_Validate(object sender, ServerValidateEventArgs e)
{
// Do not validate fixed values
DropDownList propertyField =
(DropDownList) ((Control) sender).NamingContainer.FindControl("LimitPackagePropertyField");
PackageProperties packageProperty =
(PackageProperties) Enum.Parse(typeof (PackageProperties), propertyField.SelectedValue);
if (packageProperty != PackageProperties.FixedAmountOne && packageProperty != PackageProperties.Separator0)
{
if (string.IsNullOrEmpty(e.Value))
{
e.IsValid = false;
}
else
{
Decimal result;
e.IsValid = Decimal.TryParse(e.Value, out result);
}
}
else
{
e.IsValid = true;
}
}
protected void Matches_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "New")
{
PackageMatchList matches = GetMatches();
PackageMatch match = new PackageMatch();
matches.Insert(e.Item.ItemIndex + 1, match);
DataSource = matches;
DataBindChildren();
}
else if (e.CommandName == "Delete")
{
PackageMatchList matches = GetMatches();
matches.RemoveAt(e.Item.ItemIndex);
DataSource = matches;
DataBindChildren();
}
}
protected void Matches_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
PackageMatchList matches = (PackageMatchList) DataSource;
PackageMatch match = matches[e.Item.ItemIndex];
DropDownList packagePropertyList = (DropDownList) e.Item.FindControl("MatchPackagePropertyField");
DropDownList itemPropertyList = (DropDownList) e.Item.FindControl("MatchItemPropertyField");
DropDownList customPropertyList = (DropDownList) e.Item.FindControl("MatchCustomPropertyField");
DropDownList comparisonList = (DropDownList) e.Item.FindControl("MatchComparisonTypeField");
DropDownList limitPackagePropertyList = (DropDownList) e.Item.FindControl("LimitPackagePropertyField");
DropDownList limitItemPropertyList = (DropDownList) e.Item.FindControl("LimitItemPropertyField");
DropDownList limitCustomPropertyList = (DropDownList) e.Item.FindControl("LimitCustomPropertyField");
HelpLabel customPropertyLabel = (HelpLabel) e.Item.FindControl("MatchCustomPropertyLabel");
HelpLabel limitCustomPropertyLabel = (HelpLabel) e.Item.FindControl("LimitCustomPropertyLabel");
Label multiplierLabel = (Label) e.Item.FindControl("LimitMultiplierLabel");
HelpLabel limitLabel = (HelpLabel) e.Item.FindControl("LimitLabel");
TextBox limitField = (TextBox) e.Item.FindControl("LimitField");
BaseValidator limitRequired = (BaseValidator) e.Item.FindControl("LimitRequired");
BaseValidator limitNumeric = (BaseValidator) e.Item.FindControl("LimitNumeric");
packagePropertyList.Items.Clear();
packagePropertyList.Items.AddRange(GetMatchPackageProperties());
itemPropertyList.Items.Clear();
itemPropertyList.Items.AddRange(GetItemProperties());
itemPropertyList.Visible = false;
customPropertyList.Visible = false;
if (match.PackageProperty == PackageProperties.ItemProperty)
{
itemPropertyList.Visible = true;
PrepareCustomPropertyField(customPropertyLabel, customPropertyList, match.ItemProperty);
}
else
{
PrepareCustomPropertyField(customPropertyLabel, customPropertyList, match.PackageProperty);
}
if (customPropertyList.Items.Count == 0)
customPropertyList.Items.Add(new ListItem("", match.CustomProperty));
if (customPropertyList.Items.FindByValue(match.CustomProperty) == null)
match.CustomProperty = customPropertyList.Items[0].Value;
comparisonList.Items.Clear();
comparisonList.Items.AddRange(GetComparisons());
limitPackagePropertyList.Items.Clear();
limitPackagePropertyList.Items.AddRange(GetLimitPackageProperties());
limitItemPropertyList.Items.Clear();
limitItemPropertyList.Items.AddRange(GetItemProperties());
limitItemPropertyList.Visible = false;
limitCustomPropertyList.Visible = false;
multiplierLabel.Visible = match.LimitPackageProperty != PackageProperties.FixedAmountOne;
if (match.LimitPackageProperty == PackageProperties.ItemProperty)
{
limitItemPropertyList.Visible = true;
PrepareCustomPropertyField(limitCustomPropertyLabel, limitCustomPropertyList, match.LimitItemProperty);
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric,
match.LimitItemProperty);
}
else
{
PrepareCustomPropertyField(limitCustomPropertyLabel, limitCustomPropertyList, match.LimitPackageProperty);
PrepareLimitField(multiplierLabel, limitLabel, limitField, limitRequired, limitNumeric,
match.LimitPackageProperty);
}
if (limitCustomPropertyList.Items.Count == 0)
limitCustomPropertyList.Items.Add(new ListItem("", match.LimitCustomProperty));
if (limitCustomPropertyList.Items.FindByValue(match.LimitCustomProperty) == null)
match.LimitCustomProperty = limitCustomPropertyList.Items[0].Value;
}
}
protected void MatchItemPropertyField_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender != null)
{
DropDownList itemPropertyField = (DropDownList) sender;
ItemProperties itemProperty =
(ItemProperties) Enum.Parse(typeof (ItemProperties), itemPropertyField.SelectedValue);
DropDownList customPropertyField =
(DropDownList) itemPropertyField.NamingContainer.FindControl("MatchCustomPropertyField");
HelpLabel customPropertyLabel =
(HelpLabel) itemPropertyField.NamingContainer.FindControl("MatchCustomPropertyLabel");
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, itemProperty);
}
}
protected void MatchPackagePropertyField_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender != null)
{
DropDownList propertyField = (DropDownList) sender;
PackageProperties matchProperty =
(PackageProperties) Enum.Parse(typeof (PackageProperties), propertyField.SelectedValue);
DropDownList itemPropertyField =
(DropDownList) propertyField.NamingContainer.FindControl("MatchItemPropertyField");
ItemProperties itemProperty =
(ItemProperties) Enum.Parse(typeof (ItemProperties), itemPropertyField.SelectedValue);
DropDownList customPropertyField =
(DropDownList) propertyField.NamingContainer.FindControl("MatchCustomPropertyField");
HelpLabel customPropertyLabel =
(HelpLabel) propertyField.NamingContainer.FindControl("MatchCustomPropertyLabel");
if (matchProperty == PackageProperties.ItemProperty)
{
itemPropertyField.Visible = true;
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, itemProperty);
}
else
{
itemPropertyField.Visible = false;
customPropertyField.Visible = false;
Page.Validate("RuleGroup");
if (Page.IsValid)
{
PrepareCustomPropertyField(customPropertyLabel, customPropertyField, matchProperty);
}
}
}
}
#endregion
#region Methods
private readonly Regex hiddenAddressProperties =
new Regex("bvin|lastupdated", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly Regex hiddenItemProperties =
new Regex("FixedAmountOne", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly Regex hiddenLimitPackageProperties =
new Regex("Invisible|UseMethod", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly Regex hiddenMatchPackageProperties =
new Regex("FixedAmountOne|Invisible|UseMethod", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly Regex hiddenVendorManufacturerProperties =
new Regex("address|bvin|lastupdated|dropshipemailtemplateid", RegexOptions.IgnoreCase | RegexOptions.Compiled);
protected override void DataBindChildren()
{
Matches.RuleId = RuleId;
Matches.DataSource = DataSource;
base.DataBindChildren();
}
private ListItem[] GetAddressProperties()
{
List<ListItem> properties = new List<ListItem>();
foreach (PropertyInfo property in typeof (Address).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (!hiddenAddressProperties.IsMatch(property.Name))
properties.Add(new ListItem(property.Name, property.Name));
}
properties.Sort(delegate(ListItem item1, ListItem item2) { return string.Compare(item1.Text, item2.Text); });
return properties.ToArray();
}
private static ListItem[] GetComparisons()
{
List<ListItem> comparisons = new List<ListItem>();
foreach (RuleComparisons comparison in Enum.GetValues(typeof(RuleComparisons)))
{
comparisons.Add(new ListItem(RuleComparisonsHelper.GetDisplayName(comparison), comparison.ToString()));
}
return comparisons.ToArray();
}
private ListItem[] GetItemProperties()
{
List<ListItem> properties = new List<ListItem>();
foreach (ItemProperties property in Enum.GetValues(typeof (ItemProperties)))
{
if (!hiddenItemProperties.IsMatch(property.ToString()))
{
properties.Add(new ListItem(ItemPropertiesHelper.GetDisplayName(property), property.ToString()));
}
}
return properties.ToArray();
}
public PackageMatchList GetMatches()
{
return Matches.GetMatches();
}
private ListItem[] GetLimitPackageProperties()
{
List<ListItem> properties = new List<ListItem>();
foreach (PackageProperties property in Enum.GetValues(typeof (PackageProperties)))
{
if (!hiddenLimitPackageProperties.IsMatch(property.ToString()))
{
properties.Add(new ListItem(PackagePropertiesHelper.GetDisplayName(property), property.ToString()));
}
}
return properties.ToArray();
}
private ListItem[] GetMatchPackageProperties()
{
List<ListItem> properties = new List<ListItem>();
foreach (PackageProperties property in Enum.GetValues(typeof (PackageProperties)))
{
if (!hiddenMatchPackageProperties.IsMatch(property.ToString()))
{
properties.Add(new ListItem(PackagePropertiesHelper.GetDisplayName(property), property.ToString()));
}
}
return properties.ToArray();
}
private static ListItem[] GetPropertyTypes()
{
List<ListItem> propertyTypes = new List<ListItem>();
Collection<ProductProperty> properties = ProductProperty.FindAll();
foreach (ProductProperty property in properties)
{
propertyTypes.Add(new ListItem(property.DisplayName, property.Bvin));
}
if (propertyTypes.Count == 0)
{
propertyTypes.Add(new ListItem("- n/a -", string.Empty));
}
return propertyTypes.ToArray();
}
private ListItem[] GetShippingMethods()
{
List<ListItem> methods = new List<ListItem>();
methods.Add(new ListItem("-n/a-", ""));
foreach (ShippingMethod method in ShippingMethod.FindAll())
{
if (String.Compare(method.Bvin, ShippingMethod.Bvin, true) != 0)
{
methods.Add(new ListItem(method.Name, method.Bvin));
}
}
return methods.ToArray();
}
private ListItem[] GetVendorManufacturerProperties()
{
List<ListItem> properties = new List<ListItem>();
foreach (
PropertyInfo property in
typeof (VendorManufacturerBase).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (!hiddenVendorManufacturerProperties.IsMatch(property.Name))
properties.Add(new ListItem(property.Name, property.Name));
}
properties.AddRange(GetAddressProperties());
properties.Sort(delegate(ListItem item1, ListItem item2) { return string.Compare(item1.Text, item2.Text); });
return properties.ToArray();
}
private void PrepareCustomPropertyField(WebControl label, ListControl list, ItemProperties property)
{
list.Items.Clear();
if (property == ItemProperties.CustomProperty)
{
label.ToolTip = "<p>Select the custom property to use.</p>";
list.Items.AddRange(GetPropertyTypes());
list.Visible = true;
}
else if (property == ItemProperties.Manufacturer || property == ItemProperties.Vendor)
{
label.ToolTip = string.Format("<p>Select the {0} property to use.</p>", property.ToString().ToLower());
list.Items.AddRange(GetVendorManufacturerProperties());
list.Visible = true;
}
else
{
label.ToolTip = "";
list.Items.Add(new ListItem("n/a", ""));
list.Visible = false;
}
}
private void PrepareCustomPropertyField(WebControl label, ListControl list, PackageProperties property)
{
list.Items.Clear();
if (property == PackageProperties.DestinationAddress || property == PackageProperties.SourceAddress)
{
label.ToolTip = "<p>Select the address property to use.</p>";
list.Items.AddRange(GetAddressProperties());
list.Visible = true;
}
else if (property == PackageProperties.UseMethod)
{
label.ToolTip = "<p>Select the shipping method to use.</p>";
list.Items.AddRange(GetShippingMethods());
list.Visible = true;
}
else
{
label.ToolTip = "";
list.Items.Add(new ListItem("n/a", ""));
list.Visible = false;
}
}
private static void PrepareLimitField(Control multiplier, Label label, Control field, WebControl requiredValidator, WebControl numericValidator, ItemProperties property)
{
PropertyTypes propertyType = ItemPropertiesHelper.GetPropertyType(property);
PrepareLimitField(multiplier, label, field, requiredValidator, numericValidator, propertyType);
}
private static void PrepareLimitField(Control multiplier, Label label, Control field, WebControl requiredValidator, WebControl numericValidator, PackageProperties property)
{
PropertyTypes propertyType = PackagePropertiesHelper.GetPropertyType(property);
PrepareLimitField(multiplier, label, field, requiredValidator, numericValidator, propertyType);
}
private static void PrepareLimitField(Control multiplier, Label label, Control field, WebControl requiredValidator, WebControl numericValidator, PropertyTypes propertyType)
{
if (propertyType == PropertyTypes.Numeric)
{
multiplier.Visible = true;
field.Visible = true;
label.Text = "Multiplier";
label.ToolTip = "<p>Enter the multiplier.</p>";
requiredValidator.Enabled = true;
numericValidator.Enabled = true;
}
else if (propertyType == PropertyTypes.Fixed)
{
multiplier.Visible = false;
field.Visible = true;
label.Text = "Limit";
label.ToolTip = "<p>Enter the limit used in the comparison.</p>";
requiredValidator.Enabled = false;
numericValidator.Enabled = false;
}
else
{
multiplier.Visible = false;
field.Visible = false;
requiredValidator.Enabled = false;
numericValidator.Enabled = false;
}
}
#endregion
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Boundary;
using Microsoft.MixedReality.Toolkit.Diagnostics;
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.SpatialAwareness;
using Microsoft.MixedReality.Toolkit.Teleport;
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.EventSystems;
#if UNITY_EDITOR
using Microsoft.MixedReality.Toolkit.Input.Editor;
#endif
namespace Microsoft.MixedReality.Toolkit
{
/// <summary>
/// This class is responsible for coordinating the operation of the Mixed Reality Toolkit. It is the only Singleton in the entire project.
/// It provides a service registry for all active services that are used within a project as well as providing the active configuration profile for the project.
/// The Profile can be swapped out at any time to meet the needs of your project.
/// </summary>
[DisallowMultipleComponent]
public class MixedRealityToolkit : MonoBehaviour, IMixedRealityServiceRegistrar
{
#region Mixed Reality Toolkit Profile configuration
private const string MixedRealityPlayspaceName = "MixedRealityPlayspace";
private static bool isInitializing = false;
private static bool isApplicationQuitting = false;
/// <summary>
/// Checks if there is a valid instance of the MixedRealityToolkit, then checks if there is there a valid Active Profile.
/// </summary>
public bool HasActiveProfile
{
get
{
if (!IsInitialized)
{
return false;
}
if (!ConfirmInitialized())
{
return false;
}
return ActiveProfile != null;
}
}
/// <summary>
/// The active profile of the Mixed Reality Toolkit which controls which services are active and their initial configuration.
/// *Note configuration is used on project initialization or replacement, changes to properties while it is running has no effect.
/// </summary>
[SerializeField]
[Tooltip("The current active configuration for the Mixed Reality project")]
private MixedRealityToolkitConfigurationProfile activeProfile = null;
/// <summary>
/// The public property of the Active Profile, ensuring events are raised on the change of the configuration
/// </summary>
public MixedRealityToolkitConfigurationProfile ActiveProfile
{
get
{
#if UNITY_EDITOR
if (!Application.isPlaying && activeProfile == null)
{
UnityEditor.Selection.activeObject = Instance;
UnityEditor.EditorGUIUtility.PingObject(Instance);
}
#endif // UNITY_EDITOR
return activeProfile;
}
set
{
ResetConfiguration(value);
}
}
/// <summary>
/// When a configuration Profile is replaced with a new configuration, force all services to reset and read the new values
/// </summary>
/// <param name="profile"></param>
public void ResetConfiguration(MixedRealityToolkitConfigurationProfile profile)
{
if (activeProfile != null)
{
// Services are only enabled when playing.
if (Application.IsPlaying(activeProfile))
{
DisableAllServices();
}
DestroyAllServices();
}
activeProfile = profile;
if (profile != null)
{
if (Application.IsPlaying(profile))
{
DisableAllServices();
}
DestroyAllServices();
}
InitializeServiceLocator();
if (profile != null && Application.IsPlaying(profile))
{
EnableAllServices();
}
}
#endregion Mixed Reality Toolkit Profile configuration
#region Mixed Reality runtime service registry
private static readonly Dictionary<Type, IMixedRealityService> activeSystems = new Dictionary<Type, IMixedRealityService>();
/// <summary>
/// Current active systems registered with the MixedRealityToolkit.
/// </summary>
/// <remarks>
/// Systems can only be registered once by <see cref="Type"/>
/// </remarks>
public IReadOnlyDictionary<Type, IMixedRealityService> ActiveSystems => new Dictionary<Type, IMixedRealityService>(activeSystems) as IReadOnlyDictionary<Type, IMixedRealityService>;
private static readonly List<Tuple<Type, IMixedRealityService>> registeredMixedRealityServices = new List<Tuple<Type, IMixedRealityService>>();
/// <summary>
/// Local service registry for the Mixed Reality Toolkit, to allow runtime use of the <see cref="Microsoft.MixedReality.Toolkit.IMixedRealityService"/>.
/// </summary>
public IReadOnlyList<Tuple<Type, IMixedRealityService>> RegisteredMixedRealityServices => new List<Tuple<Type, IMixedRealityService>>(registeredMixedRealityServices) as IReadOnlyList<Tuple<Type, IMixedRealityService>>;
#endregion Mixed Reality runtime service registry
#region IMixedRealityServiceRegistrar implementation
/// <inheritdoc />
public bool RegisterService<T>(T serviceInstance) where T : IMixedRealityService
{
return RegisterServiceInternal<T>(serviceInstance);
}
/// <inheritdoc />
public bool RegisterService<T>(
Type concreteType,
SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1),
params object[] args) where T : IMixedRealityService
{
if (isApplicationQuitting)
{
return false;
}
#if !UNITY_EDITOR
if (!Application.platform.IsPlatformSupported(supportedPlatforms))
#else
if (!UnityEditor.EditorUserBuildSettings.activeBuildTarget.IsPlatformSupported(supportedPlatforms))
#endif
{
return false;
}
if (concreteType == null)
{
Debug.LogError("Unable to register a service with a null concrete type.");
return false;
}
if (!typeof(IMixedRealityService).IsAssignableFrom(concreteType))
{
Debug.LogError($"Unable to register the {concreteType.Name} service. It does not implement {typeof(IMixedRealityService)}.");
return false;
}
T serviceInstance;
try
{
serviceInstance = (T)Activator.CreateInstance(concreteType, args);
}
catch (Exception e)
{
Debug.LogError($"Failed to register the {concreteType.Name} service: {e.GetType()} - {e.Message}");
return false;
}
return RegisterServiceInternal<T>(serviceInstance);
}
/// <inheritdoc />
public bool UnregisterService<T>(string name = null) where T : IMixedRealityService
{
T serviceInstance = GetServiceByName<T>(name);
if (serviceInstance == null) { return false; }
return UnregisterService<T>(serviceInstance);
}
/// <inheritdoc />
public bool UnregisterService<T>(T serviceInstance) where T : IMixedRealityService
{
Type interfaceType = typeof(T);
if (IsInitialized)
{
serviceInstance.Disable();
serviceInstance.Destroy();
}
if (IsCoreSystem(interfaceType))
{
activeSystems.Remove(interfaceType);
return true;
}
Tuple<Type, IMixedRealityService> registryInstance = new Tuple<Type, IMixedRealityService>(interfaceType, serviceInstance);
if (registeredMixedRealityServices.Contains(registryInstance))
{
registeredMixedRealityServices.Remove(registryInstance);
return true;
}
Debug.LogError($"Failed to find registry instance of {interfaceType.Name}.{serviceInstance.Name}!");
return false;
}
/// <inheritdoc />
public bool IsServiceRegistered<T>(string name = null) where T : IMixedRealityService
{
return GetService<T>(name) != null;
}
/// <inheritdoc />
public T GetService<T>(string name = null, bool showLogs = true) where T : IMixedRealityService
{
Type interfaceType = typeof(T);
T serviceInstance = GetServiceByName<T>(name);
if ((serviceInstance == null) && showLogs)
{
Debug.LogError($"Unable to find {(string.IsNullOrWhiteSpace(name) ? interfaceType.Name : name)} service.");
}
return serviceInstance;
}
/// <inheritdoc />
public IReadOnlyList<T> GetServices<T>(string name = null) where T : IMixedRealityService
{
return GetAllServicesByNameInternal<T>(typeof(T), name);
}
/// <inheritdoc />
public bool RegisterDataProvider<T>(T dataProviderInstance) where T : IMixedRealityDataProvider
{
return RegisterService<T>(dataProviderInstance);
}
/// <inheritdoc />
public bool RegisterDataProvider<T>(
Type concreteType,
SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1),
params object[] args) where T : IMixedRealityDataProvider
{
return RegisterService<T>(concreteType, supportedPlatforms, args);
}
/// <inheritdoc />
public bool UnregisterDataProvider<T>(string name = null) where T : IMixedRealityDataProvider
{
return UnregisterService<T>(name);
}
/// <inheritdoc />
public bool UnregisterDataProvider<T>(T dataProviderInstance) where T : IMixedRealityDataProvider
{
return UnregisterService<T>(dataProviderInstance);
}
/// <inheritdoc />
public bool IsDataProviderRegistered<T>(string name = null) where T : IMixedRealityDataProvider
{
return IsServiceRegistered<T>(name);
}
/// <inheritdoc />
public T GetDataProvider<T>(string name = null) where T : IMixedRealityDataProvider
{
return GetService<T>(name);
}
/// <inheritdoc />
public IReadOnlyList<T> GetDataProviders<T>(string name = null) where T : IMixedRealityDataProvider
{
return GetServices<T>(name);
}
/// <inheritdoc />
public IReadOnlyList<T> GetDataProviders<T>() where T : IMixedRealityDataProvider
{
throw new NotImplementedException();
}
#endregion IMixedRealityServiceRegistrar implementation
/// <summary>
/// Once all services are registered and properties updated, the Mixed Reality Toolkit will initialize all active services.
/// This ensures all services can reference each other once started.
/// </summary>
private void InitializeServiceLocator()
{
isInitializing = true;
//If the Mixed Reality Toolkit is not configured, stop.
if (ActiveProfile == null)
{
Debug.LogError("No Mixed Reality Configuration Profile found, cannot initialize the Mixed Reality Toolkit");
return;
}
#if UNITY_EDITOR
if (ActiveSystems.Count > 0)
{
activeSystems.Clear();
}
if (RegisteredMixedRealityServices.Count > 0)
{
registeredMixedRealityServices.Clear();
}
#endif
ClearCoreSystemCache();
EnsureMixedRealityRequirements();
if (ActiveProfile.IsCameraProfileEnabled)
{
if (ActiveProfile.CameraProfile.IsCameraPersistent)
{
CameraCache.Main.transform.root.DontDestroyOnLoad();
}
if (ActiveProfile.CameraProfile.IsOpaque)
{
ActiveProfile.CameraProfile.ApplySettingsForOpaqueDisplay();
}
else
{
ActiveProfile.CameraProfile.ApplySettingsForTransparentDisplay();
}
}
#region Services Registration
// If the Input system has been selected for initialization in the Active profile, enable it in the project
if (ActiveProfile.IsInputSystemEnabled)
{
#if UNITY_EDITOR
// Make sure unity axis mappings are set.
InputMappingAxisUtility.CheckUnityInputManagerMappings(ControllerMappingLibrary.UnityInputManagerAxes);
#endif
object[] args = { this, ActiveProfile.InputSystemProfile, Instance.MixedRealityPlayspace };
if (!RegisterService<IMixedRealityInputSystem>(ActiveProfile.InputSystemType, args: args) || InputSystem == null)
{
Debug.LogError("Failed to start the Input System!");
}
args = new object[] { this, InputSystem, ActiveProfile.InputSystemProfile };
if (!RegisterDataProvider<IMixedRealityFocusProvider>(ActiveProfile.InputSystemProfile.FocusProviderType, args: args))
{
Debug.LogError("Failed to register the focus provider! The input system will not function without it.");
return;
}
}
else
{
#if UNITY_EDITOR
InputMappingAxisUtility.RemoveMappings(ControllerMappingLibrary.UnityInputManagerAxes);
#endif
}
// If the Boundary system has been selected for initialization in the Active profile, enable it in the project
if (ActiveProfile.IsBoundarySystemEnabled)
{
object[] args = { this, ActiveProfile.BoundaryVisualizationProfile, Instance.MixedRealityPlayspace, ActiveProfile.TargetExperienceScale };
if (!RegisterService<IMixedRealityBoundarySystem>(ActiveProfile.BoundarySystemSystemType, args: args) || BoundarySystem == null)
{
Debug.LogError("Failed to start the Boundary System!");
}
}
// If the Spatial Awareness system has been selected for initialization in the Active profile, enable it in the project
if (ActiveProfile.IsSpatialAwarenessSystemEnabled)
{
#if UNITY_EDITOR
LayerExtensions.SetupLayer(31, "Spatial Awareness");
#endif
object[] args = { this, ActiveProfile.SpatialAwarenessSystemProfile };
if (!RegisterService<IMixedRealitySpatialAwarenessSystem>(ActiveProfile.SpatialAwarenessSystemSystemType, args: args) && SpatialAwarenessSystem != null)
{
Debug.LogError("Failed to start the Spatial Awareness System!");
}
}
// If the Teleport system has been selected for initialization in the Active profile, enable it in the project
if (ActiveProfile.IsTeleportSystemEnabled)
{
object[] args = { this, Instance.MixedRealityPlayspace };
if (!RegisterService<IMixedRealityTeleportSystem>(ActiveProfile.TeleportSystemSystemType, args: args) || TeleportSystem == null)
{
Debug.LogError("Failed to start the Teleport System!");
}
}
if (ActiveProfile.IsDiagnosticsSystemEnabled)
{
object[] args = { this, ActiveProfile.DiagnosticsSystemProfile, Instance.MixedRealityPlayspace };
if (!RegisterService<IMixedRealityDiagnosticsSystem>(ActiveProfile.DiagnosticsSystemSystemType, args: args) || DiagnosticsSystem == null)
{
Debug.LogError("Failed to start the Diagnostics System!");
}
}
if (ActiveProfile.RegisteredServiceProvidersProfile != null)
{
for (int i = 0; i < ActiveProfile.RegisteredServiceProvidersProfile?.Configurations?.Length; i++)
{
var configuration = ActiveProfile.RegisteredServiceProvidersProfile.Configurations[i];
if (typeof(IMixedRealityExtensionService).IsAssignableFrom(configuration.ComponentType.Type))
{
object[] args = { this, configuration.ComponentName, configuration.Priority, configuration.ConfigurationProfile };
if (!RegisterService<IMixedRealityExtensionService>(configuration.ComponentType, configuration.RuntimePlatform, args))
{
Debug.LogError($"Failed to register {configuration.ComponentName}");
}
}
}
}
#endregion Service Registration
#region Services Initialization
var orderedCoreSystems = activeSystems.OrderBy(m => m.Value.Priority).ToArray();
activeSystems.Clear();
foreach (var system in orderedCoreSystems)
{
RegisterServiceInternal(system.Key, system.Value);
}
var orderedServices = registeredMixedRealityServices.OrderBy(service => service.Item2.Priority).ToArray();
registeredMixedRealityServices.Clear();
foreach (var service in orderedServices)
{
RegisterServiceInternal(service.Item1, service.Item2);
}
InitializeAllServices();
#endregion Services Initialization
isInitializing = false;
}
private void EnsureMixedRealityRequirements()
{
// There's lots of documented cases that if the camera doesn't start at 0,0,0, things break with the WMR SDK specifically.
// We'll enforce that here, then tracking can update it to the appropriate position later.
CameraCache.Main.transform.position = Vector3.zero;
bool addedComponents = false;
if (!Application.isPlaying)
{
var eventSystems = FindObjectsOfType<EventSystem>();
if (eventSystems.Length == 0)
{
CameraCache.Main.gameObject.EnsureComponent<EventSystem>();
addedComponents = true;
}
else
{
bool raiseWarning;
if (eventSystems.Length == 1)
{
raiseWarning = eventSystems[0].gameObject != CameraCache.Main.gameObject;
}
else
{
raiseWarning = true;
}
if (raiseWarning)
{
Debug.LogWarning("Found an existing event system in your scene. The Mixed Reality Toolkit requires only one, and must be found on the main camera.");
}
}
}
if (!addedComponents)
{
CameraCache.Main.gameObject.EnsureComponent<EventSystem>();
}
}
#region MonoBehaviour Implementation
private static MixedRealityToolkit instance;
private static bool newInstanceBeingInitialized = false;
/// <summary>
/// Returns the Singleton instance of the classes type.
/// If no instance is found, then we search for an instance in the scene.
/// If more than one instance is found, we log an error and no instance is returned.
/// </summary>
public static MixedRealityToolkit Instance
{
get
{
if (IsInitialized)
{
return instance;
}
if (Application.isPlaying && !searchForInstance)
{
return null;
}
var objects = FindObjectsOfType<MixedRealityToolkit>();
searchForInstance = false;
MixedRealityToolkit newInstance;
switch (objects.Length)
{
case 0:
Debug.Assert(!newInstanceBeingInitialized, "We shouldn't be initializing another MixedRealityToolkit unless we errored on the previous.");
newInstanceBeingInitialized = true;
newInstance = new GameObject(nameof(MixedRealityToolkit)).AddComponent<MixedRealityToolkit>();
break;
case 1:
newInstanceBeingInitialized = false;
newInstance = objects[0];
break;
default:
newInstanceBeingInitialized = false;
Debug.LogError($"Expected exactly 1 {nameof(MixedRealityToolkit)} but found {objects.Length}.");
return null;
}
Debug.Assert(newInstance != null);
if (!isApplicationQuitting)
{
// Setup any additional things the instance needs.
newInstance.InitializeInstance();
}
else
{
// Don't do any additional setup because the app is quitting.
instance = newInstance;
newInstanceBeingInitialized = false;
}
Debug.Assert(instance != null);
return instance;
}
}
/// <summary>
/// Lock property for the Mixed Reality Toolkit to prevent reinitialization
/// </summary>
private static readonly object initializedLock = new object();
private void InitializeInstance()
{
lock (initializedLock)
{
if (IsInitialized)
{
newInstanceBeingInitialized = false;
return;
}
instance = this;
if (Application.isPlaying)
{
DontDestroyOnLoad(instance.transform.root);
}
Application.quitting += () =>
{
isApplicationQuitting = true;
};
#if UNITY_EDITOR
UnityEditor.EditorApplication.playModeStateChanged += playModeState =>
{
if (playModeState == UnityEditor.PlayModeStateChange.ExitingEditMode ||
playModeState == UnityEditor.PlayModeStateChange.EnteredEditMode)
{
isApplicationQuitting = false;
}
if (playModeState == UnityEditor.PlayModeStateChange.ExitingEditMode && activeProfile == null)
{
UnityEditor.EditorApplication.isPlaying = false;
UnityEditor.Selection.activeObject = Instance;
UnityEditor.EditorGUIUtility.PingObject(Instance);
}
};
UnityEditor.EditorApplication.hierarchyChanged += () =>
{
if (instance != null)
{
Debug.Assert(instance.transform.parent == null, "The MixedRealityToolkit should not be parented under any other GameObject!");
Debug.Assert(instance.transform.childCount == 0, "The MixedRealityToolkit should not have GameObject children!");
}
};
#endif // UNITY_EDITOR
if (HasActiveProfile)
{
InitializeServiceLocator();
}
newInstanceBeingInitialized = false;
}
}
/// <summary>
/// Flag to search for instance the first time Instance property is called.
/// Subsequent attempts will generally switch this flag false, unless the instance was destroyed.
/// </summary>
// ReSharper disable once StaticMemberInGenericType
private static bool searchForInstance = true;
/// <summary>
/// Expose an assertion whether the MixedRealityToolkit class is initialized.
/// </summary>
public static void AssertIsInitialized()
{
Debug.Assert(IsInitialized, "The MixedRealityToolkit has not been initialized.");
}
/// <summary>
/// Returns whether the instance has been initialized or not.
/// </summary>
public static bool IsInitialized => instance != null;
/// <summary>
/// Static function to determine if the MixedRealityToolkit class has been initialized or not.
/// </summary>
/// <returns></returns>
public static bool ConfirmInitialized()
{
// ReSharper disable once UnusedVariable
// Assigning the Instance to access is used Implicitly.
MixedRealityToolkit access = Instance;
return IsInitialized;
}
private Transform mixedRealityPlayspace;
/// <summary>
/// Returns the MixedRealityPlayspace for the local player
/// </summary>
public Transform MixedRealityPlayspace
{
get
{
AssertIsInitialized();
if (mixedRealityPlayspace)
{
return mixedRealityPlayspace;
}
if (CameraCache.Main.transform.parent == null)
{
mixedRealityPlayspace = new GameObject(MixedRealityPlayspaceName).transform;
CameraCache.Main.transform.SetParent(mixedRealityPlayspace);
}
else
{
if (CameraCache.Main.transform.parent.name != MixedRealityPlayspaceName)
{
// Since the scene is set up with a different camera parent, its likely
// that there's an expectation that that parent is going to be used for
// something else. We print a warning to call out the fact that we're
// co-opting this object for use with teleporting and such, since that
// might cause conflicts with the parent's intended purpose.
Debug.LogWarning($"The Mixed Reality Toolkit expected the camera\'s parent to be named {MixedRealityPlayspaceName}. The existing parent will be renamed and used instead.");
// If we rename it, we make it clearer that why it's being teleported around at runtime.
CameraCache.Main.transform.parent.name = MixedRealityPlayspaceName;
}
mixedRealityPlayspace = CameraCache.Main.transform.parent;
}
// It's very important that the MixedRealityPlayspace align with the tracked space,
// otherwise reality-locked things like playspace boundaries won't be aligned properly.
// For now, we'll just assume that when the playspace is first initialized, the
// tracked space origin overlaps with the world space origin. If a platform ever does
// something else (i.e, placing the lower left hand corner of the tracked space at world
// space 0,0,0), we should compensate for that here.
return mixedRealityPlayspace;
}
}
#if UNITY_EDITOR
private void OnValidate()
{
if (!newInstanceBeingInitialized && !IsInitialized && !UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
{
ConfirmInitialized();
}
}
#endif // UNITY_EDITOR
private void Awake()
{
if (IsInitialized && instance != this)
{
if (Application.isEditor)
{
DestroyImmediate(this);
}
else
{
Destroy(this);
}
Debug.LogWarning("Trying to instantiate a second instance of the Mixed Reality Toolkit. Additional Instance was destroyed");
}
else if (!IsInitialized)
{
InitializeInstance();
}
else
{
Debug.LogError("Failed to properly initialize the MixedRealityToolkit");
}
}
private void OnEnable()
{
EnableAllServices();
}
private void Update()
{
UpdateAllServices();
}
private void LateUpdate()
{
LateUpdateAllServices();
}
private void OnDisable()
{
DisableAllServices();
}
private void OnDestroy()
{
DestroyAllServices();
ClearCoreSystemCache();
if (instance == this)
{
instance = null;
searchForInstance = true;
}
}
#endregion MonoBehaviour Implementation
#region Service Container Management
#region Registration
private bool RegisterServiceInternal(Type interfaceType, IMixedRealityService serviceInstance)
{
if (serviceInstance == null)
{
Debug.LogWarning($"Unable to add a {interfaceType.Name} service with a null instance.");
return false;
}
if (!CanGetService(interfaceType)) { return false; }
IMixedRealityService preExistingService = GetServiceByNameInternal(interfaceType, serviceInstance.Name);
if (preExistingService != null)
{
Debug.LogError($"There's already a {interfaceType.Name}.{preExistingService.Name} registered!");
return false;
}
if (IsCoreSystem(interfaceType))
{
activeSystems.Add(interfaceType, serviceInstance);
}
else if (typeof(IMixedRealityDataProvider).IsAssignableFrom(interfaceType) ||
typeof(IMixedRealityExtensionService).IsAssignableFrom(interfaceType))
{
registeredMixedRealityServices.Add(new Tuple<Type, IMixedRealityService>(interfaceType, serviceInstance));
}
else
{
Debug.LogError($"Unable to register {interfaceType.Name}. Concrete type does not implement {typeof(IMixedRealityExtensionService).Name} or {typeof(IMixedRealityDataProvider).Name}.");
return false;
}
if (!isInitializing)
{
serviceInstance.Initialize();
serviceInstance.Enable();
}
return true;
}
/// <summary>
/// Internal service registration.
/// </summary>
/// <param name="interfaceType">The interface type for the system to be registered.</param>
/// <param name="serviceInstance">Instance of the service.</param>
/// <returns>True if registration is successful, false otherwise.</returns>
private bool RegisterServiceInternal<T>(T serviceInstance) where T : IMixedRealityService
{
Type interfaceType = typeof(T);
return RegisterServiceInternal(interfaceType, serviceInstance);
}
#endregion Registration
#region Multiple Service Management
/// <summary>
/// Enable all services in the Mixed Reality Toolkit active service registry for a given type
/// </summary>
/// <param name="interfaceType">The interface type for the system to be enabled. E.G. InputSystem, BoundarySystem</param>
public void EnableAllServicesByType(Type interfaceType)
{
EnableAllServicesByTypeAndName(interfaceType, string.Empty);
}
/// <summary>
/// Enable all services in the Mixed Reality Toolkit active service registry for a given type and name
/// </summary>
/// <param name="interfaceType">The interface type for the system to be enabled. E.G. InputSystem, BoundarySystem</param>
/// <param name="serviceName">Name of the specific service</param>
public void EnableAllServicesByTypeAndName(Type interfaceType, string serviceName)
{
if (interfaceType == null)
{
Debug.LogError("Unable to enable null service type.");
return;
}
IReadOnlyList<IMixedRealityService> services = GetAllServicesByNameInternal<IMixedRealityService>(interfaceType, serviceName);
for (int i = 0; i < services.Count; i++)
{
services[i].Enable();
}
}
/// <summary>
/// Disable all services in the Mixed Reality Toolkit active service registry for a given type
/// </summary>
/// <param name="interfaceType">The interface type for the system to be removed. E.G. InputSystem, BoundarySystem</param>
public void DisableAllServicesByType(Type interfaceType)
{
DisableAllServicesByTypeAndName(interfaceType, string.Empty);
}
/// <summary>
/// Disable all services in the Mixed Reality Toolkit active service registry for a given type and name
/// </summary>
/// <param name="interfaceType">The interface type for the system to be disabled. E.G. InputSystem, BoundarySystem</param>
/// <param name="serviceName">Name of the specific service</param>
public void DisableAllServicesByTypeAndName(Type interfaceType, string serviceName)
{
if (interfaceType == null)
{
Debug.LogError("Unable to disable null service type.");
return;
}
IReadOnlyList<IMixedRealityService> services = GetAllServicesByNameInternal<IMixedRealityService>(interfaceType, serviceName);
for (int i = 0; i < services.Count; i++)
{
services[i].Disable();
}
}
private void InitializeAllServices()
{
// If the Mixed Reality Toolkit is not configured, stop.
if (activeProfile == null) { return; }
// Initialize all systems
foreach (var system in activeSystems)
{
system.Value.Initialize();
}
// Initialize all registered runtime services
foreach (var service in registeredMixedRealityServices)
{
service.Item2.Initialize();
}
}
private void ResetAllServices()
{
// If the Mixed Reality Toolkit is not configured, stop.
if (activeProfile == null) { return; }
// If the Mixed Reality Toolkit is not initialized, stop.
if (!IsInitialized) { return; }
// Reset all systems
foreach (var system in activeSystems)
{
system.Value.Reset();
}
// Reset all registered runtime services
foreach (var service in registeredMixedRealityServices)
{
service.Item2.Reset();
}
}
private void EnableAllServices()
{
// If the Mixed Reality Toolkit is not configured, stop.
if (activeProfile == null) { return; }
// If the Mixed Reality Toolkit is not initialized, stop.
if (!IsInitialized) { return; }
// Enable all systems
foreach (var system in activeSystems)
{
system.Value.Enable();
}
// Reset all registered runtime services
foreach (var service in registeredMixedRealityServices)
{
service.Item2.Enable();
}
}
private void UpdateAllServices()
{
// If the Mixed Reality Toolkit is not configured, stop.
if (activeProfile == null) { return; }
// If the Mixed Reality Toolkit is not initialized, stop.
if (!IsInitialized) { return; }
// Update all systems
foreach (var system in activeSystems)
{
system.Value.Update();
}
// Update all registered runtime services
foreach (var service in registeredMixedRealityServices)
{
service.Item2.Update();
}
}
private void LateUpdateAllServices()
{
// If the Mixed Reality Toolkit is not configured, stop.
if (activeProfile == null) { return; }
// If the Mixed Reality Toolkit is not initialized, stop.
if (!IsInitialized) { return; }
// Update all systems
foreach (var system in activeSystems)
{
system.Value.LateUpdate();
}
// Update all registered runtime services
foreach (var service in registeredMixedRealityServices)
{
service.Item2.LateUpdate();
}
}
private void DisableAllServices()
{
// If the Mixed Reality Toolkit is not configured, stop.
if (activeProfile == null) { return; }
// If the Mixed Reality Toolkit is not initialized, stop.
if (!IsInitialized) { return; }
// Disable all systems
foreach (var system in activeSystems)
{
system.Value.Disable();
}
// Disable all registered runtime services
foreach (var service in registeredMixedRealityServices)
{
service.Item2.Disable();
}
}
private void DestroyAllServices()
{
// If the Mixed Reality Toolkit is not configured, stop.
if (activeProfile == null) { return; }
// If the Mixed Reality Toolkit is not initialized, stop.
if (!IsInitialized) { return; }
// Destroy all systems
foreach (var system in activeSystems)
{
system.Value.Destroy();
}
activeSystems.Clear();
// Destroy all registered runtime services
foreach (var service in registeredMixedRealityServices)
{
service.Item2.Destroy();
}
registeredMixedRealityServices.Clear();
}
#endregion Multiple Service Management
#region Service Utilities
/// <summary>
/// Generic function used to interrogate the Mixed Reality Toolkit active system registry for the existence of a core system.
/// </summary>
/// <typeparam name="T">The interface type for the system to be retrieved. E.G. InputSystem, BoundarySystem.</typeparam>
/// <remarks>
/// Note: type should be the Interface of the system to be retrieved and not the concrete class itself.
/// </remarks>
/// <returns>True, there is a system registered with the selected interface, False, no system found for that interface</returns>
public bool IsSystemRegistered<T>() where T : class
{
IMixedRealityService service;
activeSystems.TryGetValue(typeof(T), out service);
return service != null;
}
private static bool IsCoreSystem(Type type)
{
if (type == null)
{
Debug.LogWarning("Null cannot be a core system.");
return false;
}
return typeof(IMixedRealityInputSystem).IsAssignableFrom(type) ||
typeof(IMixedRealityFocusProvider).IsAssignableFrom(type) ||
typeof(IMixedRealityTeleportSystem).IsAssignableFrom(type) ||
typeof(IMixedRealityBoundarySystem).IsAssignableFrom(type) ||
typeof(IMixedRealitySpatialAwarenessSystem).IsAssignableFrom(type) ||
typeof(IMixedRealityDiagnosticsSystem).IsAssignableFrom(type);
}
private void ClearCoreSystemCache()
{
inputSystem = null;
teleportSystem = null;
boundarySystem = null;
spatialAwarenessSystem = null;
diagnosticsSystem = null;
}
private IMixedRealityService GetServiceByNameInternal(Type interfaceType, string serviceName)
{
if (!CanGetService(interfaceType)) { return null; }
IMixedRealityService serviceInstance = null;
if (IsCoreSystem(interfaceType))
{
if (activeSystems.TryGetValue(interfaceType, out serviceInstance))
{
if (CheckServiceMatch(interfaceType, serviceName, interfaceType, serviceInstance))
{
return serviceInstance;
}
}
}
else
{
for (int i = 0; i < registeredMixedRealityServices.Count; i++)
{
if (CheckServiceMatch(interfaceType, serviceName, registeredMixedRealityServices[i].Item1, registeredMixedRealityServices[i].Item2))
{
return registeredMixedRealityServices[i].Item2;
}
}
}
return null;
}
/// <summary>
/// Retrieve the first service from the registry that meets the selected type and name
/// </summary>
/// <param name="interfaceType">Interface type of the service being requested</param>
/// <param name="serviceName">Name of the specific service</param>
/// <param name="serviceInstance">return parameter of the function</param>
private T GetServiceByName<T>(string serviceName) where T : IMixedRealityService
{
return (T)GetServiceByNameInternal(typeof(T), serviceName);
}
/// <summary>
/// Gets all services by type and name.
/// </summary>
/// <param name="serviceName">The name of the service to search for. If the string is empty than any matching <see cref="interfaceType"/> will be added to the <see cref="services"/> list.</param>
private IReadOnlyList<T> GetAllServicesByNameInternal<T>(Type interfaceType, string serviceName) where T : IMixedRealityService
{
List<T> services = new List<T>();
if (!CanGetService(interfaceType)) { return new List<T>() as IReadOnlyList<T>; }
if (IsCoreSystem(interfaceType))
{
IMixedRealityService serviceInstance = GetServiceByName<T>(serviceName);
if ((serviceInstance != null) &&
CheckServiceMatch(interfaceType, serviceName, interfaceType, serviceInstance))
{
services.Add((T)serviceInstance);
}
}
else
{
for (int i = 0; i < registeredMixedRealityServices.Count; i++)
{
if (CheckServiceMatch(interfaceType, serviceName, registeredMixedRealityServices[i].Item1, registeredMixedRealityServices[i].Item2))
{
services.Add((T)registeredMixedRealityServices[i].Item2);
}
}
}
return services;
}
/// <summary>
/// Check if the interface type and name matches the registered interface type and service instance found.
/// </summary>
/// <param name="interfaceType">The interface type of the service to check.</param>
/// <param name="serviceName">The name of the service to check.</param>
/// <param name="registeredInterfaceType">The registered interface type.</param>
/// <param name="serviceInstance">The instance of the registered service.</param>
/// <returns>True, if the registered service contains the interface type and name.</returns>
private static bool CheckServiceMatch(Type interfaceType, string serviceName, Type registeredInterfaceType, IMixedRealityService serviceInstance)
{
bool isValid = string.IsNullOrEmpty(serviceName) || serviceInstance.Name == serviceName;
if ((registeredInterfaceType.Name == interfaceType.Name || serviceInstance.GetType().Name == interfaceType.Name) && isValid)
{
return true;
}
var interfaces = serviceInstance.GetType().GetInterfaces();
for (int i = 0; i < interfaces.Length; i++)
{
if (interfaces[i].Name == interfaceType.Name && isValid)
{
return true;
}
}
return false;
}
/// <summary>
/// Checks if the system is ready to get a service.
/// </summary>
/// <param name="interfaceType"></param>
/// <returns></returns>
private static bool CanGetService(Type interfaceType)
{
if (isApplicationQuitting)
{
return false;
}
if (!IsInitialized)
{
Debug.LogError("The Mixed Reality Toolkit has not been initialized!");
return false;
}
if (interfaceType == null)
{
Debug.LogError($"Interface type is null.");
return false;
}
if (!typeof(IMixedRealityService).IsAssignableFrom(interfaceType))
{
Debug.LogError($"{interfaceType.Name} does not implement {typeof(IMixedRealityService).Name}.");
return false;
}
return true;
}
#endregion Service Utilities
#endregion Service Container Management
#region Core System Accessors
private static IMixedRealityInputSystem inputSystem = null;
/// <summary>
/// The current Input System registered with the Mixed Reality Toolkit.
/// </summary>
public static IMixedRealityInputSystem InputSystem
{
get
{
if (isApplicationQuitting)
{
return null;
}
if (inputSystem != null)
{
return inputSystem;
}
inputSystem = Instance.GetService<IMixedRealityInputSystem>(showLogs: logInputSystem);
// If we found a valid system, then we turn logging back on for the next time we need to search.
// If we didn't find a valid system, then we stop logging so we don't spam the debug window.
logInputSystem = inputSystem != null;
return inputSystem;
}
}
private static bool logInputSystem = true;
private static IMixedRealityBoundarySystem boundarySystem = null;
/// <summary>
/// The current Boundary System registered with the Mixed Reality Toolkit.
/// </summary>
public static IMixedRealityBoundarySystem BoundarySystem
{
get
{
if (isApplicationQuitting)
{
return null;
}
if (boundarySystem != null)
{
return boundarySystem;
}
boundarySystem = Instance.GetService<IMixedRealityBoundarySystem>(showLogs: logBoundarySystem);
// If we found a valid system, then we turn logging back on for the next time we need to search.
// If we didn't find a valid system, then we stop logging so we don't spam the debug window.
logBoundarySystem = boundarySystem != null;
return boundarySystem;
}
}
private static bool logBoundarySystem = true;
private static IMixedRealitySpatialAwarenessSystem spatialAwarenessSystem = null;
/// <summary>
/// The current Spatial Awareness System registered with the Mixed Reality Toolkit.
/// </summary>
public static IMixedRealitySpatialAwarenessSystem SpatialAwarenessSystem
{
get
{
if (isApplicationQuitting)
{
return null;
}
if (spatialAwarenessSystem != null)
{
return spatialAwarenessSystem;
}
spatialAwarenessSystem = Instance.GetService<IMixedRealitySpatialAwarenessSystem>(showLogs: logSpatialAwarenessSystem);
// If we found a valid system, then we turn logging back on for the next time we need to search.
// If we didn't find a valid system, then we stop logging so we don't spam the debug window.
logSpatialAwarenessSystem = spatialAwarenessSystem != null;
return spatialAwarenessSystem;
}
}
private static bool logSpatialAwarenessSystem = true;
private static IMixedRealityTeleportSystem teleportSystem = null;
/// <summary>
/// Returns true if the MixedRealityToolkit exists and has an active profile that has Teleport system enabled.
/// </summary>
public static bool IsTeleportSystemEnabled => IsInitialized && Instance.HasActiveProfile && Instance.ActiveProfile.IsTeleportSystemEnabled;
/// <summary>
/// The current Teleport System registered with the Mixed Reality Toolkit.
/// </summary>
public static IMixedRealityTeleportSystem TeleportSystem
{
get
{
if (isApplicationQuitting)
{
return null;
}
if (teleportSystem != null)
{
return teleportSystem;
}
// Quiet warnings as we check for the service. If it's not available, it has probably been
// disabled. We'll notify about that, in case it's an accident, but otherwise remain calm about it.
teleportSystem = Instance.GetService<IMixedRealityTeleportSystem>(showLogs: false);
if (logTeleportSystem && (teleportSystem == null))
{
Debug.LogWarning("IMixedRealityTeleportSystem service is disabled. Teleport will not be available.\nCheck MRTK Configuration Profile settings if this is unexpected.");
}
// If we found a valid system, then we turn logging back on for the next time we need to search.
// If we didn't find a valid system, then we stop logging so we don't spam the debug window.
logTeleportSystem = teleportSystem != null;
return teleportSystem;
}
}
private static bool logTeleportSystem = true;
private static IMixedRealityDiagnosticsSystem diagnosticsSystem = null;
/// <summary>
/// The current Diagnostics System registered with the Mixed Reality Toolkit.
/// </summary>
public static IMixedRealityDiagnosticsSystem DiagnosticsSystem
{
get
{
if (isApplicationQuitting)
{
return null;
}
if (diagnosticsSystem != null)
{
return diagnosticsSystem;
}
diagnosticsSystem = Instance.GetService<IMixedRealityDiagnosticsSystem>(showLogs: logDiagnosticsSystem);
// If we found a valid system, then we turn logging back on for the next time we need to search.
// If we didn't find a valid system, then we stop logging so we don't spam the debug window.
logDiagnosticsSystem = diagnosticsSystem != null;
return diagnosticsSystem;
}
}
private static bool logDiagnosticsSystem = true;
#endregion Core System Accessors
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using Common.Logging;
using Lucene.Net.Index;
using Lucene.Net.Linq;
using Lucene.Net.Linq.Abstractions;
using Lucene.Net.Search;
using NuGet.Lucene.Util;
#if NET_4_5
using TaskEx=System.Threading.Tasks.Task;
#endif
namespace NuGet.Lucene
{
public class PackageIndexer : IPackageIndexer, IDisposable
{
public static ILog Log = LogManager.GetLogger<PackageIndexer>();
#if NET_4_5
private static readonly TimeSpan InfiniteTimeSpan = Timeout.InfiniteTimeSpan;
#else
private static readonly TimeSpan InfiniteTimeSpan = TimeSpan.FromMilliseconds(-1);
#endif
private enum UpdateType { Add, Remove, RemoveByPath, Increment }
private class Update
{
private readonly LucenePackage package;
private readonly UpdateType updateType;
private readonly TaskCompletionSource<object> signal = new TaskCompletionSource<object>();
public Update(LucenePackage package, UpdateType updateType)
{
this.package = package;
this.updateType = updateType;
}
public LucenePackage Package
{
get { return package; }
}
public UpdateType UpdateType
{
get { return updateType; }
}
public Task Task
{
get
{
return signal.Task;
}
}
public void SetComplete()
{
if (!signal.Task.IsCompleted)
{
signal.SetResult(null);
}
}
public void SetException(Exception exception)
{
signal.SetException(exception);
}
}
private volatile IndexingState indexingState = IndexingState.Idle;
private readonly object synchronizationStatusLock = new object();
private volatile SynchronizationStatus synchronizationStatus = new SynchronizationStatus(SynchronizationState.Idle);
private readonly BlockingCollection<Update> pendingUpdates = new BlockingCollection<Update>();
private Task indexUpdaterTask;
private readonly TaskPoolScheduler eventScheduler = TaskPoolScheduler.Default;
public IFileSystem FileSystem { get; set; }
public IIndexWriter Writer { get; set; }
public LuceneDataProvider Provider { get; set; }
public ILucenePackageRepository PackageRepository { get; set; }
private event EventHandler statusChanged;
public void Initialize()
{
indexUpdaterTask = Task.Factory.StartNew(IndexUpdateLoop, TaskCreationOptions.LongRunning);
}
public void Dispose()
{
pendingUpdates.CompleteAdding();
indexUpdaterTask.Wait();
}
/// <summary>
/// Gets status of index building activity.
/// </summary>
public IndexingStatus GetIndexingStatus()
{
return new IndexingStatus(indexingState, synchronizationStatus);
}
public IObservable<IndexingStatus> StatusChanged
{
get
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
eh => eh.Invoke,
eh => statusChanged += eh,
eh => statusChanged -= eh)
.Select(_ => GetIndexingStatus());
}
}
public void Optimize()
{
using (UpdateStatus(IndexingState.Optimizing))
{
Writer.Optimize();
}
}
public async Task SynchronizeIndexWithFileSystemAsync(SynchronizationMode mode, CancellationToken cancellationToken)
{
lock (synchronizationStatusLock)
{
if (synchronizationStatus.SynchronizationState != SynchronizationState.Idle)
{
throw new InvalidOperationException("Already running");
}
UpdateSynchronizationStatus(SynchronizationState.ScanningFiles);
}
try
{
var differences = IndexDifferenceCalculator.FindDifferences(
FileSystem, PackageRepository.LucenePackages, cancellationToken, UpdateSynchronizationStatus, mode);
await SynchronizeIndexWithFileSystemAsync(differences, cancellationToken);
}
finally
{
UpdateSynchronizationStatus(SynchronizationState.Idle);
}
}
public Task AddPackageAsync(LucenePackage package, CancellationToken cancellationToken)
{
var update = new Update(package, UpdateType.Add);
pendingUpdates.Add(update, cancellationToken);
return update.Task;
}
public Task RemovePackageAsync(IPackage package, CancellationToken cancellationToken)
{
if (!(package is LucenePackage)) throw new ArgumentException("Package of type " + package.GetType() + " not supported.");
var update = new Update((LucenePackage)package, UpdateType.Remove);
pendingUpdates.Add(update, cancellationToken);
return update.Task;
}
public Task IncrementDownloadCountAsync(IPackage package, CancellationToken cancellationToken)
{
if (!(package is LucenePackage)) throw new ArgumentException("Package of type " + package.GetType() + " not supported.");
if (string.IsNullOrWhiteSpace(package.Id))
{
throw new InvalidOperationException("Package Id must be specified.");
}
if (package.Version == null)
{
throw new InvalidOperationException("Package Version must be specified.");
}
var update = new Update((LucenePackage) package, UpdateType.Increment);
pendingUpdates.Add(update);
return update.Task;
}
internal async Task SynchronizeIndexWithFileSystemAsync(IndexDifferences diff, CancellationToken cancellationToken)
{
if (diff.IsEmpty) return;
var tasks = new ConcurrentQueue<Task>();
Log.Info(string.Format("Updates to process: {0} packages added, {1} packages updated, {2} packages removed.", diff.NewPackages.Count(), diff.ModifiedPackages.Count(), diff.MissingPackages.Count()));
foreach (var path in diff.MissingPackages)
{
cancellationToken.ThrowIfCancellationRequested();
var package = new LucenePackage(FileSystem) { Path = path };
var update = new Update(package, UpdateType.RemoveByPath);
pendingUpdates.Add(update, cancellationToken);
tasks.Enqueue(update.Task);
}
var pathsToIndex = diff.NewPackages.Union(diff.ModifiedPackages).OrderBy(p => p).ToArray();
var packagesToIndex = pathsToIndex.Length;
var i = 0;
Parallel.ForEach(pathsToIndex, new ParallelOptions {MaxDegreeOfParallelism = 4, CancellationToken = cancellationToken}, (p, s) =>
{
UpdateSynchronizationStatus(SynchronizationState.Indexing, Interlocked.Increment(ref i),
packagesToIndex);
tasks.Enqueue(SynchronizePackage(p, cancellationToken));
});
var task = TaskEx.WhenAll(tasks.ToArray());
try
{
await task;
}
finally
{
if (task.IsFaulted && task.Exception.InnerExceptions.Count > 1)
{
throw new AggregateException(task.Exception.InnerExceptions);
}
}
}
private async Task SynchronizePackage(string path, CancellationToken cancellationToken)
{
try
{
var package = PackageRepository.LoadFromFileSystem(path);
await AddPackageAsync(package, cancellationToken);
}
catch (Exception ex)
{
throw new IOException("The package file '" + path + "' could not be loaded.", ex);
}
}
private void IndexUpdateLoop()
{
var items = new List<Update>();
while (!pendingUpdates.IsCompleted)
{
try
{
pendingUpdates.TakeAvailable(items, InfiniteTimeSpan);
}
catch (OperationCanceledException)
{
}
if (items.Any())
{
ApplyUpdates(items);
items.Clear();
}
}
Log.Info("Update task shutting down.");
}
private void ApplyUpdates(List<Update> items)
{
Log.Info(m => m("Processing {0} updates.", items.Count()));
try
{
using (var session = OpenSession())
{
using (UpdateStatus(IndexingState.Updating))
{
var removals =
items.Where(i => i.UpdateType == UpdateType.Remove).ToList();
removals.ForEach(pkg => RemovePackageInternal(pkg, session));
var removalsByPath =
items.Where(i => i.UpdateType == UpdateType.RemoveByPath).ToList();
RemovePackagesByPath(removalsByPath, session);
var additions = items.Where(i => i.UpdateType == UpdateType.Add).ToList();
ApplyPendingAdditions(additions, session);
var downloadUpdates =
items.Where(i => i.UpdateType == UpdateType.Increment).Select(i => i.Package).ToList();
ApplyPendingDownloadIncrements(downloadUpdates, session);
}
using (UpdateStatus(IndexingState.Committing))
{
session.Commit();
items.ForEach(i => i.SetComplete());
}
}
}
catch (Exception ex)
{
Log.Error("Error while indexing packages", ex);
items.ForEach(i => i.SetException(ex));
}
}
private static void RemovePackagesByPath(IEnumerable<Update> removalsByPath, ISession<LucenePackage> session)
{
var deleteQueries = removalsByPath.Select(p => (Query) new TermQuery(new Term("Path", p.Package.Path))).ToArray();
session.Delete(deleteQueries);
}
private void ApplyPendingAdditions(List<Update> additions, ISession<LucenePackage> session)
{
foreach (var grouping in additions.GroupBy(update => update.Package.Id))
{
try
{
AddPackagesInternal(grouping.Key, grouping.Select(p => p.Package).ToList(), session);
}
catch (Exception ex)
{
additions.ForEach(i => i.SetException(ex));
}
}
}
private void AddPackagesInternal(string packageId, IEnumerable<LucenePackage> packages, ISession<LucenePackage> session)
{
var currentPackages = (from p in session.Query()
where p.Id == packageId
orderby p.Version descending
select p).ToList();
var newest = currentPackages.FirstOrDefault();
var totalDownloadCount = newest != null ? newest.DownloadCount : 0;
foreach (var package in packages)
{
var packageToReplace = currentPackages.Find(p => p.Version == package.Version);
package.DownloadCount = totalDownloadCount;
package.VersionDownloadCount = packageToReplace != null ? packageToReplace.VersionDownloadCount : 0;
if (packageToReplace == null)
{
session.Add(KeyConstraint.None, package);
}
else
{
currentPackages.Remove(packageToReplace);
package.OriginUrl = packageToReplace.OriginUrl;
session.Add(KeyConstraint.Unique, package);
}
currentPackages.Add(package);
}
UpdatePackageVersionFlags(currentPackages.OrderByDescending(p => p.Version));
}
private void RemovePackageInternal(Update update, ISession<LucenePackage> session)
{
try
{
session.Delete(update.Package);
var remainingPackages = from p in session.Query()
where p.Id == update.Package.Id
orderby p.Version descending
select p;
UpdatePackageVersionFlags(remainingPackages);
}
catch (Exception e)
{
update.SetException(e);
}
}
private void UpdatePackageVersionFlags(IEnumerable<LucenePackage> packages)
{
var first = true;
var firstNonPreRelease = true;
foreach (var p in packages)
{
if (!p.IsPrerelease && firstNonPreRelease)
{
p.IsLatestVersion = true;
firstNonPreRelease = false;
}
else
{
p.IsLatestVersion = false;
}
p.IsAbsoluteLatestVersion = first;
if (first)
{
first = false;
}
}
}
public void ApplyPendingDownloadIncrements(IList<LucenePackage> increments, ISession<LucenePackage> session)
{
if (increments.Count == 0) return;
var byId = increments.ToLookup(p => p.Id);
foreach (var grouping in byId)
{
var packageId = grouping.Key;
var packages = from p in session.Query() where p.Id == packageId select p;
var byVersion = grouping.ToLookup(p => p.Version);
foreach (var lucenePackage in packages)
{
lucenePackage.DownloadCount += grouping.Count();
lucenePackage.VersionDownloadCount += byVersion[lucenePackage.Version].Count();
}
}
}
protected internal virtual ISession<LucenePackage> OpenSession()
{
return Provider.OpenSession(() => new LucenePackage(FileSystem));
}
private void UpdateSynchronizationStatus(SynchronizationState state)
{
UpdateSynchronizationStatus(state, 0, 0);
}
private void UpdateSynchronizationStatus(SynchronizationState state, int completedPackages, int packagesToIndex)
{
synchronizationStatus = new SynchronizationStatus(
state,
completedPackages,
packagesToIndex
);
RaiseStatusChanged();
}
private IDisposable UpdateStatus(IndexingState state)
{
var prev = indexingState;
indexingState = state;
RaiseStatusChanged();
return new DisposableAction(() =>
{
indexingState = prev;
RaiseStatusChanged();
});
}
private void RaiseStatusChanged()
{
var tmp = statusChanged;
if (tmp != null)
{
eventScheduler.Schedule(() => tmp(this, new EventArgs()));
}
}
}
}
| |
using Signum.Engine.Linq;
using Signum.Entities;
using Signum.Entities.DynamicQuery;
using Signum.Entities.Reflection;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
using Signum.Utilities.Reflection;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Signum.Engine.DynamicQuery
{
public class ExpressionContainer
{
public Polymorphic<Dictionary<string, ExtensionInfo>> RegisteredExtensions =
new Polymorphic<Dictionary<string, ExtensionInfo>>(PolymorphicMerger.InheritDictionaryInterfaces, null);
public Dictionary<PropertyRoute, IExtensionDictionaryInfo> RegisteredExtensionsDictionaries =
new Dictionary<PropertyRoute, IExtensionDictionaryInfo>();
internal Expression BuildExtension(Type parentType, string key, Expression parentExpression)
{
LambdaExpression lambda = RegisteredExtensions.GetValue(parentType)[key].Lambda;
return ExpressionReplacer.Replace(Expression.Invoke(lambda, parentExpression));
}
public IEnumerable<QueryToken> GetExtensions(QueryToken parent)
{
var parentType = parent.Type.CleanType().UnNullify();
var dic = RegisteredExtensions.TryGetValue(parentType);
IEnumerable<QueryToken> extensionsTokens = dic == null ? Enumerable.Empty<QueryToken>() :
dic.Values.Where(ei => ei.Inherit || ei.SourceType == parentType).Select(v => v.CreateToken(parent));
var pr = parentType.IsEntity() && !parentType.IsAbstract ? PropertyRoute.Root(parentType) :
parentType.IsEmbeddedEntity() ? parent.GetPropertyRoute() : null;
var edi = pr == null ? null : RegisteredExtensionsDictionaries.TryGetC(pr);
IEnumerable<QueryToken> dicExtensionsTokens = edi == null ? Enumerable.Empty<QueryToken>() :
edi.GetAllTokens(parent);
return extensionsTokens.Concat(dicExtensionsTokens);
}
public ExtensionInfo Register<E, S>(Expression<Func<E, S>> lambdaToMethodOrProperty, Func<string>? niceName = null)
{
using (HeavyProfiler.LogNoStackTrace("RegisterExpression"))
{
if (lambdaToMethodOrProperty.Body.NodeType == ExpressionType.Call)
{
var mi = ReflectionTools.GetMethodInfo(lambdaToMethodOrProperty);
AssertExtensionMethod(mi);
return Register<E, S>(lambdaToMethodOrProperty, niceName ?? (() => mi.Name.NiceName()), mi.Name);
}
else if (lambdaToMethodOrProperty.Body.NodeType == ExpressionType.MemberAccess)
{
var pi = ReflectionTools.GetPropertyInfo(lambdaToMethodOrProperty);
return Register<E, S>(lambdaToMethodOrProperty, niceName ?? (() => pi.NiceName()), pi.Name);
}
else throw new InvalidOperationException("argument 'lambdaToMethodOrProperty' should be a simple lambda calling a method or property: {0}".FormatWith(lambdaToMethodOrProperty.ToString()));
}
}
private static void AssertExtensionMethod(MethodInfo mi)
{
var assembly = mi.DeclaringType!.Assembly;
if (assembly == typeof(Enumerable).Assembly ||
assembly == typeof(Csv).Assembly ||
assembly == typeof(Lite).Assembly)
throw new InvalidOperationException("The parameter 'lambdaToMethod' should be an expression calling a expression method");
}
public ExtensionInfo Register<E, S>(Expression<Func<E, S>> extensionLambda, Func<string> niceName, string key, bool replace = false)
{
var extension = new ExtensionInfo(typeof(E), extensionLambda, typeof(S), key, niceName);
return Register(extension);
}
public ExtensionInfo Register(ExtensionInfo extension, bool replace = false)
{
var dic = RegisteredExtensions.GetOrAddDefinition(extension.SourceType);
if (replace)
dic[extension.Key] = extension;
else
dic.Add(extension.Key, extension);
RegisteredExtensions.ClearCache();
return extension;
}
public ExtensionDictionaryInfo<T, KVP, K, V> RegisterDictionary<T, KVP, K, V>(
Expression<Func<T, IEnumerable<KVP>>> collectionSelector,
Expression<Func<KVP, K>> keySelector,
Expression<Func<KVP, V>> valueSelector,
ResetLazy<HashSet<K>>? allKeys = null)
where T : Entity
where K : notnull
{
var mei = new ExtensionDictionaryInfo<T, KVP, K, V>(collectionSelector, keySelector, valueSelector,
allKeys ?? GetAllKeysLazy<T, KVP, K>(collectionSelector, keySelector));
RegisteredExtensionsDictionaries.Add(PropertyRoute.Root(typeof(T)), mei);
return mei;
}
public ExtensionDictionaryInfo<M, KVP, K, V> RegisterDictionaryInEmbedded<T, M, KVP, K, V>(
Expression<Func<T, M>> embeddedSelector,
Expression<Func<M, IEnumerable<KVP>>> collectionSelector,
Expression<Func<KVP, K>> keySelector,
Expression<Func<KVP, V>> valueSelector,
ResetLazy<HashSet<K>>? allKeys = null)
where T : Entity
where M : ModifiableEntity
where K : notnull
{
var mei = new ExtensionDictionaryInfo<M, KVP, K, V>(collectionSelector, keySelector, valueSelector,
allKeys ?? GetAllKeysLazy<T, KVP, K>(CombineSelectors(embeddedSelector, collectionSelector), keySelector));
RegisteredExtensionsDictionaries.Add(PropertyRoute.Construct(embeddedSelector), mei);
return mei;
}
private Expression<Func<T, IEnumerable<KVP>>> CombineSelectors<T, M, KVP>(Expression<Func<T, M>> embeddedSelector, Expression<Func<M, IEnumerable<KVP>>> collectionSelector)
where T : Entity
where M : ModifiableEntity
{
Expression<Func<T, IEnumerable<KVP>>> result = e => collectionSelector.Evaluate(embeddedSelector.Evaluate(e));
return (Expression<Func<T, IEnumerable<KVP>>>)ExpressionCleaner.Clean(result)!;
}
private ResetLazy<HashSet<K>> GetAllKeysLazy<T, KVP, K>(Expression<Func<T, IEnumerable<KVP>>> collectionSelector, Expression<Func<KVP, K>> keySelector)
where T : Entity
{
if (typeof(K).IsEnum)
return new ResetLazy<HashSet<K>>(() => EnumExtensions.GetValues<K>().ToHashSet());
if (typeof(K).IsLite())
return GlobalLazy.WithoutInvalidations(() => Database.RetrieveAllLite(typeof(K).CleanType()).Cast<K>().ToHashSet());
if (collectionSelector.Body.Type.IsMList())
{
var lambda = Expression.Lambda<Func<T, MList<KVP>>>(collectionSelector.Body, collectionSelector.Parameters);
return GlobalLazy.WithoutInvalidations(() => Database.MListQuery(lambda).Select(kvp => keySelector.Evaluate(kvp.Element)).Distinct().ToHashSet());
}
else
{
return GlobalLazy.WithoutInvalidations(() => Database.Query<T>().SelectMany(collectionSelector).Select(keySelector).Distinct().ToHashSet());
}
}
}
public interface IExtensionDictionaryInfo
{
IEnumerable<QueryToken> GetAllTokens(QueryToken parent);
}
public class ExtensionDictionaryInfo<T, KVP, K, V> : IExtensionDictionaryInfo
where K : notnull
{
public ResetLazy<HashSet<K>> AllKeys;
public Expression<Func<T, IEnumerable<KVP>>> CollectionSelector { get; set; }
public Expression<Func<KVP, K>> KeySelector { get; set; }
public Expression<Func<KVP, V>> ValueSelector { get; set; }
readonly ConcurrentDictionary<QueryToken, ExtensionRouteInfo> metas = new ConcurrentDictionary<QueryToken, ExtensionRouteInfo>();
public ExtensionDictionaryInfo(
Expression<Func<T, IEnumerable<KVP>>> collectionSelector,
Expression<Func<KVP, K>> keySelector,
Expression<Func<KVP, V>> valueSelector,
ResetLazy<HashSet<K>> allKeys)
{
CollectionSelector = collectionSelector;
KeySelector = keySelector;
ValueSelector = valueSelector;
AllKeys = allKeys;
}
public IEnumerable<QueryToken> GetAllTokens(QueryToken parent)
{
var info = metas.GetOrAdd(parent, qt =>
{
Expression<Func<T, V>> lambda = t => ValueSelector.Evaluate(CollectionSelector.Evaluate(t).SingleOrDefaultEx());
Expression e = MetadataVisitor.JustVisit(lambda, MetaExpression.FromToken(qt, typeof(T)));
var result = new ExtensionRouteInfo();
if (e is MetaExpression me && me.Meta is CleanMeta cm && cm.PropertyRoutes.Any())
{
var cleanType = me!.Type.CleanType();
result.PropertyRoute = cm.PropertyRoutes.Only();
result.Implementations = me.Meta.Implementations;
result.Format = ColumnDescriptionFactory.GetFormat(cm.PropertyRoutes);
result.Unit = ColumnDescriptionFactory.GetUnit(cm.PropertyRoutes);
}
return result;
});
return AllKeys.Value.Select(key => new ExtensionDictionaryToken<T, K, V>(parent,
key: key,
unit: info.Unit,
format: info.Format,
implementations: info.Implementations,
propertyRoute: info.PropertyRoute,
lambda: t => ValueSelector.Evaluate(CollectionSelector.Evaluate(t).SingleOrDefaultEx(kvp => KeySelector.Evaluate(kvp).Equals(key)))
));
}
}
public class ExtensionInfo
{
ConcurrentDictionary<QueryToken, ExtensionRouteInfo> metas = new ConcurrentDictionary<QueryToken, ExtensionRouteInfo>();
public ExtensionInfo(Type sourceType, LambdaExpression lambda, Type type, string key, Func<string> niceName)
{
this.Type = type;
this.SourceType = sourceType;
this.Key = key;
this.Lambda = lambda;
this.IsProjection = type != typeof(string) && type.ElementType() != null;
this.NiceName = niceName;
}
public readonly Type Type;
public readonly Type SourceType;
public readonly string Key;
public bool IsProjection;
public bool Inherit = true;
public Implementations? ForceImplementations;
public PropertyRoute? ForcePropertyRoute;
public string? ForceFormat;
public string? ForceUnit;
public Func<string?>? ForceIsAllowed;
internal readonly LambdaExpression Lambda;
public Func<string> NiceName;
protected internal virtual ExtensionToken CreateToken(QueryToken parent)
{
var info = metas.GetOrAdd(parent, qt =>
{
Expression e = MetadataVisitor.JustVisit(Lambda, MetaExpression.FromToken(qt, SourceType));
MetaExpression? me;
if (this.IsProjection)
{
var mpe = e as MetaProjectorExpression;
if (mpe == null)
mpe = MetadataVisitor.AsProjection(e);
me = mpe == null ? null : mpe.Projector as MetaExpression;
}
else
{
me = e as MetaExpression;
}
var result = new ExtensionRouteInfo();
if (me != null && me.Meta is CleanMeta cleanMeta && cleanMeta.PropertyRoutes.Any())
{
result.PropertyRoute = cleanMeta.PropertyRoutes.Only();
result.Implementations = me.Meta.Implementations;
result.Format = ColumnDescriptionFactory.GetFormat(cleanMeta.PropertyRoutes);
result.Unit = ColumnDescriptionFactory.GetUnit(cleanMeta.PropertyRoutes);
}
else if (me?.Meta is DirtyMeta dirtyMeta)
{
result.PropertyRoute = dirtyMeta.CleanMetas.Select(cm => cm.PropertyRoutes.Only()).Distinct().Only();
var metaImps = dirtyMeta.CleanMetas.Select(cm => cm.Implementations).Distinct().Only();
if (metaImps.HasValue && metaImps.Value.Types.All(t => t.IsAssignableFrom(Type)))
{
result.Implementations = metaImps;
}
result.Format = dirtyMeta.CleanMetas.Select(cm => ColumnDescriptionFactory.GetFormat(cm.PropertyRoutes)).Distinct().Only();
result.Unit = dirtyMeta.CleanMetas.Select(cm => ColumnDescriptionFactory.GetUnit(cm.PropertyRoutes)).Distinct().Only();
}
result.IsAllowed = () => me?.Meta.IsAllowed();
if (ForcePropertyRoute != null)
result.PropertyRoute = ForcePropertyRoute!;
if (ForceImplementations != null)
result.Implementations = ForceImplementations;
if (ForceFormat != null)
result.Format = ForceFormat;
if (ForceUnit != null)
result.Unit = ForceUnit;
if (ForceIsAllowed != null)
result.IsAllowed = ForceIsAllowed!;
return result;
});
return new ExtensionToken(parent, Key, Type, IsProjection, info.Unit, info.Format,
info.Implementations, info.IsAllowed(), info.PropertyRoute, displayName: NiceName());
}
}
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
public class ExtensionRouteInfo
{
public string? Format;
public string? Unit;
public Implementations? Implementations;
public Func<string?> IsAllowed;
public PropertyRoute? PropertyRoute;
}
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using DSL.POS.DTO.DTO;
using DSL.POS.DataAccessLayer.Common.Imp;
using DSL.POS.DataAccessLayer.Interface;
namespace DSL.POS.DataAccessLayer.Imp
{
public class MemberInfoDALImp: CommonDALImp, IMemberInfoDAL
{
// Error Handling developed by Samad
// 07/12/06
private void getPKCode(MemberInfoDTO obj)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString());
string strPKCode = null;
int PKSL = 0;
string sqlSelect = "Select isnull(Max(CustId),0)+1 From MemberInfo";
SqlCommand objCmd = sqlConn.CreateCommand();
objCmd.CommandText = sqlSelect;
try
{
sqlConn.Open();
PKSL = (int)objCmd.ExecuteScalar();
}
catch (Exception Exp)
{
throw Exp;
}
finally
{
objCmd.Dispose();
objCmd.Cancel();
sqlConn.Dispose();
sqlConn.Close();
}
strPKCode = PKSL.ToString("000000");
obj.CustId = strPKCode;
//return strPKCode;
}
public override void Save(object obj)
{
MemberInfoDTO oMemberInfoDTO = (MemberInfoDTO)obj;
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString());
SqlCommand objCmd = sqlConn.CreateCommand();
if (oMemberInfoDTO.PrimaryKey.ToString() == "00000000-0000-0000-0000-000000000000")
{
String sql = "Insert Into MemberInfo(CustId,ManualId,CustName,CustAtten,ContactPerson,CustAddr," +
" CustPhone,CustFax,CustEmail,WebSite,BirthDay,Mobile,CreditLimit,EntryBy,EntryDate)" +
" values(@CustId,@ManualId,@CustName,@CustAtten,@ContactPerson,@CustAddr,@CustPhone," +
" @CustFax,@CustEmail,@WebSite,@BirthDay,@Mobile,@CreditLimit,@EntryBy,@EntryDate)";
try
{
getPKCode(oMemberInfoDTO);
objCmd.CommandText = sql;
objCmd.Parameters.Add(new SqlParameter("@CustId", SqlDbType.VarChar, 6));
objCmd.Parameters.Add(new SqlParameter("@ManualId", SqlDbType.VarChar, 20));
objCmd.Parameters.Add(new SqlParameter("@CustName", SqlDbType.VarChar, 100));
objCmd.Parameters.Add(new SqlParameter("@CustAtten", SqlDbType.VarChar, 5));
objCmd.Parameters.Add(new SqlParameter("@ContactPerson", SqlDbType.VarChar, 50));
objCmd.Parameters.Add(new SqlParameter("@CustAddr", SqlDbType.VarChar, 150));
objCmd.Parameters.Add(new SqlParameter("@CustPhone", SqlDbType.VarChar, 50));
objCmd.Parameters.Add(new SqlParameter("@CustFax", SqlDbType.VarChar, 50));
objCmd.Parameters.Add(new SqlParameter("@CustEmail", SqlDbType.VarChar, 50));
objCmd.Parameters.Add(new SqlParameter("@WebSite", SqlDbType.VarChar, 70));
objCmd.Parameters.Add(new SqlParameter("@BirthDay", SqlDbType.DateTime));
objCmd.Parameters.Add(new SqlParameter("@Mobile", SqlDbType.VarChar, 50));
objCmd.Parameters.Add(new SqlParameter("@CreditLimit", SqlDbType.Decimal, 9));
objCmd.Parameters.Add(new SqlParameter("@EntryBy", SqlDbType.VarChar, 10));
objCmd.Parameters.Add(new SqlParameter("@EntryDate", SqlDbType.DateTime));
objCmd.Parameters["@CustId"].Value = Convert.ToString(oMemberInfoDTO.CustId);
objCmd.Parameters["@ManualId"].Value = Convert.ToString(oMemberInfoDTO.ManualId);
objCmd.Parameters["@CustName"].Value = Convert.ToString(oMemberInfoDTO.CustName);
objCmd.Parameters["@CustAtten"].Value = Convert.ToString(oMemberInfoDTO.CustAtten);
objCmd.Parameters["@ContactPerson"].Value = Convert.ToString(oMemberInfoDTO.ContactPerson);
objCmd.Parameters["@CustAddr"].Value = Convert.ToString(oMemberInfoDTO.CustAddr);
objCmd.Parameters["@CustPhone"].Value = Convert.ToString(oMemberInfoDTO.CustPhone);
objCmd.Parameters["@CustFax"].Value = Convert.ToString(oMemberInfoDTO.CustFax);
objCmd.Parameters["@CustEmail"].Value = Convert.ToString(oMemberInfoDTO.CustEmail);
objCmd.Parameters["@WebSite"].Value = Convert.ToString(oMemberInfoDTO.WebSite);
if (oMemberInfoDTO.BirthDay ==null)
objCmd.Parameters["@BirthDay"].Value = "<NULL>";
else
objCmd.Parameters["@BirthDay"].Value = Convert.ToString(oMemberInfoDTO.BirthDay);
objCmd.Parameters["@Mobile"].Value = Convert.ToString(oMemberInfoDTO.Mobile);
objCmd.Parameters["@CreditLimit"].Value = Convert.ToString(oMemberInfoDTO.CreditLimit);
objCmd.Parameters["@EntryBy"].Value = Convert.ToString(oMemberInfoDTO.EntryBy);
objCmd.Parameters["@EntryDate"].Value = Convert.ToDateTime(oMemberInfoDTO.EntryDate);
sqlConn.Open();
objCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
objCmd.Dispose();
objCmd.Cancel();
sqlConn.Close();
sqlConn.Dispose();
}
}
else
{
String sql = "Update MemberInfo set " +
" CustId=@CustId,ManualId=@ManualId,CustName=@CustName,CustAtten=@CustAtten,ContactPerson=@ContactPerson," +
" CustAddr=@CustAddr,CustPhone=@CustPhone,CustFax=@CustFax,CustEmail=@CustEmail,WebSite=@WebSite," +
" BirthDay=@BirthDay,Mobile=@Mobile,CreditLimit=@CreditLimit,EntryBy=@EntryBy,EntryDate=@EntryDate" +
" where Cust_PK=@Cust_PK";
try
{
objCmd.CommandText = sql;
objCmd.Parameters.Add(new SqlParameter("@Cust_PK", SqlDbType.UniqueIdentifier, 16));
objCmd.Parameters.Add(new SqlParameter("@CustId", SqlDbType.VarChar, 6));
objCmd.Parameters.Add(new SqlParameter("@ManualId", SqlDbType.VarChar, 20));
objCmd.Parameters.Add(new SqlParameter("@CustName", SqlDbType.VarChar, 100));
objCmd.Parameters.Add(new SqlParameter("@CustAtten", SqlDbType.VarChar, 5));
objCmd.Parameters.Add(new SqlParameter("@ContactPerson", SqlDbType.VarChar, 50));
objCmd.Parameters.Add(new SqlParameter("@CustAddr", SqlDbType.VarChar, 150));
objCmd.Parameters.Add(new SqlParameter("@CustPhone", SqlDbType.VarChar, 50));
objCmd.Parameters.Add(new SqlParameter("@CustFax", SqlDbType.VarChar, 50));
objCmd.Parameters.Add(new SqlParameter("@CustEmail", SqlDbType.VarChar, 50));
objCmd.Parameters.Add(new SqlParameter("@WebSite", SqlDbType.VarChar, 70));
objCmd.Parameters.Add(new SqlParameter("@BirthDay", SqlDbType.DateTime));
objCmd.Parameters.Add(new SqlParameter("@Mobile", SqlDbType.VarChar, 50));
objCmd.Parameters.Add(new SqlParameter("@CreditLimit", SqlDbType.Decimal, 9));
objCmd.Parameters.Add(new SqlParameter("@EntryBy", SqlDbType.VarChar, 10));
objCmd.Parameters.Add(new SqlParameter("@EntryDate", SqlDbType.DateTime));
objCmd.Parameters["@Cust_PK"].Value = (Guid)oMemberInfoDTO.PrimaryKey;
objCmd.Parameters["@CustId"].Value = Convert.ToString(oMemberInfoDTO.CustId);
objCmd.Parameters["@ManualId"].Value = Convert.ToString(oMemberInfoDTO.ManualId);
objCmd.Parameters["@CustName"].Value = Convert.ToString(oMemberInfoDTO.CustName);
objCmd.Parameters["@CustAtten"].Value = Convert.ToString(oMemberInfoDTO.CustAtten);
objCmd.Parameters["@ContactPerson"].Value = Convert.ToString(oMemberInfoDTO.ContactPerson);
objCmd.Parameters["@CustAddr"].Value = Convert.ToString(oMemberInfoDTO.CustAddr);
objCmd.Parameters["@CustPhone"].Value = Convert.ToString(oMemberInfoDTO.CustPhone);
objCmd.Parameters["@CustFax"].Value = Convert.ToString(oMemberInfoDTO.CustFax);
objCmd.Parameters["@CustEmail"].Value = Convert.ToString(oMemberInfoDTO.CustEmail);
objCmd.Parameters["@WebSite"].Value = Convert.ToString(oMemberInfoDTO.WebSite);
objCmd.Parameters["@BirthDay"].Value = Convert.ToString(oMemberInfoDTO.BirthDay);
objCmd.Parameters["@Mobile"].Value = Convert.ToString(oMemberInfoDTO.Mobile);
objCmd.Parameters["@CreditLimit"].Value = Convert.ToString(oMemberInfoDTO.CreditLimit);
objCmd.Parameters["@EntryBy"].Value = Convert.ToString(oMemberInfoDTO.EntryBy);
objCmd.Parameters["@EntryDate"].Value = Convert.ToDateTime(oMemberInfoDTO.EntryDate);
objCmd.Parameters["@EntryDate"].Value = Convert.ToDateTime(oMemberInfoDTO.EntryDate);
sqlConn.Open();
objCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
objCmd.Dispose();
objCmd.Cancel();
sqlConn.Dispose();
sqlConn.Close();
}
}
}
/// <summary>
/// Delete row
/// </summary>
/// <param name="obj"></param>
public override void Delete(object obj)
{
MemberInfoDTO oMemberInfoDTO = (MemberInfoDTO)obj;
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString());
String sql = "Delete MemberInfo where Cust_PK=@Cust_PK";
SqlCommand objCmdDelete = sqlConn.CreateCommand();
objCmdDelete.CommandText = sql;
try
{
objCmdDelete.Parameters.Add("@Cust_PK", SqlDbType.UniqueIdentifier, 16);
objCmdDelete.Parameters["@Cust_PK"].Value = (Guid)oMemberInfoDTO.PrimaryKey;
sqlConn.Open();
objCmdDelete.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
objCmdDelete.Dispose();
objCmdDelete.Cancel();
sqlConn.Dispose();
sqlConn.Close();
}
}
/// <summary>
/// This Method used for get Primary Key corresponding Member Code
/// </summary>
/// <param name="strCode"></param>
/// <returns> Primary Key</returns>
///
public Guid GetPKBYCode(string strCode)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString());
Guid guidCust_ID=new Guid();
string sqlSelect = "Select Cust_PK From MemberInfo where CustId=@CustId";
SqlCommand objCmd = sqlConn.CreateCommand();
objCmd.CommandText = sqlSelect;
objCmd.Parameters.Add("@CustId", SqlDbType.VarChar, 6);
objCmd.Parameters["@CustId"].Value = strCode ;
try
{
sqlConn.Open();
SqlDataReader sqlDReader = objCmd.ExecuteReader();
//while (sqlDReader.Read())
//{
// guidCust_ID = (Guid)sqlDReader["Cust_PK"];
// //return guidCust_ID;
//}
if (sqlDReader.Read())
guidCust_ID = (Guid)sqlDReader["Cust_PK"];
//else
// guidCust_ID = (Guid)("00000000-0000-0000-0000-000000000000");
}
catch (Exception Exp)
{
throw Exp;
}
finally
{
objCmd.Dispose();
sqlConn.Dispose();
sqlConn.Close();
}
return guidCust_ID;
}
/// <summary>
/// This method used for get all data corresponding primary key.
/// </summary>
/// <param name="pk"></param>
/// <returns></returns>
///
public MemberInfoDTO findByPKDTO(Guid pk)
{
MemberInfoDTO oMemberInfoDTO = new MemberInfoDTO();
string sqlSelect = "Select Cust_PK,CustId,ManualId,CustName,CustAtten,ContactPerson,CustAddr," +
" CustPhone,CustFax,CustEmail,WebSite,BirthDay,Mobile,CreditLimit,EntryBy,EntryDate From MemberInfo where Cust_PK=@Cust_PK";
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString());
SqlCommand objCmd = sqlConn.CreateCommand();
objCmd.CommandText = sqlSelect;
objCmd.Connection = sqlConn;
try
{
objCmd.Parameters.Add("@Cust_PK", SqlDbType.UniqueIdentifier, 16);
objCmd.Parameters["@Cust_PK"].Value = pk;
sqlConn.Open();
SqlDataReader thisReader = objCmd.ExecuteReader();
while (thisReader.Read())
{
oMemberInfoDTO = populate(thisReader);
}
thisReader.Close();
thisReader.Dispose();
}
catch (Exception ex)
{
throw ex;
}
finally
{
objCmd.Dispose();
objCmd.Cancel();
sqlConn.Dispose();
sqlConn.Close();
}
return oMemberInfoDTO;
}
public List<MemberInfoDTO> getMemberInfoData()
{
string sqlSelect = "Select Cust_PK,CustId,ManualId,CustName,CustAtten,ContactPerson,CustAddr," +
" CustPhone,CustFax,CustEmail,WebSite,BirthDay,Mobile,CreditLimit,EntryBy,EntryDate From MemberInfo order by CustId Asc";
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString());
List<MemberInfoDTO> oArrayList = new List<MemberInfoDTO>();
SqlCommand objCmd = sqlConn.CreateCommand();
objCmd.CommandText = sqlSelect;
objCmd.Connection = sqlConn;
try
{
sqlConn.Open();
SqlDataReader thisReader = objCmd.ExecuteReader();
while (thisReader.Read())
{
MemberInfoDTO oMemberInfoDTO = populate(thisReader);
oArrayList.Add(oMemberInfoDTO);
}
thisReader.Close();
thisReader.Dispose();
}
catch (Exception ex)
{
throw ex;
}
finally
{
objCmd.Dispose();
objCmd.Cancel();
sqlConn.Dispose();
sqlConn.Close();
}
return oArrayList;
}
public MemberInfoDTO populate(SqlDataReader reader)
{
try
{
MemberInfoDTO dto = new MemberInfoDTO ();
dto.PrimaryKey = (Guid)reader["Cust_PK"];
dto.CustId = (string)reader["CustId"];
dto.ManualId = (string)reader["ManualId"];
dto.CustName = (string)reader["CustName"];
dto.CustAtten = (string)reader["CustAtten"];
dto.ContactPerson = (string)reader["ContactPerson"];
dto.CustAddr = (string)reader["CustAddr"];
dto.CustPhone = (string)reader["CustPhone"];
dto.CustFax = (string)reader["CustFax"];
dto.CustEmail = (string)reader["CustEmail"];
dto.WebSite = (string)reader["WebSite"];
dto.BirthDay = (DateTime)reader["BirthDay"];
dto.Mobile = (string)reader["Mobile"];
dto.CreditLimit = (Decimal)reader["CreditLimit"];
dto.EntryBy = (string)reader["EntryBy"];
dto.EntryDate = (DateTime)reader["EntryDate"];
return dto;
}
catch (Exception ex)
{
throw ex;
}
}
public MemberInfoDALImp()
{
// Todo
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Metadata;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Compute;
using Apache.Ignite.Core.Impl.Compute.Closure;
using Apache.Ignite.Core.Impl.Datastream;
using Apache.Ignite.Core.Impl.Deployment;
using Apache.Ignite.Core.Impl.Messaging;
using Apache.Ignite.Core.Log;
/// <summary>
/// Marshaller implementation.
/// </summary>
internal class Marshaller
{
/** Binary configuration. */
private readonly BinaryConfiguration _cfg;
/** Type to descriptor map. */
private readonly CopyOnWriteConcurrentDictionary<Type, BinaryFullTypeDescriptor> _typeToDesc =
new CopyOnWriteConcurrentDictionary<Type, BinaryFullTypeDescriptor>();
/** Type name to descriptor map. */
private readonly CopyOnWriteConcurrentDictionary<string, BinaryFullTypeDescriptor> _typeNameToDesc =
new CopyOnWriteConcurrentDictionary<string, BinaryFullTypeDescriptor>();
/** ID to descriptor map. */
private readonly CopyOnWriteConcurrentDictionary<long, BinaryFullTypeDescriptor> _idToDesc =
new CopyOnWriteConcurrentDictionary<long, BinaryFullTypeDescriptor>();
/** Cached binary types. */
private volatile IDictionary<int, BinaryTypeHolder> _metas = new Dictionary<int, BinaryTypeHolder>();
/** */
private volatile IIgniteInternal _ignite;
/** */
private readonly ILogger _log;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="log"></param>
public Marshaller(BinaryConfiguration cfg, ILogger log = null)
{
_cfg = cfg ?? new BinaryConfiguration();
_log = log;
CompactFooter = _cfg.CompactFooter;
if (_cfg.TypeConfigurations == null)
_cfg.TypeConfigurations = new List<BinaryTypeConfiguration>();
foreach (BinaryTypeConfiguration typeCfg in _cfg.TypeConfigurations)
{
if (string.IsNullOrEmpty(typeCfg.TypeName))
throw new BinaryObjectException("Type name cannot be null or empty: " + typeCfg);
}
// Define system types. They use internal reflective stuff, so configuration doesn't affect them.
AddSystemTypes();
// 2. Define user types.
var typeResolver = new TypeResolver();
ICollection<BinaryTypeConfiguration> typeCfgs = _cfg.TypeConfigurations;
if (typeCfgs != null)
foreach (BinaryTypeConfiguration typeCfg in typeCfgs)
AddUserType(typeCfg, typeResolver);
var typeNames = _cfg.Types;
if (typeNames != null)
foreach (string typeName in typeNames)
AddUserType(new BinaryTypeConfiguration(typeName), typeResolver);
}
/// <summary>
/// Gets or sets the backing grid.
/// </summary>
public IIgniteInternal Ignite
{
get { return _ignite; }
set
{
Debug.Assert(value != null);
_ignite = value;
}
}
/// <summary>
/// Gets the compact footer flag.
/// </summary>
public bool CompactFooter { get; set; }
/// <summary>
/// Gets or sets a value indicating whether type registration is disabled.
/// This may be desirable for static system marshallers where everything is written in unregistered mode.
/// </summary>
public bool RegistrationDisabled { get; set; }
/// <summary>
/// Marshal object.
/// </summary>
/// <param name="val">Value.</param>
/// <returns>Serialized data as byte array.</returns>
public byte[] Marshal<T>(T val)
{
using (var stream = new BinaryHeapStream(128))
{
Marshal(val, stream);
return stream.GetArrayCopy();
}
}
/// <summary>
/// Marshals an object.
/// </summary>
/// <param name="val">Value.</param>
/// <param name="stream">Output stream.</param>
private void Marshal<T>(T val, IBinaryStream stream)
{
BinaryWriter writer = StartMarshal(stream);
writer.Write(val);
FinishMarshal(writer);
}
/// <summary>
/// Start marshal session.
/// </summary>
/// <param name="stream">Stream.</param>
/// <returns>Writer.</returns>
public BinaryWriter StartMarshal(IBinaryStream stream)
{
return new BinaryWriter(this, stream);
}
/// <summary>
/// Finish marshal session.
/// </summary>
/// <param name="writer">Writer.</param>
/// <returns>Dictionary with metadata.</returns>
public void FinishMarshal(BinaryWriter writer)
{
var metas = writer.GetBinaryTypes();
var ignite = Ignite;
if (ignite != null && metas != null && metas.Count > 0)
{
ignite.BinaryProcessor.PutBinaryTypes(metas);
OnBinaryTypesSent(metas);
}
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="data">Data array.</param>
/// <param name="mode">The mode.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(byte[] data, BinaryMode mode = BinaryMode.Deserialize)
{
using (var stream = new BinaryHeapStream(data))
{
return Unmarshal<T>(stream, mode);
}
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="stream">Stream over underlying byte array with correct position.</param>
/// <param name="keepBinary">Whether to keep binary objects in binary form.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(IBinaryStream stream, bool keepBinary)
{
return Unmarshal<T>(stream, keepBinary ? BinaryMode.KeepBinary : BinaryMode.Deserialize, null);
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="stream">Stream over underlying byte array with correct position.</param>
/// <param name="mode">The mode.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(IBinaryStream stream, BinaryMode mode = BinaryMode.Deserialize)
{
return Unmarshal<T>(stream, mode, null);
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="stream">Stream over underlying byte array with correct position.</param>
/// <param name="mode">The mode.</param>
/// <param name="builder">Builder.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(IBinaryStream stream, BinaryMode mode, BinaryObjectBuilder builder)
{
return new BinaryReader(this, stream, mode, builder).Deserialize<T>();
}
/// <summary>
/// Start unmarshal session.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="keepBinary">Whether to keep binarizable as binary.</param>
/// <returns>
/// Reader.
/// </returns>
public BinaryReader StartUnmarshal(IBinaryStream stream, bool keepBinary)
{
return new BinaryReader(this, stream, keepBinary ? BinaryMode.KeepBinary : BinaryMode.Deserialize, null);
}
/// <summary>
/// Start unmarshal session.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="mode">The mode.</param>
/// <returns>Reader.</returns>
public BinaryReader StartUnmarshal(IBinaryStream stream, BinaryMode mode = BinaryMode.Deserialize)
{
return new BinaryReader(this, stream, mode, null);
}
/// <summary>
/// Gets metadata for the given type ID.
/// </summary>
/// <param name="typeId">Type ID.</param>
/// <returns>Metadata or null.</returns>
public BinaryType GetBinaryType(int typeId)
{
if (Ignite != null)
{
var meta = Ignite.BinaryProcessor.GetBinaryType(typeId);
if (meta != null)
{
return meta;
}
}
return BinaryType.Empty;
}
/// <summary>
/// Puts the binary type metadata to Ignite.
/// </summary>
/// <param name="desc">Descriptor.</param>
public void PutBinaryType(IBinaryTypeDescriptor desc)
{
Debug.Assert(desc != null);
GetBinaryTypeHandler(desc); // ensure that handler exists
if (Ignite != null)
{
var metas = new[] {new BinaryType(desc, this)};
Ignite.BinaryProcessor.PutBinaryTypes(metas);
OnBinaryTypesSent(metas);
}
}
/// <summary>
/// Gets binary type handler for the given type ID.
/// </summary>
/// <param name="desc">Type descriptor.</param>
/// <returns>Binary type handler.</returns>
public IBinaryTypeHandler GetBinaryTypeHandler(IBinaryTypeDescriptor desc)
{
BinaryTypeHolder holder;
if (!_metas.TryGetValue(desc.TypeId, out holder))
{
lock (this)
{
if (!_metas.TryGetValue(desc.TypeId, out holder))
{
IDictionary<int, BinaryTypeHolder> metas0 =
new Dictionary<int, BinaryTypeHolder>(_metas);
holder = new BinaryTypeHolder(desc.TypeId, desc.TypeName, desc.AffinityKeyFieldName,
desc.IsEnum, this);
metas0[desc.TypeId] = holder;
_metas = metas0;
}
}
}
if (holder != null)
{
ICollection<int> ids = holder.GetFieldIds();
bool newType = ids.Count == 0 && !holder.Saved();
return new BinaryTypeHashsetHandler(ids, newType);
}
return null;
}
/// <summary>
/// Callback invoked when metadata has been sent to the server and acknowledged by it.
/// </summary>
/// <param name="newMetas">Binary types.</param>
private void OnBinaryTypesSent(IEnumerable<BinaryType> newMetas)
{
foreach (var meta in newMetas)
{
_metas[meta.TypeId].Merge(meta);
}
}
/// <summary>
/// Gets descriptor for type.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>
/// Descriptor.
/// </returns>
public IBinaryTypeDescriptor GetDescriptor(Type type)
{
BinaryFullTypeDescriptor desc;
if (!_typeToDesc.TryGetValue(type, out desc) || !desc.IsRegistered)
{
desc = RegisterType(type, desc);
}
return desc;
}
/// <summary>
/// Gets descriptor for type name.
/// </summary>
/// <param name="typeName">Type name.</param>
/// <returns>Descriptor.</returns>
public IBinaryTypeDescriptor GetDescriptor(string typeName)
{
BinaryFullTypeDescriptor desc;
if (_typeNameToDesc.TryGetValue(typeName, out desc))
{
return desc;
}
var typeId = GetTypeId(typeName, _cfg.IdMapper);
return GetDescriptor(true, typeId, typeName: typeName);
}
/// <summary>
/// Gets descriptor for a type id.
/// </summary>
/// <param name="userType">User type flag.</param>
/// <param name="typeId">Type id.</param>
/// <param name="requiresType">If set to true, resulting descriptor must have Type property populated.
/// <para />
/// When working in binary mode, we don't need Type. And there is no Type at all in some cases.
/// So we should not attempt to call BinaryProcessor right away.
/// Only when we really deserialize the value, requiresType is set to true
/// and we attempt to resolve the type by all means.</param>
/// <param name="typeName">Known type name.</param>
/// <param name="knownType">Optional known type.</param>
/// <returns>
/// Descriptor.
/// </returns>
public IBinaryTypeDescriptor GetDescriptor(bool userType, int typeId, bool requiresType = false,
string typeName = null, Type knownType = null)
{
BinaryFullTypeDescriptor desc;
var typeKey = BinaryUtils.TypeKey(userType, typeId);
if (_idToDesc.TryGetValue(typeKey, out desc) && (!requiresType || desc.Type != null))
return desc;
if (!userType)
return null;
if (requiresType && _ignite != null)
{
// Check marshaller context for dynamically registered type.
var type = knownType;
if (type == null && _ignite != null)
{
typeName = typeName ?? _ignite.BinaryProcessor.GetTypeName(typeId);
if (typeName != null)
{
type = ResolveType(typeName);
if (type == null)
{
// Type is registered, but assembly is not present.
return new BinarySurrogateTypeDescriptor(_cfg, typeId, typeName);
}
}
}
if (type != null)
{
return AddUserType(type, typeId, GetTypeName(type), true, desc);
}
}
var meta = GetBinaryType(typeId);
if (meta != BinaryType.Empty)
{
var typeCfg = new BinaryTypeConfiguration(meta.TypeName)
{
IsEnum = meta.IsEnum,
AffinityKeyFieldName = meta.AffinityKeyFieldName
};
return AddUserType(typeCfg, new TypeResolver());
}
return new BinarySurrogateTypeDescriptor(_cfg, typeId, typeName);
}
/// <summary>
/// Registers the type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="desc">Existing descriptor.</param>
private BinaryFullTypeDescriptor RegisterType(Type type, BinaryFullTypeDescriptor desc)
{
Debug.Assert(type != null);
var typeName = GetTypeName(type);
var typeId = GetTypeId(typeName, _cfg.IdMapper);
var registered = _ignite != null && _ignite.BinaryProcessor.RegisterType(typeId, typeName);
return AddUserType(type, typeId, typeName, registered, desc);
}
/// <summary>
/// Add user type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="typeId">The type id.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="registered">Registered flag.</param>
/// <param name="desc">Existing descriptor.</param>
/// <returns>Descriptor.</returns>
private BinaryFullTypeDescriptor AddUserType(Type type, int typeId, string typeName, bool registered,
BinaryFullTypeDescriptor desc)
{
Debug.Assert(type != null);
Debug.Assert(typeName != null);
var ser = GetSerializer(_cfg, null, type, typeId, null, null, _log);
desc = desc == null
? new BinaryFullTypeDescriptor(type, typeId, typeName, true, _cfg.NameMapper,
_cfg.IdMapper, ser, false, AffinityKeyMappedAttribute.GetFieldNameFromAttribute(type),
BinaryUtils.IsIgniteEnum(type), registered)
: new BinaryFullTypeDescriptor(desc, type, ser, registered);
if (RegistrationDisabled)
{
return desc;
}
var typeKey = BinaryUtils.TypeKey(true, typeId);
var desc0 = _idToDesc.GetOrAdd(typeKey, x => desc);
if (desc0.Type != null && desc0.TypeName != typeName)
{
ThrowConflictingTypeError(type, desc0.Type, typeId);
}
desc0 = _typeNameToDesc.GetOrAdd(typeName, x => desc);
if (desc0.Type != null && desc0.TypeName != typeName)
{
ThrowConflictingTypeError(type, desc0.Type, typeId);
}
_typeToDesc.Set(type, desc);
return desc;
}
/// <summary>
/// Throws the conflicting type error.
/// </summary>
private static void ThrowConflictingTypeError(object type1, object type2, int typeId)
{
throw new BinaryObjectException(string.Format("Conflicting type IDs [type1='{0}', " +
"type2='{1}', typeId={2}]", type1, type2, typeId));
}
/// <summary>
/// Add user type.
/// </summary>
/// <param name="typeCfg">Type configuration.</param>
/// <param name="typeResolver">The type resolver.</param>
/// <exception cref="BinaryObjectException"></exception>
private BinaryFullTypeDescriptor AddUserType(BinaryTypeConfiguration typeCfg, TypeResolver typeResolver)
{
// Get converter/mapper/serializer.
IBinaryNameMapper nameMapper = typeCfg.NameMapper ?? _cfg.NameMapper ?? GetDefaultNameMapper();
IBinaryIdMapper idMapper = typeCfg.IdMapper ?? _cfg.IdMapper;
bool keepDeserialized = typeCfg.KeepDeserialized ?? _cfg.KeepDeserialized;
// Try resolving type.
Type type = typeResolver.ResolveType(typeCfg.TypeName);
if (type != null)
{
ValidateUserType(type);
if (typeCfg.IsEnum != BinaryUtils.IsIgniteEnum(type))
{
throw new BinaryObjectException(
string.Format(
"Invalid IsEnum flag in binary type configuration. " +
"Configuration value: IsEnum={0}, actual type: IsEnum={1}, type={2}",
typeCfg.IsEnum, type.IsEnum, type));
}
// Type is found.
var typeName = GetTypeName(type, nameMapper);
int typeId = GetTypeId(typeName, idMapper);
var affKeyFld = typeCfg.AffinityKeyFieldName
?? AffinityKeyMappedAttribute.GetFieldNameFromAttribute(type);
var serializer = GetSerializer(_cfg, typeCfg, type, typeId, nameMapper, idMapper, _log);
return AddType(type, typeId, typeName, true, keepDeserialized, nameMapper, idMapper, serializer,
affKeyFld, BinaryUtils.IsIgniteEnum(type));
}
else
{
// Type is not found.
string typeName = GetTypeName(typeCfg.TypeName, nameMapper);
int typeId = GetTypeId(typeName, idMapper);
return AddType(null, typeId, typeName, true, keepDeserialized, nameMapper, idMapper, null,
typeCfg.AffinityKeyFieldName, typeCfg.IsEnum);
}
}
/// <summary>
/// Gets the serializer.
/// </summary>
private static IBinarySerializerInternal GetSerializer(BinaryConfiguration cfg,
BinaryTypeConfiguration typeCfg, Type type, int typeId, IBinaryNameMapper nameMapper,
IBinaryIdMapper idMapper, ILogger log)
{
var serializer = (typeCfg != null ? typeCfg.Serializer : null) ??
(cfg != null ? cfg.Serializer : null);
if (serializer == null)
{
if (type.GetInterfaces().Contains(typeof(IBinarizable)))
return BinarizableSerializer.Instance;
if (type.GetInterfaces().Contains(typeof(ISerializable)))
{
LogSerializableWarning(type, log);
return new SerializableSerializer(type);
}
serializer = new BinaryReflectiveSerializer();
}
var refSerializer = serializer as BinaryReflectiveSerializer;
return refSerializer != null
? refSerializer.Register(type, typeId, nameMapper, idMapper)
: new UserSerializerProxy(serializer);
}
/// <summary>
/// Add type.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="typeId">Type ID.</param>
/// <param name="typeName">Type name.</param>
/// <param name="userType">User type flag.</param>
/// <param name="keepDeserialized">Whether to cache deserialized value in IBinaryObject</param>
/// <param name="nameMapper">Name mapper.</param>
/// <param name="idMapper">ID mapper.</param>
/// <param name="serializer">Serializer.</param>
/// <param name="affKeyFieldName">Affinity key field name.</param>
/// <param name="isEnum">Enum flag.</param>
private BinaryFullTypeDescriptor AddType(Type type, int typeId, string typeName, bool userType,
bool keepDeserialized, IBinaryNameMapper nameMapper, IBinaryIdMapper idMapper,
IBinarySerializerInternal serializer, string affKeyFieldName, bool isEnum)
{
Debug.Assert(!string.IsNullOrEmpty(typeName));
long typeKey = BinaryUtils.TypeKey(userType, typeId);
BinaryFullTypeDescriptor conflictingType;
if (_idToDesc.TryGetValue(typeKey, out conflictingType) && conflictingType.TypeName != typeName)
{
ThrowConflictingTypeError(typeName, conflictingType.TypeName, typeId);
}
var descriptor = new BinaryFullTypeDescriptor(type, typeId, typeName, userType, nameMapper, idMapper,
serializer, keepDeserialized, affKeyFieldName, isEnum);
if (RegistrationDisabled)
{
return descriptor;
}
if (type != null)
{
_typeToDesc.Set(type, descriptor);
}
if (userType)
{
_typeNameToDesc.Set(typeName, descriptor);
}
_idToDesc.Set(typeKey, descriptor);
return descriptor;
}
/// <summary>
/// Adds a predefined system type.
/// </summary>
private void AddSystemType<T>(int typeId, Func<BinaryReader, T> ctor, string affKeyFldName = null,
IBinarySerializerInternal serializer = null)
where T : IBinaryWriteAware
{
var type = typeof(T);
serializer = serializer ?? new BinarySystemTypeSerializer<T>(ctor);
// System types always use simple name mapper.
var typeName = type.Name;
if (typeId == 0)
{
typeId = BinaryUtils.GetStringHashCodeLowerCase(typeName);
}
AddType(type, typeId, typeName, false, false, null, null, serializer, affKeyFldName, false);
}
/// <summary>
/// Adds predefined system types.
/// </summary>
private void AddSystemTypes()
{
AddSystemType(BinaryTypeId.NativeJobHolder, r => new ComputeJobHolder(r));
AddSystemType(BinaryTypeId.ComputeJobWrapper, r => new ComputeJobWrapper(r));
AddSystemType(BinaryTypeId.ComputeOutFuncJob, r => new ComputeOutFuncJob(r));
AddSystemType(BinaryTypeId.ComputeOutFuncWrapper, r => new ComputeOutFuncWrapper(r));
AddSystemType(BinaryTypeId.ComputeFuncWrapper, r => new ComputeFuncWrapper(r));
AddSystemType(BinaryTypeId.ComputeFuncJob, r => new ComputeFuncJob(r));
AddSystemType(BinaryTypeId.ComputeActionJob, r => new ComputeActionJob(r));
AddSystemType(BinaryTypeId.ContinuousQueryRemoteFilterHolder, r => new ContinuousQueryFilterHolder(r));
AddSystemType(BinaryTypeId.CacheEntryProcessorHolder, r => new CacheEntryProcessorHolder(r));
AddSystemType(BinaryTypeId.CacheEntryPredicateHolder, r => new CacheEntryFilterHolder(r));
AddSystemType(BinaryTypeId.MessageListenerHolder, r => new MessageListenerHolder(r));
AddSystemType(BinaryTypeId.StreamReceiverHolder, r => new StreamReceiverHolder(r));
AddSystemType(0, r => new AffinityKey(r), "affKey");
AddSystemType(BinaryTypeId.PlatformJavaObjectFactoryProxy, r => new PlatformJavaObjectFactoryProxy());
AddSystemType(0, r => new ObjectInfoHolder(r));
AddSystemType(BinaryTypeId.IgniteUuid, r => new IgniteGuid(r));
AddSystemType(0, r => new GetAssemblyFunc());
AddSystemType(0, r => new AssemblyRequest(r));
AddSystemType(0, r => new AssemblyRequestResult(r));
AddSystemType<PeerLoadingObjectHolder>(0, null, serializer: new PeerLoadingObjectHolderSerializer());
AddSystemType<MultidimensionalArrayHolder>(0, null, serializer: new MultidimensionalArraySerializer());
}
/// <summary>
/// Logs the warning about ISerializable pitfalls.
/// </summary>
private static void LogSerializableWarning(Type type, ILogger log)
{
if (log == null)
return;
log.GetLogger(typeof(Marshaller).Name)
.Warn("Type '{0}' implements '{1}'. It will be written in Ignite binary format, however, " +
"the following limitations apply: " +
"DateTime fields would not work in SQL; " +
"sbyte, ushort, uint, ulong fields would not work in DML.", type, typeof(ISerializable));
}
/// <summary>
/// Validates binary type.
/// </summary>
// ReSharper disable once UnusedParameter.Local
private static void ValidateUserType(Type type)
{
Debug.Assert(type != null);
if (type.IsGenericTypeDefinition)
{
throw new BinaryObjectException(
"Open generic types (Type.IsGenericTypeDefinition == true) are not allowed " +
"in BinaryConfiguration: " + type.AssemblyQualifiedName);
}
if (type.IsAbstract)
{
throw new BinaryObjectException(
"Abstract types and interfaces are not allowed in BinaryConfiguration: " +
type.AssemblyQualifiedName);
}
}
/// <summary>
/// Resolves the type (opposite of <see cref="GetTypeName(Type, IBinaryNameMapper)"/>).
/// </summary>
public Type ResolveType(string typeName)
{
return new TypeResolver().ResolveType(typeName, nameMapper: _cfg.NameMapper ?? GetDefaultNameMapper());
}
/// <summary>
/// Gets the name of the type according to current name mapper.
/// See also <see cref="ResolveType"/>.
/// </summary>
public string GetTypeName(Type type, IBinaryNameMapper mapper = null)
{
return GetTypeName(type.AssemblyQualifiedName, mapper);
}
/// <summary>
/// Gets the name of the type.
/// </summary>
private string GetTypeName(string fullTypeName, IBinaryNameMapper mapper = null)
{
mapper = mapper ?? _cfg.NameMapper ?? GetDefaultNameMapper();
var typeName = mapper.GetTypeName(fullTypeName);
if (typeName == null)
{
throw new BinaryObjectException("IBinaryNameMapper returned null name for type [typeName=" +
fullTypeName + ", mapper=" + mapper + "]");
}
return typeName;
}
/// <summary>
/// Resolve type ID.
/// </summary>
/// <param name="typeName">Type name.</param>
/// <param name="idMapper">ID mapper.</param>
private static int GetTypeId(string typeName, IBinaryIdMapper idMapper)
{
Debug.Assert(typeName != null);
int id = 0;
if (idMapper != null)
{
try
{
id = idMapper.GetTypeId(typeName);
}
catch (Exception e)
{
throw new BinaryObjectException("Failed to resolve type ID due to ID mapper exception " +
"[typeName=" + typeName + ", idMapper=" + idMapper + ']', e);
}
}
if (id == 0)
{
id = BinaryUtils.GetStringHashCodeLowerCase(typeName);
}
return id;
}
/// <summary>
/// Gets the default name mapper.
/// </summary>
private static IBinaryNameMapper GetDefaultNameMapper()
{
return BinaryBasicNameMapper.FullNameInstance;
}
}
}
| |
// Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
using Nuke.Common.Tooling;
using Nuke.Common.Utilities;
using Nuke.Common.Utilities.Collections;
using Serilog;
using static Nuke.Common.Utilities.ReflectionUtility;
namespace Nuke.Common.ValueInjection
{
internal class ParameterService
{
internal static ParameterService Instance = new ParameterService(
() => EnvironmentInfo.CommandLineArguments.Skip(count: 1),
() => EnvironmentInfo.Variables);
internal ParameterService ArgumentsFromFilesService;
internal ParameterService ArgumentsFromCommitMessageService;
private readonly Func<IEnumerable<string>> _commandLineArgumentsProvider;
private readonly Func<IReadOnlyDictionary<string, string>> _environmentVariablesProvider;
public ParameterService(
[CanBeNull] Func<IEnumerable<string>> commandLineArgumentsProvider,
[CanBeNull] Func<IReadOnlyDictionary<string, string>> environmentVariablesProvider)
{
_commandLineArgumentsProvider = commandLineArgumentsProvider;
_environmentVariablesProvider = environmentVariablesProvider;
}
private string[] Arguments => _commandLineArgumentsProvider.Invoke().ToArray();
private IReadOnlyDictionary<string, string> Variables => _environmentVariablesProvider.Invoke();
public static bool IsParameter(string value)
{
return value != null && value.StartsWith("-");
}
public static string GetParameterDashedName(MemberInfo member)
{
return GetParameterDashedName(GetParameterMemberName(member));
}
public static string GetParameterDashedName(string name)
{
return name.SplitCamelHumpsWithKnownWords().JoinDash().ToLowerInvariant();
}
public static string GetParameterMemberName(string name)
{
return name.Replace("-", string.Empty);
}
public static string GetParameterMemberName<T>(Expression<Func<T>> expression)
{
var member = expression.GetMemberInfo();
return GetParameterMemberName(member);
}
public static string GetParameterMemberName(MemberInfo member)
{
var attribute = member.GetCustomAttribute<ParameterAttribute>();
var prefix = member.DeclaringType.NotNull().GetCustomAttribute<ParameterPrefixAttribute>()?.Prefix;
return prefix + (attribute.Name ?? member.Name);
}
[CanBeNull]
public static string GetParameterDescription(MemberInfo member)
{
var attribute = member.GetCustomAttribute<ParameterAttribute>();
return attribute.Description?.TrimEnd('.');
}
[CanBeNull]
public static IEnumerable<(string Text, object Object)> GetParameterValueSet(MemberInfo member, object instance)
{
var attribute = member.GetCustomAttribute<ParameterAttribute>();
var memberType = member.GetMemberType().GetScalarType();
IEnumerable<(string Text, object Object)> TryGetFromValueProvider()
{
if (attribute.ValueProviderMember == null)
return null;
var valueProviderType = attribute.ValueProviderType ?? instance.GetType();
var valueProvider = valueProviderType
.GetMember(attribute.ValueProviderMember, All)
.SingleOrDefault()
.NotNull($"No single provider '{valueProviderType.Name}.{member.Name}' found");
Assert.True(valueProvider.GetMemberType() == typeof(IEnumerable<string>),
$"Value provider '{valueProvider.Name}' must be of type '{typeof(IEnumerable<string>).GetDisplayShortName()}'");
return valueProvider.GetValue<IEnumerable<string>>(instance).Select(x => (x, (object) x));
}
IEnumerable<(string Text, object Object)> TryGetFromEnumerationClass() =>
memberType.IsSubclassOf(typeof(Enumeration))
? memberType.GetFields(Static).Select(x => (x.Name, x.GetValue()))
: null;
IEnumerable<(string Text, object Object)> TryGetFromEnum()
{
var enumType = memberType.IsEnum
? memberType
: Nullable.GetUnderlyingType(memberType) is { } underlyingType && underlyingType.IsEnum
? underlyingType
: null;
return enumType != null
? enumType.GetEnumNames().Select(x => (x, Enum.Parse(enumType, x)))
: null;
}
return (attribute.GetValueSet(member, instance) ??
TryGetFromValueProvider() ??
TryGetFromEnumerationClass() ??
TryGetFromEnum())
?.OrderBy(x => x.Item1);
}
[CanBeNull]
public static object GetFromMemberInfo(MemberInfo member, [CanBeNull] Type destinationType, Func<string, Type, char?, object> provider)
{
var attribute = member.GetCustomAttribute<ParameterAttribute>();
var separator = (attribute.Separator ?? string.Empty).SingleOrDefault();
return provider.Invoke(GetParameterMemberName(member), destinationType ?? member.GetMemberType(), separator);
}
[CanBeNull]
public object GetParameter(string parameterName, Type destinationType, char? separator)
{
object TryFromCommandLineArguments() =>
HasCommandLineArgument(parameterName)
? GetCommandLineArgument(parameterName, destinationType, separator)
: null;
object TryFromCommandLinePositionalArguments() =>
parameterName == Constants.InvokedTargetsParameterName
? GetPositionalCommandLineArguments(destinationType, separator)
: null;
object TryFromEnvironmentVariables() =>
GetEnvironmentVariable(parameterName, destinationType, separator);
// TODO: nuke <target> ?
object TryFromProfileArguments() =>
ArgumentsFromFilesService?.GetCommandLineArgument(parameterName, destinationType, separator);
object TryFromCommitMessageArguments() =>
ArgumentsFromCommitMessageService?.GetCommandLineArgument(parameterName, destinationType, separator);
return TryFromCommitMessageArguments() ??
TryFromCommandLineArguments() ??
TryFromCommandLinePositionalArguments() ??
TryFromEnvironmentVariables() ??
TryFromProfileArguments();
}
[CanBeNull]
public object GetCommandLineArgument(string argumentName, Type destinationType, char? separator)
{
var index = GetCommandLineArgumentIndex(argumentName);
if (index == -1)
return GetDefaultValue(destinationType);
var values = Arguments.Skip(index + 1).TakeUntil(IsParameter).ToArray();
return ConvertCommandLineArguments(argumentName, values, destinationType, Arguments, separator);
}
[CanBeNull]
public object GetCommandLineArgument(int position, Type destinationType, char? separator)
{
var positionalParametersCount = Arguments.TakeUntil(IsParameter).Count();
if (position < 0)
position = positionalParametersCount + position % positionalParametersCount;
if (positionalParametersCount <= position)
return null;
return ConvertCommandLineArguments(
$"$positional[{position}]",
new[] { Arguments[position] },
destinationType,
Arguments,
separator);
}
[CanBeNull]
public object GetPositionalCommandLineArguments(Type destinationType, char? separator = null)
{
var positionalArguments = Arguments.TakeUntil(IsParameter).ToArray();
if (positionalArguments.Length == 0)
return GetDefaultValue(destinationType);
return ConvertCommandLineArguments(
"$all-positional",
positionalArguments,
destinationType,
Arguments,
separator);
}
[CanBeNull]
private object ConvertCommandLineArguments(
string argumentName,
string[] values,
Type destinationType,
string[] commandLineArguments,
char? separator = null)
{
Assert.True(values.Length == 1 || !separator.HasValue || values.All(x => !x.Contains(separator.Value)),
$"Command-line argument '{argumentName}' with value [ {values.JoinCommaSpace()} ] cannot be split with separator '{separator}'");
values = separator.HasValue && values.Any(x => x.Contains(separator.Value))
? values.SingleOrDefault()?.Split(separator.Value) ?? new string[0]
: values;
try
{
return ConvertValues(argumentName, values, destinationType);
}
catch (Exception ex)
{
Assert.Fail(
new[] { ex.Message, "Command-line arguments were:" }
.Concat(commandLineArguments.Select((x, i) => $" [{i}] = {x}"))
.JoinNewLine());
// ReSharper disable once HeuristicUnreachableCode
return null;
}
}
public bool HasCommandLineArgument(string argumentName)
{
return GetCommandLineArgumentIndex(argumentName) != -1;
}
private int GetCommandLineArgumentIndex(string argumentName)
{
var index = Array.FindLastIndex(Arguments,
x => IsParameter(x) && GetParameterMemberName(x).EqualsOrdinalIgnoreCase(GetParameterMemberName(argumentName)));
// if (index == -1 && checkNames)
// {
// var candidates = Arguments.Where(x => x.StartsWith("-")).Select(x => x.Replace("-", string.Empty));
// CheckNames(argumentName, candidates);
// }
return index;
}
[CanBeNull]
public object GetEnvironmentVariable(string variableName, Type destinationType, char? separator)
{
static string GetTrimmedName(string name)
=> new string(name.Where(char.IsLetterOrDigit).ToArray());
if (!Variables.TryGetValue(variableName, out var value))
{
var trimmedVariableName = GetTrimmedName(variableName);
var alternativeValues = Variables
.Where(x => GetTrimmedName(x.Key).EqualsOrdinalIgnoreCase(trimmedVariableName) ||
GetTrimmedName(x.Key).EqualsOrdinalIgnoreCase($"NUKE{trimmedVariableName}")).ToList();
if (alternativeValues.Count > 1)
Log.Warning("Could not resolve {VariableName} since multiple values are provided", variableName);
if (alternativeValues.Count == 1)
value = alternativeValues.Single().Value;
else
return GetDefaultValue(destinationType);
}
try
{
return ConvertValues(variableName, separator.HasValue ? value.Split(separator.Value) : new[] { value }, destinationType);
}
catch (Exception ex)
{
Assert.Fail(new[] { ex.Message, "Environment variable was:", value }.JoinNewLine());
// ReSharper disable once HeuristicUnreachableCode
return null;
}
}
[CanBeNull]
private object GetDefaultValue(Type type)
{
return type.IsNullableType() ? null : Activator.CreateInstance(type);
}
[CanBeNull]
private object ConvertValues(string parameterName, IReadOnlyCollection<string> values, Type destinationType)
{
try
{
return ConvertValues(values, destinationType);
}
catch (Exception ex)
{
Assert.Fail(new[] { $"Resolving parameter '{parameterName}' failed.", ex.Message }.JoinNewLine());
// ReSharper disable once HeuristicUnreachableCode
return null;
}
}
[CanBeNull]
private object ConvertValues(IReadOnlyCollection<string> values, Type destinationType)
{
Assert.True(!destinationType.IsArray || destinationType.GetArrayRank() == 1, "Arrays must have a rank of 1");
var elementType = (destinationType.IsArray ? destinationType.GetElementType() : destinationType).NotNull();
Assert.True(values.Count < 2 || elementType != null, "values.Count < 2 || elementType != null");
if (values.Count == 0)
{
if (destinationType.IsArray)
return Array.CreateInstance(elementType, length: 0);
if (destinationType == typeof(bool) || destinationType == typeof(bool?))
return true;
return null;
}
var convertedValues = values.Select(x => Convert(x, elementType)).ToList();
if (!destinationType.IsArray)
{
Assert.HasSingleItem(convertedValues,
$"Value [ {values.JoinCommaSpace()} ] cannot be assigned to '{destinationType.GetDisplayShortName()}'");
return convertedValues.Single();
}
var array = Array.CreateInstance(elementType, convertedValues.Count);
convertedValues.ForEach((x, i) => array.SetValue(x, i));
Assert.True(destinationType.IsInstanceOfType(array),
$"Type '{array.GetType().GetDisplayShortName()}' is not an instance of '{destinationType.GetDisplayShortName()}'.");
return array;
}
private void CheckNames(string name, IEnumerable<string> candidates)
{
const double similarityThreshold = 0.5;
name = name.ToLower();
foreach (var candidate in candidates.Select(x => x.ToLower()))
{
var levenshteinDistance = (float) GetLevenshteinDistance(name, candidate);
if (levenshteinDistance / name.Length < similarityThreshold)
{
Log.Warning("Requested parameter {Name} was not found. Is there a typo with {candidate} which was passed?", name, candidate);
return;
}
}
}
private int GetLevenshteinDistance(string a, string b)
{
if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b))
return 0;
var lengthA = a.Length;
var lengthB = b.Length;
var distances = new int[lengthA + 1, lengthB + 1];
for (var i = 0; i <= lengthA; distances[i, 0] = i++)
{
}
for (var j = 0; j <= lengthB; distances[0, j] = j++)
{
}
for (var i = 1; i <= lengthA; i++)
for (var j = 1; j <= lengthB; j++)
{
var cost = b[j - 1] == a[i - 1] ? 0 : 1;
distances[i, j] = Math.Min(
Math.Min(distances[i - 1, j] + 1, distances[i, j - 1] + 1),
distances[i - 1, j - 1] + cost
);
}
return distances[lengthA, lengthB];
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ServiceFabricManagedClusters.Tests
{
using System;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.ServiceFabricManagedClusters;
using Microsoft.Azure.Management.ServiceFabricManagedClusters.Models;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Xunit;
public class ApplicationTests : ServiceFabricManagedTestBase
{
internal const string Location = "South Central US";
internal const string ResourceGroupPrefix = "sfmc-net-sdk-app-rg-";
internal const string ClusterNamePrefix = "sfmcnetsdk";
private const string AppName = "Voting";
private const string AppTypeVersionName = "1.0.0";
private const string AppTypeName = "VotingType";
private const string AppPackageUrl = "https://sfmconeboxst.blob.core.windows.net/managed-application-deployment/Voting.sfpkg";
private const string StatefulServiceName = "VotingData";
private const string StatefulServiceTypeName = "VotingDataType";
[Fact]
public void AppCreateDeleteTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var serviceFabricMcClient = GetServiceFabricMcClient(context);
var resourceClient = GetResourceManagementClient(context);
var resourceGroupName = TestUtilities.GenerateName(ResourceGroupPrefix);
var clusterName = TestUtilities.GenerateName(ClusterNamePrefix);
var nodeTypeName = TestUtilities.GenerateName("nt");
var cluster = this.CreateManagedCluster(resourceClient, serviceFabricMcClient, resourceGroupName, Location, clusterName, sku: "Basic");
cluster = serviceFabricMcClient.ManagedClusters.Get(resourceGroupName, clusterName);
Assert.NotNull(cluster);
var primaryNodeType = this.CreateNodeType(serviceFabricMcClient, resourceGroupName, clusterName, nodeTypeName, isPrimary: true, vmInstanceCount: 6);
this.WaitForClusterReadyState(serviceFabricMcClient, resourceGroupName, clusterName);
CreateAppType(serviceFabricMcClient, resourceGroupName, clusterName, cluster.ClusterId, AppTypeName);
var appTypeVersion = CreateAppTypeVersion(serviceFabricMcClient, resourceGroupName, clusterName, cluster.ClusterId, AppTypeName, AppTypeVersionName, AppPackageUrl);
CreateApplication(serviceFabricMcClient, resourceGroupName, clusterName, cluster.ClusterId, AppName, appTypeVersion.Id);
CreateService(serviceFabricMcClient, resourceGroupName, clusterName, cluster.ClusterId, AppName, StatefulServiceTypeName, StatefulServiceName);
DeleteApplication(serviceFabricMcClient, resourceGroupName, clusterName, cluster.ClusterId, AppName);
DeleteAppType(serviceFabricMcClient, resourceGroupName, clusterName, cluster.ClusterId, AppTypeName);
}
}
private void CreateAppType(
ServiceFabricManagedClustersManagementClient serviceFabricMcClient,
string resourceGroup,
string clusterName,
string clusterId,
string appTypeName)
{
var appTypeResourceId = $"{clusterId}/applicationTypes/{appTypeName}";
var appTypeParams = new ApplicationTypeResource(
name: appTypeName,
location: Location,
id: appTypeResourceId);
var appTypeResult = serviceFabricMcClient.ApplicationTypes.CreateOrUpdate(
resourceGroup,
clusterName,
appTypeName,
appTypeParams);
Assert.Equal("Succeeded", appTypeResult.ProvisioningState);
}
private ApplicationTypeVersionResource CreateAppTypeVersion(
ServiceFabricManagedClustersManagementClient serviceFabricMcClient,
string resourceGroup,
string clusterName,
string clusterId,
string appTypeName,
string appTypeVersionName,
string appPackageUrl)
{
var appTypeVersionResourceId = $"{clusterId}/applicationTypes/{appTypeName}/versions/{appTypeVersionName}";
var appTypeVersionParams = new ApplicationTypeVersionResource(
name: AppTypeVersionName,
location: Location,
id: appTypeVersionResourceId,
appPackageUrl: appPackageUrl);
var appTypeVersionResult = serviceFabricMcClient.ApplicationTypeVersions.CreateOrUpdate(
resourceGroup,
clusterName,
appTypeName,
appTypeVersionName,
appTypeVersionParams);
Assert.Equal("Succeeded", appTypeVersionResult.ProvisioningState);
Assert.Equal(appPackageUrl, appTypeVersionResult.AppPackageUrl);
return appTypeVersionResult;
}
private void CreateApplication(
ServiceFabricManagedClustersManagementClient serviceFabricMcClient,
string resourceGroup,
string clusterName,
string clusterId,
string appName,
string versionResourceId)
{
var applicationResourceId = $"{clusterId}/applications/{appName}";
var applicationParams = new ApplicationResource(
name: appName,
location: Location,
id: applicationResourceId,
version: versionResourceId,
upgradePolicy: new ApplicationUpgradePolicy(recreateApplication: true));
var applicationResult = serviceFabricMcClient.Applications.CreateOrUpdate(
resourceGroup,
clusterName,
appName,
applicationParams);
Assert.Equal("Succeeded", applicationResult.ProvisioningState);
Assert.True(applicationResult.UpgradePolicy.RecreateApplication);
Assert.Equal(versionResourceId, applicationResult.Version);
}
private void CreateService(
ServiceFabricManagedClustersManagementClient serviceFabricMcClient,
string resourceGroup,
string clusterName,
string clusterId,
string appName,
string serviceTypeName,
string serviceName)
{
var serviceResourceId = $"{clusterId}/applications/{appName}/services/{serviceName}";
var count = 1;
var lowKey = 0;
var highKey = 25;
var targetReplicaSetSize = 5;
var minReplicaSetSize = 3;
var serviceParams = new ServiceResource(
name: serviceName,
location: Location,
id: serviceResourceId,
properties: new StatefulServiceProperties(
serviceTypeName: serviceTypeName,
partitionDescription: new UniformInt64RangePartitionScheme(
count: count,
lowKey: lowKey,
highKey: highKey),
hasPersistedState: true,
targetReplicaSetSize: targetReplicaSetSize,
minReplicaSetSize: minReplicaSetSize));
var serviceResult = serviceFabricMcClient.Services.CreateOrUpdate(
resourceGroup,
clusterName,
appName,
serviceName,
serviceParams);
Assert.Equal("Succeeded", serviceResult.Properties.ProvisioningState);
Assert.IsAssignableFrom<StatefulServiceProperties>(serviceResult.Properties);
var serviceProperties = serviceResult.Properties as StatefulServiceProperties;
Assert.Equal("VotingDataType", serviceResult.Properties.ServiceTypeName);
Assert.IsAssignableFrom<UniformInt64RangePartitionScheme>(serviceResult.Properties.PartitionDescription);
var partitionDescription = serviceProperties.PartitionDescription as UniformInt64RangePartitionScheme;
Assert.Equal(count, partitionDescription.Count);
Assert.Equal(lowKey, partitionDescription.LowKey);
Assert.Equal(highKey, partitionDescription.HighKey);
Assert.True(serviceProperties.HasPersistedState);
Assert.Equal(targetReplicaSetSize, serviceProperties.TargetReplicaSetSize);
Assert.Equal(minReplicaSetSize, serviceProperties.MinReplicaSetSize);
}
private void DeleteApplication(
ServiceFabricManagedClustersManagementClient serviceFabricMcClient,
string resourceGroup,
string clusterName,
string clusterId,
string appName)
{
var deleteStartTime = DateTime.UtcNow;
var applicationResourceId = $"{clusterId}/applications/{appName}";
serviceFabricMcClient.Applications.Delete(
resourceGroup,
clusterName,
appName);
var ex = Assert.ThrowsAsync<ErrorModelException>(
() => serviceFabricMcClient.Applications.GetAsync(resourceGroup, clusterName, appName)).Result;
Assert.True(ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound);
}
private void DeleteAppType(
ServiceFabricManagedClustersManagementClient serviceFabricMcClient,
string resourceGroup,
string clusterName,
string clusterId,
string appTypeName)
{
var appTypeResourceId = $"{clusterId}/applicationTypes/{appTypeName}";
serviceFabricMcClient.ApplicationTypes.Delete(
resourceGroup,
clusterName,
appTypeName);
var ex = Assert.ThrowsAsync<ErrorModelException>(
() => serviceFabricMcClient.ApplicationTypes.GetAsync(resourceGroup, clusterName, appTypeName)).Result;
Assert.True(ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace YAF.Lucene.Net.Index
{
/*
* 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.
*/
// javadocs
using Directory = YAF.Lucene.Net.Store.Directory;
/// <summary>
/// <see cref="DirectoryReader"/> is an implementation of <see cref="CompositeReader"/>
/// that can read indexes in a <see cref="Store.Directory"/>.
///
/// <para/><see cref="DirectoryReader"/> instances are usually constructed with a call to
/// one of the static <c>Open()</c> methods, e.g. <see cref="Open(Directory)"/>.
///
/// <para/> For efficiency, in this API documents are often referred to via
/// <i>document numbers</i>, non-negative integers which each name a unique
/// document in the index. These document numbers are ephemeral -- they may change
/// as documents are added to and deleted from an index. Clients should thus not
/// rely on a given document having the same number between sessions.
///
/// <para/><b>NOTE</b>:
/// <see cref="IndexReader"/> instances are completely thread
/// safe, meaning multiple threads can call any of its methods,
/// concurrently. If your application requires external
/// synchronization, you should <b>not</b> synchronize on the
/// <see cref="IndexReader"/> instance; use your own
/// (non-Lucene) objects instead.
/// </summary>
public abstract class DirectoryReader : BaseCompositeReader<AtomicReader>
{
/// <summary>
/// Default termInfosIndexDivisor. </summary>
public static readonly int DEFAULT_TERMS_INDEX_DIVISOR = 1;
/// <summary>
/// The index directory. </summary>
protected readonly Directory m_directory;
/// <summary>
/// Returns a <see cref="IndexReader"/> reading the index in the given
/// <see cref="Store.Directory"/> </summary>
/// <param name="directory"> the index directory </param>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
new public static DirectoryReader Open(Directory directory)
{
return StandardDirectoryReader.Open(directory, null, DEFAULT_TERMS_INDEX_DIVISOR);
}
/// <summary>
/// Expert: Returns a <see cref="IndexReader"/> reading the index in the given
/// <see cref="Store.Directory"/> with the given termInfosIndexDivisor. </summary>
/// <param name="directory"> the index directory </param>
/// <param name="termInfosIndexDivisor"> Subsamples which indexed
/// terms are loaded into RAM. this has the same effect as setting
/// <see cref="LiveIndexWriterConfig.TermIndexInterval"/> (on <see cref="IndexWriterConfig"/>) except that setting
/// must be done at indexing time while this setting can be
/// set per reader. When set to N, then one in every
/// N*termIndexInterval terms in the index is loaded into
/// memory. By setting this to a value > 1 you can reduce
/// memory usage, at the expense of higher latency when
/// loading a TermInfo. The default value is 1. Set this
/// to -1 to skip loading the terms index entirely.
/// <b>NOTE:</b> divisor settings > 1 do not apply to all <see cref="Codecs.PostingsFormat"/>
/// implementations, including the default one in this release. It only makes
/// sense for terms indexes that can efficiently re-sample terms at load time. </param>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
new public static DirectoryReader Open(Directory directory, int termInfosIndexDivisor)
{
return StandardDirectoryReader.Open(directory, null, termInfosIndexDivisor);
}
/// <summary>
/// Open a near real time <see cref="IndexReader"/> from the <see cref="IndexWriter"/>.
/// <para/>
/// @lucene.experimental
/// </summary>
/// <param name="writer"> The <see cref="IndexWriter"/> to open from </param>
/// <param name="applyAllDeletes"> If <c>true</c>, all buffered deletes will
/// be applied (made visible) in the returned reader. If
/// <c>false</c>, the deletes are not applied but remain buffered
/// (in IndexWriter) so that they will be applied in the
/// future. Applying deletes can be costly, so if your app
/// can tolerate deleted documents being returned you might
/// gain some performance by passing <c>false</c>. </param>
/// <returns> The new <see cref="IndexReader"/> </returns>
/// <exception cref="CorruptIndexException"> if the index is corrupt </exception>
/// <exception cref="IOException"> if there is a low-level IO error
/// </exception>
/// <seealso cref="OpenIfChanged(DirectoryReader, IndexWriter, bool)"/>
new public static DirectoryReader Open(IndexWriter writer, bool applyAllDeletes)
{
return writer.GetReader(applyAllDeletes);
}
/// <summary>
/// Expert: returns an <see cref="IndexReader"/> reading the index in the given
/// <see cref="Index.IndexCommit"/>. </summary>
/// <param name="commit"> the commit point to open </param>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
new public static DirectoryReader Open(IndexCommit commit)
{
return StandardDirectoryReader.Open(commit.Directory, commit, DEFAULT_TERMS_INDEX_DIVISOR);
}
/// <summary>
/// Expert: returns an <see cref="IndexReader"/> reading the index in the given
/// <seealso cref="Index.IndexCommit"/> and <paramref name="termInfosIndexDivisor"/>. </summary>
/// <param name="commit"> the commit point to open </param>
/// <param name="termInfosIndexDivisor"> Subsamples which indexed
/// terms are loaded into RAM. this has the same effect as setting
/// <see cref="LiveIndexWriterConfig.TermIndexInterval"/> (on <see cref="IndexWriterConfig"/>) except that setting
/// must be done at indexing time while this setting can be
/// set per reader. When set to N, then one in every
/// N*termIndexInterval terms in the index is loaded into
/// memory. By setting this to a value > 1 you can reduce
/// memory usage, at the expense of higher latency when
/// loading a TermInfo. The default value is 1. Set this
/// to -1 to skip loading the terms index entirely.
/// <b>NOTE:</b> divisor settings > 1 do not apply to all <see cref="Codecs.PostingsFormat"/>
/// implementations, including the default one in this release. It only makes
/// sense for terms indexes that can efficiently re-sample terms at load time. </param>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
new public static DirectoryReader Open(IndexCommit commit, int termInfosIndexDivisor)
{
return StandardDirectoryReader.Open(commit.Directory, commit, termInfosIndexDivisor);
}
/// <summary>
/// If the index has changed since the provided reader was
/// opened, open and return a new reader; else, return
/// <c>null</c>. The new reader, if not <c>null</c>, will be the same
/// type of reader as the previous one, ie a near-real-time (NRT) reader
/// will open a new NRT reader, a <see cref="MultiReader"/> will open a
/// new <see cref="MultiReader"/>, etc.
///
/// <para/>This method is typically far less costly than opening a
/// fully new <see cref="DirectoryReader"/> as it shares
/// resources (for example sub-readers) with the provided
/// <see cref="DirectoryReader"/>, when possible.
///
/// <para/>The provided reader is not disposed (you are responsible
/// for doing so); if a new reader is returned you also
/// must eventually dispose it. Be sure to never dispose a
/// reader while other threads are still using it; see
/// <see cref="Search.SearcherManager"/> to simplify managing this.
/// </summary>
/// <exception cref="CorruptIndexException"> if the index is corrupt </exception>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
/// <returns> <c>null</c> if there are no changes; else, a new
/// <see cref="DirectoryReader"/> instance which you must eventually dispose </returns>
public static DirectoryReader OpenIfChanged(DirectoryReader oldReader)
{
DirectoryReader newReader = oldReader.DoOpenIfChanged();
Debug.Assert(newReader != oldReader);
return newReader;
}
/// <summary>
/// If the <see cref="Index.IndexCommit"/> differs from what the
/// provided reader is searching, open and return a new
/// reader; else, return <c>null</c>.
/// </summary>
/// <seealso cref="OpenIfChanged(DirectoryReader)"/>
public static DirectoryReader OpenIfChanged(DirectoryReader oldReader, IndexCommit commit)
{
DirectoryReader newReader = oldReader.DoOpenIfChanged(commit);
Debug.Assert(newReader != oldReader);
return newReader;
}
/// <summary>
/// Expert: If there changes (committed or not) in the
/// <see cref="IndexWriter"/> versus what the provided reader is
/// searching, then open and return a new
/// <see cref="IndexReader"/> searching both committed and uncommitted
/// changes from the writer; else, return <c>null</c> (though, the
/// current implementation never returns <c>null</c>).
///
/// <para/>This provides "near real-time" searching, in that
/// changes made during an <see cref="IndexWriter"/> session can be
/// quickly made available for searching without closing
/// the writer nor calling <see cref="IndexWriter.Commit()"/>.
///
/// <para>It's <i>near</i> real-time because there is no hard
/// guarantee on how quickly you can get a new reader after
/// making changes with <see cref="IndexWriter"/>. You'll have to
/// experiment in your situation to determine if it's
/// fast enough. As this is a new and experimental
/// feature, please report back on your findings so we can
/// learn, improve and iterate.</para>
///
/// <para>The very first time this method is called, this
/// writer instance will make every effort to pool the
/// readers that it opens for doing merges, applying
/// deletes, etc. This means additional resources (RAM,
/// file descriptors, CPU time) will be consumed.</para>
///
/// <para>For lower latency on reopening a reader, you should
/// call <see cref="LiveIndexWriterConfig.MergedSegmentWarmer"/> (on <see cref="IndexWriterConfig"/>) to
/// pre-warm a newly merged segment before it's committed
/// to the index. This is important for minimizing
/// index-to-search delay after a large merge. </para>
///
/// <para>If an AddIndexes* call is running in another thread,
/// then this reader will only search those segments from
/// the foreign index that have been successfully copied
/// over, so far.</para>
///
/// <para><b>NOTE</b>: Once the writer is disposed, any
/// outstanding readers may continue to be used. However,
/// if you attempt to reopen any of those readers, you'll
/// hit an <see cref="System.ObjectDisposedException"/>.</para>
///
/// @lucene.experimental
/// </summary>
/// <returns> <see cref="DirectoryReader"/> that covers entire index plus all
/// changes made so far by this <see cref="IndexWriter"/> instance, or
/// <c>null</c> if there are no new changes
/// </returns>
/// <param name="writer"> The <see cref="IndexWriter"/> to open from
/// </param>
/// <param name="applyAllDeletes"> If <c>true</c>, all buffered deletes will
/// be applied (made visible) in the returned reader. If
/// <c>false</c>, the deletes are not applied but remain buffered
/// (in <see cref="IndexWriter"/>) so that they will be applied in the
/// future. Applying deletes can be costly, so if your app
/// can tolerate deleted documents being returned you might
/// gain some performance by passing <c>false</c>.
/// </param>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
public static DirectoryReader OpenIfChanged(DirectoryReader oldReader, IndexWriter writer, bool applyAllDeletes)
{
DirectoryReader newReader = oldReader.DoOpenIfChanged(writer, applyAllDeletes);
Debug.Assert(newReader != oldReader);
return newReader;
}
/// <summary>
/// Returns all commit points that exist in the <see cref="Store.Directory"/>.
/// Normally, because the default is
/// <see cref="KeepOnlyLastCommitDeletionPolicy"/>, there would be only
/// one commit point. But if you're using a custom
/// <see cref="IndexDeletionPolicy"/> then there could be many commits.
/// Once you have a given commit, you can open a reader on
/// it by calling <see cref="DirectoryReader.Open(IndexCommit)"/>
/// There must be at least one commit in
/// the <see cref="Store.Directory"/>, else this method throws
/// <see cref="IndexNotFoundException"/>. Note that if a commit is in
/// progress while this method is running, that commit
/// may or may not be returned.
/// </summary>
/// <returns> a sorted list of <see cref="Index.IndexCommit"/>s, from oldest
/// to latest. </returns>
public static IList<IndexCommit> ListCommits(Directory dir)
{
string[] files = dir.ListAll();
List<IndexCommit> commits = new List<IndexCommit>();
SegmentInfos latest = new SegmentInfos();
latest.Read(dir);
long currentGen = latest.Generation;
commits.Add(new StandardDirectoryReader.ReaderCommit(latest, dir));
for (int i = 0; i < files.Length; i++)
{
string fileName = files[i];
if (fileName.StartsWith(IndexFileNames.SEGMENTS, StringComparison.Ordinal) && !fileName.Equals(IndexFileNames.SEGMENTS_GEN, StringComparison.Ordinal) && SegmentInfos.GenerationFromSegmentsFileName(fileName) < currentGen)
{
SegmentInfos sis = new SegmentInfos();
try
{
// IOException allowed to throw there, in case
// segments_N is corrupt
sis.Read(dir, fileName);
}
catch (FileNotFoundException)
{
// LUCENE-948: on NFS (and maybe others), if
// you have writers switching back and forth
// between machines, it's very likely that the
// dir listing will be stale and will claim a
// file segments_X exists when in fact it
// doesn't. So, we catch this and handle it
// as if the file does not exist
sis = null;
}
// LUCENENET specific - .NET (thankfully) only has one FileNotFoundException, so we don't need this
//catch (NoSuchFileException)
//{
// sis = null;
//}
// LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException
// in Lucene, we need to catch it here to be on the safe side.
catch (System.IO.DirectoryNotFoundException)
{
// LUCENE-948: on NFS (and maybe others), if
// you have writers switching back and forth
// between machines, it's very likely that the
// dir listing will be stale and will claim a
// file segments_X exists when in fact it
// doesn't. So, we catch this and handle it
// as if the file does not exist
sis = null;
}
if (sis != null)
{
commits.Add(new StandardDirectoryReader.ReaderCommit(sis, dir));
}
}
}
// Ensure that the commit points are sorted in ascending order.
commits.Sort();
return commits;
}
/// <summary>
/// Returns <c>true</c> if an index likely exists at
/// the specified directory. Note that if a corrupt index
/// exists, or if an index in the process of committing </summary>
/// <param name="directory"> the directory to check for an index </param>
/// <returns> <c>true</c> if an index exists; <c>false</c> otherwise </returns>
public static bool IndexExists(Directory directory)
{
// LUCENE-2812, LUCENE-2727, LUCENE-4738: this logic will
// return true in cases that should arguably be false,
// such as only IW.prepareCommit has been called, or a
// corrupt first commit, but it's too deadly to make
// this logic "smarter" and risk accidentally returning
// false due to various cases like file description
// exhaustion, access denied, etc., because in that
// case IndexWriter may delete the entire index. It's
// safer to err towards "index exists" than try to be
// smart about detecting not-yet-fully-committed or
// corrupt indices. this means that IndexWriter will
// throw an exception on such indices and the app must
// resolve the situation manually:
string[] files;
try
{
files = directory.ListAll();
}
#pragma warning disable 168
catch (DirectoryNotFoundException nsde)
#pragma warning restore 168
{
// Directory does not exist --> no index exists
return false;
}
// Defensive: maybe a Directory impl returns null
// instead of throwing NoSuchDirectoryException:
if (files != null)
{
string prefix = IndexFileNames.SEGMENTS + "_";
foreach (string file in files)
{
if (file.StartsWith(prefix, StringComparison.Ordinal) || file.Equals(IndexFileNames.SEGMENTS_GEN, StringComparison.Ordinal))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Expert: Constructs a <see cref="DirectoryReader"/> on the given <paramref name="segmentReaders"/>. </summary>
/// <param name="segmentReaders"> the wrapped atomic index segment readers. This array is
/// returned by <see cref="CompositeReader.GetSequentialSubReaders"/> and used to resolve the correct
/// subreader for docID-based methods. <b>Please note:</b> this array is <b>not</b>
/// cloned and not protected for modification outside of this reader.
/// Subclasses of <see cref="DirectoryReader"/> should take care to not allow
/// modification of this internal array, e.g. <see cref="DoOpenIfChanged()"/>. </param>
protected DirectoryReader(Directory directory, AtomicReader[] segmentReaders)
: base(segmentReaders)
{
this.m_directory = directory;
}
/// <summary>
/// Returns the directory this index resides in. </summary>
public Directory Directory
{
get
{
// Don't ensureOpen here -- in certain cases, when a
// cloned/reopened reader needs to commit, it may call
// this method on the closed original reader
return m_directory;
}
}
/// <summary>
/// Implement this method to support <see cref="OpenIfChanged(DirectoryReader)"/>.
/// If this reader does not support reopen, return <c>null</c>, so
/// client code is happy. This should be consistent with <see cref="IsCurrent()"/>
/// (should always return <c>true</c>) if reopen is not supported. </summary>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
/// <returns> <c>null</c> if there are no changes; else, a new
/// <see cref="DirectoryReader"/> instance. </returns>
protected internal abstract DirectoryReader DoOpenIfChanged();
/// <summary>
/// Implement this method to support <see cref="OpenIfChanged(DirectoryReader, IndexCommit)"/>.
/// If this reader does not support reopen from a specific <see cref="Index.IndexCommit"/>,
/// throw <see cref="NotSupportedException"/>. </summary>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
/// <returns> <c>null</c> if there are no changes; else, a new
/// <see cref="DirectoryReader"/> instance. </returns>
protected internal abstract DirectoryReader DoOpenIfChanged(IndexCommit commit);
/// <summary>
/// Implement this method to support <see cref="OpenIfChanged(DirectoryReader, IndexWriter, bool)"/>.
/// If this reader does not support reopen from <see cref="IndexWriter"/>,
/// throw <see cref="NotSupportedException"/>. </summary>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
/// <returns> <c>null</c> if there are no changes; else, a new
/// <see cref="DirectoryReader"/> instance. </returns>
protected internal abstract DirectoryReader DoOpenIfChanged(IndexWriter writer, bool applyAllDeletes);
/// <summary>
/// Version number when this <see cref="IndexReader"/> was opened.
///
/// <para>This method
/// returns the version recorded in the commit that the
/// reader opened. This version is advanced every time
/// a change is made with <see cref="IndexWriter"/>.</para>
/// </summary>
public abstract long Version { get; }
/// <summary>
/// Check whether any new changes have occurred to the
/// index since this reader was opened.
///
/// <para>If this reader was created by calling an overload of <see cref="Open(Directory)"/>,
/// then this method checks if any further commits
/// (see <see cref="IndexWriter.Commit()"/>) have occurred in the
/// directory.</para>
///
/// <para>If instead this reader is a near real-time reader
/// (ie, obtained by a call to
/// <see cref="DirectoryReader.Open(IndexWriter, bool)"/>, or by calling an overload of <see cref="OpenIfChanged(DirectoryReader)"/>
/// on a near real-time reader), then this method checks if
/// either a new commit has occurred, or any new
/// uncommitted changes have taken place via the writer.
/// Note that even if the writer has only performed
/// merging, this method will still return <c>false</c>.</para>
///
/// <para>In any event, if this returns <c>false</c>, you should call
/// an overload of <see cref="OpenIfChanged(DirectoryReader)"/> to get a new reader that sees the
/// changes.</para>
/// </summary>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
public abstract bool IsCurrent();
/// <summary>
/// Expert: return the <see cref="Index.IndexCommit"/> that this reader has opened.
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract IndexCommit IndexCommit { get; }
}
}
| |
namespace Xilium.CefGlue
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Xilium.CefGlue.Interop;
/// <summary>
/// Class used to implement render process callbacks. The methods of this class
/// will be called on the render process main thread (TID_RENDERER) unless
/// otherwise indicated.
/// </summary>
public abstract unsafe partial class CefRenderProcessHandler
{
private void on_render_thread_created(cef_render_process_handler_t* self, cef_list_value_t* extra_info)
{
CheckSelf(self);
var mExtraInfo = CefListValue.FromNative(extra_info);
OnRenderThreadCreated(mExtraInfo);
mExtraInfo.Dispose();
}
/// <summary>
/// Called after the render process main thread has been created.
/// </summary>
protected virtual void OnRenderThreadCreated(CefListValue extraInfo)
{
}
private void on_web_kit_initialized(cef_render_process_handler_t* self)
{
CheckSelf(self);
OnWebKitInitialized();
}
/// <summary>
/// Called after WebKit has been initialized.
/// </summary>
protected virtual void OnWebKitInitialized()
{
}
private void on_browser_created(cef_render_process_handler_t* self, cef_browser_t* browser)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
OnBrowserCreated(m_browser);
}
/// <summary>
/// Called after a browser has been created. When browsing cross-origin a new
/// browser will be created before the old browser with the same identifier is
/// destroyed.
/// </summary>
protected virtual void OnBrowserCreated(CefBrowser browser)
{
}
private void on_browser_destroyed(cef_render_process_handler_t* self, cef_browser_t* browser)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
OnBrowserDestroyed(m_browser);
}
/// <summary>
/// Called before a browser is destroyed.
/// </summary>
protected virtual void OnBrowserDestroyed(CefBrowser browser)
{
}
private int on_before_navigation(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request, CefNavigationType navigation_type, int is_redirect)
{
CheckSelf(self);
var mBrowser = CefBrowser.FromNative(browser);
var mFrame = CefFrame.FromNative(frame);
var mRequest = CefRequest.FromNative(request);
var result = OnBeforeNavigation(mBrowser, mFrame, mRequest, navigation_type, is_redirect != 0);
return result ? 1 : 0;
}
/// <summary>
/// Called before browser navigation. Return true to cancel the navigation or
/// false to allow the navigation to proceed. The |request| object cannot be
/// modified in this callback.
/// </summary>
protected virtual bool OnBeforeNavigation(CefBrowser browser, CefFrame frame, CefRequest request, CefNavigationType navigationType, bool isRedirect)
{
return false;
}
private void on_context_created(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_v8context_t* context)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_context = CefV8Context.FromNative(context);
OnContextCreated(m_browser, m_frame, m_context);
}
/// <summary>
/// Called immediately after the V8 context for a frame has been created. To
/// retrieve the JavaScript 'window' object use the CefV8Context::GetGlobal()
/// method. V8 handles can only be accessed from the thread on which they are
/// created. A task runner for posting tasks on the associated thread can be
/// retrieved via the CefV8Context::GetTaskRunner() method.
/// </summary>
protected virtual void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context)
{
}
private void on_context_released(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_v8context_t* context)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_context = CefV8Context.FromNative(context);
OnContextReleased(m_browser, m_frame, m_context);
}
/// <summary>
/// Called immediately before the V8 context for a frame is released. No
/// references to the context should be kept after this method is called.
/// </summary>
protected virtual void OnContextReleased(CefBrowser browser, CefFrame frame, CefV8Context context)
{
}
private void on_uncaught_exception(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_v8context_t* context, cef_v8exception_t* exception, cef_v8stack_trace_t* stackTrace)
{
CheckSelf(self);
var mBrowser = CefBrowser.FromNative(browser);
var mFrame = CefFrame.FromNative(frame);
var mContext = CefV8Context.FromNative(context);
var mException = CefV8Exception.FromNative(exception);
var mStackTrace = CefV8StackTrace.FromNative(stackTrace);
OnUncaughtException(mBrowser, mFrame, mContext, mException, mStackTrace);
}
/// <summary>
/// Called for global uncaught exceptions in a frame. Execution of this
/// callback is disabled by default. To enable set
/// CefSettings.uncaught_exception_stack_size > 0.
/// </summary>
protected virtual void OnUncaughtException(CefBrowser browser, CefFrame frame, CefV8Context context, CefV8Exception exception, CefV8StackTrace stackTrace)
{
}
private void on_focused_node_changed(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_domnode_t* node)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_node = CefDomNode.FromNativeOrNull(node);
OnFocusedNodeChanged(m_browser, m_frame, m_node);
if (m_node != null) m_node.Dispose();
}
/// <summary>
/// Called when a new node in the the browser gets focus. The |node| value may
/// be empty if no specific node has gained focus. The node object passed to
/// this method represents a snapshot of the DOM at the time this method is
/// executed. DOM objects are only valid for the scope of this method. Do not
/// keep references to or attempt to access any DOM objects outside the scope
/// of this method.
/// </summary>
protected virtual void OnFocusedNodeChanged(CefBrowser browser, CefFrame frame, CefDomNode node)
{
}
private int on_process_message_received(cef_render_process_handler_t* self, cef_browser_t* browser, CefProcessId source_process, cef_process_message_t* message)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_message = CefProcessMessage.FromNative(message);
var result = OnProcessMessageReceived(m_browser, source_process, m_message);
m_message.Dispose();
return result ? 1 : 0;
}
/// <summary>
/// Called when a new message is received from a different process. Return true
/// if the message was handled or false otherwise. Do not keep a reference to
/// or attempt to access the message outside of this callback.
/// </summary>
protected virtual bool OnProcessMessageReceived(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage message)
{
return false;
}
}
}
| |
// DraggableOptions.cs
// Script#/Libraries/jQuery/UI
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace jQueryApi.UI.Interactions {
/// <summary>
/// Options used to initialize or customize Draggable.
/// </summary>
[ScriptImport]
[ScriptIgnoreNamespace]
[ScriptName("Object")]
public sealed class DraggableOptions {
public DraggableOptions() {
}
public DraggableOptions(params object[] nameValuePairs) {
}
/// <summary>
/// This event is triggered when the draggable is created.
/// </summary>
[ScriptField]
public jQueryEventHandler Create {
get {
return null;
}
set {
}
}
/// <summary>
/// This event is triggered when the mouse is moved during the dragging.
/// </summary>
[ScriptField]
public jQueryUIEventHandler<DragEvent> Drag {
get {
return null;
}
set {
}
}
/// <summary>
/// This event is triggered when dragging starts.
/// </summary>
[ScriptField]
public jQueryUIEventHandler<DragStartEvent> Start {
get {
return null;
}
set {
}
}
/// <summary>
/// This event is triggered when dragging stops.
/// </summary>
[ScriptField]
public jQueryUIEventHandler<DragStopEvent> Stop {
get {
return null;
}
set {
}
}
/// <summary>
/// If set to false, will prevent the <code>ui-draggable</code> class from being added. This may be desired as a performance optimization when calling <code>.draggable()</code> init on many hundreds of elements.
/// </summary>
[ScriptField]
public bool AddClasses {
get {
return false;
}
set {
}
}
/// <summary>
/// The element passed to or selected by the <code>appendTo</code> option will be used as the draggable helper's container during dragging. By default, the helper is appended to the same container as the draggable.
/// </summary>
[ScriptField]
public object AppendTo {
get {
return null;
}
set {
}
}
/// <summary>
/// Constrains dragging to either the horizontal (x) or vertical (y) axis. Possible values: 'x', 'y'.
/// </summary>
[ScriptField]
public string Axis {
get {
return null;
}
set {
}
}
/// <summary>
/// Prevents dragging from starting on specified elements.
/// </summary>
[ScriptField]
public string Cancel {
get {
return null;
}
set {
}
}
/// <summary>
/// Allows the draggable to be dropped onto the specified sortables. If this option is used (<code>helper</code> must be set to 'clone' in order to work flawlessly), a draggable can be dropped onto a sortable list and then becomes part of it.
/// </summary>
[ScriptField]
public string ConnectToSortable {
get {
return null;
}
set {
}
}
/// <summary>
/// Constrains dragging to within the bounds of the specified element or region. Possible string values: 'parent', 'document', 'window', [x1, y1, x2, y2].
/// </summary>
[ScriptField]
public object Containment {
get {
return null;
}
set {
}
}
/// <summary>
/// The css cursor during the drag operation.
/// </summary>
[ScriptField]
public string Cursor {
get {
return null;
}
set {
}
}
/// <summary>
/// Sets the offset of the dragging helper relative to the mouse cursor. Coordinates can be given as a hash using a combination of one or two keys: <code>{ top, left, right, bottom }</code>.
/// </summary>
[ScriptField]
public object CursorAt {
get {
return null;
}
set {
}
}
/// <summary>
/// Time in milliseconds after mousedown until dragging should start. This option can be used to prevent unwanted drags when clicking on an element.
/// </summary>
[ScriptField]
public int Delay {
get {
return 0;
}
set {
}
}
/// <summary>
/// Disables the draggable if set to true.
/// </summary>
[ScriptField]
public bool Disabled {
get {
return false;
}
set {
}
}
/// <summary>
/// Distance in pixels after mousedown the mouse must move before dragging should start. This option can be used to prevent unwanted drags when clicking on an element.
/// </summary>
[ScriptField]
public int Distance {
get {
return 0;
}
set {
}
}
/// <summary>
/// Snaps the dragging helper to a grid, every x and y pixels. Array values: [x, y]
/// </summary>
[ScriptField]
public Array Grid {
get {
return null;
}
set {
}
}
/// <summary>
/// If specified, restricts drag start click to the specified element(s).
/// </summary>
[ScriptField]
public object Handle {
get {
return null;
}
set {
}
}
/// <summary>
/// Allows for a helper element to be used for dragging display. Possible values: 'original', 'clone', Function. If a function is specified, it must return a DOMElement.
/// </summary>
[ScriptField]
public object Helper {
get {
return null;
}
set {
}
}
/// <summary>
/// Prevent iframes from capturing the mousemove events during a drag. Useful in combination with cursorAt, or in any case, if the mouse cursor is not over the helper. If set to true, transparent overlays will be placed over all iframes on the page. If a selector is supplied, the matched iframes will have an overlay placed over them.
/// </summary>
[ScriptField]
public object IframeFix {
get {
return null;
}
set {
}
}
/// <summary>
/// Opacity for the helper while being dragged.
/// </summary>
[ScriptField]
public int Opacity {
get {
return 0;
}
set {
}
}
/// <summary>
/// If set to true, all droppable positions are calculated on every mousemove. Caution: This solves issues on highly dynamic pages, but dramatically decreases performance.
/// </summary>
[ScriptField]
public bool RefreshPositions {
get {
return false;
}
set {
}
}
/// <summary>
/// If set to true, the element will return to its start position when dragging stops. Possible string values: 'valid', 'invalid'. If set to invalid, revert will only occur if the draggable has not been dropped on a droppable. For valid, it's the other way around.
/// </summary>
[ScriptField]
public object Revert {
get {
return null;
}
set {
}
}
/// <summary>
/// The duration of the revert animation, in milliseconds. Ignored if revert is false.
/// </summary>
[ScriptField]
public int RevertDuration {
get {
return 0;
}
set {
}
}
/// <summary>
/// Used to group sets of draggable and droppable items, in addition to droppable's accept option. A draggable with the same scope value as a droppable will be accepted by the droppable.
/// </summary>
[ScriptField]
public string Scope {
get {
return null;
}
set {
}
}
/// <summary>
/// If set to true, container auto-scrolls while dragging.
/// </summary>
[ScriptField]
public bool Scroll {
get {
return false;
}
set {
}
}
/// <summary>
/// Distance in pixels from the edge of the viewport after which the viewport should scroll. Distance is relative to pointer, not the draggable.
/// </summary>
[ScriptField]
public int ScrollSensitivity {
get {
return 0;
}
set {
}
}
/// <summary>
/// The speed at which the window should scroll once the mouse pointer gets within the <code>scrollSensitivity</code> distance.
/// </summary>
[ScriptField]
public int ScrollSpeed {
get {
return 0;
}
set {
}
}
/// <summary>
/// If set to a selector or to true (equivalent to '.ui-draggable'), the draggable will snap to the edges of the selected elements when near an edge of the element.
/// </summary>
[ScriptField]
public object Snap {
get {
return null;
}
set {
}
}
/// <summary>
/// Determines which edges of snap elements the draggable will snap to. Ignored if snap is false. Possible values: 'inner', 'outer', 'both'
/// </summary>
[ScriptField]
public string SnapMode {
get {
return null;
}
set {
}
}
/// <summary>
/// The distance in pixels from the snap element edges at which snapping should occur. Ignored if snap is false.
/// </summary>
[ScriptField]
public int SnapTolerance {
get {
return 0;
}
set {
}
}
/// <summary>
/// Controls the z-Index of the set of elements that match the selector, always brings to front the dragged item. Very useful in things like window managers.
/// </summary>
[ScriptField]
public string Stack {
get {
return null;
}
set {
}
}
/// <summary>
/// z-index for the helper while being dragged.
/// </summary>
[ScriptField]
public int ZIndex {
get {
return 0;
}
set {
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Run class - Text node in Flow content (text run)
//
//---------------------------------------------------------------------------
using MS.Internal; // Invariant.Assert
using System.Windows.Markup; // ContentProperty
using System.Windows.Controls;
using MS.Internal.Documents;
namespace System.Windows.Documents
{
/// <summary>
/// A terminal element in text flow hierarchy - contains a uniformatted run of unicode characters
/// </summary>
[ContentProperty("Text")]
public class Run : Inline
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
/// <summary>
/// Initializes an instance of Run class.
/// </summary>
public Run()
{
}
/// <summary>
/// Initializes an instance of Run class specifying its text content.
/// </summary>
/// <param name="text">
/// Text content assigned to the Run.
/// </param>
public Run(string text) : this(text, null)
{
}
/// <summary>
/// Creates a new Run instance.
/// </summary>
/// <param name="text">
/// Optional text content. May be null.
/// </param>
/// <param name="insertionPosition">
/// Optional position at which to insert the new Run. May
/// be null.
/// </param>
public Run(string text, TextPointer insertionPosition)
{
if (insertionPosition != null)
{
insertionPosition.TextContainer.BeginChange();
}
try
{
if (insertionPosition != null)
{
// This will throw InvalidOperationException if schema validity is violated.
insertionPosition.InsertInline(this);
}
if (text != null)
{
// No need to duplicate the string data in TextProperty here. TextContainer will
// set the property to a deferred reference.
this.ContentStart.InsertTextInRun(text);
}
}
finally
{
if (insertionPosition != null)
{
insertionPosition.TextContainer.EndChange();
}
}
}
#endregion Constructors
//-------------------------------------------------------------------
//
// Public Properties
//
//-------------------------------------------------------------------
#region Public Properties
/// <summary>
/// Dependency property backing Text.
/// </summary>
/// <remarks>
/// Note that when a TextRange that intersects with this Run gets modified (e.g. by editing
/// a selection in RichTextBox), we will get two changes to this property since we delete
/// and then insert when setting the content of a TextRange.
/// </remarks>
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(Run),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
new PropertyChangedCallback(OnTextPropertyChanged), new CoerceValueCallback(CoerceText)));
/// <summary>
/// The content spanned by this TextElement.
/// </summary>
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
#endregion Public Properties
//-------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Updates TextProperty when it is no longer in [....] with the backing store. Called by
/// TextContainer when a change affects the text contained by this Run.
/// </summary>
/// <remarks>
/// If a public TextChanged event is added, we need to raise the event only when the
/// outermost call to this function exits.
/// </remarks>
internal override void OnTextUpdated()
{
// If the value of Run.Text comes from a local value without a binding expression, we purposely allow the
// redundant roundtrip property set here. (SetValue on Run.TextProperty causes a TextContainer change,
// which causes this notification, and we set the property again.) We want to avoid keeping duplicate string
// data (both in the property system and in the backing store) when Run.Text is set, so we replace the
// original string property value with a deferred reference. This causes an extra property changed
// notification, but this is better than duplicating the data.
ValueSource textPropertySource = DependencyPropertyHelper.GetValueSource(this, TextProperty);
if (!_isInsideDeferredSet && (_changeEventNestingCount == 0 || (textPropertySource.BaseValueSource == BaseValueSource.Local
&& !textPropertySource.IsExpression)))
{
_changeEventNestingCount++;
_isInsideDeferredSet = true;
try
{
// Use a deferred reference as a performance optimization. Most of the time, no
// one will even be watching this property.
SetCurrentDeferredValue(TextProperty, new DeferredRunTextReference(this));
}
finally
{
_isInsideDeferredSet = false;
_changeEventNestingCount--;
}
}
}
/// <summary>
/// Increments the reference count that prevents reentrancy during TextContainer changes.
/// </summary>
/// <remarks>
/// Adding/removing elements from the logical tree will cause bindings on Run.Text to get
/// invalidated. We don't want to indirectly cause a TextContainer change when that happens.
/// </remarks>
internal override void BeforeLogicalTreeChange()
{
_changeEventNestingCount++;
}
/// <summary>
/// Decrements the reference count that prevents reentrancy during TextContainer changes.
/// </summary>
/// <remarks>
/// Adding/removing elements from the logical tree will cause bindings on Run.Text to get
/// invalidated. We don't want to indirectly cause a TextContainer change when that happens.
/// </remarks>
internal override void AfterLogicalTreeChange()
{
_changeEventNestingCount--;
}
//
// This property
// 1. Finds the correct initial size for the _effectiveValues store on the current DependencyObject
// 2. This is a performance optimization
//
internal override int EffectiveValuesInitialSize
{
get { return 13; }
}
/// <summary>
/// This method is used by TypeDescriptor to determine if this property should
/// be serialized.
/// </summary>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public bool ShouldSerializeText(XamlDesignerSerializationManager manager)
{
return manager != null && manager.XmlWriter == null;
}
#endregion Internal Methods
//-------------------------------------------------------------------
//
// Private Methods
//
//-------------------------------------------------------------------
#region Private Methods
/// <summary>
/// Changed handler for the Text property.
/// </summary>
/// <param name="d">The source of the event.</param>
/// <param name="e">A PropertyChangedEventArgs that contains the event data.</param>
/// <remarks>
/// We can't assume the value is a string here -- it may be a DeferredRunTextReference.
/// </remarks>
private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Run run = (Run)d;
// Return if this update was caused by a TextContainer change or a reentrant change.
if (run._changeEventNestingCount > 0)
{
return;
}
Invariant.Assert(!e.NewEntry.IsDeferredReference);
// CoerceText will have already converted null -> String.Empty, but our default
// CoerceValueCallback could be overridden by a derived class. So check again here.
string newText = (string)e.NewValue;
if (newText == null)
{
newText = String.Empty;
}
// Run.TextProperty has changed. Update the backing store.
run._changeEventNestingCount++;
try
{
TextContainer textContainer = run.TextContainer;
textContainer.BeginChange();
try
{
TextPointer contentStart = run.ContentStart;
if (!run.IsEmpty)
{
textContainer.DeleteContentInternal(contentStart, run.ContentEnd);
}
contentStart.InsertTextInRun(newText);
}
finally
{
textContainer.EndChange();
}
}
finally
{
run._changeEventNestingCount--;
}
// We need to clear undo stack if we are in a RichTextBox and the value comes from
// data binding or some other expression.
FlowDocument document = run.TextContainer.Parent as FlowDocument;
if (document != null)
{
RichTextBox rtb = document.Parent as RichTextBox;
if (rtb != null && run.HasExpression(run.LookupEntry(Run.TextProperty.GlobalIndex), Run.TextProperty))
{
UndoManager undoManager = rtb.TextEditor._GetUndoManager();
if (undoManager != null && undoManager.IsEnabled)
{
undoManager.Clear();
}
}
}
}
/// <summary>
/// Coercion callback for the Text property.
/// </summary>
/// <param name="d">The object that the property exists on.</param>
/// <param name="baseValue">The new value of the property, prior to any coercion attempt.</param>
/// <returns>The coerced value.</returns>
/// <remarks>
/// We can't assume the value is a string here -- it may be a DeferredRunTextReference.
/// </remarks>
private static object CoerceText(DependencyObject d, object baseValue)
{
if (baseValue == null)
{
baseValue = string.Empty;
}
return baseValue;
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// Number of nested TextContainer change notifications.
private int _changeEventNestingCount;
// If we are inside a property set caused by a backing store change.
private bool _isInsideDeferredSet;
#endregion Private Fields
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Globalization;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Subtext.Extensibility;
using Subtext.Extensibility.Interfaces;
using Subtext.Framework.Components;
using Subtext.Framework.Configuration;
using Subtext.Framework.Services;
using Subtext.Web.Admin.Pages;
using Subtext.Web.Properties;
using Subtext.Web.UI.Controls;
namespace Subtext.Web.Admin.Feedback
{
public partial class Default : ConfirmationPage
{
FeedbackStatusFlag _feedbackStatusFilter;
int _pageIndex;
FeedbackState _uiState;
public Default()
{
TabSectionId = "Feedback";
}
protected new FeedbackMaster Master
{
get { return base.Master as FeedbackMaster; }
}
public FeedbackState FeedbackState
{
get
{
return _uiState;
}
}
protected override void OnLoad(EventArgs e)
{
_feedbackStatusFilter = Master.FeedbackStatus;
_uiState = FeedbackState.GetUiState(_feedbackStatusFilter);
filterTypeDropDown.SelectedValue = Master.FeedbackType.ToString();
BindUserInterface();
if (!IsPostBack)
{
if (!Contact.ShowContactMessages)
{
filterTypeDropDown.Items.RemoveAt(3);
}
BindList();
}
base.OnLoad(e);
}
private void BindUserInterface()
{
headerLiteral.InnerText = _uiState.HeaderText;
btnEmpty.Visible = _uiState.Emptyable;
btnEmpty.ToolTip = _uiState.EmptyToolTip;
}
private void BindList()
{
noCommentsMessage.Visible = false;
if (Request.QueryString[Keys.QRYSTR_PAGEINDEX] != null)
{
_pageIndex = Convert.ToInt32(Request.QueryString[Keys.QRYSTR_PAGEINDEX]);
}
resultsPager.UrlFormat = "Default.aspx?pg={0}&status=" + _feedbackStatusFilter;
resultsPager.PageSize = Preferences.ListingItemCount;
resultsPager.PageIndex = _pageIndex;
// Deleted is a special case. If a feedback has the deleted
// bit set, it is in the trash no matter what other bits are set.
FeedbackStatusFlag excludeFilter = _feedbackStatusFilter == FeedbackStatusFlag.Deleted ? FeedbackStatusFlag.None : FeedbackStatusFlag.Deleted;
IPagedCollection<FeedbackItem> selectionList = Repository.GetPagedFeedback(_pageIndex
, resultsPager.PageSize
, _feedbackStatusFilter
, excludeFilter
, Master.FeedbackType);
if (selectionList.Count > 0)
{
resultsPager.Visible = true;
resultsPager.ItemCount = selectionList.MaxItems;
feedbackRepeater.DataSource = selectionList;
feedbackRepeater.ItemCreated += FeedbackItemDataBound;
feedbackRepeater.DataBind();
}
else
{
resultsPager.Visible = false;
noCommentsMessage.Text = _uiState.NoCommentsHtml;
feedbackRepeater.Controls.Clear();
noCommentsMessage.Visible = true;
btnEmpty.Visible = false;
}
Master.BindCounts();
}
void FeedbackItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Author = new FeedbackAuthorViewModel(e.Item.DataItem);
}
}
protected FeedbackAuthorViewModel Author
{
get;
private set;
}
/// <summary>
/// Gets the body of the feedback represented by the dataItem.
/// </summary>
/// <param name="dataItem"></param>
/// <returns></returns>
protected static string GetBody(object dataItem)
{
var feedbackItem = (FeedbackItem)dataItem;
if (feedbackItem.FeedbackType != FeedbackType.PingTrack)
{
return feedbackItem.Body;
}
return string.Format(CultureInfo.InvariantCulture,
"{0}<br /><a target=\"_blank\" title=\"{3}: {1}\" href=\"{2}\">Pingback/TrackBack</a>",
feedbackItem.Body, feedbackItem.Title, feedbackItem.SourceUrl, Resources.Label_View);
}
/// <summary>
/// Gets the title.
/// </summary>
/// <param name="dataItem">The data item.</param>
/// <returns></returns>
protected string GetTitle(object dataItem)
{
var feedbackItem = (FeedbackItem)dataItem;
string feedbackUrl = Url.FeedbackUrl(feedbackItem);
if (!String.IsNullOrEmpty(feedbackUrl))
{
return string.Format(@"<a href=""{0}"" title=""{0}"">{1}</a>", feedbackUrl, feedbackItem.Title);
}
return feedbackItem.Title;
}
protected void OnEmptyClick(object sender, EventArgs e)
{
Repository.Destroy(_feedbackStatusFilter);
BindList();
}
/// <summary>
/// Event handler for the approve button click event.
/// Approves the checked comments.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void OnApproveClick(object sender, EventArgs e)
{
if (ApplyActionToCheckedFeedback(Repository.Approve) == 0)
{
Messages.ShowMessage(Resources.Feedback_NothingToApprove, true);
return;
}
BindList();
}
/// <summary>
/// Event handler for the Delete button Click event. Deletes
/// the checked comments.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void OnDeleteClick(object sender, EventArgs e)
{
if (ApplyActionToCheckedFeedback((item, service) => Repository.Delete(item)) == 0)
{
Messages.ShowMessage(Resources.Feedback_NothingToDelete, true);
return;
}
BindList();
}
/// <summary>
/// Called when the confirm spam button is clicked.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void OnConfirmSpam(object sender, EventArgs e)
{
if (ApplyActionToCheckedFeedback(Repository.ConfirmSpam) == 0)
{
Messages.ShowMessage(Resources.Feedback_NothingFlaggedAsSpam, true);
return;
}
BindList();
}
private int ApplyActionToCheckedFeedback(Action<FeedbackItem, ICommentSpamService> action)
{
ICommentSpamService feedbackService = null;
if (Blog.FeedbackSpamServiceEnabled)
{
feedbackService = new AkismetSpamService(Config.CurrentBlog.FeedbackSpamServiceKey, Config.CurrentBlog,
null, Url);
}
int actionsApplied = 0;
foreach (RepeaterItem item in feedbackRepeater.Items)
{
// Get the checkbox from the item or the alternating item.
var deleteCheck = item.FindControl("chkDelete") as CheckBox ?? item.FindControl("chkDeleteAlt") as CheckBox;
if (deleteCheck != null && deleteCheck.Checked)
{
// Get the FeedbackId from the item or the alternating item.
var feedbackId = item.FindControl("FeedbackId") as HtmlInputHidden ?? item.FindControl("FeedbackIdAlt") as HtmlInputHidden;
int id;
if (feedbackId != null && int.TryParse(feedbackId.Value, out id))
{
FeedbackItem feedbackItem = Repository.Get(id);
if (feedbackItem != null)
{
actionsApplied++;
action(feedbackItem, feedbackService);
}
}
}
}
return actionsApplied;
}
}
}
| |
#pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
namespace Signum.Engine.PostgresCatalog;
[TableName("pg_catalog.pg_namespace")]
public class PgNamespace : IView
{
[ViewPrimaryKey]
public int oid;
public string nspname;
[AutoExpressionField]
public bool IsInternal() => As.Expression(() => nspname == "information_schema" || nspname.StartsWith("pg_"));
[AutoExpressionField]
public IQueryable<PgClass> Tables() =>
As.Expression(() => Database.View<PgClass>().Where(t => t.relnamespace == this.oid && t.relkind == RelKind.Table));
}
[TableName("pg_catalog.pg_class")]
public class PgClass : IView
{
[ViewPrimaryKey]
public int oid;
public string relname;
public int relnamespace;
public char relkind;
public int reltuples;
[AutoExpressionField]
public IQueryable<PgTrigger> Triggers() =>
As.Expression(() => Database.View<PgTrigger>().Where(t => t.tgrelid == this.oid));
[AutoExpressionField]
public IQueryable<PgIndex> Indices() =>
As.Expression(() => Database.View<PgIndex>().Where(t => t.indrelid == this.oid));
[AutoExpressionField]
public IQueryable<PgAttribute> Attributes() =>
As.Expression(() => Database.View<PgAttribute>().Where(t => t.attrelid == this.oid));
[AutoExpressionField]
public IQueryable<PgConstraint> Constraints() =>
As.Expression(() => Database.View<PgConstraint>().Where(t => t.conrelid == this.oid));
[AutoExpressionField]
public PgNamespace? Namespace() =>
As.Expression(() => Database.View<PgNamespace>().SingleOrDefault(t => t.oid == this.relnamespace));
}
public static class RelKind
{
public const char Table = 'r';
public const char Index = 'i';
public const char Sequence = 's';
public const char Toast = 't';
public const char View = 'v';
public const char MaterializedView = 'n';
public const char CompositeType = 'c';
public const char ForeignKey = 'f';
public const char PartitionTable = 'p';
public const char PartitionIndex = 'I';
}
[TableName("pg_catalog.pg_attribute")]
public class PgAttribute : IView
{
[ViewPrimaryKey]
public int attrelid;
[ViewPrimaryKey]
public string attname;
public int atttypid;
public int atttypmod;
public short attlen;
public short attnum;
public bool attnotnull;
public char attidentity;
[AutoExpressionField]
public PgType? Type() => As.Expression(() => Database.View<PgType>().SingleOrDefault(t => t.oid == this.atttypid));
[AutoExpressionField]
public PgAttributeDef? Default() => As.Expression(() => Database.View<PgAttributeDef>().SingleOrDefault(d => d.adrelid == this.attrelid && d.adnum == this.attnum));
}
[TableName("pg_catalog.pg_attrdef")]
public class PgAttributeDef : IView
{
[ViewPrimaryKey]
public int oid;
public int adrelid;
public short adnum;
public string /*not really*/ adbin;
}
[TableName("pg_catalog.pg_type")]
public class PgType : IView
{
[ViewPrimaryKey]
public int oid;
public string typname;
public int typnamespace;
public short typlen;
public bool typbyval;
}
[TableName("pg_catalog.pg_trigger")]
public class PgTrigger : IView
{
[ViewPrimaryKey]
public int oid;
public int tgrelid;
public string tgname;
public int tgfoid;
public byte[] tgargs;
[AutoExpressionField]
public PgProc? Proc() => As.Expression(() => Database.View<PgProc>().SingleOrDefault(p => p.oid == this.tgfoid));
}
[TableName("pg_catalog.pg_proc")]
public class PgProc : IView
{
[ViewPrimaryKey]
public int oid;
public int pronamespace;
[AutoExpressionField]
public PgNamespace? Namespace() => As.Expression(() => Database.View<PgNamespace>().SingleOrDefault(t => t.oid == this.pronamespace));
public string proname;
}
[TableName("pg_catalog.pg_index")]
public class PgIndex : IView
{
[ViewPrimaryKey]
public int indexrelid;
public int indrelid;
public short indnatts;
public short indnkeyatts;
public bool indisunique;
public bool indisprimary;
public short[] indkey;
public string? indexprs;
public string? indpred;
[AutoExpressionField]
public PgClass Class() =>
As.Expression(() => Database.View<PgClass>().Single(t => t.oid == this.indexrelid));
}
[TableName("pg_catalog.pg_constraint")]
public class PgConstraint : IView
{
[ViewPrimaryKey]
public int oid;
public string conname;
public int connamespace;
public char contype;
public int conrelid;
public short[] conkey;
public int confrelid;
public short[] confkey;
[AutoExpressionField]
public PgClass TargetTable() =>
As.Expression(() => Database.View<PgClass>().Single(t => t.oid == this.confrelid));
[AutoExpressionField]
public PgNamespace? Namespace() =>
As.Expression(() => Database.View<PgNamespace>().SingleOrDefault(t => t.oid == this.connamespace));
}
public static class ConstraintType
{
public const char Check = 'c';
public const char ForeignKey = 'f';
public const char PrimaryKey = 'p';
public const char Unique = 'u';
public const char Trigger= 't';
public const char Exclusion = 'x';
}
#pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.