context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using AIM.Web.Admin.Models.EntityModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using TrackableEntities;
using TrackableEntities.Client;
using System.ComponentModel.DataAnnotations;
namespace AIM.Web.Admin.Models.EntityModels
{
[JsonObject(IsReference = true)]
[DataContract(IsReference = true, Namespace = "http://schemas.datacontract.org/2004/07/TrackableEntities.Models")]
public partial class Education : ModelBase<Education>, IEquatable<Education>, ITrackable
{
[DataMember]
[Display(Name = "Education ID")]
public int EducationId
{
get { return _EducationId; }
set
{
if (Equals(value, _EducationId)) return;
_EducationId = value;
NotifyPropertyChanged(m => m.EducationId);
}
}
private int _EducationId;
[DataMember]
[Display(Name = "School Name")]
public string SchoolName
{
get { return _SchoolName; }
set
{
if (Equals(value, _SchoolName)) return;
_SchoolName = value;
NotifyPropertyChanged(m => m.SchoolName);
}
}
private string _SchoolName;
[DataMember]
[Display(Name = "Degree")]
public string Degree
{
get { return _Degree; }
set
{
if (Equals(value, _Degree)) return;
_Degree = value;
NotifyPropertyChanged(m => m.Degree);
}
}
private string _Degree;
[DataMember]
[Display(Name = "Graduated")]
public Nullable<System.DateTime> Graduated
{
get { return _Graduated; }
set
{
if (Equals(value, _Graduated)) return;
_Graduated = value;
NotifyPropertyChanged(m => m.Graduated);
}
}
private Nullable<System.DateTime> _Graduated;
[DataMember]
[Display(Name = "Years Attended")]
public string YearsAttended
{
get { return _YearsAttended; }
set
{
if (Equals(value, _YearsAttended)) return;
_YearsAttended = value;
NotifyPropertyChanged(m => m.YearsAttended);
}
}
private string _YearsAttended;
[DataMember]
[Display(Name = "Street")]
public string Street
{
get { return _Street; }
set
{
if (Equals(value, _Street)) return;
_Street = value;
NotifyPropertyChanged(m => m.Street);
}
}
private string _Street;
[DataMember]
[Display(Name = "Street 2")]
public string Street2
{
get { return _Street2; }
set
{
if (Equals(value, _Street2)) return;
_Street2 = value;
NotifyPropertyChanged(m => m.Street2);
}
}
private string _Street2;
[DataMember]
[Display(Name = "City")]
public string City
{
get { return _City; }
set
{
if (Equals(value, _City)) return;
_City = value;
NotifyPropertyChanged(m => m.City);
}
}
private string _City;
[DataMember]
[Display(Name = "State")]
public StateEnum? State
{
get { return _state; }
set
{
if (Equals(value, _state)) return;
_state = value;
NotifyPropertyChanged(m => m.State);
}
}
private StateEnum? _state;
[DataMember]
[Display(Name = "Zip Code")]
public string Zip
{
get { return _Zip; }
set
{
if (Equals(value, _Zip)) return;
_Zip = value;
NotifyPropertyChanged(m => m.Zip);
}
}
private string _Zip;
[DataMember]
[Display(Name = "Applicant ID")]
public int? ApplicantId
{
get { return _ApplicantId; }
set
{
if (Equals(value, _ApplicantId)) return;
_ApplicantId = value;
NotifyPropertyChanged(m => m.ApplicantId);
}
}
private int? _ApplicantId;
[DataMember]
[Display(Name = "Applicant")]
public Applicant Applicant
{
get { return _Applicant; }
set
{
if (Equals(value, _Applicant)) return;
_Applicant = value;
ApplicantChangeTracker = _Applicant == null ? null
: new ChangeTrackingCollection<Applicant> { _Applicant };
NotifyPropertyChanged(m => m.Applicant);
}
}
private Applicant _Applicant;
private ChangeTrackingCollection<Applicant> ApplicantChangeTracker { get; set; }
#region Change Tracking
[DataMember]
public TrackingState TrackingState { get; set; }
[DataMember]
public ICollection<string> ModifiedProperties { get; set; }
[JsonProperty, DataMember]
private Guid EntityIdentifier { get; set; }
#pragma warning disable 414
[JsonProperty, DataMember]
private Guid _entityIdentity = default(Guid);
#pragma warning restore 414
bool IEquatable<Education>.Equals(Education other)
{
if (EntityIdentifier != default(Guid))
return EntityIdentifier == other.EntityIdentifier;
return false;
}
#endregion Change Tracking
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// this file contains the data structures for the in memory database
// containing display and formatting information
using System.Collections.Generic;
using Microsoft.PowerShell.Commands;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
#region List View Definitions
/// <summary>
/// In line definition of a list control.
/// </summary>
internal sealed class ListControlBody : ControlBody
{
/// <summary>
/// Default list entry definition
/// It's mandatory.
/// </summary>
internal ListControlEntryDefinition defaultEntryDefinition = null;
/// <summary>
/// Optional list of list entry definition overrides. It can be empty if there are no overrides.
/// </summary>
internal List<ListControlEntryDefinition> optionalEntryList = new List<ListControlEntryDefinition>();
internal override ControlBase Copy()
{
ListControlBody result = new ListControlBody();
result.autosize = this.autosize;
if (defaultEntryDefinition != null)
{
result.defaultEntryDefinition = this.defaultEntryDefinition.Copy();
}
foreach (ListControlEntryDefinition lced in this.optionalEntryList)
{
result.optionalEntryList.Add(lced);
}
return result;
}
}
/// <summary>
/// Definition of the data to be displayed in a list entry.
/// </summary>
internal sealed class ListControlEntryDefinition
{
/// <summary>
/// Applicability clause
/// Only valid if not the default definition.
/// </summary>
internal AppliesTo appliesTo = null;
/// <summary>
/// Mandatory list of list view items.
/// It cannot be empty.
/// </summary>
internal List<ListControlItemDefinition> itemDefinitionList = new List<ListControlItemDefinition>();
/// <summary>
/// Returns a Shallow Copy of the current object.
/// </summary>
/// <returns></returns>
internal ListControlEntryDefinition Copy()
{
ListControlEntryDefinition result = new ListControlEntryDefinition();
result.appliesTo = this.appliesTo;
foreach (ListControlItemDefinition lcid in this.itemDefinitionList)
{
result.itemDefinitionList.Add(lcid);
}
return result;
}
}
/// <summary>
/// Cell definition inside a row.
/// </summary>
internal sealed class ListControlItemDefinition
{
/// <summary>
/// Optional expression for conditional binding.
/// </summary>
internal ExpressionToken conditionToken;
/// <summary>
/// Optional label
/// If not present, use the name of the property from the matching
/// mandatory item description.
/// </summary>
internal TextToken label = null;
/// <summary>
/// Format directive body telling how to format the cell
/// RULE: the body can only contain
/// * TextToken
/// * PropertyToken
/// * NOTHING (provide an empty cell)
/// </summary>
internal List<FormatToken> formatTokenList = new List<FormatToken>();
}
#endregion
}
namespace System.Management.Automation
{
/// <summary>
/// Defines a list control.
/// </summary>
public sealed class ListControl : PSControl
{
/// <summary>Entries in this list control</summary>
public List<ListControlEntry> Entries { get; internal set; }
/// <summary></summary>
public static ListControlBuilder Create(bool outOfBand = false)
{
var list = new ListControl { OutOfBand = false };
return new ListControlBuilder(list);
}
internal override void WriteToXml(FormatXmlWriter writer)
{
writer.WriteListControl(this);
}
/// <summary>Indicates if this control does not have any script blocks and is safe to export</summary>
internal override bool SafeForExport()
{
if (!base.SafeForExport())
return false;
foreach (var entry in Entries)
{
if (!entry.SafeForExport())
return false;
}
return true;
}
/// <summary>Initiate an instance of ListControl</summary>
public ListControl()
{
Entries = new List<ListControlEntry>();
}
/// <summary>To go from internal representation to external - for Get-FormatData</summary>
internal ListControl(ListControlBody listcontrolbody, ViewDefinition viewDefinition)
: this()
{
this.GroupBy = PSControlGroupBy.Get(viewDefinition.groupBy);
this.OutOfBand = viewDefinition.outOfBand;
Entries.Add(new ListControlEntry(listcontrolbody.defaultEntryDefinition));
foreach (ListControlEntryDefinition lced in listcontrolbody.optionalEntryList)
{
Entries.Add(new ListControlEntry(lced));
}
}
/// <summary>Public constructor for ListControl</summary>
public ListControl(IEnumerable<ListControlEntry> entries)
: this()
{
if (entries == null)
throw PSTraceSource.NewArgumentNullException("entries");
foreach (ListControlEntry entry in entries)
{
this.Entries.Add(entry);
}
}
internal override bool CompatibleWithOldPowerShell()
{
if (!base.CompatibleWithOldPowerShell())
return false;
foreach (var entry in Entries)
{
if (!entry.CompatibleWithOldPowerShell())
return false;
}
return true;
}
}
/// <summary>
/// Defines one entry in a list control.
/// </summary>
public sealed class ListControlEntry
{
/// <summary>List of items in the entry</summary>
public List<ListControlEntryItem> Items { get; internal set; }
/// <summary>List of typenames which select this entry, deprecated, use EntrySelectedBy</summary>
public List<string> SelectedBy
{
get
{
if (EntrySelectedBy == null)
EntrySelectedBy = new EntrySelectedBy { TypeNames = new List<string>() };
return EntrySelectedBy.TypeNames;
}
}
/// <summary>List of typenames and/or a script block which select this entry.</summary>
public EntrySelectedBy EntrySelectedBy { get; internal set; }
/// <summary>Initiate an instance of ListControlEntry</summary>
public ListControlEntry()
{
Items = new List<ListControlEntryItem>();
}
internal ListControlEntry(ListControlEntryDefinition entrydefn)
: this()
{
if (entrydefn.appliesTo != null)
{
EntrySelectedBy = EntrySelectedBy.Get(entrydefn.appliesTo.referenceList);
}
foreach (ListControlItemDefinition itemdefn in entrydefn.itemDefinitionList)
{
Items.Add(new ListControlEntryItem(itemdefn));
}
}
/// <summary>Public constructor for ListControlEntry</summary>
public ListControlEntry(IEnumerable<ListControlEntryItem> listItems)
: this()
{
if (listItems == null)
throw PSTraceSource.NewArgumentNullException("listItems");
foreach (ListControlEntryItem item in listItems)
{
this.Items.Add(item);
}
}
/// <summary>Public constructor for ListControlEntry</summary>
public ListControlEntry(IEnumerable<ListControlEntryItem> listItems, IEnumerable<string> selectedBy)
{
if (listItems == null)
throw PSTraceSource.NewArgumentNullException("listItems");
if (selectedBy == null)
throw PSTraceSource.NewArgumentNullException("selectedBy");
EntrySelectedBy = new EntrySelectedBy { TypeNames = new List<string>(selectedBy) };
foreach (ListControlEntryItem item in listItems)
{
this.Items.Add(item);
}
}
internal bool SafeForExport()
{
foreach (var item in Items)
{
if (!item.SafeForExport())
return false;
}
return EntrySelectedBy == null || EntrySelectedBy.SafeForExport();
}
internal bool CompatibleWithOldPowerShell()
{
foreach (var item in Items)
{
if (!item.CompatibleWithOldPowerShell())
return false;
}
return EntrySelectedBy == null || EntrySelectedBy.CompatibleWithOldPowerShell();
}
}
/// <summary>
/// Defines one row in a list control entry.
/// </summary>
public sealed class ListControlEntryItem
{
/// <summary>
/// Gets the label for this List Control Entry Item
/// If nothing is specified, then it uses the
/// property name.
/// </summary>
public string Label { get; internal set; }
/// <summary>Display entry</summary>
public DisplayEntry DisplayEntry { get; internal set; }
/// <summary/>
public DisplayEntry ItemSelectionCondition { get; internal set; }
/// <summary>Format string to apply</summary>
public string FormatString { get; internal set; }
internal ListControlEntryItem()
{
}
internal ListControlEntryItem(ListControlItemDefinition definition)
{
if (definition.label != null)
{
Label = definition.label.text;
}
FieldPropertyToken fpt = definition.formatTokenList[0] as FieldPropertyToken;
if (fpt != null)
{
if (fpt.fieldFormattingDirective.formatString != null)
{
FormatString = fpt.fieldFormattingDirective.formatString;
}
DisplayEntry = new DisplayEntry(fpt.expression);
if (definition.conditionToken != null)
{
ItemSelectionCondition = new DisplayEntry(definition.conditionToken);
}
}
}
/// <summary>
/// Public constructor for ListControlEntryItem
/// Label and Entry could be null.
/// </summary>
/// <param name="label"></param>
/// <param name="entry"></param>
public ListControlEntryItem(string label, DisplayEntry entry)
{
this.Label = label;
this.DisplayEntry = entry;
}
internal bool SafeForExport()
{
return DisplayEntry.SafeForExport() &&
(ItemSelectionCondition == null || ItemSelectionCondition.SafeForExport());
}
internal bool CompatibleWithOldPowerShell()
{
// Old versions of PowerShell know nothing about ItemSelectionCondition.
return ItemSelectionCondition == null;
}
}
/// <summary/>
public class ListEntryBuilder
{
private readonly ListControlBuilder _listBuilder;
internal ListControlEntry _listEntry;
internal ListEntryBuilder(ListControlBuilder listBuilder, ListControlEntry listEntry)
{
_listBuilder = listBuilder;
_listEntry = listEntry;
}
private ListEntryBuilder AddItem(string value, string label, DisplayEntryValueType kind, string format)
{
if (string.IsNullOrEmpty(value))
throw PSTraceSource.NewArgumentNullException("property");
_listEntry.Items.Add(new ListControlEntryItem
{
DisplayEntry = new DisplayEntry(value, kind),
Label = label,
FormatString = format
});
return this;
}
/// <summary></summary>
public ListEntryBuilder AddItemScriptBlock(string scriptBlock, string label = null, string format = null)
{
return AddItem(scriptBlock, label, DisplayEntryValueType.ScriptBlock, format);
}
/// <summary></summary>
public ListEntryBuilder AddItemProperty(string property, string label = null, string format = null)
{
return AddItem(property, label, DisplayEntryValueType.Property, format);
}
/// <summary></summary>
public ListControlBuilder EndEntry()
{
return _listBuilder;
}
}
/// <summary></summary>
public class ListControlBuilder
{
internal ListControl _list;
internal ListControlBuilder(ListControl list)
{
_list = list;
}
/// <summary>Group instances by the property name with an optional label.</summary>
public ListControlBuilder GroupByProperty(string property, CustomControl customControl = null, string label = null)
{
_list.GroupBy = new PSControlGroupBy
{
Expression = new DisplayEntry(property, DisplayEntryValueType.Property),
CustomControl = customControl,
Label = label
};
return this;
}
/// <summary>Group instances by the script block expression with an optional label.</summary>
public ListControlBuilder GroupByScriptBlock(string scriptBlock, CustomControl customControl = null, string label = null)
{
_list.GroupBy = new PSControlGroupBy
{
Expression = new DisplayEntry(scriptBlock, DisplayEntryValueType.ScriptBlock),
CustomControl = customControl,
Label = label
};
return this;
}
/// <summary></summary>
public ListEntryBuilder StartEntry(IEnumerable<string> entrySelectedByType = null, IEnumerable<DisplayEntry> entrySelectedByCondition = null)
{
var listEntry = new ListControlEntry
{
EntrySelectedBy = EntrySelectedBy.Get(entrySelectedByType, entrySelectedByCondition)
};
_list.Entries.Add(listEntry);
return new ListEntryBuilder(this, listEntry);
}
/// <summary></summary>
public ListControl EndList()
{
return _list;
}
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Agent.Worker;
using Moq;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker
{
public sealed class TaskManagerL0
{
private const string TestDataFolderName = "TestData";
private readonly CancellationTokenSource _ecTokenSource = new CancellationTokenSource();
private Mock<IJobServer> _jobServer;
private Mock<ITaskServer> _taskServer;
private Mock<IConfigurationStore> _configurationStore;
private Mock<IExecutionContext> _ec;
private TestHostContext _hc;
private TaskManager _taskManager;
private string _workFolder;
//Test the cancellation flow: interrupt download task via HostContext cancellation token.
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async void BubblesCancellation()
{
try
{
//Arrange
Setup();
var bingTask = new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = "Bing",
Version = "0.1.2",
Id = Guid.NewGuid()
}
};
var pingTask = new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = "Ping",
Version = "0.1.1",
Id = Guid.NewGuid()
}
};
var bingVersion = new TaskVersion(bingTask.Reference.Version);
var pingVersion = new TaskVersion(pingTask.Reference.Version);
_taskServer
.Setup(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), _ec.Object.CancellationToken))
.Returns((Guid taskId, TaskVersion taskVersion, CancellationToken token) =>
{
_ecTokenSource.Cancel();
return Task.FromResult<Stream>(GetZipStream());
});
var tasks = new List<Pipelines.TaskStep>(new Pipelines.TaskStep[] { bingTask, pingTask });
//Act
//should initiate a download with a mocked IJobServer, which sets a cancellation token and
//download task is expected to be in cancelled state
Task downloadTask = _taskManager.DownloadAsync(_ec.Object, tasks);
Task[] taskToWait = { downloadTask, Task.Delay(2000) };
//wait for the task to be cancelled to exit
await Task.WhenAny(taskToWait);
//Assert
//verify task completed in less than 2sec and it is in cancelled state
Assert.True(downloadTask.IsCompleted, $"{nameof(_taskManager.DownloadAsync)} timed out.");
Assert.True(!downloadTask.IsFaulted, downloadTask.Exception?.ToString());
Assert.True(downloadTask.IsCanceled);
//check if the task.json was not downloaded for ping and bing tasks
Assert.Equal(
0,
Directory.GetFiles(_hc.GetDirectory(WellKnownDirectory.Tasks), "*", SearchOption.AllDirectories).Length);
//assert download was invoked only once, because the first task cancelled the second task download
_taskServer
.Verify(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), _ec.Object.CancellationToken), Times.Once());
}
finally
{
Teardown();
}
}
//Test how exceptions are propagated to the caller.
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async void BubblesNetworkException()
{
try
{
// Arrange.
Setup();
var pingTask = new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = "Ping",
Version = "0.1.1",
Id = Guid.NewGuid()
}
};
var pingVersion = new TaskVersion(pingTask.Reference.Version);
Exception expectedException = new System.Net.Http.HttpRequestException("simulated network error");
_taskServer
.Setup(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), _ec.Object.CancellationToken))
.Returns((Guid taskId, TaskVersion taskVersion, CancellationToken token) =>
{
throw expectedException;
});
var tasks = new List<Pipelines.TaskStep>(new Pipelines.TaskStep[] { pingTask });
//Act
Exception actualException = null;
try
{
await _taskManager.DownloadAsync(_ec.Object, tasks);
}
catch (Exception ex)
{
actualException = ex;
}
//Assert
//verify task completed in less than 2sec and it is in failed state state
Assert.Equal(expectedException, actualException);
//see if the task.json was not downloaded
Assert.Equal(
0,
Directory.GetFiles(_hc.GetDirectory(WellKnownDirectory.Tasks), "*", SearchOption.AllDirectories).Length);
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void DeserializesPlatformSupportedHandlersOnly()
{
try
{
// Arrange.
Setup();
// Prepare the content.
const string Content = @"
{
""execution"": {
""Node"": { },
""Process"": { },
}
}";
// Write the task.json to disk.
Pipelines.TaskStep instance;
string directory;
CreateTask(jsonContent: Content, instance: out instance, directory: out directory);
// Act.
Definition definition = _taskManager.Load(instance);
// Assert.
Assert.NotNull(definition);
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Execution);
Assert.NotNull(definition.Data.Execution.Node);
#if OS_WINDOWS
Assert.NotNull(definition.Data.Execution.Process);
#else
Assert.Null(definition.Data.Execution.Process);
#endif
}
finally
{
Teardown();
}
}
//Test the normal flow, which downloads a few tasks and skips disabled, duplicate and cached tasks.
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async void DownloadsTasks()
{
try
{
//Arrange
Setup();
var bingGuid = Guid.NewGuid();
string bingTaskName = "Bing";
string bingVersion = "1.21.2";
var tasks = new List<Pipelines.TaskStep>
{
new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = bingTaskName,
Version = bingVersion,
Id = bingGuid
}
},
new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = bingTaskName,
Version = bingVersion,
Id = bingGuid
}
}
};
_taskServer
.Setup(x => x.GetTaskContentZipAsync(
bingGuid,
It.Is<TaskVersion>(y => string.Equals(y.ToString(), bingVersion, StringComparison.Ordinal)),
_ec.Object.CancellationToken))
.Returns(Task.FromResult<Stream>(GetZipStream()));
//Act
//first invocation will download and unzip the task from mocked IJobServer
await _taskManager.DownloadAsync(_ec.Object, tasks);
//second and third invocations should find the task in the cache and do nothing
await _taskManager.DownloadAsync(_ec.Object, tasks);
await _taskManager.DownloadAsync(_ec.Object, tasks);
//Assert
//see if the task.json was downloaded
string destDirectory = Path.Combine(
_hc.GetDirectory(WellKnownDirectory.Tasks),
$"{bingTaskName}_{bingGuid}",
bingVersion);
Assert.True(File.Exists(Path.Combine(destDirectory, Constants.Path.TaskJsonFile)));
//assert download has happened only once, because disabled, duplicate and cached tasks are not downloaded
_taskServer
.Verify(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), It.IsAny<CancellationToken>()), Times.Once());
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void DoesNotMatchPlatform()
{
try
{
// Arrange.
Setup();
#if !OS_WINDOWS
const string Platform = "windows";
#else
const string Platform = "nosuch"; // TODO: What to do here?
#endif
HandlerData data = new NodeHandlerData() { Platforms = new string[] { Platform } };
// Act/Assert.
Assert.False(data.PreferredOnCurrentPlatform());
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void LoadsDefinition()
{
try
{
// Arrange.
Setup();
// Prepare the task.json content.
const string Content = @"
{
""inputs"": [
{
""extraInputKey"": ""Extra input value"",
""name"": ""someFilePathInput"",
""type"": ""filePath"",
""label"": ""Some file path input label"",
""defaultValue"": ""Some default file path"",
""required"": true,
""helpMarkDown"": ""Some file path input markdown""
},
{
""name"": ""someStringInput"",
""type"": ""string"",
""label"": ""Some string input label"",
""defaultValue"": ""Some default string"",
""helpMarkDown"": ""Some string input markdown"",
""required"": false,
""groupName"": ""advanced""
}
],
""execution"": {
""Node"": {
""target"": ""Some Node target"",
""extraNodeArg"": ""Extra node arg value""
},
""Process"": {
""target"": ""Some process target"",
""argumentFormat"": ""Some process argument format"",
""workingDirectory"": ""Some process working directory"",
""extraProcessArg"": ""Some extra process arg"",
""platforms"": [
""windows""
]
},
""NoSuchHandler"": {
""target"": ""no such target""
}
},
""someExtraSection"": {
""someExtraKey"": ""Some extra value""
}
}";
// Write the task.json to disk.
Pipelines.TaskStep instance;
string directory;
CreateTask(jsonContent: Content, instance: out instance, directory: out directory);
// Act.
Definition definition = _taskManager.Load(instance);
// Assert.
Assert.NotNull(definition);
Assert.Equal(directory, definition.Directory);
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Assert.Equal(2, definition.Data.Inputs.Length);
Assert.Equal("someFilePathInput", definition.Data.Inputs[0].Name);
Assert.Equal("Some default file path", definition.Data.Inputs[0].DefaultValue);
Assert.Equal("someStringInput", definition.Data.Inputs[1].Name);
Assert.Equal("Some default string", definition.Data.Inputs[1].DefaultValue);
Assert.NotNull(definition.Data.Execution); // execution
#if OS_WINDOWS
// Process handler should only be deserialized on Windows.
Assert.Equal(2, definition.Data.Execution.All.Count);
#else
// Only Node handler should be deserialized on non-Windows.
Assert.Equal(1, definition.Data.Execution.All.Count);
#endif
// Node handler should always be deserialized.
Assert.NotNull(definition.Data.Execution.Node); // execution.Node
Assert.Equal(definition.Data.Execution.Node, definition.Data.Execution.All[0]);
Assert.Equal("Some Node target", definition.Data.Execution.Node.Target);
#if OS_WINDOWS
// Process handler should only be deserialized on Windows.
Assert.NotNull(definition.Data.Execution.Process); // execution.Process
Assert.Equal(definition.Data.Execution.Process, definition.Data.Execution.All[1]);
Assert.Equal("Some process argument format", definition.Data.Execution.Process.ArgumentFormat);
Assert.NotNull(definition.Data.Execution.Process.Platforms);
Assert.Equal(1, definition.Data.Execution.Process.Platforms.Length);
Assert.Equal("windows", definition.Data.Execution.Process.Platforms[0]);
Assert.Equal("Some process target", definition.Data.Execution.Process.Target);
Assert.Equal("Some process working directory", definition.Data.Execution.Process.WorkingDirectory);
#endif
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void MatchesPlatform()
{
try
{
// Arrange.
Setup();
#if OS_WINDOWS
const string Platform = "WiNdOwS";
#else
// TODO: What to do here?
const string Platform = "";
if (string.IsNullOrEmpty(Platform))
{
return;
}
#endif
HandlerData data = new NodeHandlerData() { Platforms = new[] { Platform } };
// Act/Assert.
Assert.True(data.PreferredOnCurrentPlatform());
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void ReplacesMacros()
{
try
{
// Arrange.
Setup();
const string Directory = "Some directory";
Definition definition = new Definition() { Directory = Directory };
NodeHandlerData node = new NodeHandlerData()
{
Target = @"$(CuRrEnTdIrEcToRy)\Some node target",
WorkingDirectory = @"$(CuRrEnTdIrEcToRy)\Some node working directory",
};
ProcessHandlerData process = new ProcessHandlerData()
{
ArgumentFormat = @"$(CuRrEnTdIrEcToRy)\Some process argument format",
Target = @"$(CuRrEnTdIrEcToRy)\Some process target",
WorkingDirectory = @"$(CuRrEnTdIrEcToRy)\Some process working directory",
};
// Act.
node.ReplaceMacros(_hc, definition);
process.ReplaceMacros(_hc, definition);
// Assert.
Assert.Equal($@"{Directory}\Some node target", node.Target);
Assert.Equal($@"{Directory}\Some node working directory", node.WorkingDirectory);
Assert.Equal($@"{Directory}\Some process argument format", process.ArgumentFormat);
Assert.Equal($@"{Directory}\Some process target", process.Target);
Assert.Equal($@"{Directory}\Some process working directory", process.WorkingDirectory);
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void ReplacesMacrosAndPreventsInfiniteRecursion()
{
try
{
// Arrange.
Setup();
string directory = "$(currentdirectory)$(currentdirectory)";
Definition definition = new Definition() { Directory = directory };
NodeHandlerData node = new NodeHandlerData()
{
Target = @"$(currentDirectory)\Some node target",
};
// Act.
node.ReplaceMacros(_hc, definition);
// Assert.
Assert.Equal($@"{directory}\Some node target", node.Target);
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void ReplacesMultipleMacroInstances()
{
try
{
// Arrange.
Setup();
const string Directory = "Some directory";
Definition definition = new Definition() { Directory = Directory };
NodeHandlerData node = new NodeHandlerData()
{
Target = @"$(CuRrEnTdIrEcToRy)$(CuRrEnTdIrEcToRy)\Some node target",
};
// Act.
node.ReplaceMacros(_hc, definition);
// Assert.
Assert.Equal($@"{Directory}{Directory}\Some node target", node.Target);
}
finally
{
Teardown();
}
}
private void CreateTask(string jsonContent, out Pipelines.TaskStep instance, out string directory)
{
const string TaskName = "SomeTask";
const string TaskVersion = "1.2.3";
Guid taskGuid = Guid.NewGuid();
directory = Path.Combine(_workFolder, Constants.Path.TasksDirectory, $"{TaskName}_{taskGuid}", TaskVersion);
string file = Path.Combine(directory, Constants.Path.TaskJsonFile);
Directory.CreateDirectory(Path.GetDirectoryName(file));
File.WriteAllText(file, jsonContent);
instance = new Pipelines.TaskStep()
{
Reference = new Pipelines.TaskStepDefinitionReference()
{
Id = taskGuid,
Name = TaskName,
Version = TaskVersion,
}
};
}
private Stream GetZipStream()
{
// Locate the test data folder containing the task.json.
string sourceFolder = Path.Combine(TestUtil.GetTestDataPath(), nameof(TaskManagerL0));
Assert.True(Directory.Exists(sourceFolder), $"Directory does not exist: {sourceFolder}");
Assert.True(File.Exists(Path.Combine(sourceFolder, Constants.Path.TaskJsonFile)));
// Create the zip file under the work folder so it gets cleaned up.
string zipFile = Path.Combine(
_workFolder,
$"{Guid.NewGuid()}.zip");
Directory.CreateDirectory(_workFolder);
ZipFile.CreateFromDirectory(sourceFolder, zipFile, CompressionLevel.Fastest, includeBaseDirectory: false);
return new FileStream(zipFile, FileMode.Open);
}
private void Setup([CallerMemberName] string name = "")
{
// Mocks.
_jobServer = new Mock<IJobServer>();
_taskServer = new Mock<ITaskServer>();
_ec = new Mock<IExecutionContext>();
_ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token);
// Test host context.
_hc = new TestHostContext(this, name);
// Random work folder.
_workFolder = _hc.GetDirectory(WellKnownDirectory.Work);
_hc.SetSingleton<IJobServer>(_jobServer.Object);
_hc.SetSingleton<ITaskServer>(_taskServer.Object);
_configurationStore = new Mock<IConfigurationStore>();
_configurationStore
.Setup(x => x.GetSettings())
.Returns(
new AgentSettings
{
WorkFolder = _workFolder
});
_hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
// Instance to test.
_taskManager = new TaskManager();
_taskManager.Initialize(_hc);
}
private void Teardown()
{
_hc?.Dispose();
if (!string.IsNullOrEmpty(_workFolder) && Directory.Exists(_workFolder))
{
Directory.Delete(_workFolder, recursive: true);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Globalization.Tests
{
public class CharUnicodeInfoGetUnicodeCategoryTests
{
[Fact]
public void GetUnicodeCategory()
{
foreach (CharUnicodeInfoTestCase testCase in CharUnicodeInfoTestData.TestCases)
{
if (testCase.Utf32CodeValue.Length == 1)
{
// Test the char overload for a single char
GetUnicodeCategory(testCase.Utf32CodeValue[0], testCase.GeneralCategory);
}
// Test the string overload for a surrogate pair or a single char
GetUnicodeCategory(testCase.Utf32CodeValue, new UnicodeCategory[] { testCase.GeneralCategory });
}
}
[Theory]
[InlineData('\uFFFF', UnicodeCategory.OtherNotAssigned)]
public void GetUnicodeCategory(char ch, UnicodeCategory expected)
{
UnicodeCategory actual = CharUnicodeInfo.GetUnicodeCategory(ch);
Assert.True(actual == expected, ErrorMessage(ch, expected, actual));
}
[Theory]
[InlineData("aA1!", new UnicodeCategory[] { UnicodeCategory.LowercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.OtherPunctuation })]
[InlineData("\uD808\uDF6C", new UnicodeCategory[] { UnicodeCategory.OtherLetter, UnicodeCategory.Surrogate })]
[InlineData("a\uD808\uDF6Ca", new UnicodeCategory[] { UnicodeCategory.LowercaseLetter, UnicodeCategory.OtherLetter, UnicodeCategory.Surrogate, UnicodeCategory.LowercaseLetter })]
public void GetUnicodeCategory(string s, UnicodeCategory[] expected)
{
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], CharUnicodeInfo.GetUnicodeCategory(s, i));
}
}
[Fact]
public void GetUnicodeCategory_String_InvalidSurrogatePairs()
{
// High, high surrogate pair
GetUnicodeCategory("\uD808\uD808", new UnicodeCategory[] { UnicodeCategory.Surrogate, UnicodeCategory.Surrogate });
// Low, low surrogate pair
GetUnicodeCategory("\uDF6C\uDF6C", new UnicodeCategory[] { UnicodeCategory.Surrogate, UnicodeCategory.Surrogate });
// Low, high surrogate pair
GetUnicodeCategory("\uDF6C\uD808", new UnicodeCategory[] { UnicodeCategory.Surrogate, UnicodeCategory.Surrogate });
}
[Fact]
public void GetUnicodeCategory_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => CharUnicodeInfo.GetUnicodeCategory(null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetUnicodeCategory("abc", -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetUnicodeCategory("abc", 3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetUnicodeCategory("", 0));
}
[Fact]
public void GetNumericValue()
{
foreach (CharUnicodeInfoTestCase testCase in CharUnicodeInfoTestData.TestCases)
{
if (testCase.Utf32CodeValue.Length == 1)
{
// Test the char overload for a single char
GetNumericValue(testCase.Utf32CodeValue[0], testCase.NumericValue);
}
// Test the string overload for a surrogate pair
GetNumericValue(testCase.Utf32CodeValue, new double[] { testCase.NumericValue });
}
}
[Theory]
[InlineData("\uFFFF", -1)]
public void GetNumericValue(char ch, double expected)
{
double actual = CharUnicodeInfo.GetNumericValue(ch);
Assert.True(expected == actual, ErrorMessage(ch, expected, actual));
}
[Theory]
[MemberData(nameof(s_GetNumericValueData))]
public void GetNumericValue(string s, double[] expected)
{
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], CharUnicodeInfo.GetNumericValue(s, i));
}
}
public static readonly object[][] s_GetNumericValueData =
{
new object[] {"aA1!", new double[] { -1, -1, 1, -1 }},
// Numeric surrogate (CUNEIFORM NUMERIC SIGN FIVE BAN2 VARIANT FORM)
new object[] {"\uD809\uDC55", new double[] { 5, -1 }},
new object[] {"a\uD809\uDC55a", new double[] { -1, 5, -1 , -1 }},
// Numeric surrogate (CUNEIFORM NUMERIC SIGN FIVE BAN2 VARIANT FORM)
new object[] {"\uD808\uDF6C", new double[] { -1, -1 }},
new object[] {"a\uD808\uDF6Ca", new double[] { -1, -1, -1, -1 }},
};
[Fact]
public void GetNumericValue_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => CharUnicodeInfo.GetNumericValue(null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetNumericValue("abc", -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetNumericValue("abc", 3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetNumericValue("", 0));
}
private static string ErrorMessage(char ch, object expected, object actual)
{
return $"CodeValue: {((int)ch).ToString("X")}; Expected: {expected}; Actual: {actual}";
}
public static string s_numericsCodepoints =
"\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037\u0038\u0039" +
"\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669" +
"\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9" +
"\u07c0\u07c1\u07c2\u07c3\u07c4\u07c5\u07c6\u07c7\u07c8\u07c9" +
"\u0966\u0967\u0968\u0969\u096a\u096b\u096c\u096d\u096e\u096f" +
"\u09e6\u09e7\u09e8\u09e9\u09ea\u09eb\u09ec\u09ed\u09ee\u09ef" +
"\u0a66\u0a67\u0a68\u0a69\u0a6a\u0a6b\u0a6c\u0a6d\u0a6e\u0a6f" +
"\u0ae6\u0ae7\u0ae8\u0ae9\u0aea\u0aeb\u0aec\u0aed\u0aee\u0aef" +
"\u0b66\u0b67\u0b68\u0b69\u0b6a\u0b6b\u0b6c\u0b6d\u0b6e\u0b6f" +
"\u0be6\u0be7\u0be8\u0be9\u0bea\u0beb\u0bec\u0bed\u0bee\u0bef" +
"\u0c66\u0c67\u0c68\u0c69\u0c6a\u0c6b\u0c6c\u0c6d\u0c6e\u0c6f" +
"\u0ce6\u0ce7\u0ce8\u0ce9\u0cea\u0ceb\u0cec\u0ced\u0cee\u0cef" +
"\u0d66\u0d67\u0d68\u0d69\u0d6a\u0d6b\u0d6c\u0d6d\u0d6e\u0d6f" +
"\u0e50\u0e51\u0e52\u0e53\u0e54\u0e55\u0e56\u0e57\u0e58\u0e59" +
"\u0ed0\u0ed1\u0ed2\u0ed3\u0ed4\u0ed5\u0ed6\u0ed7\u0ed8\u0ed9" +
"\u0f20\u0f21\u0f22\u0f23\u0f24\u0f25\u0f26\u0f27\u0f28\u0f29" +
"\u1040\u1041\u1042\u1043\u1044\u1045\u1046\u1047\u1048\u1049" +
"\u1090\u1091\u1092\u1093\u1094\u1095\u1096\u1097\u1098\u1099" +
"\u17e0\u17e1\u17e2\u17e3\u17e4\u17e5\u17e6\u17e7\u17e8\u17e9" +
"\u1810\u1811\u1812\u1813\u1814\u1815\u1816\u1817\u1818\u1819" +
"\u1946\u1947\u1948\u1949\u194a\u194b\u194c\u194d\u194e\u194f" +
"\u19d0\u19d1\u19d2\u19d3\u19d4\u19d5\u19d6\u19d7\u19d8\u19d9" +
"\u1a80\u1a81\u1a82\u1a83\u1a84\u1a85\u1a86\u1a87\u1a88\u1a89" +
"\u1a90\u1a91\u1a92\u1a93\u1a94\u1a95\u1a96\u1a97\u1a98\u1a99" +
"\u1b50\u1b51\u1b52\u1b53\u1b54\u1b55\u1b56\u1b57\u1b58\u1b59" +
"\u1bb0\u1bb1\u1bb2\u1bb3\u1bb4\u1bb5\u1bb6\u1bb7\u1bb8\u1bb9" +
"\u1c40\u1c41\u1c42\u1c43\u1c44\u1c45\u1c46\u1c47\u1c48\u1c49" +
"\u1c50\u1c51\u1c52\u1c53\u1c54\u1c55\u1c56\u1c57\u1c58\u1c59" +
"\ua620\ua621\ua622\ua623\ua624\ua625\ua626\ua627\ua628\ua629" +
"\ua8d0\ua8d1\ua8d2\ua8d3\ua8d4\ua8d5\ua8d6\ua8d7\ua8d8\ua8d9" +
"\ua900\ua901\ua902\ua903\ua904\ua905\ua906\ua907\ua908\ua909" +
"\ua9d0\ua9d1\ua9d2\ua9d3\ua9d4\ua9d5\ua9d6\ua9d7\ua9d8\ua9d9" +
"\uaa50\uaa51\uaa52\uaa53\uaa54\uaa55\uaa56\uaa57\uaa58\uaa59" +
"\uabf0\uabf1\uabf2\uabf3\uabf4\uabf5\uabf6\uabf7\uabf8\uabf9" +
"\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19";
public static string s_nonNumericsCodepoints =
"abcdefghijklmnopqrstuvwxyz" +
"\u1369\u136a\u136b\u136c\u136d\u136e\u136f\u1370\u1371\u1372\u1373" +
"\u1374\u1375\u1376\u1377\u1378\u1379\u137a\u137b\u137c\u137d";
public static string s_numericNonDecimalCodepoints =
"\u00b2\u00b3\u00b9\u1369\u136a\u136b\u136c\u136d\u136e\u136f\u1370" +
"\u1371\u19da\u2070\u2074\u2075\u2076\u2077\u2078\u2079\u2080\u2081" +
"\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u2460\u2461\u2462" +
"\u2463\u2464\u2465\u2466\u2467\u2468\u2474\u2475\u2476\u2477\u2478" +
"\u2479\u247a\u247b\u247c\u2488\u2489\u248a\u248b\u248c\u248d\u248e" +
"\u248f\u2490\u24ea\u24f5\u24f6\u24f7\u24f8\u24f9\u24fa\u24fb\u24fc" +
"\u24fd\u24ff\u2776\u2777\u2778\u2779\u277a\u277b\u277c\u277d\u277e" +
"\u2780\u2781\u2782\u2783\u2784\u2785\u2786\u2787\u2788\u278a\u278b" +
"\u278c\u278d\u278e\u278f\u2790\u2791\u2792";
public static int [] s_numericNonDecimalValues = new int []
{
2, 3, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 4, 5, 6, 7, 8, 9, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7,
8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1,
2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6,
7, 8, 9
};
[Fact]
public static void DigitsDecimalTest()
{
Assert.Equal(s_numericsCodepoints.Length % 10, 0);
for (int i=0; i < s_numericsCodepoints.Length; i+= 10)
{
for (int j=0; j < 10; j++)
{
Assert.Equal(j, CharUnicodeInfo.GetDecimalDigitValue(s_numericsCodepoints[i + j]));
Assert.Equal(j, CharUnicodeInfo.GetDecimalDigitValue(s_numericsCodepoints, i + j));
}
}
}
[Fact]
public static void NegativeDigitsTest()
{
for (int i=0; i < s_nonNumericsCodepoints.Length; i++)
{
Assert.Equal(-1, CharUnicodeInfo.GetDecimalDigitValue(s_nonNumericsCodepoints[i]));
Assert.Equal(-1, CharUnicodeInfo.GetDecimalDigitValue(s_nonNumericsCodepoints, i));
}
}
[Fact]
public static void DigitsTest()
{
Assert.Equal(s_numericNonDecimalCodepoints.Length, s_numericNonDecimalValues.Length);
for (int i=0; i < s_numericNonDecimalCodepoints.Length; i++)
{
Assert.Equal(s_numericNonDecimalValues[i], CharUnicodeInfo.GetDigitValue(s_numericNonDecimalCodepoints[i]));
Assert.Equal(s_numericNonDecimalValues[i], CharUnicodeInfo.GetDigitValue(s_numericNonDecimalCodepoints, i));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Remoting.Messaging;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost.Extensions;
using Orleans.TestingHost.Utils;
namespace Orleans.TestingHost
{
/// <summary>
/// Important note: <see cref="TestingSiloHost"/> will be eventually deprectated. It is recommended that you use <see cref="TestCluster"/> instead.
/// A host class for local testing with Orleans using in-process silos.
///
/// Runs a Primary and Secondary silo in seperate app domains, and client in the main app domain.
/// Additional silos can also be started in-process if required for particular test cases.
/// </summary>
/// <remarks>
/// Make sure the following files are included in any test projects that use <c>TestingSiloHost</c>,
/// and ensure "Copy if Newer" is set to ensure the config files are included in the test set.
/// <code>
/// OrleansConfigurationForTesting.xml
/// ClientConfigurationForTesting.xml
/// </code>
/// Also make sure that your test project references your test grains and test grain interfaces
/// projects, and has CopyLocal=True set on those references [which should be the default].
/// </remarks>
public class TestingSiloHost
{
/// <summary> Single instance of TestingSiloHost </summary>
public static TestingSiloHost Instance { get; set; }
/// <summary> Primary silo handle </summary>
public SiloHandle Primary { get; private set; }
/// <summary> List of handles to the secondary silos </summary>
public SiloHandle Secondary { get; private set; }
private readonly List<SiloHandle> additionalSilos = new List<SiloHandle>();
private readonly Dictionary<string, GeneratedAssembly> additionalAssemblies = new Dictionary<string, GeneratedAssembly>();
private TestingSiloOptions siloInitOptions { get; set; }
private TestingClientOptions clientInitOptions { get; set; }
/// <summary> Get or set the client configuration/// </summary>
public ClientConfiguration ClientConfig { get; private set; }
/// <summary> Get or set the global configuration </summary>
public GlobalConfiguration Globals { get; private set; }
/// <summary> The deploymentId value to use in the cluster </summary>
public string DeploymentId = null;
/// <summary> The prefix to use in the deploymentId </summary>
public string DeploymentIdPrefix = null;
/// <summary> Base port number for silos in cluster </summary>
public const int BasePort = 22222;
/// <summary> Base port number for the gateway silos </summary>
public const int ProxyBasePort = 40000;
/// <summary> Number of silos in the cluster </summary>
private static int InstanceCounter = 0;
/// <summary> GrainFactory to use in the tests </summary>
public IGrainFactory GrainFactory { get; private set; }
/// <summary> Get the logger to use in tests </summary>
protected Logger logger
{
get { return GrainClient.Logger; }
}
/// <summary>
/// Start the default Primary and Secondary test silos, plus client in-process,
/// using the default silo config options.
/// </summary>
public TestingSiloHost()
: this(false)
{
}
/// <summary>
/// Start the default Primary and Secondary test silos, plus client in-process,
/// ensuring that fresh silos are started if they were already running.
/// </summary>
public TestingSiloHost(bool startFreshOrleans)
: this(new TestingSiloOptions { StartFreshOrleans = startFreshOrleans }, new TestingClientOptions())
{
}
/// <summary>
/// Start the default Primary and Secondary test silos, plus client in-process,
/// using the specified silo config options.
/// </summary>
public TestingSiloHost(TestingSiloOptions siloOptions)
: this(siloOptions, new TestingClientOptions())
{
}
/// <summary>
/// Start the default Primary and Secondary test silos, plus client in-process,
/// using the specified silo and client config options.
/// </summary>
public TestingSiloHost(TestingSiloOptions siloOptions, TestingClientOptions clientOptions)
{
DeployTestingSiloHost(siloOptions, clientOptions);
}
private TestingSiloHost(string ignored)
{
}
/// <summary> Create a new TestingSiloHost without initialization </summary>
public static TestingSiloHost CreateUninitialized()
{
return new TestingSiloHost("Uninitialized");
}
private void DeployTestingSiloHost(TestingSiloOptions siloOptions, TestingClientOptions clientOptions)
{
siloInitOptions = siloOptions;
clientInitOptions = clientOptions;
AppDomain.CurrentDomain.UnhandledException += ReportUnobservedException;
InitializeLogWriter();
try
{
string startMsg = "----------------------------- STARTING NEW UNIT TEST SILO HOST: " + GetType().FullName + " -------------------------------------";
WriteLog(startMsg);
InitializeAsync(siloOptions, clientOptions).Wait();
UninitializeLogWriter();
Instance = this;
}
catch (TimeoutException te)
{
FlushLogToConsole();
throw new TimeoutException("Timeout during test initialization", te);
}
catch (Exception ex)
{
StopAllSilos();
Exception baseExc = ex.GetBaseException();
FlushLogToConsole();
if (baseExc is TimeoutException)
{
throw new TimeoutException("Timeout during test initialization", ex);
}
// IMPORTANT:
// Do NOT re-throw the original exception here, also not as an internal exception inside AggregateException
// Due to the way MS tests works, if the original exception is an Orleans exception,
// it's assembly might not be loaded yet in this phase of the test.
// As a result, we will get "MSTest: Unit Test Adapter threw exception: Type is not resolved for member XXX"
// and will loose the original exception. This makes debugging tests super hard!
// The root cause has to do with us initializing our tests from Test constructor and not from TestInitialize method.
// More details: http://dobrzanski.net/2010/09/20/mstest-unit-test-adapter-threw-exception-type-is-not-resolved-for-member/
throw new Exception(
string.Format("Exception during test initialization: {0}",
LogFormatter.PrintException(baseExc)));
}
}
/// <summary>
/// Stop the TestingSilo and restart it.
/// </summary>
/// <param name="siloOptions">Cluster options to use.</param>
/// <param name="clientOptions">Client optin to use.</param>
public void RedeployTestingSiloHost(TestingSiloOptions siloOptions = null, TestingClientOptions clientOptions = null)
{
StopAllSilos();
DeployTestingSiloHost(siloOptions ?? new TestingSiloOptions(), clientOptions ?? new TestingClientOptions());
}
/// <summary>
/// Get the list of current active silos.
/// </summary>
/// <returns>List of current silos.</returns>
public IEnumerable<SiloHandle> GetActiveSilos()
{
WriteLog("GetActiveSilos: Primary={0} Secondary={1} + {2} Additional={3}",
Primary, Secondary, additionalSilos.Count, Orleans.Runtime.Utils.EnumerableToString(additionalSilos));
if (null != Primary && Primary.IsActive == true) yield return Primary;
if (null != Secondary && Secondary.IsActive == true) yield return Secondary;
if (additionalSilos.Count > 0)
foreach (var s in additionalSilos)
if (null != s && s.IsActive == true)
yield return s;
}
/// <summary>
/// Find the silo handle for the specified silo address.
/// </summary>
/// <param name="siloAddress">Silo address to be found.</param>
/// <returns>SiloHandle of the appropriate silo, or <c>null</c> if not found.</returns>
public SiloHandle GetSiloForAddress(SiloAddress siloAddress)
{
List<SiloHandle> activeSilos = GetActiveSilos().ToList();
var ret = activeSilos.Where(s => s.SiloAddress.Equals(siloAddress)).FirstOrDefault();
return ret;
}
/// <summary>
/// Wait for the silo liveness sub-system to detect and act on any recent cluster membership changes.
/// </summary>
/// <param name="didKill">Whether recent membership changes we done by graceful Stop.</param>
public async Task WaitForLivenessToStabilizeAsync(bool didKill = false)
{
TimeSpan stabilizationTime = GetLivenessStabilizationTime(Globals, didKill);
WriteLog(Environment.NewLine + Environment.NewLine + "WaitForLivenessToStabilize is about to sleep for {0}", stabilizationTime);
await Task.Delay(stabilizationTime);
WriteLog("WaitForLivenessToStabilize is done sleeping");
}
private static TimeSpan GetLivenessStabilizationTime(GlobalConfiguration global, bool didKill = false)
{
TimeSpan stabilizationTime = TimeSpan.Zero;
if (didKill)
{
// in case of hard kill (kill and not Stop), we should give silos time to detect failures first.
stabilizationTime = TestingUtils.Multiply(global.ProbeTimeout, global.NumMissedProbesLimit);
}
if (global.UseLivenessGossip)
{
stabilizationTime += TimeSpan.FromSeconds(5);
}
else
{
stabilizationTime += TestingUtils.Multiply(global.TableRefreshTimeout, 2);
}
return stabilizationTime;
}
/// <summary>
/// Start an additional silo, so that it joins the existing cluster with the default Primary and Secondary silos.
/// </summary>
/// <returns>SiloHandle for the newly started silo.</returns>
public SiloHandle StartAdditionalSilo()
{
SiloHandle instance = StartOrleansSilo(
Silo.SiloType.Secondary,
siloInitOptions,
InstanceCounter++);
additionalSilos.Add(instance);
return instance;
}
/// <summary>
/// Start a number of additional silo, so that they join the existing cluster with the default Primary and Secondary silos.
/// </summary>
/// <param name="numExtraSilos">Number of additional silos to start.</param>
/// <returns>List of SiloHandles for the newly started silos.</returns>
public List<SiloHandle> StartAdditionalSilos(int numExtraSilos)
{
List<SiloHandle> instances = new List<SiloHandle>();
for (int i = 0; i < numExtraSilos; i++)
{
SiloHandle instance = StartAdditionalSilo();
instances.Add(instance);
}
return instances;
}
/// <summary>
/// Stop any additional silos, not including the default Primary and Secondary silos.
/// </summary>
public void StopAdditionalSilos()
{
foreach (SiloHandle instance in additionalSilos)
{
StopSilo(instance);
}
additionalSilos.Clear();
}
/// <summary>
/// Restart all additional silos, not including the default Primary and Secondary silos.
/// </summary>
public void RestartAllAdditionalSilos()
{
if (additionalSilos.Count == 0) return;
var restartedAdditionalSilos = new List<SiloHandle>();
foreach (SiloHandle instance in additionalSilos.ToArray())
{
if (instance.IsActive == true)
{
var restartedSilo = RestartSilo(instance);
restartedAdditionalSilos.Add(restartedSilo);
}
}
}
/// <summary>
/// Stop the default Primary and Secondary silos.
/// </summary>
public void StopDefaultSilos()
{
try
{
GrainClient.Uninitialize();
}
catch (Exception exc) { WriteLog("Exception Uninitializing grain client: {0}", exc); }
StopSilo(Secondary);
StopSilo(Primary);
Secondary = null;
Primary = null;
InstanceCounter = 0;
DeploymentId = null;
}
/// <summary>
/// Stop all current silos.
/// </summary>
public void StopAllSilos()
{
StopAdditionalSilos();
StopDefaultSilos();
AppDomain.CurrentDomain.UnhandledException -= ReportUnobservedException;
Instance = null;
}
/// <summary>
/// Stop all current silos if running.
/// </summary>
public static void StopAllSilosIfRunning()
{
var host = Instance;
if (host != null)
{
host.StopAllSilos();
}
}
/// <summary>
/// Restart the default Primary and Secondary silos.
/// </summary>
public void RestartDefaultSilos(bool pickNewDeploymentId=false)
{
TestingSiloOptions primarySiloOptions = Primary != null ? this.siloInitOptions : null;
TestingSiloOptions secondarySiloOptions = Secondary != null ? this.siloInitOptions : null;
// Restart as the same deployment
string deploymentId = DeploymentId;
StopDefaultSilos();
DeploymentId = pickNewDeploymentId ? null : deploymentId;
if (primarySiloOptions != null)
{
primarySiloOptions.PickNewDeploymentId = pickNewDeploymentId;
Primary = StartOrleansSilo(Silo.SiloType.Primary, primarySiloOptions, InstanceCounter++);
}
if (secondarySiloOptions != null)
{
secondarySiloOptions.PickNewDeploymentId = pickNewDeploymentId;
Secondary = StartOrleansSilo(Silo.SiloType.Secondary, secondarySiloOptions, InstanceCounter++);
}
WaitForLivenessToStabilizeAsync().Wait();
GrainClient.Initialize(this.ClientConfig);
}
/// <summary>
/// Start a Secondary silo with a given instanceCounter
/// (allows to set the port number as before or new, depending on the scenario).
/// </summary>
public void StartSecondarySilo(TestingSiloOptions secondarySiloOptions, int instanceCounter)
{
secondarySiloOptions.PickNewDeploymentId = false;
Secondary = StartOrleansSilo(Silo.SiloType.Secondary, secondarySiloOptions, instanceCounter);
}
/// <summary>
/// Do a semi-graceful Stop of the specified silo.
/// </summary>
/// <param name="instance">Silo to be stopped.</param>
public void StopSilo(SiloHandle instance)
{
if (instance != null)
{
StopOrleansSilo(instance, true);
}
}
/// <summary>
/// Do an immediate Kill of the specified silo.
/// </summary>
/// <param name="instance">Silo to be killed.</param>
public void KillSilo(SiloHandle instance)
{
if (instance != null)
{
// do NOT stop, just kill directly, to simulate crash.
StopOrleansSilo(instance, false);
}
}
/// <summary>
/// Performs a hard kill on client. Client will not cleanup reasources.
/// </summary>
public void KillClient()
{
GrainClient.HardKill();
}
/// <summary>
/// Do a Stop or Kill of the specified silo, followed by a restart.
/// </summary>
/// <param name="instance">Silo to be restarted.</param>
public SiloHandle RestartSilo(SiloHandle instance)
{
if (instance != null)
{
var options = this.siloInitOptions;
var type = instance.Type;
StopOrleansSilo(instance, true);
var newInstance = StartOrleansSilo(type, options, InstanceCounter++);
if (Primary == instance)
{
Primary = newInstance;
}
else if (Secondary == instance)
{
Secondary = newInstance;
}
else
{
additionalSilos.Remove(instance);
additionalSilos.Add(newInstance);
}
return newInstance;
}
return null;
}
/// <summary> Modify the cluster configurations to the test environment </summary>
/// <param name="config">The cluster configuration to modify</param>
/// <param name="options">the TestingSiloOptions to modify</param>
public static void AdjustForTest(ClusterConfiguration config, TestingSiloOptions options)
{
if (options.AdjustConfig != null) {
options.AdjustConfig(config);
}
config.AdjustForTestEnvironment(TestClusterOptions.FallbackOptions.DefaultExtendedConfiguration["DataConnectionString"]);
}
/// <summary> Modify the ClientConfiguration to the test environment </summary>
/// <param name="config">The client configuration to modify</param>
/// <param name="options">the TestingClientOptions to modify</param>
public static void AdjustForTest(ClientConfiguration config, TestingClientOptions options)
{
if (options.AdjustConfig != null) {
options.AdjustConfig(config);
}
config.AdjustForTestEnvironment(TestClusterOptions.FallbackOptions.DefaultExtendedConfiguration["DataConnectionString"]);
}
#region Private methods
/// <summary> Initialize the grain client </summary>
public void InitializeClient()
{
InitializeClient(clientInitOptions, siloInitOptions.LargeMessageWarningThreshold);
}
private void InitializeClient(TestingClientOptions clientOptions, int largeMessageWarningThreshold)
{
if (!GrainClient.IsInitialized)
{
WriteLog("Initializing Grain Client");
ClientConfiguration clientConfig;
try
{
if (clientOptions.ClientConfigFile != null)
{
clientConfig = ClientConfiguration.LoadFromFile(clientOptions.ClientConfigFile.FullName);
}
else
{
clientConfig = ClientConfiguration.StandardLoad();
}
}
catch (FileNotFoundException)
{
if (clientOptions.ClientConfigFile != null
&& !string.Equals(clientOptions.ClientConfigFile.Name, TestingClientOptions.DEFAULT_CLIENT_CONFIG_FILE, StringComparison.InvariantCultureIgnoreCase))
{
// if the user is not using the defaults, then throw because the file was legitimally not found
throw;
}
clientConfig = ClientConfiguration.LocalhostSilo();
}
if (clientOptions.ProxiedGateway && clientOptions.Gateways != null)
{
clientConfig.Gateways = clientOptions.Gateways;
if (clientOptions.PreferedGatewayIndex >= 0)
clientConfig.PreferedGatewayIndex = clientOptions.PreferedGatewayIndex;
}
if (clientOptions.PropagateActivityId)
{
clientConfig.PropagateActivityId = clientOptions.PropagateActivityId;
}
if (!String.IsNullOrEmpty(DeploymentId))
{
clientConfig.DeploymentId = DeploymentId;
}
if (Debugger.IsAttached)
{
// Test is running inside debugger - Make timeout ~= infinite
clientConfig.ResponseTimeout = TimeSpan.FromMilliseconds(1000000);
}
else if (clientOptions.ResponseTimeout > TimeSpan.Zero)
{
clientConfig.ResponseTimeout = clientOptions.ResponseTimeout;
}
if (largeMessageWarningThreshold > 0)
{
clientConfig.LargeMessageWarningThreshold = largeMessageWarningThreshold;
}
AdjustForTest(clientConfig, clientOptions);
this.ClientConfig = clientConfig;
GrainClient.Initialize(clientConfig);
GrainFactory = GrainClient.GrainFactory;
}
}
private async Task InitializeAsync(TestingSiloOptions options, TestingClientOptions clientOptions)
{
bool doStartPrimary = false;
bool doStartSecondary = false;
if (options.StartFreshOrleans)
{
// the previous test was !startFresh, so we need to cleanup after it.
StopAllSilosIfRunning();
if (options.StartPrimary)
{
doStartPrimary = true;
}
if (options.StartSecondary)
{
doStartSecondary = true;
}
}
else
{
var runningInstance = Instance;
if (runningInstance != null)
{
this.Primary = runningInstance.Primary;
this.Secondary = runningInstance.Secondary;
this.Globals = runningInstance.Globals;
this.ClientConfig = runningInstance.ClientConfig;
this.DeploymentId = runningInstance.DeploymentId;
this.DeploymentIdPrefix = runningInstance.DeploymentIdPrefix;
this.GrainFactory = runningInstance.GrainFactory;
this.additionalSilos.AddRange(runningInstance.additionalSilos);
foreach (var additionalAssembly in runningInstance.additionalAssemblies)
{
this.additionalAssemblies.Add(additionalAssembly.Key, additionalAssembly.Value);
}
}
if (options.StartPrimary && Primary == null)
{
// first time.
doStartPrimary = true;
}
if (options.StartSecondary && Secondary == null)
{
doStartSecondary = true;
}
}
if (options.PickNewDeploymentId && String.IsNullOrEmpty(DeploymentId))
{
DeploymentId = GetDeploymentId();
}
if (options.ParallelStart)
{
var handles = new List<Task<SiloHandle>>();
if (doStartPrimary)
{
int instanceCount = InstanceCounter++;
handles.Add(Task.Run(() => StartOrleansSilo(Silo.SiloType.Primary, options, instanceCount)));
}
if (doStartSecondary)
{
int instanceCount = InstanceCounter++;
handles.Add(Task.Run(() => StartOrleansSilo(Silo.SiloType.Secondary, options, instanceCount)));
}
await Task.WhenAll(handles.ToArray());
if (doStartPrimary)
{
Primary = await handles[0];
}
if (doStartSecondary)
{
Secondary = await handles[1];
}
}
else
{
if (doStartPrimary)
{
Primary = StartOrleansSilo(Silo.SiloType.Primary, options, InstanceCounter++);
}
if (doStartSecondary)
{
Secondary = StartOrleansSilo(Silo.SiloType.Secondary, options, InstanceCounter++);
}
}
WriteLog("Done initializing cluster");
if (!GrainClient.IsInitialized && options.StartClient)
{
InitializeClient(clientOptions, options.LargeMessageWarningThreshold);
}
}
private SiloHandle StartOrleansSilo(Silo.SiloType type, TestingSiloOptions options, int instanceCount, AppDomain shared = null)
{
return StartOrleansSilo(this, type, options, instanceCount, shared);
}
/// <summary>
/// Start a new silo in the target cluster
/// </summary>
/// <param name="host">The target cluster</param>
/// <param name="type">The type of the silo to deploy</param>
/// <param name="options">The options to use for the silo</param>
/// <param name="instanceCount">The instance count of the silo</param>
/// <param name="shared">The shared AppDomain to use</param>
/// <returns>A handle to the deployed silo</returns>
public static SiloHandle StartOrleansSilo(TestingSiloHost host, Silo.SiloType type, TestingSiloOptions options, int instanceCount, AppDomain shared = null)
{
if (host == null) throw new ArgumentNullException("host");
// Load initial config settings, then apply some overrides below.
ClusterConfiguration config = new ClusterConfiguration();
try
{
if (options.SiloConfigFile == null)
{
config.StandardLoad();
}
else
{
config.LoadFromFile(options.SiloConfigFile.FullName);
}
}
catch (FileNotFoundException)
{
if (options.SiloConfigFile != null
&& !string.Equals(options.SiloConfigFile.Name, TestingSiloOptions.DEFAULT_SILO_CONFIG_FILE, StringComparison.InvariantCultureIgnoreCase))
{
// if the user is not using the defaults, then throw because the file was legitimally not found
throw;
}
config = ClusterConfiguration.LocalhostPrimarySilo();
config.AddMemoryStorageProvider("Default");
config.AddMemoryStorageProvider("MemoryStore");
}
int basePort = options.BasePort < 0 ? BasePort : options.BasePort;
if (config.Globals.SeedNodes.Count > 0 && options.BasePort < 0)
{
config.PrimaryNode = config.Globals.SeedNodes[0];
}
else
{
config.PrimaryNode = new IPEndPoint(IPAddress.Loopback, basePort);
}
config.Globals.SeedNodes.Clear();
config.Globals.SeedNodes.Add(config.PrimaryNode);
if (!String.IsNullOrEmpty(host.DeploymentId))
{
config.Globals.DeploymentId = host.DeploymentId;
}
config.Defaults.PropagateActivityId = options.PropagateActivityId;
if (options.LargeMessageWarningThreshold > 0)
{
config.Defaults.LargeMessageWarningThreshold = options.LargeMessageWarningThreshold;
}
config.Globals.LivenessType = options.LivenessType;
config.Globals.ReminderServiceType = options.ReminderServiceType;
if (!String.IsNullOrEmpty(options.DataConnectionString))
{
config.Globals.DataConnectionString = options.DataConnectionString;
}
host.Globals = config.Globals;
string siloName;
switch (type)
{
case Silo.SiloType.Primary:
siloName = "Primary";
break;
default:
siloName = "Secondary_" + instanceCount.ToString(CultureInfo.InvariantCulture);
break;
}
NodeConfiguration nodeConfig = config.GetOrCreateNodeConfigurationForSilo(siloName);
nodeConfig.HostNameOrIPAddress = "loopback";
nodeConfig.Port = basePort + instanceCount;
nodeConfig.DefaultTraceLevel = config.Defaults.DefaultTraceLevel;
nodeConfig.PropagateActivityId = config.Defaults.PropagateActivityId;
nodeConfig.BulkMessageLimit = config.Defaults.BulkMessageLimit;
int? gatewayport = null;
if (nodeConfig.ProxyGatewayEndpoint != null && nodeConfig.ProxyGatewayEndpoint.Address != null)
{
gatewayport = (options.ProxyBasePort < 0 ? ProxyBasePort : options.ProxyBasePort) + instanceCount;
nodeConfig.ProxyGatewayEndpoint = new IPEndPoint(nodeConfig.ProxyGatewayEndpoint.Address, gatewayport.Value);
}
config.Globals.ExpectedClusterSize = 2;
config.Overrides[siloName] = nodeConfig;
AdjustForTest(config, options);
WriteLog("Starting a new silo in app domain {0} with config {1}", siloName, config.ToString(siloName));
return AppDomainSiloHandle.Create(siloName, type, config, nodeConfig, host.additionalAssemblies);
}
private void StopOrleansSilo(SiloHandle instance, bool stopGracefully)
{
instance.StopSilo(stopGracefully);
instance.Dispose();
}
private string GetDeploymentId()
{
if (!String.IsNullOrEmpty(DeploymentId))
{
return DeploymentId;
}
string prefix = DeploymentIdPrefix ?? "testdepid-";
int randomSuffix = ThreadSafeRandom.Next(1000);
DateTime now = DateTime.UtcNow;
string DateTimeFormat = "yyyy-MM-dd-hh-mm-ss-fff";
string depId = String.Format("{0}{1}-{2}",
prefix, now.ToString(DateTimeFormat, CultureInfo.InvariantCulture), randomSuffix);
return depId;
}
#endregion
#region Tracing helper functions. Will eventually go away entirely
private const string LogWriterContextKey = "TestingSiloHost_LogWriter";
private static void ReportUnobservedException(object sender, UnhandledExceptionEventArgs eventArgs)
{
Exception exception = (Exception)eventArgs.ExceptionObject;
WriteLog("Unobserved exception: {0}", exception);
}
private static void WriteLog(string format, params object[] args)
{
var trace = CallContext.LogicalGetData(LogWriterContextKey);
if (trace != null)
{
CallContext.LogicalSetData(LogWriterContextKey, string.Format(format, args) + Environment.NewLine);
}
}
private static void FlushLogToConsole()
{
var trace = CallContext.LogicalGetData(LogWriterContextKey);
if (trace != null)
{
Console.WriteLine(trace);
UninitializeLogWriter();
}
}
private static void WriteLog(object value)
{
WriteLog(value.ToString());
}
private static void InitializeLogWriter()
{
CallContext.LogicalSetData(LogWriterContextKey, string.Empty);
}
private static void UninitializeLogWriter()
{
CallContext.FreeNamedDataSlot(LogWriterContextKey);
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Cluster
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.Metadata;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Compute;
using Apache.Ignite.Core.Impl.Events;
using Apache.Ignite.Core.Impl.Messaging;
using Apache.Ignite.Core.Impl.Services;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Messaging;
using Apache.Ignite.Core.Services;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Ignite projection implementation.
/// </summary>
internal class ClusterGroupImpl : PlatformTarget, IClusterGroupEx
{
/** Attribute: platform. */
private const string AttrPlatform = "org.apache.ignite.platform";
/** Platform. */
private const string Platform = "dotnet";
/** Initial topver; invalid from Java perspective, so update will be triggered when this value is met. */
private const int TopVerInit = 0;
/** */
private const int OpAllMetadata = 1;
/** */
private const int OpForAttribute = 2;
/** */
private const int OpForCache = 3;
/** */
private const int OpForClient = 4;
/** */
private const int OpForData = 5;
/** */
private const int OpForHost = 6;
/** */
private const int OpForNodeIds = 7;
/** */
private const int OpMetadata = 8;
/** */
private const int OpMetrics = 9;
/** */
private const int OpMetricsFiltered = 10;
/** */
private const int OpNodeMetrics = 11;
/** */
private const int OpNodes = 12;
/** */
private const int OpPingNode = 13;
/** */
private const int OpTopology = 14;
/** Initial Ignite instance. */
private readonly Ignite _ignite;
/** Predicate. */
private readonly Func<IClusterNode, bool> _pred;
/** Topology version. */
private long _topVer = TopVerInit;
/** Nodes for the given topology version. */
private volatile IList<IClusterNode> _nodes;
/** Processor. */
private readonly IUnmanagedTarget _proc;
/** Compute. */
private readonly Lazy<Compute> _comp;
/** Messaging. */
private readonly Lazy<Messaging> _msg;
/** Events. */
private readonly Lazy<Events> _events;
/** Services. */
private readonly Lazy<IServices> _services;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="proc">Processor.</param>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="ignite">Grid.</param>
/// <param name="pred">Predicate.</param>
[SuppressMessage("Microsoft.Performance", "CA1805:DoNotInitializeUnnecessarily")]
public ClusterGroupImpl(IUnmanagedTarget proc, IUnmanagedTarget target, Marshaller marsh,
Ignite ignite, Func<IClusterNode, bool> pred)
: base(target, marsh)
{
_proc = proc;
_ignite = ignite;
_pred = pred;
_comp = new Lazy<Compute>(() =>
new Compute(new ComputeImpl(UU.ProcessorCompute(proc, target), marsh, this, false)));
_msg = new Lazy<Messaging>(() => new Messaging(UU.ProcessorMessage(proc, target), marsh, this));
_events = new Lazy<Events>(() => new Events(UU.ProcessorEvents(proc, target), marsh, this));
_services = new Lazy<IServices>(() =>
new Services(UU.ProcessorServices(proc, target), marsh, this, false, false));
}
/** <inheritDoc /> */
public IIgnite Ignite
{
get { return _ignite; }
}
/** <inheritDoc /> */
public ICompute GetCompute()
{
return _comp.Value;
}
/** <inheritDoc /> */
public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes)
{
IgniteArgumentCheck.NotNull(nodes, "nodes");
return ForNodeIds0(nodes, node => node.Id);
}
/** <inheritDoc /> */
public IClusterGroup ForNodes(params IClusterNode[] nodes)
{
IgniteArgumentCheck.NotNull(nodes, "nodes");
return ForNodeIds0(nodes, node => node.Id);
}
/** <inheritDoc /> */
public IClusterGroup ForNodeIds(IEnumerable<Guid> ids)
{
IgniteArgumentCheck.NotNull(ids, "ids");
return ForNodeIds0(ids, null);
}
/** <inheritDoc /> */
public IClusterGroup ForNodeIds(params Guid[] ids)
{
IgniteArgumentCheck.NotNull(ids, "ids");
return ForNodeIds0(ids, null);
}
/// <summary>
/// Internal routine to get projection for specific node IDs.
/// </summary>
/// <param name="items">Items.</param>
/// <param name="func">Function to transform item to Guid (optional).</param>
/// <returns></returns>
private IClusterGroup ForNodeIds0<T>(IEnumerable<T> items, Func<T, Guid> func)
{
Debug.Assert(items != null);
IUnmanagedTarget prj = DoProjetionOutOp(OpForNodeIds, writer =>
{
WriteEnumerable(writer, items, func);
});
return GetClusterGroup(prj);
}
/** <inheritDoc /> */
public IClusterGroup ForPredicate(Func<IClusterNode, bool> p)
{
var newPred = _pred == null ? p : node => _pred(node) && p(node);
return new ClusterGroupImpl(_proc, Target, Marshaller, _ignite, newPred);
}
/** <inheritDoc /> */
public IClusterGroup ForAttribute(string name, string val)
{
IgniteArgumentCheck.NotNull(name, "name");
IUnmanagedTarget prj = DoProjetionOutOp(OpForAttribute, writer =>
{
writer.WriteString(name);
writer.WriteString(val);
});
return GetClusterGroup(prj);
}
/// <summary>
/// Creates projection with a specified op.
/// </summary>
/// <param name="name">Cache name to include into projection.</param>
/// <param name="op">Operation id.</param>
/// <returns>
/// Projection over nodes that have specified cache running.
/// </returns>
private IClusterGroup ForCacheNodes(string name, int op)
{
IUnmanagedTarget prj = DoProjetionOutOp(op, writer =>
{
writer.WriteString(name);
});
return GetClusterGroup(prj);
}
/** <inheritDoc /> */
public IClusterGroup ForCacheNodes(string name)
{
return ForCacheNodes(name, OpForCache);
}
/** <inheritDoc /> */
public IClusterGroup ForDataNodes(string name)
{
return ForCacheNodes(name, OpForData);
}
/** <inheritDoc /> */
public IClusterGroup ForClientNodes(string name)
{
return ForCacheNodes(name, OpForClient);
}
/** <inheritDoc /> */
public IClusterGroup ForRemotes()
{
return GetClusterGroup(UU.ProjectionForRemotes(Target));
}
/** <inheritDoc /> */
public IClusterGroup ForHost(IClusterNode node)
{
IgniteArgumentCheck.NotNull(node, "node");
IUnmanagedTarget prj = DoProjetionOutOp(OpForHost, writer =>
{
writer.WriteGuid(node.Id);
});
return GetClusterGroup(prj);
}
/** <inheritDoc /> */
public IClusterGroup ForRandom()
{
return GetClusterGroup(UU.ProjectionForRandom(Target));
}
/** <inheritDoc /> */
public IClusterGroup ForOldest()
{
return GetClusterGroup(UU.ProjectionForOldest(Target));
}
/** <inheritDoc /> */
public IClusterGroup ForYoungest()
{
return GetClusterGroup(UU.ProjectionForYoungest(Target));
}
/** <inheritDoc /> */
public IClusterGroup ForDotNet()
{
return ForAttribute(AttrPlatform, Platform);
}
/** <inheritDoc /> */
public ICollection<IClusterNode> GetNodes()
{
return RefreshNodes();
}
/** <inheritDoc /> */
public IClusterNode GetNode(Guid id)
{
return GetNodes().FirstOrDefault(node => node.Id == id);
}
/** <inheritDoc /> */
public IClusterNode GetNode()
{
return GetNodes().FirstOrDefault();
}
/** <inheritDoc /> */
public IClusterMetrics GetMetrics()
{
if (_pred == null)
{
return DoInOp(OpMetrics, stream =>
{
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
return reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null;
});
}
return DoOutInOp(OpMetricsFiltered, writer =>
{
WriteEnumerable(writer, GetNodes().Select(node => node.Id));
}, stream =>
{
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
return reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null;
});
}
/** <inheritDoc /> */
public IMessaging GetMessaging()
{
return _msg.Value;
}
/** <inheritDoc /> */
public IEvents GetEvents()
{
return _events.Value;
}
/** <inheritDoc /> */
public IServices GetServices()
{
return _services.Value;
}
/// <summary>
/// Pings a remote node.
/// </summary>
/// <param name="nodeId">ID of a node to ping.</param>
/// <returns>True if node for a given ID is alive, false otherwise.</returns>
internal bool PingNode(Guid nodeId)
{
return DoOutOp(OpPingNode, nodeId) == True;
}
/// <summary>
/// Predicate (if any).
/// </summary>
public Func<IClusterNode, bool> Predicate
{
get { return _pred; }
}
/// <summary>
/// Refresh cluster node metrics.
/// </summary>
/// <param name="nodeId">Node</param>
/// <param name="lastUpdateTime"></param>
/// <returns></returns>
internal ClusterMetricsImpl RefreshClusterNodeMetrics(Guid nodeId, long lastUpdateTime)
{
return DoOutInOp(OpNodeMetrics, writer =>
{
writer.WriteGuid(nodeId);
writer.WriteLong(lastUpdateTime);
}, stream =>
{
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
return reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null;
}
);
}
/// <summary>
/// Gets a topology by version. Returns null if topology history storage doesn't contain
/// specified topology version (history currently keeps the last 1000 snapshots).
/// </summary>
/// <param name="version">Topology version.</param>
/// <returns>Collection of Ignite nodes which represented by specified topology version,
/// if it is present in history storage, {@code null} otherwise.</returns>
/// <exception cref="IgniteException">If underlying SPI implementation does not support
/// topology history. Currently only {@link org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi}
/// supports topology history.</exception>
internal ICollection<IClusterNode> Topology(long version)
{
return DoOutInOp(OpTopology, writer => writer.WriteLong(version),
input => IgniteUtils.ReadNodes(Marshaller.StartUnmarshal(input)));
}
/// <summary>
/// Topology version.
/// </summary>
internal long TopologyVersion
{
get
{
RefreshNodes();
return Interlocked.Read(ref _topVer);
}
}
/// <summary>
/// Update topology.
/// </summary>
/// <param name="newTopVer">New topology version.</param>
/// <param name="newNodes">New nodes.</param>
internal void UpdateTopology(long newTopVer, List<IClusterNode> newNodes)
{
lock (this)
{
// If another thread already advanced topology version further, we still
// can safely return currently received nodes, but we will not assign them.
if (_topVer < newTopVer)
{
Interlocked.Exchange(ref _topVer, newTopVer);
_nodes = newNodes.AsReadOnly();
}
}
}
/// <summary>
/// Get current nodes without refreshing the topology.
/// </summary>
/// <returns>Current nodes.</returns>
internal IList<IClusterNode> NodesNoRefresh()
{
return _nodes;
}
/// <summary>
/// Creates new Cluster Group from given native projection.
/// </summary>
/// <param name="prj">Native projection.</param>
/// <returns>New cluster group.</returns>
private IClusterGroup GetClusterGroup(IUnmanagedTarget prj)
{
return new ClusterGroupImpl(_proc, prj, Marshaller, _ignite, _pred);
}
/// <summary>
/// Refresh projection nodes.
/// </summary>
/// <returns>Nodes.</returns>
private IList<IClusterNode> RefreshNodes()
{
long oldTopVer = Interlocked.Read(ref _topVer);
List<IClusterNode> newNodes = null;
DoOutInOp(OpNodes, writer =>
{
writer.WriteLong(oldTopVer);
}, input =>
{
BinaryReader reader = Marshaller.StartUnmarshal(input);
if (reader.ReadBoolean())
{
// Topology has been updated.
long newTopVer = reader.ReadLong();
newNodes = IgniteUtils.ReadNodes(reader, _pred);
UpdateTopology(newTopVer, newNodes);
}
});
if (newNodes != null)
return newNodes;
// No topology changes.
Debug.Assert(_nodes != null, "At least one topology update should have occurred.");
return _nodes;
}
/// <summary>
/// Perform synchronous out operation returning value.
/// </summary>
/// <param name="type">Operation type.</param>
/// <param name="action">Action.</param>
/// <returns>Native projection.</returns>
private IUnmanagedTarget DoProjetionOutOp(int type, Action<BinaryWriter> action)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
var writer = Marshaller.StartMarshal(stream);
action(writer);
FinishMarshal(writer);
return UU.ProjectionOutOpRet(Target, type, stream.SynchronizeOutput());
}
}
/** <inheritDoc /> */
public IBinaryType GetBinaryType(int typeId)
{
return DoOutInOp<IBinaryType>(OpMetadata,
writer => writer.WriteInt(typeId),
stream =>
{
var reader = Marshaller.StartUnmarshal(stream, false);
return reader.ReadBoolean() ? new BinaryType(reader) : null;
}
);
}
/// <summary>
/// Gets metadata for all known types.
/// </summary>
public List<IBinaryType> GetBinaryTypes()
{
return DoInOp(OpAllMetadata, s =>
{
var reader = Marshaller.StartUnmarshal(s);
var size = reader.ReadInt();
var res = new List<IBinaryType>(size);
for (var i = 0; i < size; i++)
res.Add(reader.ReadBoolean() ? new BinaryType(reader) : null);
return res;
});
}
}
}
| |
// 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.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal interface ICodeModelService : ICodeModelNavigationPointService
{
/// <summary>
/// Retrieves the Option nodes (i.e. VB Option statements) parented
/// by the given node.
/// </summary>
IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent);
/// <summary>
/// Retrieves the import nodes (e.g. using/Import directives) parented
/// by the given node.
/// </summary>
IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent);
/// <summary>
/// Retrieves the attributes parented or owned by the given node.
/// </summary>
IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent);
/// <summary>
/// Retrieves the attribute arguments parented by the given node.
/// </summary>
IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent);
/// <summary>
/// Retrieves the Inherits nodes (i.e. VB Inherits statements) parented
/// or owned by the given node.
/// </summary>
IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent);
/// <summary>
/// Retrieves the Implements nodes (i.e. VB Implements statements) parented
/// or owned by the given node.
/// </summary>
IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent);
/// <summary>
/// Retrieves the members of a specified <paramref name="container"/> node. The members that are
/// returned can be controlled by passing various parameters.
/// </summary>
/// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param>
/// <param name="includeSelf">If true, the container is returned as well.</param>
/// <param name="recursive">If true, members are recursed to return descendent members as well
/// as immediate children. For example, a namespace would return the namespaces and types within.
/// However, if <paramref name="recursive"/> is true, members with the namespaces and types would
/// also be returned.</param>
/// <param name="logicalFields">If true, field declarations are broken into their respecitive declarators.
/// For example, the field "int x, y" would return two declarators, one for x and one for y in place
/// of the field.</param>
/// <param name="onlySuportedNodes">If true, only members supported by Code Model are returned.</param>
IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySuportedNodes);
IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container);
SyntaxNodeKey GetNodeKey(SyntaxNode node);
SyntaxNodeKey TryGetNodeKey(SyntaxNode node);
SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree);
bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node);
bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope);
string Language { get; }
string AssemblyAttributeString { get; }
EnvDTE.CodeElement CreateInternalCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node);
EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol);
EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node);
EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel);
EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol);
/// <summary>
/// Used by RootCodeModel.CreateCodeTypeRef to create an EnvDTE.CodeTypeRef.
/// </summary>
EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type);
EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol);
string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol);
string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol);
bool IsParameterNode(SyntaxNode node);
bool IsAttributeNode(SyntaxNode node);
bool IsAttributeArgumentNode(SyntaxNode node);
bool IsOptionNode(SyntaxNode node);
bool IsImportNode(SyntaxNode node);
ISymbol ResolveSymbol(Workspace workspace, ProjectId projectId, SymbolKey symbolId);
string GetUnescapedName(string name);
/// <summary>
/// Retrieves the value to be returned from the EnvDTE.CodeElement.Name property.
/// </summary>
string GetName(SyntaxNode node);
SyntaxNode GetNodeWithName(SyntaxNode node);
SyntaxNode SetName(SyntaxNode node, string name);
/// <summary>
/// Retrieves the value to be returned from the EnvDTE.CodeElement.FullName property.
/// </summary>
string GetFullName(SyntaxNode node, SemanticModel semanticModel);
/// <summary>
/// Retrieves the value to be returned from the EnvDTE.CodeElement.FullName property for external code elements
/// </summary>
string GetFullName(ISymbol symbol);
/// <summary>
/// Given a name, attempts to convert it to a fully qualified name.
/// </summary>
string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel);
void Rename(ISymbol symbol, string newName, Solution solution);
SyntaxNode GetNodeWithModifiers(SyntaxNode node);
SyntaxNode GetNodeWithType(SyntaxNode node);
SyntaxNode GetNodeWithInitializer(SyntaxNode node);
EnvDTE.vsCMAccess GetAccess(ISymbol symbol);
EnvDTE.vsCMAccess GetAccess(SyntaxNode node);
SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access);
EnvDTE.vsCMElement GetElementKind(SyntaxNode node);
bool IsAccessorNode(SyntaxNode node);
MethodKind GetAccessorKind(SyntaxNode node);
bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode);
bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode);
bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode);
bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode);
bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode);
bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode);
bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode);
bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode);
void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal);
void GetInheritsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode inheritsNode, out string namespaceName, out int ordinal);
void GetImplementsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode implementsNode, out string namespaceName, out int ordinal);
void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index);
void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal);
SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode);
string GetAttributeTarget(SyntaxNode attributeNode);
string GetAttributeValue(SyntaxNode attributeNode);
SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value);
SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value);
/// <summary>
/// Given a node, finds the related node that holds on to the attribute information.
/// Generally, this will be an ancestor node. For example, given a C# VariableDeclarator,
/// looks up the syntax tree to find the FieldDeclaration.
/// </summary>
SyntaxNode GetNodeWithAttributes(SyntaxNode node);
/// <summary>
/// Given node for an attribute, returns a node that can represent the parent.
/// For example, an attribute on a C# field cannot use the FieldDeclaration (as it is
/// not keyed) but instead must use one of the FieldDeclaration's VariableDeclarators.
/// </summary>
SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node);
SyntaxNode CreateAttributeNode(string name, string value, string target = null);
SyntaxNode CreateAttributeArgumentNode(string name, string value);
SyntaxNode CreateImportNode(string name, string alias = null);
SyntaxNode CreateParameterNode(string name, string type);
string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode);
string GetImportAlias(SyntaxNode node);
string GetImportNamespaceOrType(SyntaxNode node);
string GetParameterName(SyntaxNode node);
string GetParameterFullName(SyntaxNode node);
EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node);
SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind);
IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent);
EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name);
bool SupportsEventThrower { get; }
bool GetCanOverride(SyntaxNode memberNode);
SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value);
EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind);
string GetComment(SyntaxNode node);
SyntaxNode SetComment(SyntaxNode node, string value);
EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode);
SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind);
EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol);
SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind);
string GetDocComment(SyntaxNode node);
SyntaxNode SetDocComment(SyntaxNode node, string value);
EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol);
EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
SyntaxNode SetInheritanceKind(SyntaxNode node, EnvDTE80.vsCMInheritanceKind kind);
bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol);
SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value);
bool GetIsConstant(SyntaxNode memberNode);
SyntaxNode SetIsConstant(SyntaxNode memberNode, bool value);
bool GetIsDefault(SyntaxNode propertyNode);
SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value);
bool GetIsGeneric(SyntaxNode memberNode);
bool GetIsPropertyStyleEvent(SyntaxNode eventNode);
bool GetIsShared(SyntaxNode memberNode, ISymbol symbol);
SyntaxNode SetIsShared(SyntaxNode memberNode, bool value);
bool GetMustImplement(SyntaxNode memberNode);
SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value);
EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode);
SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind);
EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode);
SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol);
Document Delete(Document document, SyntaxNode node);
string GetMethodXml(SyntaxNode node, SemanticModel semanticModel);
string GetInitExpression(SyntaxNode node);
SyntaxNode AddInitExpression(SyntaxNode node, string value);
CodeGenerationDestination GetDestination(SyntaxNode containerNode);
/// <summary>
/// Retrieves the Accessibility for an EnvDTE.vsCMAccess. If the specified value is
/// EnvDTE.vsCMAccess.vsCMAccessDefault, then the SymbolKind and CodeGenerationDestination hints
/// will be used to retrieve the correct Accessibility for the current language.
/// </summary>
Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified);
bool GetWithEvents(EnvDTE.vsCMAccess access);
/// <summary>
/// Given an "type" argument received from a CodeModel client, converts it to an ITypeSymbol. Note that
/// this parameter is a VARIANT and could be an EnvDTE.vsCMTypeRef, a string representing a fully-qualified
/// type name, or an EnvDTE.CodeTypeRef.
/// </summary>
ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position);
ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation);
SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type);
int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel);
int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel);
int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel);
int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel);
int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel);
SyntaxNode InsertAttribute(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeNode,
CancellationToken cancellationToken,
out Document newDocument);
SyntaxNode InsertAttributeArgument(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeArgumentNode,
CancellationToken cancellationToken,
out Document newDocument);
SyntaxNode InsertImport(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode importNode,
CancellationToken cancellationToken,
out Document newDocument);
SyntaxNode InsertMember(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode newMemberNode,
CancellationToken cancellationToken,
out Document newDocument);
SyntaxNode InsertParameter(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode parameterNode,
CancellationToken cancellationToken,
out Document newDocument);
Document UpdateNode(
Document document,
SyntaxNode node,
SyntaxNode newNode,
CancellationToken cancellationToken);
Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree);
bool IsNamespace(SyntaxNode node);
bool IsType(SyntaxNode node);
IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel);
bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel);
Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken);
Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken);
string[] GetFunctionExtenderNames();
object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol);
string[] GetPropertyExtenderNames();
object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol);
string[] GetExternalTypeExtenderNames();
object GetExternalTypeExtender(string name, string externalLocation);
string[] GetTypeExtenderNames();
object GetTypeExtender(string name, AbstractCodeType codeType);
bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol);
SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol);
SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags);
void AttachFormatTrackingToBuffer(ITextBuffer buffer);
void DetachFormatTrackingToBuffer(ITextBuffer buffer);
void EnsureBufferFormatted(ITextBuffer buffer);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using EpicMorg.Tools;
namespace vk_parser
{
public static class Exts
{
public static int ReadLines(this TextReader t, string[] buf, int offset, int count)
{
int i = 0;
for (i = 0; i < count; i++)
if ((buf[i + offset] = t.ReadLine()) == null)
break;
return i;
}
}
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.binParse(args);
}
void binParse(string[] args)
{
#region VARS
#region System
#region IO
Stream _sr = null, _sw = null;
BufferedStream _br = null, _bw = null;
StreamReader read_stream = null;
int count = 0;
#endregion
#region DBS
string[] name_dictionary;
uint[] countries;
uint[] cities;
Dictionary<uint,string> universities = new Dictionary<uint,string>(100000);
Dictionary<uint,string> faculties = new Dictionary<uint,string>(100000);
#endregion
#region Temp
int[] indeces = new int[23];
uint out_temp = 0, out_temp2 = 0;
char t = '\t';
string tmp = null;
string str = null;
#endregion
#endregion
#region USER
int WRITE_BUF = 512 * 1024 * 1024,
READ_BUF = 128 * 1024 * 1204,
VERBOSITY=5000;
#if DEBUG
int MAX_DEBUG=5000;
#endif
#endregion
#endregion
#region Load data
string _input_file = Q("Type input filename");
string _list_directory = Q("Type directory with lists");
string _output = Q("Type output directory");
try
{
I("Loading names");
name_dictionary = File.ReadAllLines(Path.Combine(_list_directory, "names.lst"));
}
catch (Exception ex) { E("Failed to load names", ex); return; }
I("Loading countries");
try
{
countries = File.ReadAllLines(Path.Combine(_list_directory, "countries.lst")).Select(a => uint.Parse(a)).ToArray();
}
catch (Exception ex) { E("Failed to load countries", ex); return; }
I("Loading cities");
try
{
cities = File.ReadAllLines(Path.Combine(_list_directory, "cities.lst")).Select(a => uint.Parse(a)).ToArray();
}
catch (Exception ex) { E("Failed to load cities", ex); return; }
try
{
if (!Directory.Exists(_output))
Directory.CreateDirectory(_output);
}
catch (Exception ex) { E("Failed to set output directory", ex); return; }
#endregion
try
{
#region Streams
_sr = File.OpenRead(_input_file);
_br = new BufferedStream(_sr, READ_BUF);
read_stream = new StreamReader(_br);
_sw = File.Open(Path.Combine(_output, "users.emdbf"), FileMode.CreateNew);
_bw = new BufferedStream(_sw, WRITE_BUF);
#endregion
while ((str = read_stream.ReadLine()) != null)
{
#region Parsing
indeces[0] = str.IndexOf(t);
for (int i = 1; i < 22; i++)
indeces[i] = str.IndexOf(t, indeces[i - 1] + 1);
char[] temp_chars = str.ToCharArray();
_(uint.Parse(new string(temp_chars, 0, indeces[0])),_bw);
//UID
_(Convert.ToUInt32(Array_Ext.BinarySearch(name_dictionary,
Normalize(new string(temp_chars, indeces[0], indeces[1] - indeces[0])),
(a, b) => String.Compare(a, b, StringComparison.Ordinal))),_bw);
//NAME_ID
_(Convert.ToUInt32(Array_Ext.BinarySearch(name_dictionary,
Normalize(new string(temp_chars, indeces[1], indeces[2] - indeces[1])),
(a, b) => String.Compare(a, b, StringComparison.Ordinal))), _bw);
//LAST_NAME_ID
tmp = new string(temp_chars, indeces[3], indeces[3] - indeces[1]);
_(
(((tmp.Length > 0 ? (tmp[0] == '1' ? 1U : 2U) : 2U) << 24) & 0xFF000000U) &
//SEX
((((uint) Array.BinarySearch(cities, uint.TryParse(new string(temp_chars, indeces[5], indeces[6] - indeces[5]), out out_temp) ? out_temp : 0)) << 8) & 0xFFFF00U) &
//CITY
((uint) Array.BinarySearch(cities, uint.TryParse(new string(temp_chars, indeces[6], indeces[7] - indeces[6]), out out_temp) ? out_temp : 0) & 0xFFU),_bw);
//COUNTRY
tmp = new string(temp_chars, indeces[16], indeces[17] - indeces[16]);
_(out_temp = tmp.Length == 0 ? 0 : uint.Parse(tmp), _bw);
//UNIVERSITY
tmp = new string(temp_chars, indeces[17], indeces[18] - indeces[17]);
if (!universities.ContainsKey(out_temp))
universities.Add(out_temp,tmp);
//UNIVERSITY_NAME
tmp = new string(temp_chars, indeces[18], indeces[19] - indeces[18]);
_(out_temp = tmp.Length == 0 ? 0 : uint.Parse(tmp), _bw);
//FACULTY
tmp = new string(temp_chars, indeces[19], indeces[20] - indeces[19]);
if (!faculties.ContainsKey(out_temp))
faculties.Add(out_temp,tmp);
//FACULTY_NAME
tmp = new string(temp_chars, indeces[20], indeces[21] - indeces[20]);
out_temp = (tmp.Length == 0 ? 0U : uint.Parse(tmp) - 1900U);
//GRADUATION-1900 //0=>no
tmp = new string(temp_chars, indeces[20], indeces[21] - indeces[20]);
out_temp2 = tmp.Length == 0 ? 100U : (tmp[0] == '-' ? 0U : uint.Parse(tmp));
//RATE
_(((out_temp << 24) & 0xFF000000U) &
//GRADUATION-1900 //0=>no
((out_temp2) & 0x00FFFFFFU), _bw);
//RATE
count++;
#endregion
#region DEBUG
#if DEBUG
if (count>=MAX_DEBUG)
break;
#endif
if (count % VERBOSITY == 0)
I(count + " records proceed");
#endregion
}
#region Save uiniversities
var _univer_file=Path.Combine(_output,"univesities.dict");
if (File.Exists(_univer_file))
{
E("Univer file already exists");
_univer_file+=new Random().Next().ToString();
I("Writing to "+_univer_file);
}
File.WriteAllLines(_univer_file, universities.Select(a => a.Key.ToString() + '\t' + a.Value).ToArray());
#endregion
#region Save faculties
var _faculty_file = Path.Combine(_output, "faculties.dict");
if (File.Exists(_faculty_file))
{
E("Univer file already exists");
_faculty_file += new Random().Next().ToString();
I("Writing to " + _faculty_file);
}
File.WriteAllLines(_faculty_file, faculties.Select(a => a.Key.ToString() + '\t' + a.Value).ToArray());
#endregion
}
catch (Exception ex) { E("Failed to process", ex); return; }
#region Cleanup
finally
{
try { _br.Close(); }
catch { }
try { _sr.Close(); }
catch { }
try { _bw.Flush(); _bw.Close(); }
catch { }
try { _sw.Flush(); _sw.Close(); }
catch { }
try { read_stream.Close(); }
catch { }
}
#endregion
}
private void _(uint p, Stream s)
{
s.Write(BitConverter.GetBytes(p), 0, 4);
}
string Normalize(string input)
{
char[] c = input.ToCharArray();
int h = c.Length, tmp = 0, cnt = 0;
char[] c2 = new char[h];
string s;
for (int i = 0; i < h; i++)
{
tmp = (int) c[i];
if (tmp < 1300 && tmp > 47 && (tmp > 1000 || (tmp < 123 && (tmp > 96 || (tmp < 91 && tmp > 64) || tmp < 58))))
c2[cnt++] = c[i];
}
c = null;
s = new string(c2, 0, cnt);
c2 = null;
return s;
}
string Q(string text)
{
var c = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("&");
Console.WriteLine(text);
Console.Write('>');
Console.ForegroundColor = c;
return Console.ReadLine();
}
void I(string text)
{
var c = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.White;
Console.Write("#");
Console.WriteLine(text);
Console.ForegroundColor = c;
}
void E(string text = "", Exception ex = null)
{
var c = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("#Error");
if (ex == null)
Console.WriteLine(text != null ? ": {0}" : "!", text);
else
Console.WriteLine(text != null ? " ({0}): " : ": ", text, ex.Message);
Console.ForegroundColor = c;
}
#region Old
char[] al = { ' ', '(', ')', '-' };
int[] cs = { 47, 58, 64, 91, 96, 123, 1000, 1300 };
EpicMorg.Tools.StringTools rep = new EpicMorg.Tools.StringTools();
string Norm(string b)
{
return new string(b.ToCharArray().Where(a => IsNormal(a)).ToArray()).Replace("((", "").Replace("))", "").Trim();
}
bool IsNormal(char a)
{
int c = Convert.ToChar(a);
if (c > cs[7])
return false;
//c<cs[7]
if (c > cs[6])
return true;
//c<cs[6]
if (c > cs[5])
return false;
//c<c[5]
if (c > cs[4] || (c > cs[2] && c < cs[3]))
return true;
//<cs[2]
if (c < cs[1] && c > cs[0])
return true;
if (c < cs[0])
return (al[0] == a || al[1] == a || al[2] == a || al[3] == a);
return false;
}
void m(string[] args)
{
int BUF_SIZE = 524288;
Console.WriteLine("type input");
var input = Console.ReadLine();
Console.WriteLine("type temp");
var temp = Console.ReadLine();
var fr = File.OpenRead(input);
var br = new BufferedStream(fr, 64 * 1024 * 1024);
var tr = new StreamReader(br);
char[] split = new char[] { '\t' };
string[] buf = new string[BUF_SIZE];
int cnt = 0;
while (((TextReader) tr).ReadLines(buf, 0, BUF_SIZE) > 0)
{
File.WriteAllLines(Path.Combine(temp, cnt.ToString()), (buf.AsParallel().SelectMany(a => a.Split(split).Skip(1).Take(2).Select(b => Norm(b)).Where(c => c.Length > 0)).ToArray()).Distinct().ToArray());
for (int tmp_cnt = 0; tmp_cnt < BUF_SIZE; buf[tmp_cnt++] = null) ;
GC.Collect();
Console.WriteLine(++cnt * BUF_SIZE + " proceed");
}
Console.WriteLine("type outp dict");
var outp = Console.ReadLine();
//File.WriteAllLines(outp, buf2);
//p.Generate(inp, outp);
Console.WriteLine("Finished");
Console.ReadLine();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal abstract class CType
{
private TypeKind _typeKind;
private Name _pName;
private bool _fHasErrors; // Whether anyituents have errors. This is immutable.
private bool _isBogus; // can't be used in our language -- unsupported type(s)
private bool _checkedBogus; // Have we checked a method args/return for bogus types
// Is and As methods.
public AggregateType AsAggregateType() { return this as AggregateType; }
public ErrorType AsErrorType() { return this as ErrorType; }
public ArrayType AsArrayType() { return this as ArrayType; }
public PointerType AsPointerType() { return this as PointerType; }
public ParameterModifierType AsParameterModifierType() { return this as ParameterModifierType; }
public NullableType AsNullableType() { return this as NullableType; }
public TypeParameterType AsTypeParameterType() { return this as TypeParameterType; }
public bool IsAggregateType() { return this is AggregateType; }
public bool IsVoidType() { return this is VoidType; }
public bool IsNullType() { return this is NullType; }
public bool IsOpenTypePlaceholderType() { return this is OpenTypePlaceholderType; }
public bool IsBoundLambdaType() { return this is BoundLambdaType; }
public bool IsMethodGroupType() { return this is MethodGroupType; }
public bool IsErrorType() { return this is ErrorType; }
public bool IsArrayType() { return this is ArrayType; }
public bool IsPointerType() { return this is PointerType; }
public bool IsParameterModifierType() { return this is ParameterModifierType; }
public bool IsNullableType() { return this is NullableType; }
public bool IsTypeParameterType() { return this is TypeParameterType; }
public bool IsWindowsRuntimeType()
{
return (AssociatedSystemType.Attributes & TypeAttributes.WindowsRuntime) == TypeAttributes.WindowsRuntime;
}
public bool IsCollectionType()
{
if ((AssociatedSystemType.IsGenericType &&
(AssociatedSystemType.GetGenericTypeDefinition() == typeof(IList<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(ICollection<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IEnumerable<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IReadOnlyList<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IReadOnlyCollection<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IDictionary<,>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>))) ||
AssociatedSystemType == typeof(System.Collections.IList) ||
AssociatedSystemType == typeof(System.Collections.ICollection) ||
AssociatedSystemType == typeof(System.Collections.IEnumerable) ||
AssociatedSystemType == typeof(System.Collections.Specialized.INotifyCollectionChanged) ||
AssociatedSystemType == typeof(System.ComponentModel.INotifyPropertyChanged))
{
return true;
}
return false;
}
// API similar to System.Type
public bool IsGenericParameter
{
get { return IsTypeParameterType(); }
}
private Type _associatedSystemType;
public Type AssociatedSystemType
{
get
{
if (_associatedSystemType == null)
{
_associatedSystemType = CalculateAssociatedSystemType(this);
}
return _associatedSystemType;
}
}
private static Type CalculateAssociatedSystemType(CType src)
{
Type result = null;
switch (src.GetTypeKind())
{
case TypeKind.TK_ArrayType:
ArrayType a = src.AsArrayType();
Type elementType = a.GetElementType().AssociatedSystemType;
result = a.IsSZArray ? elementType.MakeArrayType() : elementType.MakeArrayType(a.rank);
break;
case TypeKind.TK_NullableType:
NullableType n = src.AsNullableType();
Type underlyingType = n.GetUnderlyingType().AssociatedSystemType;
result = typeof(Nullable<>).MakeGenericType(underlyingType);
break;
case TypeKind.TK_PointerType:
PointerType p = src.AsPointerType();
Type referentType = p.GetReferentType().AssociatedSystemType;
result = referentType.MakePointerType();
break;
case TypeKind.TK_ParameterModifierType:
ParameterModifierType r = src.AsParameterModifierType();
Type parameterType = r.GetParameterType().AssociatedSystemType;
result = parameterType.MakeByRefType();
break;
case TypeKind.TK_AggregateType:
result = CalculateAssociatedSystemTypeForAggregate(src.AsAggregateType());
break;
case TypeKind.TK_TypeParameterType:
TypeParameterType t = src.AsTypeParameterType();
if (t.IsMethodTypeParameter())
{
MethodInfo meth = t.GetOwningSymbol().AsMethodSymbol().AssociatedMemberInfo as MethodInfo;
result = meth.GetGenericArguments()[t.GetIndexInOwnParameters()];
}
else
{
Type parentType = t.GetOwningSymbol().AsAggregateSymbol().AssociatedSystemType;
result = parentType.GetGenericArguments()[t.GetIndexInOwnParameters()];
}
break;
case TypeKind.TK_ArgumentListType:
case TypeKind.TK_BoundLambdaType:
case TypeKind.TK_ErrorType:
case TypeKind.TK_MethodGroupType:
case TypeKind.TK_NaturalIntegerType:
case TypeKind.TK_NullType:
case TypeKind.TK_OpenTypePlaceholderType:
case TypeKind.TK_UnboundLambdaType:
case TypeKind.TK_VoidType:
default:
break;
}
Debug.Assert(result != null || src.GetTypeKind() == TypeKind.TK_AggregateType);
return result;
}
private static Type CalculateAssociatedSystemTypeForAggregate(AggregateType aggtype)
{
AggregateSymbol agg = aggtype.GetOwningAggregate();
TypeArray typeArgs = aggtype.GetTypeArgsAll();
List<Type> list = new List<Type>();
// Get each type arg.
for (int i = 0; i < typeArgs.Count; i++)
{
// Unnamed type parameter types are just placeholders.
if (typeArgs[i].IsTypeParameterType() && typeArgs[i].AsTypeParameterType().GetTypeParameterSymbol().name == null)
{
return null;
}
list.Add(typeArgs[i].AssociatedSystemType);
}
Type[] systemTypeArgs = list.ToArray();
Type uninstantiatedType = agg.AssociatedSystemType;
if (uninstantiatedType.IsGenericType)
{
try
{
return uninstantiatedType.MakeGenericType(systemTypeArgs);
}
catch (ArgumentException)
{
// If the constraints don't work, just return the type without substituting it.
return uninstantiatedType;
}
}
return uninstantiatedType;
}
public TypeKind GetTypeKind() { return _typeKind; }
public void SetTypeKind(TypeKind kind) { _typeKind = kind; }
public Name GetName() { return _pName; }
public void SetName(Name pName) { _pName = pName; }
public bool checkBogus() { return _isBogus; }
public bool getBogus() { return _isBogus; }
public bool hasBogus() { return _checkedBogus; }
public void setBogus(bool isBogus)
{
_isBogus = isBogus;
_checkedBogus = true;
}
public bool computeCurrentBogusState()
{
if (hasBogus())
{
return checkBogus();
}
bool fBogus = false;
switch (GetTypeKind())
{
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
if (GetBaseOrParameterOrElementType() != null)
{
fBogus = GetBaseOrParameterOrElementType().computeCurrentBogusState();
}
break;
case TypeKind.TK_ErrorType:
setBogus(false);
break;
case TypeKind.TK_AggregateType:
fBogus = AsAggregateType().getAggregate().computeCurrentBogusState();
for (int i = 0; !fBogus && i < AsAggregateType().GetTypeArgsAll().Count; i++)
{
fBogus |= AsAggregateType().GetTypeArgsAll()[i].computeCurrentBogusState();
}
break;
case TypeKind.TK_TypeParameterType:
case TypeKind.TK_VoidType:
case TypeKind.TK_NullType:
case TypeKind.TK_OpenTypePlaceholderType:
case TypeKind.TK_ArgumentListType:
case TypeKind.TK_NaturalIntegerType:
setBogus(false);
break;
default:
throw Error.InternalCompilerError();
//setBogus(false);
//break;
}
if (fBogus)
{
// Only set this if at least 1 declared thing is bogus
setBogus(fBogus);
}
return hasBogus() && checkBogus();
}
// This call switches on the kind and dispatches accordingly. This should really only be
// used when dereferencing TypeArrays. We should consider refactoring our code to not
// need this type of thing - strongly typed handling of TypeArrays would be much better.
public CType GetBaseOrParameterOrElementType()
{
switch (GetTypeKind())
{
case TypeKind.TK_ArrayType:
return AsArrayType().GetElementType();
case TypeKind.TK_PointerType:
return AsPointerType().GetReferentType();
case TypeKind.TK_ParameterModifierType:
return AsParameterModifierType().GetParameterType();
case TypeKind.TK_NullableType:
return AsNullableType().GetUnderlyingType();
default:
return null;
}
}
public void InitFromParent()
{
Debug.Assert(!IsAggregateType());
CType typePar = null;
if (IsErrorType())
{
typePar = AsErrorType().GetTypeParent();
}
else
{
typePar = GetBaseOrParameterOrElementType();
}
_fHasErrors = typePar.HasErrors();
}
public bool HasErrors()
{
return _fHasErrors;
}
public void SetErrors(bool fHasErrors)
{
_fHasErrors = fHasErrors;
}
////////////////////////////////////////////////////////////////////////////////
// Given a symbol, determine its fundamental type. This is the type that
// indicate how the item is stored and what instructions are used to reference
// if. The fundamental types are:
// one of the integral/float types (includes enums with that underlying type)
// reference type
// struct/value type
public FUNDTYPE fundType()
{
switch (GetTypeKind())
{
case TypeKind.TK_AggregateType:
{
AggregateSymbol sym = AsAggregateType().getAggregate();
// Treat enums like their underlying types.
if (sym.IsEnum())
{
sym = sym.GetUnderlyingType().getAggregate();
}
if (sym.IsStruct())
{
// Struct type could be predefined (int, long, etc.) or some other struct.
if (sym.IsPredefined())
return PredefinedTypeFacts.GetFundType(sym.GetPredefType());
return FUNDTYPE.FT_STRUCT;
}
return FUNDTYPE.FT_REF; // Interfaces, classes, delegates are reference types.
}
case TypeKind.TK_TypeParameterType:
return FUNDTYPE.FT_VAR;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullType:
return FUNDTYPE.FT_REF;
case TypeKind.TK_PointerType:
return FUNDTYPE.FT_PTR;
case TypeKind.TK_NullableType:
return FUNDTYPE.FT_STRUCT;
default:
return FUNDTYPE.FT_NONE;
}
}
public ConstValKind constValKind()
{
if (isPointerLike())
{
return ConstValKind.IntPtr;
}
switch (fundType())
{
case FUNDTYPE.FT_I8:
case FUNDTYPE.FT_U8:
return ConstValKind.Long;
case FUNDTYPE.FT_STRUCT:
// Here we can either have a decimal type, or an enum
// whose fundamental type is decimal.
Debug.Assert((getAggregate().IsEnum() && getAggregate().GetUnderlyingType().getPredefType() == PredefinedType.PT_DECIMAL)
|| (isPredefined() && getPredefType() == PredefinedType.PT_DATETIME)
|| (isPredefined() && getPredefType() == PredefinedType.PT_DECIMAL));
if (isPredefined() && getPredefType() == PredefinedType.PT_DATETIME)
{
return ConstValKind.Long;
}
return ConstValKind.Decimal;
case FUNDTYPE.FT_REF:
if (isPredefined() && getPredefType() == PredefinedType.PT_STRING)
{
return ConstValKind.String;
}
else
{
return ConstValKind.IntPtr;
}
case FUNDTYPE.FT_R4:
return ConstValKind.Float;
case FUNDTYPE.FT_R8:
return ConstValKind.Double;
case FUNDTYPE.FT_I1:
return ConstValKind.Boolean;
default:
return ConstValKind.Int;
}
}
public CType underlyingType()
{
if (IsAggregateType() && getAggregate().IsEnum())
return getAggregate().GetUnderlyingType();
return this;
}
////////////////////////////////////////////////////////////////////////////////
// Strips off ArrayType, ParameterModifierType, PointerType, PinnedType and optionally NullableType
// and returns the result.
public CType GetNakedType(bool fStripNub)
{
for (CType type = this; ;)
{
switch (type.GetTypeKind())
{
default:
return type;
case TypeKind.TK_NullableType:
if (!fStripNub)
return type;
type = type.GetBaseOrParameterOrElementType();
break;
case TypeKind.TK_ArrayType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.GetBaseOrParameterOrElementType();
break;
}
}
}
public AggregateSymbol GetNakedAgg()
{
return GetNakedAgg(false);
}
private AggregateSymbol GetNakedAgg(bool fStripNub)
{
CType type = GetNakedType(fStripNub);
if (type != null && type.IsAggregateType())
return type.AsAggregateType().getAggregate();
return null;
}
public AggregateSymbol getAggregate()
{
Debug.Assert(IsAggregateType());
return AsAggregateType().GetOwningAggregate();
}
public virtual CType StripNubs() => this;
public virtual CType StripNubs(out bool wasNullable)
{
wasNullable = false;
return this;
}
public bool isDelegateType()
{
return (IsAggregateType() && getAggregate().IsDelegate());
}
////////////////////////////////////////////////////////////////////////////////
// A few types are considered "simple" types for purposes of conversions and so
// on. They are the fundamental types the compiler knows about for operators and
// conversions.
public bool isSimpleType()
{
return (isPredefined() &&
PredefinedTypeFacts.IsSimpleType(getPredefType()));
}
public bool isSimpleOrEnum()
{
return isSimpleType() || isEnumType();
}
public bool isSimpleOrEnumOrString()
{
return isSimpleType() || isPredefType(PredefinedType.PT_STRING) || isEnumType();
}
private bool isPointerLike()
{
return IsPointerType() || isPredefType(PredefinedType.PT_INTPTR) || isPredefType(PredefinedType.PT_UINTPTR);
}
////////////////////////////////////////////////////////////////////////////////
// A few types are considered "numeric" types. They are the fundamental number
// types the compiler knows about for operators and conversions.
public bool isNumericType()
{
return (isPredefined() &&
PredefinedTypeFacts.IsNumericType(getPredefType()));
}
public bool isStructOrEnum()
{
return (IsAggregateType() && (getAggregate().IsStruct() || getAggregate().IsEnum())) || IsNullableType();
}
public bool isStructType()
{
return IsAggregateType() && getAggregate().IsStruct() || IsNullableType();
}
public bool isEnumType()
{
return (IsAggregateType() && getAggregate().IsEnum());
}
public bool isInterfaceType()
{
return (IsAggregateType() && getAggregate().IsInterface());
}
public bool isClassType()
{
return (IsAggregateType() && getAggregate().IsClass());
}
public AggregateType underlyingEnumType()
{
Debug.Assert(isEnumType());
return getAggregate().GetUnderlyingType();
}
public bool isUnsigned()
{
if (IsAggregateType())
{
AggregateType sym = AsAggregateType();
if (sym.isEnumType())
{
sym = sym.underlyingEnumType();
}
if (sym.isPredefined())
{
PredefinedType pt = sym.getPredefType();
return pt == PredefinedType.PT_UINTPTR || pt == PredefinedType.PT_BYTE || (pt >= PredefinedType.PT_USHORT && pt <= PredefinedType.PT_ULONG);
}
else
{
return false;
}
}
else
{
return IsPointerType();
}
}
public bool isUnsafe()
{
// Pointer types are the only unsafe types.
// Note that generics may not be instantiated with pointer types
return (this != null && (IsPointerType() || (IsArrayType() && AsArrayType().GetElementType().isUnsafe())));
}
public bool isPredefType(PredefinedType pt)
{
if (IsAggregateType())
return AsAggregateType().getAggregate().IsPredefined() && AsAggregateType().getAggregate().GetPredefType() == pt;
return (IsVoidType() && pt == PredefinedType.PT_VOID);
}
public bool isPredefined()
{
return IsAggregateType() && getAggregate().IsPredefined();
}
public PredefinedType getPredefType()
{
//ASSERT(isPredefined());
return getAggregate().GetPredefType();
}
public bool isStaticClass()
{
AggregateSymbol agg = GetNakedAgg(false);
if (agg == null)
return false;
if (!agg.IsStatic())
return false;
return true;
}
public CType GetDelegateTypeOfPossibleExpression()
{
if (isPredefType(PredefinedType.PT_G_EXPRESSION))
{
return AsAggregateType().GetTypeArgsThis()[0];
}
return this;
}
// These check for AGGTYPESYMs, TYVARSYMs and others as appropriate.
public bool IsValType()
{
switch (GetTypeKind())
{
case TypeKind.TK_TypeParameterType:
return AsTypeParameterType().IsValueType();
case TypeKind.TK_AggregateType:
return AsAggregateType().getAggregate().IsValueType();
case TypeKind.TK_NullableType:
return true;
default:
return false;
}
}
public bool IsNonNubValType()
{
switch (GetTypeKind())
{
case TypeKind.TK_TypeParameterType:
return AsTypeParameterType().IsNonNullableValueType();
case TypeKind.TK_AggregateType:
return AsAggregateType().getAggregate().IsValueType();
case TypeKind.TK_NullableType:
return false;
default:
return false;
}
}
public bool IsRefType()
{
switch (GetTypeKind())
{
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullType:
return true;
case TypeKind.TK_TypeParameterType:
return AsTypeParameterType().IsReferenceType();
case TypeKind.TK_AggregateType:
return AsAggregateType().getAggregate().IsRefType();
default:
return false;
}
}
// A few types can be the same pointer value and not actually
// be equivalent or convertible (like ANONMETHSYMs)
public bool IsNeverSameType()
{
return IsBoundLambdaType() || IsMethodGroupType() || (IsErrorType() && !AsErrorType().HasParent());
}
}
}
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace IronScheme.Editor.Algorithms
{
static class StringExtensions
{
readonly static Dictionary<string, Regex> tokenizecache = new Dictionary<string,Regex>();
public static string[] Tokenize(this string name, params string[] delimiters)
{
for (int i = 0; i < delimiters.Length; i++)
{
delimiters[i] = Regex.Escape(delimiters[i]);
}
string del = string.Join("|", delimiters);
Regex re = null;
if (tokenizecache.ContainsKey(del))
{
re = tokenizecache[del] as Regex;
}
else
{
tokenizecache.Add(del, re = new Regex(del, RegexOptions.Compiled));
}
List<string> tokens = new List<string>();
int lastend = 0;
foreach (Match m in re.Matches(name))
{
if (m.Index > lastend)
{
tokens.Add(name.Substring(lastend, m.Index - lastend));
}
tokens.Add(m.Value);
lastend = m.Index + m.Length;
}
tokens.Add(name.Substring(lastend));
return tokens.ToArray();
}
}
/// <summary>
/// Implementation of the Boyer Moore string search algorithm.
/// </summary>
/// <example>
/// <code>
/// int index = 0, start = 0;
/// string sub = "hello", text = "to the hello world I say hello";
///
/// while (index > -1)
/// {
/// index = BoyerMoore.IndexOf(sub, text, start);
/// Console.WriteLine(index);
/// start += index + 1;
/// }
/// </code>
/// </example>
public sealed class BoyerMoore
{
static string temppat = string.Empty, revpat = string.Empty;
static Dictionary<char, int> tempjmp, revjmp;
BoyerMoore(){}
/// <summary>
/// Finds a substring in text searching from the front.
/// </summary>
/// <param name="pattern">the substring to search for</param>
/// <param name="text">the text to search in</param>
/// <returns>the start index of the substring if found, else -1 if not found</returns>
public static int IndexOf(string pattern, string text)
{
return IndexOf(pattern, text, 0);
}
/// <summary>
/// Finds a substring in text searching from the front and starting from start.
/// </summary>
/// <param name="pattern">the substring to search for</param>
/// <param name="text">the text to search in</param>
/// <param name="start">the start index of 'text' where to search from</param>
/// <returns>the start index of the substring if found, else -1 if not found</returns>
public static int IndexOf(string pattern, string text, int start)
{
if (temppat != pattern)
{
tempjmp = PreIndexOf(temppat = pattern);
}
return IndexOf(pattern, text, start, tempjmp);
}
static Dictionary<char, int> PreIndexOf(string pattern)
{
int m = pattern.Length - 1;
Dictionary<char, int> pa = new Dictionary<char, int>(m * 3);
for (int i = 0; i <= m; i++)
{
pa[pattern[i]] = m - i;
}
return pa;
}
static int IndexOf(string pattern, string text, int start, Dictionary<char, int> jmptbl)
{
/*const*/int n = text.Length,
/*const*/ m = pattern.Length,
/*const*/ far = m - 1;
int index = start;
if (m == 0 || start >= n)
{
return -1;
}
while (index + m <= n)
{
char t = text[far + index];
if (t == pattern[far])
{
if (far == 0)
{
return index;
}
int near = far - 1;
while ((t = text[near + index]) == pattern[near])
{
if (near-- == 0)
{
return index;
}
}
index++;
}
if (jmptbl.ContainsKey(t))
{
index += jmptbl[t];
}
else
{
index += m;
}
}
return -1;
}
/// <summary>
/// Finds a substring in text searching from the rear.
/// </summary>
/// <param name="pattern">the substring to search for</param>
/// <param name="text">the text to search in</param>
/// <returns>the start index of the substring if found, else -1 if not found</returns>
public static int LastIndexOf(string pattern, string text)
{
return LastIndexOf(pattern, text, text.Length);
}
/// <summary>
/// Finds a substring in text searching from the rear and starting at start.
/// </summary>
/// <param name="pattern">the substring to search for</param>
/// <param name="text">the text to search in</param>
/// <param name="start">the end index of 'text' where to search from</param>
/// <returns>the start index of the substring if found, else -1 if not found</returns>
public static int LastIndexOf(string pattern, string text, int start)
{
if (revpat != pattern)
{
revjmp = PreLastIndexOf(revpat = pattern);
}
return LastIndexOf(pattern, text, start, revjmp);
}
static Dictionary<char, int> PreLastIndexOf(string pattern)
{
int m = pattern.Length - 1;
Dictionary<char, int> pa = new Dictionary<char, int>(m * 3);
for (int i = m; i >= 0; i--)
{
pa[pattern[i]] = i;
}
return pa;
}
static int LastIndexOf(string pattern, string text, int start, Dictionary<char, int> jmptbl)
{
/*const*/int n = text.Length < start ? text.Length : start,
/*const*/ m = pattern.Length;
int index = n - m;
char f = pattern[0];
if (m == 0 || n < 0)
{
return -1;
}
while (index >= 0)
{
char t = text[index];
if (t == f)
{
int near = 1;
while ((t = text[near + index]) == pattern[near])
{
if (++near >= m)
{
return index;
}
}
index--;
}
if (jmptbl.ContainsKey(t))
{
index -= jmptbl[t];
}
else
{
index -= m;
}
}
return -1;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.ServiceModel.Channels;
public class MessageQueryTable<TItem> : IDictionary<MessageQuery, TItem>
{
Dictionary<Type, MessageQueryCollection> collectionsByType;
Dictionary<MessageQuery, TItem> dictionary;
public MessageQueryTable()
{
this.dictionary = new Dictionary<MessageQuery, TItem>();
this.collectionsByType = new Dictionary<Type, MessageQueryCollection>();
}
public int Count
{
get { return this.dictionary.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public ICollection<MessageQuery> Keys
{
get { return this.dictionary.Keys; }
}
public ICollection<TItem> Values
{
get { return this.dictionary.Values; }
}
public TItem this[MessageQuery key]
{
get
{
return this.dictionary[key];
}
set
{
this.Add(key, value);
}
}
[SuppressMessage(FxCop.Category.Usage, "CA2301:EmbeddableTypesInContainersRule", MessageId = "collectionsByType", Justification = "No need to support type equivalence here.")]
public void Add(MessageQuery key, TItem value)
{
if (key == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
}
Type queryType = key.GetType();
MessageQueryCollection collection;
if (!this.collectionsByType.TryGetValue(queryType, out collection))
{
collection = key.CreateMessageQueryCollection();
if (collection == null)
{
collection = new SequentialMessageQueryCollection();
}
this.collectionsByType.Add(queryType, collection);
}
collection.Add(key);
this.dictionary.Add(key, value);
}
public void Add(KeyValuePair<MessageQuery, TItem> item)
{
this.Add(item.Key, item.Value);
}
public void Clear()
{
this.collectionsByType.Clear();
this.dictionary.Clear();
}
public bool Contains(KeyValuePair<MessageQuery, TItem> item)
{
return ((ICollection<KeyValuePair<MessageQuery, TItem>>) this.dictionary).Contains(item);
}
public bool ContainsKey(MessageQuery key)
{
return this.dictionary.ContainsKey(key);
}
public void CopyTo(KeyValuePair<MessageQuery, TItem>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<MessageQuery, TItem>>) this.dictionary).CopyTo(array, arrayIndex);
}
public IEnumerable<KeyValuePair<MessageQuery, TResult>> Evaluate<TResult>(Message message)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
return new MessageEnumerable<TResult>(this, message);
}
public IEnumerable<KeyValuePair<MessageQuery, TResult>> Evaluate<TResult>(MessageBuffer buffer)
{
if (buffer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
}
return new MessageBufferEnumerable<TResult>(this, buffer);
}
public IEnumerator<KeyValuePair<MessageQuery, TItem>> GetEnumerator()
{
return ((ICollection<KeyValuePair<MessageQuery, TItem>>) this.dictionary).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
[SuppressMessage(FxCop.Category.Usage, "CA2301:EmbeddableTypesInContainersRule", MessageId = "collectionsByType", Justification = "No need to support type equivalence here.")]
public bool Remove(MessageQuery key)
{
if (this.dictionary.Remove(key))
{
MessageQueryCollection collection;
Type queryType = key.GetType();
collection = this.collectionsByType[queryType];
collection.Remove(key);
if (collection.Count == 0)
{
this.collectionsByType.Remove(queryType);
}
return true;
}
else
{
return false;
}
}
public bool Remove(KeyValuePair<MessageQuery, TItem> item)
{
return this.Remove(item.Key);
}
public bool TryGetValue(MessageQuery key, out TItem value)
{
return this.dictionary.TryGetValue(key, out value);
}
class SequentialMessageQueryCollection : MessageQueryCollection
{
public override IEnumerable<KeyValuePair<MessageQuery, TResult>> Evaluate<TResult>(Message message)
{
return new MessageSequentialResultEnumerable<TResult>(this, message);
}
public override IEnumerable<KeyValuePair<MessageQuery, TResult>> Evaluate<TResult>(MessageBuffer buffer)
{
return new MessageBufferSequentialResultEnumerable<TResult>(this, buffer);
}
abstract class SequentialResultEnumerable<TSource, TResult> : IEnumerable<KeyValuePair<MessageQuery, TResult>>
{
SequentialMessageQueryCollection collection;
TSource source;
public SequentialResultEnumerable(SequentialMessageQueryCollection collection, TSource source)
{
this.collection = collection;
this.source = source;
}
SequentialMessageQueryCollection Collection
{
get
{
return this.collection;
}
}
protected TSource Source
{
get
{
return this.source;
}
}
public IEnumerator<KeyValuePair<MessageQuery, TResult>> GetEnumerator()
{
return new SequentialResultEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
protected abstract TResult Evaluate(MessageQuery query);
class SequentialResultEnumerator : IEnumerator<KeyValuePair<MessageQuery, TResult>>
{
SequentialResultEnumerable<TSource, TResult> enumerable;
IEnumerator<MessageQuery> queries;
public SequentialResultEnumerator(SequentialResultEnumerable<TSource, TResult> enumerable)
{
this.enumerable = enumerable;
this.queries = enumerable.Collection.GetEnumerator();
}
public KeyValuePair<MessageQuery, TResult> Current
{
get
{
MessageQuery query = queries.Current;
TResult result = enumerable.Evaluate(query);
return new KeyValuePair<MessageQuery, TResult>(query, result);
}
}
object IEnumerator.Current
{
get
{
return this.Current;
}
}
public void Dispose()
{
}
public bool MoveNext()
{
return this.queries.MoveNext();
}
public void Reset()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
}
}
class MessageSequentialResultEnumerable<TResult> : SequentialResultEnumerable<Message, TResult>
{
public MessageSequentialResultEnumerable(
SequentialMessageQueryCollection collection, Message message)
: base(collection, message)
{
}
protected override TResult Evaluate(MessageQuery query)
{
return query.Evaluate<TResult>(this.Source);
}
}
class MessageBufferSequentialResultEnumerable<TResult> : SequentialResultEnumerable<MessageBuffer, TResult>
{
public MessageBufferSequentialResultEnumerable(
SequentialMessageQueryCollection collection, MessageBuffer buffer)
: base(collection, buffer)
{
}
protected override TResult Evaluate(MessageQuery query)
{
return query.Evaluate<TResult>(this.Source);
}
}
}
abstract class Enumerable<TSource, TResult> : IEnumerable<KeyValuePair<MessageQuery, TResult>>
{
TSource source;
MessageQueryTable<TItem> table;
public Enumerable(MessageQueryTable<TItem> table, TSource source)
{
this.table = table;
this.source = source;
}
protected TSource Source
{
get
{
return this.source;
}
}
public IEnumerator<KeyValuePair<MessageQuery, TResult>> GetEnumerator()
{
return new Enumerator(this);
}
protected abstract IEnumerator<KeyValuePair<MessageQuery, TResult>> GetInnerEnumerator(MessageQueryCollection collection);
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
class Enumerator : IEnumerator<KeyValuePair<MessageQuery, TResult>>
{
Enumerable<TSource, TResult> enumerable;
IEnumerator<KeyValuePair<MessageQuery, TResult>> innerEnumerator;
IEnumerator<MessageQueryCollection> outerEnumerator;
public Enumerator(Enumerable<TSource, TResult> enumerable)
{
this.outerEnumerator = enumerable.table.collectionsByType.Values.GetEnumerator();
this.enumerable = enumerable;
}
public KeyValuePair<MessageQuery, TResult> Current
{
get { return this.innerEnumerator.Current; }
}
object IEnumerator.Current
{
get
{
return this.Current;
}
}
public void Dispose()
{
}
public bool MoveNext()
{
if (innerEnumerator == null || !this.innerEnumerator.MoveNext())
{
if (!this.outerEnumerator.MoveNext())
{
return false;
}
else
{
MessageQueryCollection collection = this.outerEnumerator.Current;
this.innerEnumerator = this.enumerable.GetInnerEnumerator(collection);
return this.innerEnumerator.MoveNext();
}
}
else
{
return true;
}
}
public void Reset()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
}
}
class MessageBufferEnumerable<TResult> : Enumerable<MessageBuffer, TResult>
{
public MessageBufferEnumerable(MessageQueryTable<TItem> table, MessageBuffer buffer)
: base(table, buffer)
{
}
protected override IEnumerator<KeyValuePair<MessageQuery, TResult>> GetInnerEnumerator(
MessageQueryCollection collection)
{
return collection.Evaluate<TResult>(this.Source).GetEnumerator();
}
}
class MessageEnumerable<TResult> : Enumerable<Message, TResult>
{
public MessageEnumerable(MessageQueryTable<TItem> table, Message message)
: base(table, message)
{
}
protected override IEnumerator<KeyValuePair<MessageQuery, TResult>> GetInnerEnumerator(
MessageQueryCollection collection)
{
return collection.Evaluate<TResult>(this.Source).GetEnumerator();
}
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to install, execute and perform the Spine Runtimes
* Software (the "Software") solely for internal use. Without the written
* permission of Esoteric Software, you may not (a) modify, translate, adapt or
* otherwise create derivative works, improvements of the Software or develop
* new applications using the Software or (b) remove, delete, alter or obscure
* any trademarks or any copyright, trademark, patent or other intellectual
* property or proprietary rights notices on or in the Software, including
* any copy thereof. Redistributions in binary or source form must include
* this license and terms. THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE
* "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 ESOTERIC SOFTARE BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
#if WINDOWS_STOREAPP
using System.Threading.Tasks;
using Windows.Storage;
#endif
namespace Spine {
public class Atlas {
List<AtlasPage> pages = new List<AtlasPage>();
List<AtlasRegion> regions = new List<AtlasRegion>();
TextureLoader textureLoader;
#if WINDOWS_STOREAPP
private async Task ReadFile(string path, TextureLoader textureLoader) {
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync(path).AsTask().ConfigureAwait(false);
using (var reader = new StreamReader(await file.OpenStreamForReadAsync().ConfigureAwait(false))) {
try {
Load(reader, Path.GetDirectoryName(path), textureLoader);
} catch (Exception ex) {
throw new Exception("Error reading atlas file: " + path, ex);
}
}
}
public Atlas(String path, TextureLoader textureLoader) {
this.ReadFile(path, textureLoader).Wait();
}
#else
public Atlas (String path, TextureLoader textureLoader) {
#if WINDOWS_PHONE
Stream stream = Microsoft.Xna.Framework.TitleContainer.OpenStream(path);
using (StreamReader reader = new StreamReader(stream))
{
#else
using (StreamReader reader = new StreamReader(path)) {
#endif
try {
Load(reader, Path.GetDirectoryName(path), textureLoader);
} catch (Exception ex) {
throw new Exception("Error reading atlas file: " + path, ex);
}
}
}
#endif
public Atlas (TextReader reader, String dir, TextureLoader textureLoader) {
Load(reader, dir, textureLoader);
}
public Atlas (List<AtlasPage> pages, List<AtlasRegion> regions) {
this.pages = pages;
this.regions = regions;
this.textureLoader = null;
}
private void Load (TextReader reader, String imagesDir, TextureLoader textureLoader) {
if (textureLoader == null) throw new ArgumentNullException("textureLoader cannot be null.");
this.textureLoader = textureLoader;
String[] tuple = new String[4];
AtlasPage page = null;
while (true) {
String line = reader.ReadLine();
if (line == null) break;
if (line.Trim().Length == 0)
page = null;
else if (page == null) {
page = new AtlasPage();
page.name = line;
page.format = (Format)Enum.Parse(typeof(Format), readValue(reader), false);
readTuple(reader, tuple);
page.minFilter = (TextureFilter)Enum.Parse(typeof(TextureFilter), tuple[0], false);
page.magFilter = (TextureFilter)Enum.Parse(typeof(TextureFilter), tuple[1], false);
String direction = readValue(reader);
page.uWrap = TextureWrap.ClampToEdge;
page.vWrap = TextureWrap.ClampToEdge;
if (direction == "x")
page.uWrap = TextureWrap.Repeat;
else if (direction == "y")
page.vWrap = TextureWrap.Repeat;
else if (direction == "xy")
page.uWrap = page.vWrap = TextureWrap.Repeat;
textureLoader.Load(page, Path.Combine(imagesDir, line));
pages.Add(page);
} else {
AtlasRegion region = new AtlasRegion();
region.name = line;
region.page = page;
region.rotate = Boolean.Parse(readValue(reader));
readTuple(reader, tuple);
int x = int.Parse(tuple[0]);
int y = int.Parse(tuple[1]);
readTuple(reader, tuple);
int width = int.Parse(tuple[0]);
int height = int.Parse(tuple[1]);
region.u = x / (float)page.width;
region.v = y / (float)page.height;
if (region.rotate) {
region.u2 = (x + height) / (float)page.width;
region.v2 = (y + width) / (float)page.height;
} else {
region.u2 = (x + width) / (float)page.width;
region.v2 = (y + height) / (float)page.height;
}
region.x = x;
region.y = y;
region.width = Math.Abs(width);
region.height = Math.Abs(height);
if (readTuple(reader, tuple) == 4) { // split is optional
region.splits = new int[] {int.Parse(tuple[0]), int.Parse(tuple[1]),
int.Parse(tuple[2]), int.Parse(tuple[3])};
if (readTuple(reader, tuple) == 4) { // pad is optional, but only present with splits
region.pads = new int[] {int.Parse(tuple[0]), int.Parse(tuple[1]),
int.Parse(tuple[2]), int.Parse(tuple[3])};
readTuple(reader, tuple);
}
}
region.originalWidth = int.Parse(tuple[0]);
region.originalHeight = int.Parse(tuple[1]);
readTuple(reader, tuple);
region.offsetX = int.Parse(tuple[0]);
region.offsetY = int.Parse(tuple[1]);
region.index = int.Parse(readValue(reader));
regions.Add(region);
}
}
}
static String readValue (TextReader reader) {
String line = reader.ReadLine();
int colon = line.IndexOf(':');
if (colon == -1) throw new Exception("Invalid line: " + line);
return line.Substring(colon + 1).Trim();
}
/// <summary>Returns the number of tuple values read (2 or 4).</summary>
static int readTuple (TextReader reader, String[] tuple) {
String line = reader.ReadLine();
int colon = line.IndexOf(':');
if (colon == -1) throw new Exception("Invalid line: " + line);
int i = 0, lastMatch = colon + 1;
for (; i < 3; i++) {
int comma = line.IndexOf(',', lastMatch);
if (comma == -1) {
if (i == 0) throw new Exception("Invalid line: " + line);
break;
}
tuple[i] = line.Substring(lastMatch, comma - lastMatch).Trim();
lastMatch = comma + 1;
}
tuple[i] = line.Substring(lastMatch).Trim();
return i + 1;
}
/// <summary>Returns the first region found with the specified name. This method uses string comparison to find the region, so the result
/// should be cached rather than calling this method multiple times.</summary>
/// <returns>The region, or null.</returns>
public AtlasRegion FindRegion (String name) {
for (int i = 0, n = regions.Count; i < n; i++)
if (regions[i].name == name) return regions[i];
return null;
}
public void Dispose () {
if (textureLoader == null) return;
for (int i = 0, n = pages.Count; i < n; i++)
textureLoader.Unload(pages[i].rendererObject);
}
}
public enum Format {
Alpha,
Intensity,
LuminanceAlpha,
RGB565,
RGBA4444,
RGB888,
RGBA8888
}
public enum TextureFilter {
Nearest,
Linear,
MipMap,
MipMapNearestNearest,
MipMapLinearNearest,
MipMapNearestLinear,
MipMapLinearLinear
}
public enum TextureWrap {
MirroredRepeat,
ClampToEdge,
Repeat
}
public class AtlasPage {
public String name;
public Format format;
public TextureFilter minFilter;
public TextureFilter magFilter;
public TextureWrap uWrap;
public TextureWrap vWrap;
public Object rendererObject;
public int width, height;
}
public class AtlasRegion {
public AtlasPage page;
public String name;
public int x, y, width, height;
public float u, v, u2, v2;
public float offsetX, offsetY;
public int originalWidth, originalHeight;
public int index;
public bool rotate;
public int[] splits;
public int[] pads;
}
public interface TextureLoader {
void Load (AtlasPage page, String path);
void Unload (Object texture);
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Faithlife.Utility.Tests
{
[TestFixture]
public class CachingStreamTests
{
public void Dispose()
{
var data = GenerateData(1000);
using (var memoryStream = new MemoryStream(data, writable: false))
using (var cachingStream = new CachingStream(memoryStream, Ownership.Owns))
{
cachingStream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { cachingStream.Flush(); });
Assert.Throws<ObjectDisposedException>(() =>
{
var temp = cachingStream.Length;
});
Assert.Throws<ObjectDisposedException>(() =>
{
var temp = cachingStream.Position;
});
Assert.Throws<ObjectDisposedException>(() => { cachingStream.Position = 1; });
Assert.Throws<ObjectDisposedException>(() => cachingStream.ReadByte());
Assert.Throws<ObjectDisposedException>(() => cachingStream.Read(new byte[10], 0, 1));
Assert.Throws<ObjectDisposedException>(() => cachingStream.Seek(1, SeekOrigin.Begin));
}
}
[TestCase(0)]
[TestCase(1)]
[TestCase(1000)]
[TestCase(2000)]
public void Position(int position)
{
var data = GenerateData(1000);
using (var memoryStream = new MemoryStream(data, writable: false))
using (var cachingStream = new CachingStream(memoryStream, Ownership.Owns))
{
cachingStream.Position = position;
Assert.AreEqual(position, cachingStream.Position);
}
}
[TestCase(-1)]
public void PositionOutOfRange(int position)
{
var data = GenerateData(1000);
using (var memoryStream = new MemoryStream(data, writable: false))
using (var cachingStream = new CachingStream(memoryStream, Ownership.Owns))
{
Assert.Throws<ArgumentOutOfRangeException>(() => cachingStream.Position = position);
}
}
[TestCase(0)]
[TestCase(1)]
[TestCase(100)]
[TestCase(4095)]
[TestCase(4096)]
[TestCase(4097)]
[TestCase(8191)]
[TestCase(8192)]
[TestCase(8193)]
public void ReadBlock(int size)
{
var data = GenerateData(size);
using (var memoryStream = new MemoryStream(data, writable: false))
using (var cachingStream = new CachingStream(memoryStream, Ownership.Owns))
{
var buffer = new byte[size + 1];
var read = cachingStream.ReadBlock(buffer, 0, buffer.Length);
Assert.AreEqual(size, read);
Assert.AreEqual(data, buffer.Take(size));
Assert.AreEqual(size, (int) cachingStream.Position);
}
}
[TestCase(0)]
[TestCase(1)]
[TestCase(100)]
[TestCase(4095)]
[TestCase(4096)]
[TestCase(4097)]
[TestCase(8191)]
[TestCase(8192)]
[TestCase(8193)]
public void ReadByte(int size)
{
var data = GenerateData(size);
using (var memoryStream = new MemoryStream(data, writable: false))
using (var cachingStream = new CachingStream(memoryStream, Ownership.Owns))
{
for (var i = 0; i < size; i++)
Assert.AreEqual(data[i], cachingStream.ReadByte());
Assert.AreEqual(size, (int) cachingStream.Position);
Assert.AreEqual(-1, cachingStream.ReadByte());
Assert.AreEqual(size, (int) cachingStream.Position);
}
}
[Test]
public void SeekAndRead()
{
var random = new Random(1);
var data = GenerateData(1234567);
using (var memoryStream = new MemoryStream(data, writable: false))
using (var cachingStream = new CachingStream(memoryStream, Ownership.Owns))
{
for (var i = 0; i < 100; i++)
{
var offset = random.Next(data.Length - 100);
var length = random.Next(1, data.Length - offset);
Assert.AreEqual(offset, cachingStream.Seek(offset, SeekOrigin.Begin));
var read = cachingStream.ReadExactly(length);
Assert.AreEqual(data.Skip(offset).Take(length), read);
}
}
}
[Test]
public async Task SeekAndReadAsync()
{
var random = new Random(1);
var data = GenerateData(1234567);
using (var memoryStream = new MemoryStream(data, writable: false))
using (var cachingStream = new CachingStream(memoryStream, Ownership.Owns))
{
for (var i = 0; i < 100; i++)
{
var offset = random.Next(data.Length - 100);
var length = random.Next(1, data.Length - offset);
Assert.AreEqual(offset, cachingStream.Seek(offset, SeekOrigin.Begin));
var read = await cachingStream.ReadExactlyAsync(length);
Assert.AreEqual(data.Skip(offset).Take(length), read);
}
}
}
[Test]
public void SeekAndCopyTo()
{
var random = new Random(1);
var data = GenerateData(54321);
using (var memoryStream = new MemoryStream(data, writable: false))
using (var cachingStream = new CachingStream(memoryStream, Ownership.Owns))
{
for (var i = 0; i < 100; i++)
{
var offset = random.Next(data.Length - 100);
Assert.AreEqual(offset, cachingStream.Seek(offset, SeekOrigin.Begin));
using (var destination = new MemoryStream(data.Length))
{
cachingStream.CopyTo(destination);
Assert.AreEqual(data.Skip(offset), destination.ToArray());
}
}
}
}
[Test]
public async Task SeekAndCopyToAsync()
{
var random = new Random(1);
var data = GenerateData(54321);
using (var memoryStream = new MemoryStream(data, writable: false))
using (var cachingStream = new CachingStream(memoryStream, Ownership.Owns))
{
for (var i = 0; i < 100; i++)
{
var offset = random.Next(data.Length - 100);
Assert.AreEqual(offset, cachingStream.Seek(offset, SeekOrigin.Begin));
using (var destination = new MemoryStream(data.Length))
{
await cachingStream.CopyToAsync(destination);
Assert.AreEqual(data.Skip(offset), destination.ToArray());
}
}
}
}
[TestCase(1000)]
[TestCase(1001)]
[TestCase(4000)]
[TestCase(5000)]
[TestCase(50000)]
public void SeekAndReadAfterEnd(int position)
{
var data = GenerateData(1000);
using (var memoryStream = new MemoryStream(data, writable: false))
using (var cachingStream = new CachingStream(memoryStream, Ownership.Owns))
{
cachingStream.Position = position;
var buffer = new byte[10];
Assert.AreEqual(0, cachingStream.Read(buffer, 0, buffer.Length));
}
}
[Test]
public void SeekAndReadByte()
{
var random = new Random(2);
var data = GenerateData(123456);
using (var memoryStream = new MemoryStream(data, writable: false))
using (var cachingStream = new CachingStream(memoryStream, Ownership.Owns))
{
for (var i = 0; i < 100; i++)
{
var offset = random.Next(data.Length - 1);
cachingStream.Position = offset;
Assert.AreEqual(data[offset], cachingStream.ReadByte());
}
}
}
[Test]
public void Write()
{
var data = GenerateData(1000);
using (var memoryStream = new MemoryStream(data, writable: true))
using (var cachingStream = new CachingStream(memoryStream, Ownership.Owns))
{
Assert.IsFalse(cachingStream.CanWrite);
Assert.Throws<NotSupportedException>(() => cachingStream.SetLength(2000));
Assert.Throws<NotSupportedException>(() => cachingStream.Write(new byte[1], 0, 1));
Assert.Throws<NotSupportedException>(() => cachingStream.WriteByte(1));
Assert.Throws<NotSupportedException>(() => cachingStream.BeginWrite(new byte[1], 0, 1, null!, null));
Assert.Throws<NotSupportedException>(() => cachingStream.WriteAsync(new byte[1], 0, 1));
}
}
private static byte[] GenerateData(int size)
{
var results = new byte[size];
for (var index = 0; index < size; index++)
{
var value = index / 4;
var temp = BitConverter.GetBytes(value);
results[index] = temp[index % 4];
}
return results;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.MachineLearning.CommitmentPlans
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for CommitmentPlansOperations.
/// </summary>
public static partial class CommitmentPlansOperationsExtensions
{
/// <summary>
/// Retrieve an Azure ML commitment plan by its subscription, resource group
/// and name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='commitmentPlanName'>
/// The Azure ML commitment plan name.
/// </param>
public static CommitmentPlan Get(this ICommitmentPlansOperations operations, string resourceGroupName, string commitmentPlanName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICommitmentPlansOperations)s).GetAsync(resourceGroupName, commitmentPlanName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve an Azure ML commitment plan by its subscription, resource group
/// and name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='commitmentPlanName'>
/// The Azure ML commitment plan name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CommitmentPlan> GetAsync(this ICommitmentPlansOperations operations, string resourceGroupName, string commitmentPlanName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, commitmentPlanName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new Azure ML commitment plan resource or updates an existing one.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='createOrUpdatePayload'>
/// The payload to create or update the Azure ML commitment plan.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='commitmentPlanName'>
/// The Azure ML commitment plan name.
/// </param>
public static CommitmentPlan CreateOrUpdate(this ICommitmentPlansOperations operations, CommitmentPlan createOrUpdatePayload, string resourceGroupName, string commitmentPlanName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICommitmentPlansOperations)s).CreateOrUpdateAsync(createOrUpdatePayload, resourceGroupName, commitmentPlanName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Azure ML commitment plan resource or updates an existing one.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='createOrUpdatePayload'>
/// The payload to create or update the Azure ML commitment plan.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='commitmentPlanName'>
/// The Azure ML commitment plan name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CommitmentPlan> CreateOrUpdateAsync(this ICommitmentPlansOperations operations, CommitmentPlan createOrUpdatePayload, string resourceGroupName, string commitmentPlanName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(createOrUpdatePayload, resourceGroupName, commitmentPlanName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Remove an existing Azure ML commitment plan.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='commitmentPlanName'>
/// The Azure ML commitment plan name.
/// </param>
public static void Remove(this ICommitmentPlansOperations operations, string resourceGroupName, string commitmentPlanName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ICommitmentPlansOperations)s).RemoveAsync(resourceGroupName, commitmentPlanName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Remove an existing Azure ML commitment plan.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='commitmentPlanName'>
/// The Azure ML commitment plan name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task RemoveAsync(this ICommitmentPlansOperations operations, string resourceGroupName, string commitmentPlanName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.RemoveWithHttpMessagesAsync(resourceGroupName, commitmentPlanName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Patch an existing Azure ML commitment plan resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='patchPayload'>
/// The payload to patch the Azure ML commitment plan with. Only tags and SKU
/// may be modified on an existing commitment plan.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='commitmentPlanName'>
/// The Azure ML commitment plan name.
/// </param>
public static CommitmentPlan Patch(this ICommitmentPlansOperations operations, CommitmentPlanPatchPayload patchPayload, string resourceGroupName, string commitmentPlanName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICommitmentPlansOperations)s).PatchAsync(patchPayload, resourceGroupName, commitmentPlanName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patch an existing Azure ML commitment plan resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='patchPayload'>
/// The payload to patch the Azure ML commitment plan with. Only tags and SKU
/// may be modified on an existing commitment plan.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='commitmentPlanName'>
/// The Azure ML commitment plan name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CommitmentPlan> PatchAsync(this ICommitmentPlansOperations operations, CommitmentPlanPatchPayload patchPayload, string resourceGroupName, string commitmentPlanName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.PatchWithHttpMessagesAsync(patchPayload, resourceGroupName, commitmentPlanName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieve all Azure ML commitment plans in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='skipToken'>
/// Continuation token for pagination.
/// </param>
public static Microsoft.Rest.Azure.IPage<CommitmentPlan> List(this ICommitmentPlansOperations operations, string skipToken = default(string))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICommitmentPlansOperations)s).ListAsync(skipToken), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve all Azure ML commitment plans in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='skipToken'>
/// Continuation token for pagination.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<CommitmentPlan>> ListAsync(this ICommitmentPlansOperations operations, string skipToken = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(skipToken, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieve all Azure ML commitment plans in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='skipToken'>
/// Continuation token for pagination.
/// </param>
public static Microsoft.Rest.Azure.IPage<CommitmentPlan> ListInResourceGroup(this ICommitmentPlansOperations operations, string resourceGroupName, string skipToken = default(string))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICommitmentPlansOperations)s).ListInResourceGroupAsync(resourceGroupName, skipToken), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve all Azure ML commitment plans in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='skipToken'>
/// Continuation token for pagination.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<CommitmentPlan>> ListInResourceGroupAsync(this ICommitmentPlansOperations operations, string resourceGroupName, string skipToken = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListInResourceGroupWithHttpMessagesAsync(resourceGroupName, skipToken, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieve all Azure ML commitment plans in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<CommitmentPlan> ListNext(this ICommitmentPlansOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICommitmentPlansOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve all Azure ML commitment plans in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<CommitmentPlan>> ListNextAsync(this ICommitmentPlansOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieve all Azure ML commitment plans in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<CommitmentPlan> ListInResourceGroupNext(this ICommitmentPlansOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICommitmentPlansOperations)s).ListInResourceGroupNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve all Azure ML commitment plans in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<CommitmentPlan>> ListInResourceGroupNextAsync(this ICommitmentPlansOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListInResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
namespace Tests
{
[Serializable]
internal sealed class Options
{
const string RelativeRoot = @"..\..\..\..\";
const string TestHarnessDirectory = @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug";
public readonly string RootDirectory;
public readonly string SourceFile;
private readonly string compilerCode;
public string FoxtrotOptions;
private List<string> libPaths;
public readonly List<string> References;
public bool UseContractReferenceAssemblies;
public string BuildFramework = "v4.5";
public string ReferencesFramework
{
get
{
return referencesFramework ?? BuildFramework;
}
set
{
referencesFramework = value;
}
}
private string referencesFramework;
public string ContractFramework = "v4.5";
public bool UseBinDir = true;
public bool UseExe = true;
/// <summary>
/// If set to true, verification will include reading contracts back from the rewritten
/// assembly in addition to running peverify.
/// </summary>
public bool DeepVerify = false;
public List<string> LibPaths
{
get
{
if (libPaths == null) { libPaths = new List<string>(); }
return libPaths;
}
}
public string TestName
{
get
{
if (SourceFile != null) { return Path.GetFileNameWithoutExtension(SourceFile); }
else return "Unknown";
}
}
/// <summary>
/// Should be true, if old (pre-RC) Roslyn compiler needs to be used.
/// </summary>
public bool IsLegacyRoslyn { get; set; }
public string Compiler
{
get
{
switch (compilerCode)
{
case "VB":
return IsLegacyRoslyn ? "rvbc.exe" : "vbc.exe";
default:
return IsLegacyRoslyn ? "rcsc.exe" : "csc.exe";
}
}
}
public string CompilerPath
{
get { return compilerPath ?? BuildFramework; }
set { compilerPath = value; }
}
private string compilerPath;
public bool IsV35 { get { return this.BuildFramework.Contains("v3.5"); } }
public bool IsV40 { get { return this.BuildFramework.Contains("v4.0"); } }
public bool IsV45 { get { return this.BuildFramework.Contains("v4.5") || IsRoslynBasedCompiler; } }
bool IsSilverlight { get { return this.BuildFramework.Contains("Silverlight"); } }
public bool IsRoslynBasedCompiler { get { return CompilerPath.Contains("Roslyn"); } }
public string GetCompilerAbsolutePath(string toolsRoot)
{
return MakeAbsolute(Path.Combine(toolsRoot, CompilerPath, Compiler));
}
public string GetPEVerifyFullPath(string toolsRoot)
{
return MakeAbsolute(Path.Combine(toolsRoot, CompilerPath, "peverify.exe"));
}
string Moniker
{
get
{
if (!IsLegacyRoslyn) { return FrameworkMoniker; }
if (compilerCode == "VB")
{
return FrameworkMoniker + ",ROSLYN";
}
return FrameworkMoniker + ";ROSLYN";
}
}
string FrameworkMoniker
{
get
{
if (IsSilverlight)
{
if (IsV40)
{
return "SILVERLIGHT_4_0";
}
if (IsV45)
{
return "SILVERLIGHT_4_5";
}
{
return "SILVERLIGHT_3_0";
}
}
else
{
if (IsV40)
{
return "NETFRAMEWORK_4_0";
}
if (IsV45)
{
return "NETFRAMEWORK_4_5";
}
{
return "NETFRAMEWORK_3_5";
}
}
}
}
public bool UseTestHarness { get; set; }
private string DefaultCompilerOptions
{
get
{
if (compilerCode == "VB")
{
return
String.Format("/noconfig /nostdlib /define:\"DEBUG=-1,{0},CONTRACTS_FULL\",_MyType=\\\"Console\\\" " +
"/imports:Microsoft.VisualBasic,System,System.Collections,System.Collections.Generic,System.Data,System.Diagnostics,System.Linq,System.Xml.Linq " +
"/optioncompare:Binary /optionexplicit+ /optionstrict+ /optioninfer+ ",
Moniker);
}
if (IsRoslynBasedCompiler)
{
if (UseTestHarness)
{
return String.Format("/d:CONTRACTS_FULL;ROSLYN;DEBUG;{0} /noconfig /nostdlib {1}", Moniker,
MakeAbsolute(@"Foxtrot\Tests\Sources\TestHarness.cs"));
}
else
{
return String.Format("/d:CONTRACTS_FULL;ROSLYN;DEBUG;{0} /noconfig /nostdlib", Moniker);
}
}
else
{
if (UseTestHarness)
{
return String.Format("/d:CONTRACTS_FULL;DEBUG;{0} /noconfig /nostdlib {1}", Moniker,
MakeAbsolute(@"Foxtrot\Tests\Sources\TestHarness.cs"));
}
else
{
return String.Format("/d:CONTRACTS_FULL;DEBUG;{0} /noconfig /nostdlib", Moniker);
}
}
}
}
public string FinalCompilerOptions
{
get
{
return DefaultCompilerOptions + " " + CompilerOptions;
}
}
public string CompilerOptions { get; set; }
public Options(
string sourceFile,
string foxtrotOptions,
bool useContractReferenceAssemblies,
string compilerOptions,
string[] references,
string[] libPaths,
string compilerCode,
bool useBinDir,
bool useExe,
bool mustSucceed,
bool optimize,
bool releaseMode,
bool pdbOnly)
{
this.SourceFile = sourceFile;
this.FoxtrotOptions = foxtrotOptions;
this.UseContractReferenceAssemblies = useContractReferenceAssemblies;
this.CompilerOptions = compilerOptions;
this.References = new List<string>(new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" });
this.References.AddRange(references);
this.libPaths = new List<string>(libPaths ?? Enumerable.Empty<string>());
this.compilerCode = compilerCode;
this.UseBinDir = useBinDir;
this.UseExe = useExe;
this.MustSucceed = mustSucceed;
this.Optimize = optimize;
this.ReleaseMode = releaseMode;
this.PdbOnly = pdbOnly;
this.RootDirectory = Path.GetFullPath(RelativeRoot);
}
public Options(
string sourceFile,
string foxtrotOptions,
bool useContractReferenceAssemblies,
string compilerOptions,
string[] references,
string[] libPaths,
string compilerCode,
bool useBinDir,
bool useExe,
bool mustSucceed)
: this(
sourceFile,
foxtrotOptions,
useContractReferenceAssemblies,
compilerOptions,
references,
libPaths,
compilerCode,
useBinDir,
useExe,
mustSucceed,
false,
false,
false)
{
}
public Options WithSourceFile(string sourceFile)
{
Contract.Requires(!string.IsNullOrEmpty(sourceFile));
return new Options(
sourceFile: sourceFile,
foxtrotOptions: FoxtrotOptions,
useContractReferenceAssemblies: UseContractReferenceAssemblies,
compilerOptions: CompilerOptions,
references: References.ToArray(),
libPaths: LibPaths.ToArray(),
compilerCode: compilerCode,
useBinDir: UseBinDir,
useExe: UseExe,
mustSucceed: MustSucceed);
}
public bool ReleaseMode { get; set; }
public bool Optimize { get; set; }
public bool PdbOnly { get; set; }
private static string LoadString(System.Data.DataRow dataRow, string name)
{
if (!ColumnExists(dataRow, name)) return "";
return dataRow[name] as string;
}
private static List<string> LoadList(System.Data.DataRow dataRow, string name, params string[] initial)
{
var result = new List<string>(initial);
if (!ColumnExists(dataRow, name)) return result;
string listdata = dataRow[name] as string;
if (!string.IsNullOrEmpty(listdata))
{
result.AddRange(listdata.Split(';'));
}
return result;
}
private static bool ColumnExists(System.Data.DataRow dataRow, string name)
{
return dataRow.Table.Columns.IndexOf(name) >= 0;
}
private bool LoadBool(string name, System.Data.DataRow dataRow, bool defaultValue)
{
if (!ColumnExists(dataRow, name)) return defaultValue;
var booloption = dataRow[name] as string;
if (!string.IsNullOrEmpty(booloption))
{
bool result;
if (bool.TryParse(booloption, out result))
{
return result;
}
}
return defaultValue;
}
private string LoadString(string name, System.Data.DataRow dataRow, string defaultValue)
{
if (!ColumnExists(dataRow, name)) return defaultValue;
var option = dataRow[name] as string;
if (!string.IsNullOrEmpty(option))
{
return option;
}
return defaultValue;
}
/// <summary>
/// Not only makes the exe absolute but also tries to find it in the deployment dir to make code coverage work.
/// </summary>
public string GetFullExecutablePath(string relativePath)
{
return MakeAbsolute(relativePath);
}
public string MakeAbsolute(string relativeToRoot)
{
return Path.GetFullPath(Path.Combine(this.RootDirectory, relativeToRoot));
}
internal void Delete(string fileName)
{
var absolute = MakeAbsolute(fileName);
if (File.Exists(absolute))
{
File.Delete(absolute);
}
}
public bool MustSucceed { get; set; }
}
}
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.Security.Principal;
using EventStore.Common.Utils;
using EventStore.Core.Bus;
using EventStore.Core.Data;
using EventStore.Core.Helpers;
using EventStore.Core.Messages;
using EventStore.Core.Services;
using EventStore.Core.Services.TimerService;
using EventStore.Projections.Core.Messages;
namespace EventStore.Projections.Core.Services.Processing
{
public class ByStreamCatalogEventReader : EventReader
{
private readonly IODispatcher _ioDispatcher;
private readonly string _catalogStreamName;
private int _catalogCurrentSequenceNumber;
private int _catalogNextSequenceNumber;
private long? _limitingCommitPosition;
private readonly ITimeProvider _timeProvider;
private readonly bool _resolveLinkTos;
private int _maxReadCount = 111;
private int _deliveredEvents;
private string _dataStreamName;
private int _dataNextSequenceNumber;
private readonly Queue<string> _pendingStreams = new Queue<string>();
private Guid _catalogReadRequestId;
private Guid _dataReadRequestId;
private bool _catalogEof;
public ByStreamCatalogEventReader(
IPublisher publisher, Guid eventReaderCorrelationId, IPrincipal readAs, IODispatcher ioDispatcher,
string catalogCatalogStreamName, int catalogNextSequenceNumber, string dataStreamName,
int dataNextSequenceNumber, long? limitingCommitPosition, ITimeProvider timeProvider, bool resolveLinkTos,
int? stopAfterNEvents = null)
: base(ioDispatcher, publisher, eventReaderCorrelationId, readAs, true, stopAfterNEvents)
{
_ioDispatcher = ioDispatcher;
_catalogStreamName = catalogCatalogStreamName;
_catalogCurrentSequenceNumber = catalogNextSequenceNumber - 1;
_catalogNextSequenceNumber = catalogNextSequenceNumber;
_dataStreamName = dataStreamName;
_dataNextSequenceNumber = dataNextSequenceNumber;
_limitingCommitPosition = limitingCommitPosition;
_timeProvider = timeProvider;
_resolveLinkTos = resolveLinkTos;
}
protected override bool AreEventsRequested()
{
return _catalogReadRequestId != Guid.Empty || _dataReadRequestId != Guid.Empty;
}
private bool CheckEnough()
{
if (_stopAfterNEvents != null && _deliveredEvents >= _stopAfterNEvents)
{
_publisher.Publish(
new ReaderSubscriptionMessage.EventReaderEof(EventReaderCorrelationId, maxEventsReached: true));
Dispose();
return true;
}
return false;
}
protected override void RequestEvents()
{
if (_disposed) throw new InvalidOperationException("Disposed");
if (AreEventsRequested())
throw new InvalidOperationException("Read operation is already in progress");
if (PauseRequested || Paused)
throw new InvalidOperationException("Paused or pause requested");
if (_pendingStreams.Count < 10 && !_catalogEof)
{
_catalogReadRequestId = _ioDispatcher.ReadForward(
_catalogStreamName, _catalogNextSequenceNumber, _maxReadCount, false, ReadAs, ReadCatalogCompleted);
}
else
{
TakeNextStreamIfRequired();
if (!_disposed)
{
_dataReadRequestId = _ioDispatcher.ReadForward(
_dataStreamName, _dataNextSequenceNumber, _maxReadCount, _resolveLinkTos, ReadAs,
ReadDataStreamCompleted);
}
}
}
private void TakeNextStreamIfRequired()
{
if (_dataNextSequenceNumber == int.MaxValue || _dataStreamName == null)
{
if (_dataStreamName != null)
SendPartitionEof(
_dataStreamName,
CheckpointTag.FromByStreamPosition(
0, _catalogStreamName, _catalogCurrentSequenceNumber, _dataStreamName, int.MaxValue,
_limitingCommitPosition.Value));
if (_catalogEof && _pendingStreams.Count == 0)
{
SendEof();
return;
}
_dataStreamName = _pendingStreams.Dequeue();
_catalogCurrentSequenceNumber++;
_dataNextSequenceNumber = 0;
}
}
private void ReadDataStreamCompleted(ClientMessage.ReadStreamEventsForwardCompleted completed)
{
_dataReadRequestId = Guid.Empty;
if (Paused)
throw new InvalidOperationException("Paused");
switch (completed.Result)
{
case ReadStreamResult.AccessDenied:
SendNotAuthorized();
return;
case ReadStreamResult.NoStream:
_dataNextSequenceNumber = int.MaxValue;
if (completed.LastEventNumber >= 0)
SendPartitionDeleted(_dataStreamName, -1, null, null, null, null);
PauseOrContinueProcessing();
break;
case ReadStreamResult.StreamDeleted:
_dataNextSequenceNumber = int.MaxValue;
SendPartitionDeleted(_dataStreamName, -1, null, null, null, null);
PauseOrContinueProcessing();
break;
case ReadStreamResult.Success:
foreach (var e in completed.Events)
{
DeliverEvent(e, 17.7f);
if (CheckEnough())
return;
}
if (completed.IsEndOfStream)
_dataNextSequenceNumber = int.MaxValue;
PauseOrContinueProcessing();
break;
default:
throw new NotSupportedException();
}
}
private void ReadCatalogCompleted(ClientMessage.ReadStreamEventsForwardCompleted completed)
{
_catalogReadRequestId = Guid.Empty;
if (Paused)
throw new InvalidOperationException("Paused");
switch (completed.Result)
{
case ReadStreamResult.AccessDenied:
SendNotAuthorized();
return;
case ReadStreamResult.NoStream:
case ReadStreamResult.StreamDeleted:
_catalogEof = true;
SendEof();
return;
case ReadStreamResult.Success:
_limitingCommitPosition = _limitingCommitPosition ?? completed.TfLastCommitPosition;
foreach (var e in completed.Events)
EnqueueStreamForProcessing(e);
if (completed.IsEndOfStream)
_catalogEof = true;
PauseOrContinueProcessing();
break;
default:
throw new NotSupportedException();
}
}
private void EnqueueStreamForProcessing(EventStore.Core.Data.ResolvedEvent resolvedEvent)
{
//TODO: consider catalog referring to earlier written events (should we check here?)
if (resolvedEvent.OriginalEvent.LogPosition > _limitingCommitPosition)
return;
var streamId = SystemEventTypes.StreamReferenceEventToStreamId(resolvedEvent.Event.EventType, resolvedEvent.Event.Data);
_pendingStreams.Enqueue(streamId);
_catalogNextSequenceNumber = resolvedEvent.OriginalEventNumber;
}
private void DeliverEvent(EventStore.Core.Data.ResolvedEvent pair, float progress)
{
_deliveredEvents++;
EventRecord positionEvent = pair.OriginalEvent;
if (positionEvent.LogPosition > _limitingCommitPosition)
return;
var resolvedEvent = new ResolvedEvent(pair, null);
if (resolvedEvent.IsLinkToDeletedStream || resolvedEvent.IsStreamDeletedEvent)
return;
_publisher.Publish(
//TODO: publish both link and event data
new ReaderSubscriptionMessage.CommittedEventDistributed(
EventReaderCorrelationId, resolvedEvent,
_stopOnEof ? (long?) null : positionEvent.LogPosition, progress, source: GetType(),
preTagged:
CheckpointTag.FromByStreamPosition(
0, _catalogStreamName, _catalogCurrentSequenceNumber, positionEvent.EventStreamId,
positionEvent.EventNumber, _limitingCommitPosition.Value)));
//TODO: consider passing phase from outside instead of using 0 (above)
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DLAppService.cs">
// Copyright (c) 2014-present Andrea Di Giorgi
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// <author>Andrea Di Giorgi</author>
// <website>https://github.com/Ithildir/liferay-sdk-builder-windows</website>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Liferay.SDK.Service.V62.DLApp
{
public class DLAppService : ServiceBase
{
public DLAppService(ISession session)
: base(session)
{
}
public async Task<dynamic> AddFileEntryAsync(long repositoryId, long folderId, string sourceFileName, string mimeType, string title, string description, string changeLog, byte[] bytes, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("sourceFileName", sourceFileName);
_parameters.Add("mimeType", mimeType);
_parameters.Add("title", title);
_parameters.Add("description", description);
_parameters.Add("changeLog", changeLog);
_parameters.Add("bytes", bytes);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/add-file-entry", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> AddFileEntryAsync(long repositoryId, long folderId, string sourceFileName, string mimeType, string title, string description, string changeLog, Stream file, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("sourceFileName", sourceFileName);
_parameters.Add("mimeType", mimeType);
_parameters.Add("title", title);
_parameters.Add("description", description);
_parameters.Add("changeLog", changeLog);
_parameters.Add("file", file);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/add-file-entry", _parameters }
};
var _obj = await this.Session.UploadAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> AddFileShortcutAsync(long repositoryId, long folderId, long toFileEntryId, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("toFileEntryId", toFileEntryId);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/add-file-shortcut", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> AddFolderAsync(long repositoryId, long parentFolderId, string name, string description, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("name", name);
_parameters.Add("description", description);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/add-folder", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> AddTempFileEntryAsync(long groupId, long folderId, string fileName, string tempFolderName, Stream file, string mimeType)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("folderId", folderId);
_parameters.Add("fileName", fileName);
_parameters.Add("tempFolderName", tempFolderName);
_parameters.Add("file", file);
_parameters.Add("mimeType", mimeType);
var _command = new JsonObject()
{
{ "/dlapp/add-temp-file-entry", _parameters }
};
var _obj = await this.Session.UploadAsync(_command);
return (dynamic)_obj;
}
public async Task CancelCheckOutAsync(long fileEntryId)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
var _command = new JsonObject()
{
{ "/dlapp/cancel-check-out", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task CheckInFileEntryAsync(long fileEntryId, string lockUuid)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("lockUuid", lockUuid);
var _command = new JsonObject()
{
{ "/dlapp/check-in-file-entry", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task CheckInFileEntryAsync(long fileEntryId, string lockUuid, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("lockUuid", lockUuid);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/check-in-file-entry", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task CheckInFileEntryAsync(long fileEntryId, bool majorVersion, string changeLog, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("majorVersion", majorVersion);
_parameters.Add("changeLog", changeLog);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/check-in-file-entry", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task CheckOutFileEntryAsync(long fileEntryId, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/check-out-file-entry", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<dynamic> CheckOutFileEntryAsync(long fileEntryId, string owner, long expirationTime, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("owner", owner);
_parameters.Add("expirationTime", expirationTime);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/check-out-file-entry", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> CopyFolderAsync(long repositoryId, long sourceFolderId, long parentFolderId, string name, string description, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("sourceFolderId", sourceFolderId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("name", name);
_parameters.Add("description", description);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/copy-folder", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task DeleteFileEntryAsync(long fileEntryId)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
var _command = new JsonObject()
{
{ "/dlapp/delete-file-entry", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task DeleteFileEntryByTitleAsync(long repositoryId, long folderId, string title)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("title", title);
var _command = new JsonObject()
{
{ "/dlapp/delete-file-entry-by-title", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task DeleteFileShortcutAsync(long fileShortcutId)
{
var _parameters = new JsonObject();
_parameters.Add("fileShortcutId", fileShortcutId);
var _command = new JsonObject()
{
{ "/dlapp/delete-file-shortcut", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task DeleteFileVersionAsync(long fileEntryId, string version)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("version", version);
var _command = new JsonObject()
{
{ "/dlapp/delete-file-version", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task DeleteFolderAsync(long folderId)
{
var _parameters = new JsonObject();
_parameters.Add("folderId", folderId);
var _command = new JsonObject()
{
{ "/dlapp/delete-folder", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task DeleteFolderAsync(long repositoryId, long parentFolderId, string name)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("name", name);
var _command = new JsonObject()
{
{ "/dlapp/delete-folder", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task DeleteTempFileEntryAsync(long groupId, long folderId, string fileName, string tempFolderName)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("folderId", folderId);
_parameters.Add("fileName", fileName);
_parameters.Add("tempFolderName", tempFolderName);
var _command = new JsonObject()
{
{ "/dlapp/delete-temp-file-entry", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<IEnumerable<dynamic>> GetFileEntriesAsync(long repositoryId, long folderId)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entries", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFileEntriesAsync(long repositoryId, long folderId, long fileEntryTypeId)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("fileEntryTypeId", fileEntryTypeId);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entries", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFileEntriesAsync(long repositoryId, long folderId, IEnumerable<string> mimeTypes)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("mimeTypes", mimeTypes);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entries", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFileEntriesAsync(long repositoryId, long folderId, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entries", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFileEntriesAsync(long repositoryId, long folderId, long fileEntryTypeId, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("fileEntryTypeId", fileEntryTypeId);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entries", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFileEntriesAsync(long repositoryId, long folderId, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entries", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFileEntriesAsync(long repositoryId, long folderId, long fileEntryTypeId, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("fileEntryTypeId", fileEntryTypeId);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entries", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFileEntriesAndFileShortcutsAsync(long repositoryId, long folderId, int status, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("status", status);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entries-and-file-shortcuts", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<long> GetFileEntriesAndFileShortcutsCountAsync(long repositoryId, long folderId, int status)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("status", status);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entries-and-file-shortcuts-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> GetFileEntriesAndFileShortcutsCountAsync(long repositoryId, long folderId, int status, IEnumerable<string> mimeTypes)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("status", status);
_parameters.Add("mimeTypes", mimeTypes);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entries-and-file-shortcuts-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> GetFileEntriesCountAsync(long repositoryId, long folderId)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entries-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> GetFileEntriesCountAsync(long repositoryId, long folderId, long fileEntryTypeId)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("fileEntryTypeId", fileEntryTypeId);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entries-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<dynamic> GetFileEntryAsync(long fileEntryId)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entry", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> GetFileEntryAsync(long groupId, long folderId, string title)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("folderId", folderId);
_parameters.Add("title", title);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entry", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> GetFileEntryByUuidAndGroupIdAsync(string uuid, long groupId)
{
var _parameters = new JsonObject();
_parameters.Add("uuid", uuid);
_parameters.Add("groupId", groupId);
var _command = new JsonObject()
{
{ "/dlapp/get-file-entry-by-uuid-and-group-id", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> GetFileShortcutAsync(long fileShortcutId)
{
var _parameters = new JsonObject();
_parameters.Add("fileShortcutId", fileShortcutId);
var _command = new JsonObject()
{
{ "/dlapp/get-file-shortcut", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> GetFolderAsync(long folderId)
{
var _parameters = new JsonObject();
_parameters.Add("folderId", folderId);
var _command = new JsonObject()
{
{ "/dlapp/get-folder", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> GetFolderAsync(long repositoryId, long parentFolderId, string name)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("name", name);
var _command = new JsonObject()
{
{ "/dlapp/get-folder", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<IEnumerable<dynamic>> GetFoldersAsync(long repositoryId, long parentFolderId)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
var _command = new JsonObject()
{
{ "/dlapp/get-folders", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFoldersAsync(long repositoryId, long parentFolderId, bool includeMountFolders)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("includeMountFolders", includeMountFolders);
var _command = new JsonObject()
{
{ "/dlapp/get-folders", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFoldersAsync(long repositoryId, long parentFolderId, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/dlapp/get-folders", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFoldersAsync(long repositoryId, long parentFolderId, bool includeMountFolders, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("includeMountFolders", includeMountFolders);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/dlapp/get-folders", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFoldersAsync(long repositoryId, long parentFolderId, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/dlapp/get-folders", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFoldersAsync(long repositoryId, long parentFolderId, bool includeMountFolders, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("includeMountFolders", includeMountFolders);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/dlapp/get-folders", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFoldersAsync(long repositoryId, long parentFolderId, int status, bool includeMountFolders, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("status", status);
_parameters.Add("includeMountFolders", includeMountFolders);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/dlapp/get-folders", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFoldersAndFileEntriesAndFileShortcutsAsync(long repositoryId, long folderId, int status, bool includeMountFolders, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("status", status);
_parameters.Add("includeMountFolders", includeMountFolders);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/dlapp/get-folders-and-file-entries-and-file-shortcuts", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFoldersAndFileEntriesAndFileShortcutsAsync(long repositoryId, long folderId, int status, bool includeMountFolders, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("status", status);
_parameters.Add("includeMountFolders", includeMountFolders);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/dlapp/get-folders-and-file-entries-and-file-shortcuts", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetFoldersAndFileEntriesAndFileShortcutsAsync(long repositoryId, long folderId, int status, IEnumerable<string> mimeTypes, bool includeMountFolders, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("status", status);
_parameters.Add("mimeTypes", mimeTypes);
_parameters.Add("includeMountFolders", includeMountFolders);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/dlapp/get-folders-and-file-entries-and-file-shortcuts", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<long> GetFoldersAndFileEntriesAndFileShortcutsCountAsync(long repositoryId, long folderId, int status, bool includeMountFolders)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("status", status);
_parameters.Add("includeMountFolders", includeMountFolders);
var _command = new JsonObject()
{
{ "/dlapp/get-folders-and-file-entries-and-file-shortcuts-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> GetFoldersAndFileEntriesAndFileShortcutsCountAsync(long repositoryId, long folderId, int status, IEnumerable<string> mimeTypes, bool includeMountFolders)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("status", status);
_parameters.Add("mimeTypes", mimeTypes);
_parameters.Add("includeMountFolders", includeMountFolders);
var _command = new JsonObject()
{
{ "/dlapp/get-folders-and-file-entries-and-file-shortcuts-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> GetFoldersCountAsync(long repositoryId, long parentFolderId)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
var _command = new JsonObject()
{
{ "/dlapp/get-folders-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> GetFoldersCountAsync(long repositoryId, long parentFolderId, bool includeMountFolders)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("includeMountFolders", includeMountFolders);
var _command = new JsonObject()
{
{ "/dlapp/get-folders-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> GetFoldersCountAsync(long repositoryId, long parentFolderId, int status, bool includeMountFolders)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("status", status);
_parameters.Add("includeMountFolders", includeMountFolders);
var _command = new JsonObject()
{
{ "/dlapp/get-folders-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> GetFoldersFileEntriesCountAsync(long repositoryId, IEnumerable<object> folderIds, int status)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderIds", folderIds);
_parameters.Add("status", status);
var _command = new JsonObject()
{
{ "/dlapp/get-folders-file-entries-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<IEnumerable<dynamic>> GetGroupFileEntriesAsync(long groupId, long userId, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("userId", userId);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/dlapp/get-group-file-entries", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetGroupFileEntriesAsync(long groupId, long userId, long rootFolderId, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("userId", userId);
_parameters.Add("rootFolderId", rootFolderId);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/dlapp/get-group-file-entries", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetGroupFileEntriesAsync(long groupId, long userId, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("userId", userId);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/dlapp/get-group-file-entries", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetGroupFileEntriesAsync(long groupId, long userId, long rootFolderId, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("userId", userId);
_parameters.Add("rootFolderId", rootFolderId);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/dlapp/get-group-file-entries", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetGroupFileEntriesAsync(long groupId, long userId, long rootFolderId, IEnumerable<string> mimeTypes, int status, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("userId", userId);
_parameters.Add("rootFolderId", rootFolderId);
_parameters.Add("mimeTypes", mimeTypes);
_parameters.Add("status", status);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/dlapp/get-group-file-entries", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<long> GetGroupFileEntriesCountAsync(long groupId, long userId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("userId", userId);
var _command = new JsonObject()
{
{ "/dlapp/get-group-file-entries-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> GetGroupFileEntriesCountAsync(long groupId, long userId, long rootFolderId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("userId", userId);
_parameters.Add("rootFolderId", rootFolderId);
var _command = new JsonObject()
{
{ "/dlapp/get-group-file-entries-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<long> GetGroupFileEntriesCountAsync(long groupId, long userId, long rootFolderId, IEnumerable<string> mimeTypes, int status)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("userId", userId);
_parameters.Add("rootFolderId", rootFolderId);
_parameters.Add("mimeTypes", mimeTypes);
_parameters.Add("status", status);
var _command = new JsonObject()
{
{ "/dlapp/get-group-file-entries-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<IEnumerable<dynamic>> GetMountFoldersAsync(long repositoryId, long parentFolderId)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
var _command = new JsonObject()
{
{ "/dlapp/get-mount-folders", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetMountFoldersAsync(long repositoryId, long parentFolderId, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/dlapp/get-mount-folders", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetMountFoldersAsync(long repositoryId, long parentFolderId, int start, int end, JsonObjectWrapper obc)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("start", start);
_parameters.Add("end", end);
this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);
var _command = new JsonObject()
{
{ "/dlapp/get-mount-folders", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<long> GetMountFoldersCountAsync(long repositoryId, long parentFolderId)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
var _command = new JsonObject()
{
{ "/dlapp/get-mount-folders-count", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (long)_obj;
}
public async Task<IEnumerable<dynamic>> GetSubfolderIdsAsync(long repositoryId, long folderId)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
var _command = new JsonObject()
{
{ "/dlapp/get-subfolder-ids", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetSubfolderIdsAsync(long repositoryId, long folderId, bool recurse)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("recurse", recurse);
var _command = new JsonObject()
{
{ "/dlapp/get-subfolder-ids", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task GetSubfolderIdsAsync(long repositoryId, IEnumerable<object> folderIds, long folderId)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderIds", folderIds);
_parameters.Add("folderId", folderId);
var _command = new JsonObject()
{
{ "/dlapp/get-subfolder-ids", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<IEnumerable<string>> GetTempFileEntryNamesAsync(long groupId, long folderId, string tempFolderName)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("folderId", folderId);
_parameters.Add("tempFolderName", tempFolderName);
var _command = new JsonObject()
{
{ "/dlapp/get-temp-file-entry-names", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
var _jsonArray = (JsonArray)_obj;
return _jsonArray.Cast<string>();
}
public async Task<dynamic> LockFileEntryAsync(long fileEntryId)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
var _command = new JsonObject()
{
{ "/dlapp/lock-file-entry", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> LockFileEntryAsync(long fileEntryId, string owner, long expirationTime)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("owner", owner);
_parameters.Add("expirationTime", expirationTime);
var _command = new JsonObject()
{
{ "/dlapp/lock-file-entry", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> LockFolderAsync(long repositoryId, long folderId)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
var _command = new JsonObject()
{
{ "/dlapp/lock-folder", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> LockFolderAsync(long repositoryId, long folderId, string owner, bool inheritable, long expirationTime)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("owner", owner);
_parameters.Add("inheritable", inheritable);
_parameters.Add("expirationTime", expirationTime);
var _command = new JsonObject()
{
{ "/dlapp/lock-folder", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> MoveFileEntryAsync(long fileEntryId, long newFolderId, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("newFolderId", newFolderId);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/move-file-entry", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> MoveFileEntryFromTrashAsync(long fileEntryId, long newFolderId, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("newFolderId", newFolderId);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/move-file-entry-from-trash", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> MoveFileEntryToTrashAsync(long fileEntryId)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
var _command = new JsonObject()
{
{ "/dlapp/move-file-entry-to-trash", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> MoveFileShortcutFromTrashAsync(long fileShortcutId, long newFolderId, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("fileShortcutId", fileShortcutId);
_parameters.Add("newFolderId", newFolderId);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/move-file-shortcut-from-trash", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> MoveFileShortcutToTrashAsync(long fileShortcutId)
{
var _parameters = new JsonObject();
_parameters.Add("fileShortcutId", fileShortcutId);
var _command = new JsonObject()
{
{ "/dlapp/move-file-shortcut-to-trash", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> MoveFolderAsync(long folderId, long parentFolderId, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("folderId", folderId);
_parameters.Add("parentFolderId", parentFolderId);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/move-folder", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> MoveFolderFromTrashAsync(long folderId, long parentFolderId, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("folderId", folderId);
_parameters.Add("parentFolderId", parentFolderId);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/move-folder-from-trash", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> MoveFolderToTrashAsync(long folderId)
{
var _parameters = new JsonObject();
_parameters.Add("folderId", folderId);
var _command = new JsonObject()
{
{ "/dlapp/move-folder-to-trash", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> RefreshFileEntryLockAsync(string lockUuid, long companyId, long expirationTime)
{
var _parameters = new JsonObject();
_parameters.Add("lockUuid", lockUuid);
_parameters.Add("companyId", companyId);
_parameters.Add("expirationTime", expirationTime);
var _command = new JsonObject()
{
{ "/dlapp/refresh-file-entry-lock", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> RefreshFolderLockAsync(string lockUuid, long companyId, long expirationTime)
{
var _parameters = new JsonObject();
_parameters.Add("lockUuid", lockUuid);
_parameters.Add("companyId", companyId);
_parameters.Add("expirationTime", expirationTime);
var _command = new JsonObject()
{
{ "/dlapp/refresh-folder-lock", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task RestoreFileEntryFromTrashAsync(long fileEntryId)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
var _command = new JsonObject()
{
{ "/dlapp/restore-file-entry-from-trash", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task RestoreFileShortcutFromTrashAsync(long fileShortcutId)
{
var _parameters = new JsonObject();
_parameters.Add("fileShortcutId", fileShortcutId);
var _command = new JsonObject()
{
{ "/dlapp/restore-file-shortcut-from-trash", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task RestoreFolderFromTrashAsync(long folderId)
{
var _parameters = new JsonObject();
_parameters.Add("folderId", folderId);
var _command = new JsonObject()
{
{ "/dlapp/restore-folder-from-trash", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task RevertFileEntryAsync(long fileEntryId, string version, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("version", version);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/revert-file-entry", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<dynamic> SearchAsync(long repositoryId, JsonObjectWrapper searchContext)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
this.MangleWrapper(_parameters, "searchContext", "com.liferay.portal.kernel.search.SearchContext", searchContext);
var _command = new JsonObject()
{
{ "/dlapp/search", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> SearchAsync(long repositoryId, JsonObjectWrapper searchContext, JsonObjectWrapper query)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
this.MangleWrapper(_parameters, "searchContext", "com.liferay.portal.kernel.search.SearchContext", searchContext);
this.MangleWrapper(_parameters, "query", "com.liferay.portal.kernel.search.Query", query);
var _command = new JsonObject()
{
{ "/dlapp/search", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> SearchAsync(long repositoryId, long creatorUserId, int status, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("creatorUserId", creatorUserId);
_parameters.Add("status", status);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/dlapp/search", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> SearchAsync(long repositoryId, long creatorUserId, long folderId, IEnumerable<string> mimeTypes, int status, int start, int end)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("creatorUserId", creatorUserId);
_parameters.Add("folderId", folderId);
_parameters.Add("mimeTypes", mimeTypes);
_parameters.Add("status", status);
_parameters.Add("start", start);
_parameters.Add("end", end);
var _command = new JsonObject()
{
{ "/dlapp/search", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task SubscribeFileEntryTypeAsync(long groupId, long fileEntryTypeId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("fileEntryTypeId", fileEntryTypeId);
var _command = new JsonObject()
{
{ "/dlapp/subscribe-file-entry-type", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task SubscribeFolderAsync(long groupId, long folderId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("folderId", folderId);
var _command = new JsonObject()
{
{ "/dlapp/subscribe-folder", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task UnlockFileEntryAsync(long fileEntryId)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
var _command = new JsonObject()
{
{ "/dlapp/unlock-file-entry", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task UnlockFileEntryAsync(long fileEntryId, string lockUuid)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("lockUuid", lockUuid);
var _command = new JsonObject()
{
{ "/dlapp/unlock-file-entry", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task UnlockFolderAsync(long repositoryId, long folderId, string lockUuid)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("lockUuid", lockUuid);
var _command = new JsonObject()
{
{ "/dlapp/unlock-folder", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task UnlockFolderAsync(long repositoryId, long parentFolderId, string name, string lockUuid)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("parentFolderId", parentFolderId);
_parameters.Add("name", name);
_parameters.Add("lockUuid", lockUuid);
var _command = new JsonObject()
{
{ "/dlapp/unlock-folder", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task UnsubscribeFileEntryTypeAsync(long groupId, long fileEntryTypeId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("fileEntryTypeId", fileEntryTypeId);
var _command = new JsonObject()
{
{ "/dlapp/unsubscribe-file-entry-type", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task UnsubscribeFolderAsync(long groupId, long folderId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
_parameters.Add("folderId", folderId);
var _command = new JsonObject()
{
{ "/dlapp/unsubscribe-folder", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<dynamic> UpdateFileEntryAsync(long fileEntryId, string sourceFileName, string mimeType, string title, string description, string changeLog, bool majorVersion, byte[] bytes, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("sourceFileName", sourceFileName);
_parameters.Add("mimeType", mimeType);
_parameters.Add("title", title);
_parameters.Add("description", description);
_parameters.Add("changeLog", changeLog);
_parameters.Add("majorVersion", majorVersion);
_parameters.Add("bytes", bytes);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/update-file-entry", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> UpdateFileEntryAsync(long fileEntryId, string sourceFileName, string mimeType, string title, string description, string changeLog, bool majorVersion, Stream file, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("sourceFileName", sourceFileName);
_parameters.Add("mimeType", mimeType);
_parameters.Add("title", title);
_parameters.Add("description", description);
_parameters.Add("changeLog", changeLog);
_parameters.Add("majorVersion", majorVersion);
_parameters.Add("file", file);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/update-file-entry", _parameters }
};
var _obj = await this.Session.UploadAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> UpdateFileEntryAndCheckInAsync(long fileEntryId, string sourceFileName, string mimeType, string title, string description, string changeLog, bool majorVersion, Stream file, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("sourceFileName", sourceFileName);
_parameters.Add("mimeType", mimeType);
_parameters.Add("title", title);
_parameters.Add("description", description);
_parameters.Add("changeLog", changeLog);
_parameters.Add("majorVersion", majorVersion);
_parameters.Add("file", file);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/update-file-entry-and-check-in", _parameters }
};
var _obj = await this.Session.UploadAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> UpdateFileShortcutAsync(long fileShortcutId, long folderId, long toFileEntryId, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("fileShortcutId", fileShortcutId);
_parameters.Add("folderId", folderId);
_parameters.Add("toFileEntryId", toFileEntryId);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/update-file-shortcut", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> UpdateFolderAsync(long folderId, string name, string description, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("folderId", folderId);
_parameters.Add("name", name);
_parameters.Add("description", description);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/dlapp/update-folder", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<bool> VerifyFileEntryCheckOutAsync(long repositoryId, long fileEntryId, string lockUuid)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("lockUuid", lockUuid);
var _command = new JsonObject()
{
{ "/dlapp/verify-file-entry-check-out", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (bool)_obj;
}
public async Task<bool> VerifyFileEntryLockAsync(long repositoryId, long fileEntryId, string lockUuid)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("fileEntryId", fileEntryId);
_parameters.Add("lockUuid", lockUuid);
var _command = new JsonObject()
{
{ "/dlapp/verify-file-entry-lock", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (bool)_obj;
}
public async Task<bool> VerifyInheritableLockAsync(long repositoryId, long folderId, string lockUuid)
{
var _parameters = new JsonObject();
_parameters.Add("repositoryId", repositoryId);
_parameters.Add("folderId", folderId);
_parameters.Add("lockUuid", lockUuid);
var _command = new JsonObject()
{
{ "/dlapp/verify-inheritable-lock", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (bool)_obj;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using OpenMetaverse;
using log4net;
namespace OpenSim.Framework
{
public abstract class TerrainData
{
// Terrain always is a square
public int SizeX { get; protected set; }
public int SizeY { get; protected set; }
public int SizeZ { get; protected set; }
// A height used when the user doesn't specify anything
public const float DefaultTerrainHeight = 21f;
public abstract float this[int x, int y] { get; set; }
// Someday terrain will have caves
public abstract float this[int x, int y, int z] { get; set; }
public abstract bool IsTaintedAt(int xx, int yy);
public abstract bool IsTaintedAt(int xx, int yy, bool clearOnTest);
public abstract void TaintAllTerrain();
public abstract void ClearTaint();
public abstract void ClearLand();
public abstract void ClearLand(float height);
// Return a representation of this terrain for storing as a blob in the database.
// Returns 'true' to say blob was stored in the 'out' locations.
public abstract bool GetDatabaseBlob(out int DBFormatRevisionCode, out Array blob);
// Given a revision code and a blob from the database, create and return the right type of TerrainData.
// The sizes passed are the expected size of the region. The database info will be used to
// initialize the heightmap of that sized region with as much data is in the blob.
// Return created TerrainData or 'null' if unsuccessful.
public static TerrainData CreateFromDatabaseBlobFactory(int pSizeX, int pSizeY, int pSizeZ, int pFormatCode, byte[] pBlob)
{
// For the moment, there is only one implementation class
return new HeightmapTerrainData(pSizeX, pSizeY, pSizeZ, pFormatCode, pBlob);
}
// return a special compressed representation of the heightmap in ints
public abstract int[] GetCompressedMap();
public abstract float CompressionFactor { get; }
public abstract float[] GetFloatsSerialized();
public abstract double[,] GetDoubles();
public abstract TerrainData Clone();
}
// The terrain is stored in the database as a blob with a 'revision' field.
// Some implementations of terrain storage would fill the revision field with
// the time the terrain was stored. When real revisions were added and this
// feature removed, that left some old entries with the time in the revision
// field.
// Thus, if revision is greater than 'RevisionHigh' then terrain db entry is
// left over and it is presumed to be 'Legacy256'.
// Numbers are arbitrary and are chosen to to reduce possible mis-interpretation.
// If a revision does not match any of these, it is assumed to be Legacy256.
public enum DBTerrainRevision
{
// Terrain is 'double[256,256]'
Legacy256 = 11,
// Terrain is 'int32, int32, float[,]' where the ints are X and Y dimensions
// The dimensions are presumed to be multiples of 16 and, more likely, multiples of 256.
Variable2D = 22,
// Terrain is 'int32, int32, int32, int16[]' where the ints are X and Y dimensions
// and third int is the 'compression factor'. The heights are compressed as
// "int compressedHeight = (int)(height * compressionFactor);"
// The dimensions are presumed to be multiples of 16 and, more likely, multiples of 256.
Compressed2D = 27,
// A revision that is not listed above or any revision greater than this value is 'Legacy256'.
RevisionHigh = 1234
}
// Version of terrain that is a heightmap.
// This should really be 'LLOptimizedHeightmapTerrainData' as it includes knowledge
// of 'patches' which are 16x16 terrain areas which can be sent separately to the viewer.
// The heighmap is kept as an array of integers. The integer values are converted to
// and from floats by TerrainCompressionFactor.
public class HeightmapTerrainData : TerrainData
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static string LogHeader = "[HEIGHTMAP TERRAIN DATA]";
// TerrainData.this[x, y]
public override float this[int x, int y]
{
get { return FromCompressedHeight(m_heightmap[x, y]); }
set {
int newVal = ToCompressedHeight(value);
if (m_heightmap[x, y] != newVal)
{
m_heightmap[x, y] = newVal;
m_taint[x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize] = true;
}
}
}
// TerrainData.this[x, y, z]
public override float this[int x, int y, int z]
{
get { return this[x, y]; }
set { this[x, y] = value; }
}
// TerrainData.ClearTaint
public override void ClearTaint()
{
SetAllTaint(false);
}
// TerrainData.TaintAllTerrain
public override void TaintAllTerrain()
{
SetAllTaint(true);
}
private void SetAllTaint(bool setting)
{
for (int ii = 0; ii < m_taint.GetLength(0); ii++)
for (int jj = 0; jj < m_taint.GetLength(1); jj++)
m_taint[ii, jj] = setting;
}
// TerrainData.ClearLand
public override void ClearLand()
{
ClearLand(DefaultTerrainHeight);
}
// TerrainData.ClearLand(float)
public override void ClearLand(float pHeight)
{
int flatHeight = ToCompressedHeight(pHeight);
for (int xx = 0; xx < SizeX; xx++)
for (int yy = 0; yy < SizeY; yy++)
m_heightmap[xx, yy] = flatHeight;
}
// Return 'true' of the patch that contains these region coordinates has been modified.
// Note that checking the taint clears it.
// There is existing code that relies on this feature.
public override bool IsTaintedAt(int xx, int yy, bool clearOnTest)
{
int tx = xx / Constants.TerrainPatchSize;
int ty = yy / Constants.TerrainPatchSize;
bool ret = m_taint[tx, ty];
if (ret && clearOnTest)
m_taint[tx, ty] = false;
return ret;
}
// Old form that clears the taint flag when we check it.
public override bool IsTaintedAt(int xx, int yy)
{
return IsTaintedAt(xx, yy, true /* clearOnTest */);
}
// TerrainData.GetDatabaseBlob
// The user wants something to store in the database.
public override bool GetDatabaseBlob(out int DBRevisionCode, out Array blob)
{
bool ret = false;
if (SizeX == Constants.RegionSize && SizeY == Constants.RegionSize)
{
DBRevisionCode = (int)DBTerrainRevision.Legacy256;
blob = ToLegacyTerrainSerialization();
ret = true;
}
else
{
DBRevisionCode = (int)DBTerrainRevision.Compressed2D;
blob = ToCompressedTerrainSerialization();
ret = true;
}
return ret;
}
// TerrainData.CompressionFactor
private float m_compressionFactor = 100.0f;
public override float CompressionFactor { get { return m_compressionFactor; } }
// TerrainData.GetCompressedMap
public override int[] GetCompressedMap()
{
int[] newMap = new int[SizeX * SizeY];
int ind = 0;
for (int xx = 0; xx < SizeX; xx++)
for (int yy = 0; yy < SizeY; yy++)
newMap[ind++] = m_heightmap[xx, yy];
return newMap;
}
// TerrainData.Clone
public override TerrainData Clone()
{
HeightmapTerrainData ret = new HeightmapTerrainData(SizeX, SizeY, SizeZ);
ret.m_heightmap = (int[,])this.m_heightmap.Clone();
return ret;
}
// TerrainData.GetFloatsSerialized
// This one dimensional version is ordered so height = map[y*sizeX+x];
// DEPRECATED: don't use this function as it does not retain the dimensions of the terrain
// and the caller will probably do the wrong thing if the terrain is not the legacy 256x256.
public override float[] GetFloatsSerialized()
{
int points = SizeX * SizeY;
float[] heights = new float[points];
int idx = 0;
for (int jj = 0; jj < SizeY; jj++)
for (int ii = 0; ii < SizeX; ii++)
{
heights[idx++] = FromCompressedHeight(m_heightmap[ii, jj]);
}
return heights;
}
// TerrainData.GetDoubles
public override double[,] GetDoubles()
{
double[,] ret = new double[SizeX, SizeY];
for (int xx = 0; xx < SizeX; xx++)
for (int yy = 0; yy < SizeY; yy++)
ret[xx, yy] = FromCompressedHeight(m_heightmap[xx, yy]);
return ret;
}
// =============================================================
private int[,] m_heightmap;
// Remember subregions of the heightmap that has changed.
private bool[,] m_taint;
// To save space (especially for large regions), keep the height as a short integer
// that is coded as the float height times the compression factor (usually '100'
// to make for two decimal points).
public int ToCompressedHeight(double pHeight)
{
return (int)(pHeight * CompressionFactor);
}
public float FromCompressedHeight(int pHeight)
{
return ((float)pHeight) / CompressionFactor;
}
// To keep with the legacy theme, create an instance of this class based on the
// way terrain used to be passed around.
public HeightmapTerrainData(double[,] pTerrain)
{
SizeX = pTerrain.GetLength(0);
SizeY = pTerrain.GetLength(1);
SizeZ = (int)Constants.RegionHeight;
m_compressionFactor = 100.0f;
m_heightmap = new int[SizeX, SizeY];
for (int ii = 0; ii < SizeX; ii++)
{
for (int jj = 0; jj < SizeY; jj++)
{
m_heightmap[ii, jj] = ToCompressedHeight(pTerrain[ii, jj]);
}
}
// m_log.DebugFormat("{0} new by doubles. sizeX={1}, sizeY={2}, sizeZ={3}", LogHeader, SizeX, SizeY, SizeZ);
m_taint = new bool[SizeX / Constants.TerrainPatchSize, SizeY / Constants.TerrainPatchSize];
ClearTaint();
}
// Create underlying structures but don't initialize the heightmap assuming the caller will immediately do that
public HeightmapTerrainData(int pX, int pY, int pZ)
{
SizeX = pX;
SizeY = pY;
SizeZ = pZ;
m_compressionFactor = 100.0f;
m_heightmap = new int[SizeX, SizeY];
m_taint = new bool[SizeX / Constants.TerrainPatchSize, SizeY / Constants.TerrainPatchSize];
// m_log.DebugFormat("{0} new by dimensions. sizeX={1}, sizeY={2}, sizeZ={3}", LogHeader, SizeX, SizeY, SizeZ);
ClearTaint();
ClearLand(0f);
}
public HeightmapTerrainData(int[] cmap, float pCompressionFactor, int pX, int pY, int pZ) : this(pX, pY, pZ)
{
m_compressionFactor = pCompressionFactor;
int ind = 0;
for (int xx = 0; xx < SizeX; xx++)
for (int yy = 0; yy < SizeY; yy++)
m_heightmap[xx, yy] = cmap[ind++];
// m_log.DebugFormat("{0} new by compressed map. sizeX={1}, sizeY={2}, sizeZ={3}", LogHeader, SizeX, SizeY, SizeZ);
}
// Create a heighmap from a database blob
public HeightmapTerrainData(int pSizeX, int pSizeY, int pSizeZ, int pFormatCode, byte[] pBlob) : this(pSizeX, pSizeY, pSizeZ)
{
switch ((DBTerrainRevision)pFormatCode)
{
case DBTerrainRevision.Compressed2D:
FromCompressedTerrainSerialization(pBlob);
m_log.DebugFormat("{0} HeightmapTerrainData create from Compressed2D serialization. Size=<{1},{2}>", LogHeader, SizeX, SizeY);
break;
default:
FromLegacyTerrainSerialization(pBlob);
m_log.DebugFormat("{0} HeightmapTerrainData create from legacy serialization. Size=<{1},{2}>", LogHeader, SizeX, SizeY);
break;
}
}
// Just create an array of doubles. Presumes the caller implicitly knows the size.
public Array ToLegacyTerrainSerialization()
{
Array ret = null;
using (MemoryStream str = new MemoryStream((int)Constants.RegionSize * (int)Constants.RegionSize * sizeof(double)))
{
using (BinaryWriter bw = new BinaryWriter(str))
{
for (int xx = 0; xx < Constants.RegionSize; xx++)
{
for (int yy = 0; yy < Constants.RegionSize; yy++)
{
double height = this[xx, yy];
if (height == 0.0)
height = double.Epsilon;
bw.Write(height);
}
}
}
ret = str.ToArray();
}
return ret;
}
// Just create an array of doubles. Presumes the caller implicitly knows the size.
public void FromLegacyTerrainSerialization(byte[] pBlob)
{
// In case database info doesn't match real terrain size, initialize the whole terrain.
ClearLand();
using (MemoryStream mstr = new MemoryStream(pBlob))
{
using (BinaryReader br = new BinaryReader(mstr))
{
for (int xx = 0; xx < (int)Constants.RegionSize; xx++)
{
for (int yy = 0; yy < (int)Constants.RegionSize; yy++)
{
float val = (float)br.ReadDouble();
if (xx < SizeX && yy < SizeY)
m_heightmap[xx, yy] = ToCompressedHeight(val);
}
}
}
ClearTaint();
}
}
// See the reader below.
public Array ToCompressedTerrainSerialization()
{
Array ret = null;
using (MemoryStream str = new MemoryStream((3 * sizeof(Int32)) + (SizeX * SizeY * sizeof(Int16))))
{
using (BinaryWriter bw = new BinaryWriter(str))
{
bw.Write((Int32)DBTerrainRevision.Compressed2D);
bw.Write((Int32)SizeX);
bw.Write((Int32)SizeY);
bw.Write((Int32)CompressionFactor);
for (int yy = 0; yy < SizeY; yy++)
for (int xx = 0; xx < SizeX; xx++)
{
bw.Write((Int16)m_heightmap[xx, yy]);
}
}
ret = str.ToArray();
}
return ret;
}
// Initialize heightmap from blob consisting of:
// int32, int32, int32, int32, int16[]
// where the first int32 is format code, next two int32s are the X and y of heightmap data and
// the forth int is the compression factor for the following int16s
// This is just sets heightmap info. The actual size of the region was set on this instance's
// creation and any heights not initialized by theis blob are set to the default height.
public void FromCompressedTerrainSerialization(byte[] pBlob)
{
Int32 hmFormatCode, hmSizeX, hmSizeY, hmCompressionFactor;
using (MemoryStream mstr = new MemoryStream(pBlob))
{
using (BinaryReader br = new BinaryReader(mstr))
{
hmFormatCode = br.ReadInt32();
hmSizeX = br.ReadInt32();
hmSizeY = br.ReadInt32();
hmCompressionFactor = br.ReadInt32();
m_compressionFactor = hmCompressionFactor;
// In case database info doesn't match real terrain size, initialize the whole terrain.
ClearLand();
for (int yy = 0; yy < hmSizeY; yy++)
{
for (int xx = 0; xx < hmSizeX; xx++)
{
Int16 val = br.ReadInt16();
if (xx < SizeX && yy < SizeY)
m_heightmap[xx, yy] = val;
}
}
}
ClearTaint();
m_log.InfoFormat("{0} Read compressed 2d heightmap. Heightmap size=<{1},{2}>. Region size=<{3},{4}>. CompFact={5}",
LogHeader, hmSizeX, hmSizeY, SizeX, SizeY, hmCompressionFactor);
}
}
}
}
| |
using System;
using Android.Content;
using Android.Views;
using Android.Widget;
using Android.Graphics.Drawables;
using Android.Views.Animations;
using Android.Graphics.Drawables.Shapes;
using Android.Util;
using Android.Graphics;
namespace eShopOnContainers.Droid.Renderers
{
public class BadgeView : TextView
{
public enum BadgePosition
{
PositionTopLeft = 1,
PositionTopRight = 2,
PositionBottomLeft = 3,
PositionBottomRight = 4,
PositionCenter = 5
}
private const int DefaultHmarginDip = -10;
private const int DefaultVmarginDip = 2;
private const int DefaultLrPaddingDip = 4;
private const int DefaultCornerRadiusDip = 7;
private static Animation _fadeInAnimation;
private static Animation _fadeOutAnimation;
private Context _context;
private readonly Color _defaultBadgeColor = Color.ParseColor("#CCFF0000");
private ShapeDrawable _backgroundShape;
public View Target { get; private set; }
public BadgePosition Postion { get; set; } = BadgePosition.PositionTopRight;
public int BadgeMarginH { get; set; }
public int BadgeMarginV { get; set; }
public static int TextSizeDip { get; set; } = 11;
public Color BadgeColor
{
get { return _backgroundShape.Paint.Color; }
set
{
_backgroundShape.Paint.Color = value;
Background.InvalidateSelf();
}
}
public Color TextColor
{
get { return new Color(CurrentTextColor); }
set { SetTextColor(value); }
}
public BadgeView(Context context, View target) : this(context, null, Android.Resource.Attribute.TextViewStyle, target)
{
}
public BadgeView(Context context, IAttributeSet attrs, int defStyle, View target) : base(context, attrs, defStyle)
{
Init(context, target);
}
private void Init(Context context, View target)
{
_context = context;
Target = target;
BadgeMarginH = DipToPixels(DefaultHmarginDip);
BadgeMarginV = DipToPixels(DefaultVmarginDip);
Typeface = Typeface.DefaultBold;
var paddingPixels = DipToPixels(DefaultLrPaddingDip);
SetPadding(paddingPixels, 0, paddingPixels, 0);
SetTextColor(Color.White);
SetTextSize(ComplexUnitType.Dip, TextSizeDip);
_fadeInAnimation = new AlphaAnimation(0, 1)
{
Interpolator = new DecelerateInterpolator(),
Duration = 200
};
_fadeOutAnimation = new AlphaAnimation(1, 0)
{
Interpolator = new AccelerateInterpolator(),
Duration = 200
};
_backgroundShape = CreateBackgroundShape();
Background = _backgroundShape;
BadgeColor = _defaultBadgeColor;
if (Target != null)
{
ApplyTo(Target);
}
else
{
Show();
}
}
private ShapeDrawable CreateBackgroundShape()
{
var radius = DipToPixels(DefaultCornerRadiusDip);
var outerR = new float[] { radius, radius, radius, radius, radius, radius, radius, radius };
return new ShapeDrawable(new RoundRectShape(outerR, null, null));
}
private void ApplyTo(View target)
{
var lp = target.LayoutParameters;
var parent = target.Parent;
var group = parent as ViewGroup;
if (group == null)
{
Console.WriteLine("Badge target parent has to be a view group");
return;
}
group.SetClipChildren(false);
group.SetClipToPadding(false);
var container = new FrameLayout(_context);
var index = group.IndexOfChild(target);
group.RemoveView(target);
group.AddView(container, index, lp);
container.AddView(target);
group.Invalidate();
Visibility = ViewStates.Gone;
container.AddView(this);
}
public void Show()
{
Show(false, null);
}
public void Show(bool animate)
{
Show(animate, _fadeInAnimation);
}
public void Hide(bool animate)
{
Hide(animate, _fadeOutAnimation);
}
private void Show(bool animate, Animation anim)
{
ApplyLayoutParams();
if (animate)
{
StartAnimation(anim);
}
Visibility = ViewStates.Visible;
}
private void Hide(bool animate, Animation anim)
{
Visibility = ViewStates.Gone;
if (animate)
{
StartAnimation(anim);
}
}
private void ApplyLayoutParams()
{
var layoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
switch (Postion)
{
case BadgePosition.PositionTopLeft:
layoutParameters.Gravity = GravityFlags.Left | GravityFlags.Top;
layoutParameters.SetMargins(BadgeMarginH, BadgeMarginV, 0, 0);
break;
case BadgePosition.PositionTopRight:
layoutParameters.Gravity = GravityFlags.Right | GravityFlags.Top;
layoutParameters.SetMargins(0, BadgeMarginV, BadgeMarginH, 0);
break;
case BadgePosition.PositionBottomLeft:
layoutParameters.Gravity = GravityFlags.Left | GravityFlags.Bottom;
layoutParameters.SetMargins(BadgeMarginH, 0, 0, BadgeMarginV);
break;
case BadgePosition.PositionBottomRight:
layoutParameters.Gravity = GravityFlags.Right | GravityFlags.Bottom;
layoutParameters.SetMargins(0, 0, BadgeMarginH, BadgeMarginV);
break;
case BadgePosition.PositionCenter:
layoutParameters.Gravity = GravityFlags.Center;
layoutParameters.SetMargins(0, 0, 0, 0);
break;
}
LayoutParameters = layoutParameters;
}
private int DipToPixels(int dip)
{
return (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, dip, Resources.DisplayMetrics);
}
public new string Text
{
get { return base.Text; }
set
{
base.Text = value;
if (Visibility == ViewStates.Visible && string.IsNullOrEmpty(value))
{
Hide(true);
}
else if (Visibility == ViewStates.Gone && !string.IsNullOrEmpty(value))
{
Show(true);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
namespace System.Globalization
{
//
// This class implements the Julian calendar. In 48 B.C. Julius Caesar ordered a calendar reform, and this calendar
// is called Julian calendar. It consisted of a solar year of twelve months and of 365 days with an extra day
// every fourth year.
//*
//* Calendar support range:
//* Calendar Minimum Maximum
//* ========== ========== ==========
//* Gregorian 0001/01/01 9999/12/31
//* Julia 0001/01/03 9999/10/19
public class JulianCalendar : Calendar
{
public static readonly int JulianEra = 1;
private const int DatePartYear = 0;
private const int DatePartDayOfYear = 1;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
// Number of days in a non-leap year
private const int JulianDaysPerYear = 365;
// Number of days in 4 years
private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1;
private static readonly int[] s_daysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
private static readonly int[] s_daysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
// Gregorian Calendar 9999/12/31 = Julian Calendar 9999/10/19
// keep it as variable field for serialization compat.
internal int MaxYear = 9999;
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
public JulianCalendar()
{
// There is no system setting of TwoDigitYear max, so set the value here.
twoDigitYearMax = 2029;
}
internal override CalendarId ID
{
get
{
return CalendarId.JULIAN;
}
}
internal static void CheckEraRange(int era)
{
if (era != CurrentEra && era != JulianEra)
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal void CheckYearEraRange(int year, int era)
{
CheckEraRange(era);
if (year <= 0 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxYear));
}
}
internal static void CheckMonthRange(int month)
{
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
}
/*===================================CheckDayRange============================
**Action: Check for if the day value is valid.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** Before calling this method, call CheckYearEraRange()/CheckMonthRange() to make
** sure year/month values are correct.
============================================================================*/
internal static void CheckDayRange(int year, int month, int day)
{
if (year == 1 && month == 1)
{
// The mimimum supported Julia date is Julian 0001/01/03.
if (day < 3)
{
throw new ArgumentOutOfRangeException(null,
SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
bool isLeapYear = (year % 4) == 0;
int[] days = isLeapYear ? s_daysToMonth366 : s_daysToMonth365;
int monthDays = days[month] - days[month - 1];
if (day < 1 || day > monthDays)
{
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
monthDays));
}
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
internal static int GetDatePart(long ticks, int part)
{
// Gregorian 1/1/0001 is Julian 1/3/0001. Remember DateTime(0) is refered to Gregorian 1/1/0001.
// The following line convert Gregorian ticks to Julian ticks.
long julianTicks = ticks + TicksPerDay * 2;
// n = number of days since 1/1/0001
int n = (int)(julianTicks / TicksPerDay);
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / JulianDaysPer4Years;
// n = day number within 4-year period
n -= y4 * JulianDaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / JulianDaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return (y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * JulianDaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3);
int[] days = leapYear ? s_daysToMonth366 : s_daysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = (n >> 5) + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
if (part == DatePartMonth) return (m);
// Return 1-based day-of-month
return (n - days[m - 1] + 1);
}
// Returns the tick count corresponding to the given year, month, and day.
internal static long DateToTicks(int year, int month, int day)
{
int[] days = (year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365;
int y = year - 1;
int n = y * 365 + y / 4 + days[month - 1] + day - 1;
// Gregorian 1/1/0001 is Julian 1/3/0001. n * TicksPerDay is the ticks in JulianCalendar.
// Therefore, we subtract two days in the following to convert the ticks in JulianCalendar
// to ticks in Gregorian calendar.
return ((n - 2) * TicksPerDay);
}
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? s_daysToMonth366 : s_daysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
int[] days = (year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365;
return (days[month] - days[month - 1]);
}
public override int GetDaysInYear(int year, int era)
{
// Year/Era range is done in IsLeapYear().
return (IsLeapYear(year, era) ? 366 : 365);
}
public override int GetEra(DateTime time)
{
return (JulianEra);
}
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
public override int[] Eras
{
get
{
return (new int[] { JulianEra });
}
}
public override int GetMonthsInYear(int year, int era)
{
CheckYearEraRange(year, era);
return (12);
}
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
CheckMonthRange(month);
// Year/Era range check is done in IsLeapYear().
if (IsLeapYear(year, era))
{
CheckDayRange(year, month, day);
return (month == 2 && day == 29);
}
CheckDayRange(year, month, day);
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
CheckYearEraRange(year, era);
return (0);
}
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearEraRange(year, era);
return (year % 4 == 0);
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
CheckDayRange(year, month, day);
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
MillisPerSecond - 1));
}
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
return new DateTime(DateToTicks(year, month, day) + (new TimeSpan(0, hour, minute, second, millisecond)).Ticks);
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
}
public override int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
1,
MaxYear));
}
return (base.ToFourDigitYear(year));
}
}
}
| |
/* ====================================================================
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 is1 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.Record
{
using System;
using NUnit.Framework;
using NPOI.HSSF.Record;
using NPOI.HSSF.Record.CF;
using NPOI.SS.Formula;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Model;
using NPOI.HSSF.Util;
using NPOI.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Formula.PTG;
/**
* Tests the serialization and deserialization of the TestCFRuleRecord
* class works correctly.
*
* @author Dmitriy Kumshayev
*/
[TestFixture]
public class TestCFRuleRecord
{
[Test]
public void TestConstructors()
{
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet();
CFRuleRecord rule1 = CFRuleRecord.Create((HSSFSheet)sheet, "7");
Assert.AreEqual(CFRuleRecord.CONDITION_TYPE_FORMULA, rule1.ConditionType);
Assert.AreEqual((byte)ComparisonOperator.NoComparison, rule1.ComparisonOperation);
Assert.IsNotNull(rule1.ParsedExpression1);
Assert.AreSame(Ptg.EMPTY_PTG_ARRAY, rule1.ParsedExpression2);
CFRuleRecord rule2 = CFRuleRecord.Create((HSSFSheet)sheet, (byte)ComparisonOperator.Between, "2", "5");
Assert.AreEqual(CFRuleRecord.CONDITION_TYPE_CELL_VALUE_IS, rule2.ConditionType);
Assert.AreEqual((byte)ComparisonOperator.Between, rule2.ComparisonOperation);
Assert.IsNotNull(rule2.ParsedExpression1);
Assert.IsNotNull(rule2.ParsedExpression2);
CFRuleRecord rule3 = CFRuleRecord.Create((HSSFSheet)sheet, (byte)ComparisonOperator.Equal, null, null);
Assert.AreEqual(CFRuleRecord.CONDITION_TYPE_CELL_VALUE_IS, rule3.ConditionType);
Assert.AreEqual((byte)ComparisonOperator.Equal, rule3.ComparisonOperation);
Assert.AreSame(Ptg.EMPTY_PTG_ARRAY, rule3.ParsedExpression2);
Assert.AreSame(Ptg.EMPTY_PTG_ARRAY, rule3.ParsedExpression2);
}
[Test]
public void TestCreateCFRuleRecord()
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
CFRuleRecord record = CFRuleRecord.Create(sheet, "7");
TestCFRuleRecord1(record);
// Serialize
byte[] SerializedRecord = record.Serialize();
// Strip header
byte[] recordData = new byte[SerializedRecord.Length - 4];
Array.Copy(SerializedRecord, 4, recordData, 0, recordData.Length);
// DeSerialize
record = new CFRuleRecord(TestcaseRecordInputStream.Create(CFRuleRecord.sid, recordData));
// Serialize again
byte[] output = record.Serialize();
// Compare
Assert.AreEqual(recordData.Length + 4, output.Length, "Output size"); //includes sid+recordlength
for (int i = 0; i < recordData.Length; i++)
{
Assert.AreEqual(recordData[i], output[i + 4], "CFRuleRecord doesn't match");
}
}
private void TestCFRuleRecord1(CFRuleRecord record)
{
FontFormatting fontFormatting = new FontFormatting();
TestFontFormattingAccessors(fontFormatting);
Assert.IsFalse(record.ContainsFontFormattingBlock);
record.FontFormatting = (fontFormatting);
Assert.IsTrue(record.ContainsFontFormattingBlock);
BorderFormatting borderFormatting = new BorderFormatting();
TestBorderFormattingAccessors(borderFormatting);
Assert.IsFalse(record.ContainsBorderFormattingBlock);
record.BorderFormatting = (borderFormatting);
Assert.IsTrue(record.ContainsBorderFormattingBlock);
Assert.IsFalse(record.IsLeftBorderModified);
record.IsLeftBorderModified = (true);
Assert.IsTrue(record.IsLeftBorderModified);
Assert.IsFalse(record.IsRightBorderModified);
record.IsRightBorderModified = (true);
Assert.IsTrue(record.IsRightBorderModified);
Assert.IsFalse(record.IsTopBorderModified);
record.IsTopBorderModified = (true);
Assert.IsTrue(record.IsTopBorderModified);
Assert.IsFalse(record.IsBottomBorderModified);
record.IsBottomBorderModified = (true);
Assert.IsTrue(record.IsBottomBorderModified);
Assert.IsFalse(record.IsTopLeftBottomRightBorderModified);
record.IsTopLeftBottomRightBorderModified = (true);
Assert.IsTrue(record.IsTopLeftBottomRightBorderModified);
Assert.IsFalse(record.IsBottomLeftTopRightBorderModified);
record.IsBottomLeftTopRightBorderModified = (true);
Assert.IsTrue(record.IsBottomLeftTopRightBorderModified);
PatternFormatting patternFormatting = new PatternFormatting();
TestPatternFormattingAccessors(patternFormatting);
Assert.IsFalse(record.ContainsPatternFormattingBlock);
record.PatternFormatting = (patternFormatting);
Assert.IsTrue(record.ContainsPatternFormattingBlock);
Assert.IsFalse(record.IsPatternBackgroundColorModified);
record.IsPatternBackgroundColorModified = (true);
Assert.IsTrue(record.IsPatternBackgroundColorModified);
Assert.IsFalse(record.IsPatternColorModified);
record.IsPatternColorModified = (true);
Assert.IsTrue(record.IsPatternColorModified);
Assert.IsFalse(record.IsPatternStyleModified);
record.IsPatternStyleModified = (true);
Assert.IsTrue(record.IsPatternStyleModified);
}
private void TestPatternFormattingAccessors(PatternFormatting patternFormatting)
{
patternFormatting.FillBackgroundColor = (HSSFColor.Green.Index);
Assert.AreEqual(HSSFColor.Green.Index, patternFormatting.FillBackgroundColor);
patternFormatting.FillForegroundColor = (HSSFColor.Indigo.Index);
Assert.AreEqual(HSSFColor.Indigo.Index, patternFormatting.FillForegroundColor);
patternFormatting.FillPattern = FillPattern.Diamonds;
Assert.AreEqual(FillPattern.Diamonds, patternFormatting.FillPattern);
}
private void TestBorderFormattingAccessors(BorderFormatting borderFormatting)
{
borderFormatting.IsBackwardDiagonalOn = (false);
Assert.IsFalse(borderFormatting.IsBackwardDiagonalOn);
borderFormatting.IsBackwardDiagonalOn = (true);
Assert.IsTrue(borderFormatting.IsBackwardDiagonalOn);
borderFormatting.BorderBottom = BorderStyle.Dotted;
Assert.AreEqual(BorderStyle.Dotted, borderFormatting.BorderBottom);
borderFormatting.BorderDiagonal = (BorderStyle.Medium);
Assert.AreEqual(BorderStyle.Medium, borderFormatting.BorderDiagonal);
borderFormatting.BorderLeft = (BorderStyle.MediumDashDotDot);
Assert.AreEqual(BorderStyle.MediumDashDotDot, borderFormatting.BorderLeft);
borderFormatting.BorderRight = (BorderStyle.MediumDashed);
Assert.AreEqual(BorderStyle.MediumDashed, borderFormatting.BorderRight);
borderFormatting.BorderTop = (BorderStyle.Hair);
Assert.AreEqual(BorderStyle.Hair, borderFormatting.BorderTop);
borderFormatting.BottomBorderColor = (HSSFColor.Aqua.Index);
Assert.AreEqual(HSSFColor.Aqua.Index, borderFormatting.BottomBorderColor);
borderFormatting.DiagonalBorderColor = (HSSFColor.Red.Index);
Assert.AreEqual(HSSFColor.Red.Index, borderFormatting.DiagonalBorderColor);
Assert.IsFalse(borderFormatting.IsForwardDiagonalOn);
borderFormatting.IsForwardDiagonalOn = (true);
Assert.IsTrue(borderFormatting.IsForwardDiagonalOn);
borderFormatting.LeftBorderColor = (HSSFColor.Black.Index);
Assert.AreEqual(HSSFColor.Black.Index, borderFormatting.LeftBorderColor);
borderFormatting.RightBorderColor = (HSSFColor.Blue.Index);
Assert.AreEqual(HSSFColor.Blue.Index, borderFormatting.RightBorderColor);
borderFormatting.TopBorderColor = (HSSFColor.Gold.Index);
Assert.AreEqual(HSSFColor.Gold.Index, borderFormatting.TopBorderColor);
}
private void TestFontFormattingAccessors(FontFormatting fontFormatting)
{
// Check for defaults
Assert.IsFalse(fontFormatting.IsEscapementTypeModified);
Assert.IsFalse(fontFormatting.IsFontCancellationModified);
Assert.IsFalse(fontFormatting.IsFontOutlineModified);
Assert.IsFalse(fontFormatting.IsFontShadowModified);
Assert.IsFalse(fontFormatting.IsFontStyleModified);
Assert.IsFalse(fontFormatting.IsUnderlineTypeModified);
Assert.IsFalse(fontFormatting.IsFontWeightModified);
Assert.IsFalse(fontFormatting.IsBold);
Assert.IsFalse(fontFormatting.IsItalic);
Assert.IsFalse(fontFormatting.IsOutlineOn);
Assert.IsFalse(fontFormatting.IsShadowOn);
Assert.IsFalse(fontFormatting.IsStruckout);
Assert.AreEqual(FontSuperScript.None, fontFormatting.EscapementType);
Assert.AreEqual(-1, fontFormatting.FontColorIndex);
Assert.AreEqual(-1, fontFormatting.FontHeight);
Assert.AreEqual(0, fontFormatting.FontWeight);
Assert.AreEqual(FontUnderlineType.None, fontFormatting.UnderlineType);
fontFormatting.IsBold = (true);
Assert.IsTrue(fontFormatting.IsBold);
fontFormatting.IsBold = (false);
Assert.IsFalse(fontFormatting.IsBold);
fontFormatting.EscapementType = FontSuperScript.Sub;
Assert.AreEqual(FontSuperScript.Sub, fontFormatting.EscapementType);
fontFormatting.EscapementType = FontSuperScript.Super;
Assert.AreEqual(FontSuperScript.Super, fontFormatting.EscapementType);
fontFormatting.EscapementType = FontSuperScript.None;
Assert.AreEqual(FontSuperScript.None, fontFormatting.EscapementType);
fontFormatting.IsEscapementTypeModified = (false);
Assert.IsFalse(fontFormatting.IsEscapementTypeModified);
fontFormatting.IsEscapementTypeModified = (true);
Assert.IsTrue(fontFormatting.IsEscapementTypeModified);
fontFormatting.IsFontWeightModified = (false);
Assert.IsFalse(fontFormatting.IsFontWeightModified);
fontFormatting.IsFontWeightModified = (true);
Assert.IsTrue(fontFormatting.IsFontWeightModified);
fontFormatting.IsFontCancellationModified = (false);
Assert.IsFalse(fontFormatting.IsFontCancellationModified);
fontFormatting.IsFontCancellationModified = (true);
Assert.IsTrue(fontFormatting.IsFontCancellationModified);
fontFormatting.FontColorIndex = ((short)10);
Assert.AreEqual(10, fontFormatting.FontColorIndex);
fontFormatting.FontHeight = (100);
Assert.AreEqual(100, fontFormatting.FontHeight);
fontFormatting.IsFontOutlineModified = (false);
Assert.IsFalse(fontFormatting.IsFontOutlineModified);
fontFormatting.IsFontOutlineModified = (true);
Assert.IsTrue(fontFormatting.IsFontOutlineModified);
fontFormatting.IsFontShadowModified = (false);
Assert.IsFalse(fontFormatting.IsFontShadowModified);
fontFormatting.IsFontShadowModified = (true);
Assert.IsTrue(fontFormatting.IsFontShadowModified);
fontFormatting.IsFontStyleModified = (false);
Assert.IsFalse(fontFormatting.IsFontStyleModified);
fontFormatting.IsFontStyleModified = (true);
Assert.IsTrue(fontFormatting.IsFontStyleModified);
fontFormatting.IsItalic = (false);
Assert.IsFalse(fontFormatting.IsItalic);
fontFormatting.IsItalic = (true);
Assert.IsTrue(fontFormatting.IsItalic);
fontFormatting.IsOutlineOn = (false);
Assert.IsFalse(fontFormatting.IsOutlineOn);
fontFormatting.IsOutlineOn = (true);
Assert.IsTrue(fontFormatting.IsOutlineOn);
fontFormatting.IsShadowOn = (false);
Assert.IsFalse(fontFormatting.IsShadowOn);
fontFormatting.IsShadowOn = (true);
Assert.IsTrue(fontFormatting.IsShadowOn);
fontFormatting.IsStruckout = (false);
Assert.IsFalse(fontFormatting.IsStruckout);
fontFormatting.IsStruckout = (true);
Assert.IsTrue(fontFormatting.IsStruckout);
fontFormatting.UnderlineType = FontUnderlineType.DoubleAccounting;
Assert.AreEqual(FontUnderlineType.DoubleAccounting, fontFormatting.UnderlineType);
fontFormatting.IsUnderlineTypeModified = (false);
Assert.IsFalse(fontFormatting.IsUnderlineTypeModified);
fontFormatting.IsUnderlineTypeModified = (true);
Assert.IsTrue(fontFormatting.IsUnderlineTypeModified);
}
[Test]
public void TestWrite() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
CFRuleRecord rr = CFRuleRecord.Create(sheet, (byte)ComparisonOperator.Between, "5", "10");
PatternFormatting patternFormatting = new PatternFormatting();
patternFormatting.FillPattern = FillPattern.Bricks;
rr.PatternFormatting=(patternFormatting);
byte[] data = rr.Serialize();
Assert.AreEqual(26, data.Length);
Assert.AreEqual(3, LittleEndian.GetShort(data, 6));
Assert.AreEqual(3, LittleEndian.GetShort(data, 8));
int flags = LittleEndian.GetInt(data, 10);
Assert.AreEqual(0x00380000, flags & 0x00380000,"unused flags should be 111");
Assert.AreEqual(0, flags & 0x03C00000,"undocumented flags should be 0000"); // Otherwise Excel s unhappy
// check all remaining flag bits (some are not well understood yet)
Assert.AreEqual(0x203FFFFF, flags);
}
private static byte[] DATA_REFN = {
// formula extracted from bugzilla 45234 att 22141
1, 3,
9, // formula 1 length
0, 0, 0, unchecked((byte)-1), unchecked((byte)-1), 63, 32, 2, unchecked((byte)-128), 0, 0, 0, 5,
// formula 1: "=B3=1" (formula is relative to B4)
76, unchecked((byte)-1), unchecked((byte)-1), 0, unchecked((byte)-64), // tRefN(B1)
30, 1, 0,
11,
};
/**
* tRefN and tAreaN tokens must be preserved when re-serializing conditional format formulas
*/
[Test]
public void TestReserializeRefNTokens()
{
RecordInputStream is1 = TestcaseRecordInputStream.Create (CFRuleRecord.sid, DATA_REFN);
CFRuleRecord rr = new CFRuleRecord(is1);
Ptg[] ptgs = rr.ParsedExpression1;
Assert.AreEqual(3, ptgs.Length);
if (ptgs[0] is RefPtg) {
throw new AssertionException("Identified bug 45234");
}
Assert.AreEqual(typeof(RefNPtg), ptgs[0].GetType());
RefNPtg refNPtg = (RefNPtg) ptgs[0];
Assert.IsTrue(refNPtg.IsColRelative);
Assert.IsTrue(refNPtg.IsRowRelative);
byte[] data = rr.Serialize();
TestcaseRecordInputStream.ConfirmRecordEncoding(CFRuleRecord.sid, DATA_REFN, data);
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Windows.Ink;
namespace MS.Internal.Ink.InkSerializedFormat
{
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
internal static class KnownIdCache
{
// This id table includes the original Guids that were hardcoded
// into ISF for the TabletPC v1 release
public static Guid[] OriginalISFIdTable = {
new Guid(0x598a6a8f, 0x52c0, 0x4ba0, 0x93, 0xaf, 0xaf, 0x35, 0x74, 0x11, 0xa5, 0x61),
new Guid(0xb53f9f75, 0x04e0, 0x4498, 0xa7, 0xee, 0xc3, 0x0d, 0xbb, 0x5a, 0x90, 0x11),
new Guid(0x735adb30, 0x0ebb, 0x4788, 0xa0, 0xe4, 0x0f, 0x31, 0x64, 0x90, 0x05, 0x5d),
new Guid(0x6e0e07bf, 0xafe7, 0x4cf7, 0x87, 0xd1, 0xaf, 0x64, 0x46, 0x20, 0x84, 0x18),
new Guid(0x436510c5, 0xfed3, 0x45d1, 0x8b, 0x76, 0x71, 0xd3, 0xea, 0x7a, 0x82, 0x9d),
new Guid(0x78a81b56, 0x0935, 0x4493, 0xba, 0xae, 0x00, 0x54, 0x1a, 0x8a, 0x16, 0xc4),
new Guid(0x7307502d, 0xf9f4, 0x4e18, 0xb3, 0xf2, 0x2c, 0xe1, 0xb1, 0xa3, 0x61, 0x0c),
new Guid(0x6da4488b, 0x5244, 0x41ec, 0x90, 0x5b, 0x32, 0xd8, 0x9a, 0xb8, 0x08, 0x09),
new Guid(0x8b7fefc4, 0x96aa, 0x4bfe, 0xac, 0x26, 0x8a, 0x5f, 0x0b, 0xe0, 0x7b, 0xf5),
new Guid(0xa8d07b3a, 0x8bf0, 0x40b0, 0x95, 0xa9, 0xb8, 0x0a, 0x6b, 0xb7, 0x87, 0xbf),
new Guid(0x0e932389, 0x1d77, 0x43af, 0xac, 0x00, 0x5b, 0x95, 0x0d, 0x6d, 0x4b, 0x2d),
new Guid(0x029123b4, 0x8828, 0x410b, 0xb2, 0x50, 0xa0, 0x53, 0x65, 0x95, 0xe5, 0xdc),
new Guid(0x82dec5c7, 0xf6ba, 0x4906, 0x89, 0x4f, 0x66, 0xd6, 0x8d, 0xfc, 0x45, 0x6c),
new Guid(0x0d324960, 0x13b2, 0x41e4, 0xac, 0xe6, 0x7a, 0xe9, 0xd4, 0x3d, 0x2d, 0x3b),
new Guid(0x7f7e57b7, 0xbe37, 0x4be1, 0xa3, 0x56, 0x7a, 0x84, 0x16, 0x0e, 0x18, 0x93),
new Guid(0x5d5d5e56, 0x6ba9, 0x4c5b, 0x9f, 0xb0, 0x85, 0x1c, 0x91, 0x71, 0x4e, 0x56),
new Guid(0x6a849980, 0x7c3a, 0x45b7, 0xaa, 0x82, 0x90, 0xa2, 0x62, 0x95, 0x0e, 0x89),
new Guid(0x33c1df83, 0xecdb, 0x44f0, 0xb9, 0x23, 0xdb, 0xd1, 0xa5, 0xb2, 0x13, 0x6e),
new Guid(0x5329cda5, 0xfa5b, 0x4ed2, 0xbb, 0x32, 0x83, 0x46, 0x01, 0x72, 0x44, 0x28),
new Guid(0x002df9af, 0xdd8c, 0x4949, 0xba, 0x46, 0xd6, 0x5e, 0x10, 0x7d, 0x1a, 0x8a),
new Guid(0x9d32b7ca, 0x1213, 0x4f54, 0xb7, 0xe4, 0xc9, 0x05, 0x0e, 0xe1, 0x7a, 0x38),
new Guid(0xe71caab9, 0x8059, 0x4c0d, 0xa2, 0xdb, 0x7c, 0x79, 0x54, 0x47, 0x8d, 0x82),
new Guid(0x5c0b730a, 0xf394, 0x4961, 0xa9, 0x33, 0x37, 0xc4, 0x34, 0xf4, 0xb7, 0xeb),
new Guid(0x2812210f, 0x871e, 0x4d91, 0x86, 0x07, 0x49, 0x32, 0x7d, 0xdf, 0x0a, 0x9f),
new Guid(0x8359a0fa, 0x2f44, 0x4de6, 0x92, 0x81, 0xce, 0x5a, 0x89, 0x9c, 0xf5, 0x8f),
new Guid(0x4c4642dd, 0x479e, 0x4c66, 0xb4, 0x40, 0x1f, 0xcd, 0x83, 0x95, 0x8f, 0x00),
new Guid(0xce2d9a8a, 0xe58e, 0x40ba, 0x93, 0xfa, 0x18, 0x9b, 0xb3, 0x90, 0x00, 0xae),
new Guid(0xc3c7480f, 0x5839, 0x46ef, 0xa5, 0x66, 0xd8, 0x48, 0x1c, 0x7a, 0xfe, 0xc1),
new Guid(0xea2278af, 0xc59d, 0x4ef4, 0x98, 0x5b, 0xd4, 0xbe, 0x12, 0xdf, 0x22, 0x34),
new Guid(0xb8630dc9, 0xcc5c, 0x4c33, 0x8d, 0xad, 0xb4, 0x7f, 0x62, 0x2b, 0x8c, 0x79),
new Guid(0x15e2f8e6, 0x6381, 0x4e8b, 0xa9, 0x65, 0x01, 0x1f, 0x7d, 0x7f, 0xca, 0x38),
new Guid(0x7066fbe4, 0x473e, 0x4675, 0x9c, 0x25, 0x00, 0x26, 0x82, 0x9b, 0x40, 0x1f),
new Guid(0xbbc85b9a, 0xade6, 0x4093, 0xb3, 0xbb, 0x64, 0x1f, 0xa1, 0xd3, 0x7a, 0x1a),
new Guid(0x39143d3, 0x78cb, 0x449c, 0xa8, 0xe7, 0x67, 0xd1, 0x88, 0x64, 0xc3, 0x32),
new Guid(0x67743782, 0xee5, 0x419a, 0xa1, 0x2b, 0x27, 0x3a, 0x9e, 0xc0, 0x8f, 0x3d),
new Guid(0xf0720328, 0x663b, 0x418f, 0x85, 0xa6, 0x95, 0x31, 0xae, 0x3e, 0xcd, 0xfa),
new Guid(0xa1718cdd, 0xdac, 0x4095, 0xa1, 0x81, 0x7b, 0x59, 0xcb, 0x10, 0x6b, 0xfb),
new Guid(0x810a74d2, 0x6ee2, 0x4e39, 0x82, 0x5e, 0x6d, 0xef, 0x82, 0x6a, 0xff, 0xc5),
};
// Size of data used by identified by specified Guid/Id
public static uint[] OriginalISFIdPersistenceSize = {
Native.SizeOfInt, // X 0
Native.SizeOfInt, // Y 1
Native.SizeOfInt, // Z 2
Native.SizeOfInt, // PACKET_STATUS 3
2 * Native.SizeOfUInt, // FILETIME : TIMER_TICK 4
Native.SizeOfUInt, // SERIAL_NUMBER 5
Native.SizeOfUShort, // NORMAL_PRESSURE 6
Native.SizeOfUShort, // TANGENT_PRESSURE 7
Native.SizeOfUShort, // BUTTON_PRESSURE 8
Native.SizeOfFloat, // X_TILT_ORIENTATION 9
Native.SizeOfFloat, // Y_TILT_ORIENTATION 10
Native.SizeOfFloat, // AZIMUTH_ORIENTATION 11
Native.SizeOfInt, // ALTITUDE_ORIENTATION 12
Native.SizeOfInt, // TWIST_ORIENTATION 13
Native.SizeOfUShort, // PITCH_ROTATION 14
Native.SizeOfUShort, // ROLL_ROTATION 15
Native.SizeOfUShort, // YAW_ROTATION 16
Native.SizeOfUShort, // PEN_STYLE 17
Native.SizeOfUInt, // COLORREF: COLORREF 18
Native.SizeOfUInt, // PEN_WIDTH 19
Native.SizeOfUInt, // PEN_HEIGHT 20
Native.SizeOfByte, // PEN_TIP 21
Native.SizeOfUInt, // DRAWING_FLAGS 22
Native.SizeOfUInt, // CURSORID 23
0, // WORD_ALTERNATES 24
0, // CHAR_ALTERNATES 25
5 * Native.SizeOfUInt, // INKMETRICS 26
3 * Native.SizeOfUInt, // GUIDE_STRUCTURE 27
8 * Native.SizeOfUShort, // SYSTEMTIME TIME_STAMP 28
Native.SizeOfUShort, // LANGUAGE 29
Native.SizeOfByte, // TRANSPARENCY 30
Native.SizeOfUInt, // CURVE_FITTING_ERROR 31
0, // RECO_LATTICE 32
Native.SizeOfInt, // CURSORDOWN 33
Native.SizeOfInt, // SECONDARYTIPSWITCH 34
Native.SizeOfInt, // BARRELDOWN 35
Native.SizeOfInt, // TABLETPICK 36
Native.SizeOfInt, // ROP 37
};
public enum OriginalISFIdIndex : uint
{
X = 0,
Y = 1,
Z = 2,
PacketStatus = 3,
TimerTick = 4,
SerialNumber = 5,
NormalPressure = 6,
TangentPressure = 7,
ButtonPressure = 8,
XTiltOrientation = 9,
YTiltOrientation = 10,
AzimuthOrientation = 11,
AltitudeOrientation = 12,
TwistOrientation = 13,
PitchRotation = 14,
RollRotation = 15,
YawRotation = 16,
PenStyle = 17,
ColorRef = 18,
StylusWidth = 19,
StylusHeight = 20,
PenTip = 21,
DrawingFlags = 22,
CursorId = 23,
WordAlternates = 24,
CharAlternates = 25,
InkMetrics = 26,
GuideStructure = 27,
Timestamp = 28,
Language = 29,
Transparency = 30,
CurveFittingError = 31,
RecoLattice = 32,
CursorDown = 33,
SecondaryTipSwitch = 34,
BarrelDown = 35,
TabletPick = 36,
RasterOperation = 37,
MAXIMUM = 37,
}
// This id table includes the Guids that used the internal persistence APIs
// - meaning they didn't have the data type information encoded in ISF
public static Guid[] TabletInternalIdTable = {
// Highlighter
new Guid(0x9b6267b8, 0x3968, 0x4048, 0xab, 0x74, 0xf4, 0x90, 0x40, 0x6a, 0x2d, 0xfa),
// Ink properties
new Guid(0x7fc30e91, 0xd68d, 0x4f07, 0x8b, 0x62, 0x6, 0xf6, 0xd2, 0x73, 0x1b, 0xed),
// Ink Style Bold
new Guid(0xe02fb5c1, 0x9693, 0x4312, 0xa4, 0x34, 0x0, 0xde, 0x7f, 0x3a, 0xd4, 0x93),
// Ink Style Italics
new Guid(0x5253b51, 0x49c6, 0x4a04, 0x89, 0x93, 0x64, 0xdd, 0x9a, 0xbd, 0x84, 0x2a),
// Stroke Timestamp
new Guid(0x4ea66c4, 0xf33a, 0x461b, 0xb8, 0xfe, 0x68, 0x7, 0xd, 0x9c, 0x75, 0x75),
// Stroke Time Id
new Guid(0x50b6bc8, 0x3b7d, 0x4816, 0x8c, 0x61, 0xbc, 0x7e, 0x90, 0x5b, 0x21, 0x32),
// Stroke Lattice
new Guid(0x82871c85, 0xe247, 0x4d8c, 0x8d, 0x71, 0x22, 0xe5, 0xd6, 0xf2, 0x57, 0x76),
// Ink Custom Strokes
new Guid(0x33cdbbb3, 0x588f, 0x4e94, 0xb1, 0xfe, 0x5d, 0x79, 0xff, 0xe7, 0x6e, 0x76),
};
// lookup indices for table of GUIDs used with non-Automation APIs
internal enum TabletInternalIdIndex
{
Highlighter = 0,
InkProperties = 1,
InkStyleBold = 2,
InkStyleItalics = 3,
StrokeTimestamp = 4,
StrokeTimeId = 5,
InkStrokeLattice = 6,
InkCustomStrokes = 7,
MAXIMUM = 7
}
static internal KnownTagCache.KnownTagIndex KnownGuidBaseIndex = (KnownTagCache.KnownTagIndex)KnownTagCache.MaximumPossibleKnownTags;
// The maximum value that can be encoded into a single byte is 127.
// To improve the chances of storing all of the guids in the ISF guid table
// with single-byte lookups, the guids are broken into two ranges
// 0-50 known tags
// 50-100 known guids (reserved)
// 101-127 custom guids (user-defined guids)
// 128-... more custom guids, but requiring multiples bytes for guid table lookup
// These values aren't currently used, so comment them out
// static internal uint KnownGuidIndexLimit = MaximumPossibleKnownGuidIndex;
static internal uint MaximumPossibleKnownGuidIndex = 100;
static internal uint CustomGuidBaseIndex = MaximumPossibleKnownGuidIndex;
// This id table includes the Guids that have been added to ISF as ExtendedProperties
// Note that they are visible to 3rd party applications
public static Guid[] ExtendedISFIdTable = {
// Highlighter
new Guid(0x9b6267b8, 0x3968, 0x4048, 0xab, 0x74, 0xf4, 0x90, 0x40, 0x6a, 0x2d, 0xfa),
// Ink properties
new Guid(0x7fc30e91, 0xd68d, 0x4f07, 0x8b, 0x62, 0x6, 0xf6, 0xd2, 0x73, 0x1b, 0xed),
// Ink Style Bold
new Guid(0xe02fb5c1, 0x9693, 0x4312, 0xa4, 0x34, 0x0, 0xde, 0x7f, 0x3a, 0xd4, 0x93),
// Ink Style Italics
new Guid(0x5253b51, 0x49c6, 0x4a04, 0x89, 0x93, 0x64, 0xdd, 0x9a, 0xbd, 0x84, 0x2a),
// Stroke Timestamp
new Guid(0x4ea66c4, 0xf33a, 0x461b, 0xb8, 0xfe, 0x68, 0x7, 0xd, 0x9c, 0x75, 0x75),
// Stroke Time Id
new Guid(0x50b6bc8, 0x3b7d, 0x4816, 0x8c, 0x61, 0xbc, 0x7e, 0x90, 0x5b, 0x21, 0x32),
// Stroke Lattice
new Guid(0x82871c85, 0xe247, 0x4d8c, 0x8d, 0x71, 0x22, 0xe5, 0xd6, 0xf2, 0x57, 0x76),
// Ink Custom Strokes
new Guid(0x33cdbbb3, 0x588f, 0x4e94, 0xb1, 0xfe, 0x5d, 0x79, 0xff, 0xe7, 0x6e, 0x76),
};
}
internal static class KnownTagCache
{
internal enum KnownTagIndex : uint
{
Unknown = 0,
InkSpaceRectangle = 0,
GuidTable = 1,
DrawingAttributesTable = 2,
DrawingAttributesBlock = 3,
StrokeDescriptorTable = 4,
StrokeDescriptorBlock = 5,
Buttons = 6,
NoX = 7,
NoY = 8,
DrawingAttributesTableIndex = 9,
Stroke = 10,
StrokePropertyList = 11,
PointProperty = 12,
StrokeDescriptorTableIndex = 13,
CompressionHeader = 14,
TransformTable = 15,
Transform = 16,
TransformIsotropicScale = 17,
TransformAnisotropicScale = 18,
TransformRotate = 19,
TransformTranslate = 20,
TransformScaleAndTranslate = 21,
TransformQuad = 22,
TransformTableIndex = 23,
MetricTable = 24,
MetricBlock = 25,
MetricTableIndex = 26,
Mantissa = 27,
PersistenceFormat = 28,
HimetricSize = 29,
StrokeIds = 30,
ExtendedTransformTable = 31,
}
// See comments for KnownGuidBaseIndex to determine ranges of tags/guids/indices
static internal uint MaximumPossibleKnownTags = 50;
static internal uint KnownTagCount = (byte)MaximumPossibleKnownTags;
}
}
| |
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.38.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Stackdriver Profiler API Version v2
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://cloud.google.com/profiler/'>Stackdriver Profiler API</a>
* <tr><th>API Version<td>v2
* <tr><th>API Rev<td>20190204 (1495)
* <tr><th>API Docs
* <td><a href='https://cloud.google.com/profiler/'>
* https://cloud.google.com/profiler/</a>
* <tr><th>Discovery Name<td>cloudprofiler
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Stackdriver Profiler API can be found at
* <a href='https://cloud.google.com/profiler/'>https://cloud.google.com/profiler/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.CloudProfiler.v2
{
/// <summary>The CloudProfiler Service.</summary>
public class CloudProfilerService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v2";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public CloudProfilerService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public CloudProfilerService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "cloudprofiler"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://cloudprofiler.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://cloudprofiler.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Stackdriver Profiler API.</summary>
public class Scope
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>View and write monitoring data for all of your Google and third-party Cloud and API
/// projects</summary>
public static string Monitoring = "https://www.googleapis.com/auth/monitoring";
/// <summary>Publish metric data to your Google Cloud projects</summary>
public static string MonitoringWrite = "https://www.googleapis.com/auth/monitoring.write";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Stackdriver Profiler API.</summary>
public static class ScopeConstants
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>View and write monitoring data for all of your Google and third-party Cloud and API
/// projects</summary>
public const string Monitoring = "https://www.googleapis.com/auth/monitoring";
/// <summary>Publish metric data to your Google Cloud projects</summary>
public const string MonitoringWrite = "https://www.googleapis.com/auth/monitoring.write";
}
private readonly ProjectsResource projects;
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects
{
get { return projects; }
}
}
///<summary>A base abstract class for CloudProfiler requests.</summary>
public abstract class CloudProfilerBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new CloudProfilerBaseServiceRequest instance.</summary>
protected CloudProfilerBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes CloudProfiler parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
profiles = new ProfilesResource(service);
}
private readonly ProfilesResource profiles;
/// <summary>Gets the Profiles resource.</summary>
public virtual ProfilesResource Profiles
{
get { return profiles; }
}
/// <summary>The "profiles" collection of methods.</summary>
public class ProfilesResource
{
private const string Resource = "profiles";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProfilesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>CreateProfile creates a new profile resource in the online mode.
///
/// The server ensures that the new profiles are created at a constant rate per deployment, so the creation
/// request may hang for some time until the next profile session is available.
///
/// The request may fail with ABORTED error if the creation is not available within ~1m, the response will
/// indicate the duration of the backoff the client should take before attempting creating a profile again.
/// The backoff duration is returned in google.rpc.RetryInfo extension on the response status. To a gRPC
/// client, the extension will be return as a binary-serialized proto in the trailing metadata item named
/// "google.rpc.retryinfo-bin".</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Parent project to create the profile in.</param>
public virtual CreateRequest Create(Google.Apis.CloudProfiler.v2.Data.CreateProfileRequest body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>CreateProfile creates a new profile resource in the online mode.
///
/// The server ensures that the new profiles are created at a constant rate per deployment, so the creation
/// request may hang for some time until the next profile session is available.
///
/// The request may fail with ABORTED error if the creation is not available within ~1m, the response will
/// indicate the duration of the backoff the client should take before attempting creating a profile again.
/// The backoff duration is returned in google.rpc.RetryInfo extension on the response status. To a gRPC
/// client, the extension will be return as a binary-serialized proto in the trailing metadata item named
/// "google.rpc.retryinfo-bin".</summary>
public class CreateRequest : CloudProfilerBaseServiceRequest<Google.Apis.CloudProfiler.v2.Data.Profile>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudProfiler.v2.Data.CreateProfileRequest body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Parent project to create the profile in.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudProfiler.v2.Data.CreateProfileRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2/{+parent}/profiles"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
/// <summary>CreateOfflineProfile creates a new profile resource in the offline mode. The client provides
/// the profile to create along with the profile bytes, the server records it.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Parent project to create the profile in.</param>
public virtual CreateOfflineRequest CreateOffline(Google.Apis.CloudProfiler.v2.Data.Profile body, string parent)
{
return new CreateOfflineRequest(service, body, parent);
}
/// <summary>CreateOfflineProfile creates a new profile resource in the offline mode. The client provides
/// the profile to create along with the profile bytes, the server records it.</summary>
public class CreateOfflineRequest : CloudProfilerBaseServiceRequest<Google.Apis.CloudProfiler.v2.Data.Profile>
{
/// <summary>Constructs a new CreateOffline request.</summary>
public CreateOfflineRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudProfiler.v2.Data.Profile body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Parent project to create the profile in.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudProfiler.v2.Data.Profile Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "createOffline"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2/{+parent}/profiles:createOffline"; }
}
/// <summary>Initializes CreateOffline parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
/// <summary>UpdateProfile updates the profile bytes and labels on the profile resource created in the
/// online mode. Updating the bytes for profiles created in the offline mode is currently not supported: the
/// profile content must be provided at the time of the profile creation.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">Output only. Opaque, server-assigned, unique ID for this profile.</param>
public virtual PatchRequest Patch(Google.Apis.CloudProfiler.v2.Data.Profile body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>UpdateProfile updates the profile bytes and labels on the profile resource created in the
/// online mode. Updating the bytes for profiles created in the offline mode is currently not supported: the
/// profile content must be provided at the time of the profile creation.</summary>
public class PatchRequest : CloudProfilerBaseServiceRequest<Google.Apis.CloudProfiler.v2.Data.Profile>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudProfiler.v2.Data.Profile body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>Output only. Opaque, server-assigned, unique ID for this profile.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Field mask used to specify the fields to be overwritten. Currently only profile_bytes and
/// labels fields are supported by UpdateProfile, so only those fields can be specified in the mask.
/// When no mask is provided, all fields are overwritten.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudProfiler.v2.Data.Profile Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2/{+name}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/profiles/[^/]+$",
});
RequestParameters.Add(
"updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
}
namespace Google.Apis.CloudProfiler.v2.Data
{
/// <summary>CreateProfileRequest describes a profile resource online creation request. The deployment field must be
/// populated. The profile_type specifies the list of profile types supported by the agent. The creation call will
/// hang until a profile of one of these types needs to be collected.</summary>
public class CreateProfileRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Deployment details.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deployment")]
public virtual Deployment Deployment { get; set; }
/// <summary>One or more profile types that the agent is capable of providing.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("profileType")]
public virtual System.Collections.Generic.IList<string> ProfileType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Deployment contains the deployment identification information.</summary>
public class Deployment : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Labels identify the deployment within the user universe and same target. Validation regex for label
/// names: `^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$`. Value for an individual label must be <= 512 bytes, the total
/// size of all label names and values must be <= 1024 bytes.
///
/// Label named "language" can be used to record the programming language of the profiled deployment. The
/// standard choices for the value include "java", "go", "python", "ruby", "nodejs", "php", "dotnet".
///
/// For deployments running on Google Cloud Platform, "zone" or "region" label should be present describing the
/// deployment location. An example of a zone is "us-central1-a", an example of a region is "us-central1" or
/// "us-central".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string,string> Labels { get; set; }
/// <summary>Project ID is the ID of a cloud project. Validation regex: `^a-z{4,61}[a-z0-9]$`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("projectId")]
public virtual string ProjectId { get; set; }
/// <summary>Target is the service name used to group related deployments: * Service name for GAE Flex /
/// Standard. * Cluster and container name for GKE. * User-specified string for direct GCE profiling (e.g.
/// Java). * Job name for Dataflow. Validation regex: `^[a-z]([-a-z0-9_.]{0,253}[a-z0-9])?$`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("target")]
public virtual string Target { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Profile resource.</summary>
public class Profile : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Deployment this profile corresponds to.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deployment")]
public virtual Deployment Deployment { get; set; }
/// <summary>Duration of the profiling session. Input (for the offline mode) or output (for the online mode).
/// The field represents requested profiling duration. It may slightly differ from the effective profiling
/// duration, which is recorded in the profile data, in case the profiling can't be stopped immediately (e.g. in
/// case stopping the profiling is handled asynchronously).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("duration")]
public virtual object Duration { get; set; }
/// <summary>Input only. Labels associated to this specific profile. These labels will get merged with the
/// deployment labels for the final data set. See documentation on deployment labels for validation rules and
/// limits.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string,string> Labels { get; set; }
/// <summary>Output only. Opaque, server-assigned, unique ID for this profile.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Input only. Profile bytes, as a gzip compressed serialized proto, the format is
/// https://github.com/google/pprof/blob/master/proto/profile.proto.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("profileBytes")]
public virtual string ProfileBytes { get; set; }
/// <summary>Type of profile. For offline mode, this must be specified when creating the profile. For online
/// mode it is assigned and returned by the server.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("profileType")]
public virtual string ProfileType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.TestHooks;
using Orleans.Statistics;
using UnitTests.TesterInternal;
using Xunit;
using Xunit.Abstractions;
namespace UnitTests.SchedulerTests
{
public class OrleansTaskSchedulerAdvancedTests : MarshalByRefObject, IDisposable
{
private readonly ITestOutputHelper output;
private OrleansTaskScheduler orleansTaskScheduler;
private bool mainDone;
private int stageNum1;
private int stageNum2;
private static readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1);
private static readonly TimeSpan TwoSeconds = TimeSpan.FromSeconds(2);
private static readonly int WaitFactor = Debugger.IsAttached ? 100 : 1;
private readonly ILoggerFactory loggerFactory;
private readonly TestHooksHostEnvironmentStatistics performanceMetrics;
public OrleansTaskSchedulerAdvancedTests(ITestOutputHelper output)
{
this.output = output;
this.loggerFactory = OrleansTaskSchedulerBasicTests.InitSchedulerLogging();
this.performanceMetrics = new TestHooksHostEnvironmentStatistics();
}
public void Dispose()
{
if (this.orleansTaskScheduler != null)
{
this.orleansTaskScheduler.Stop();
}
this.loggerFactory.Dispose();
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public void Sched_AC_Test()
{
int n = 0;
bool insideTask = false;
UnitTestSchedulingContext context = new UnitTestSchedulingContext();
this.orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.performanceMetrics, this.loggerFactory);
this.output.WriteLine("Running Main in Context=" + RuntimeContext.Current);
this.orleansTaskScheduler.QueueWorkItem(new ClosureWorkItem(() =>
{
for (int i = 0; i < 10; i++)
{
Task.Factory.StartNew(() =>
{
// ReSharper disable AccessToModifiedClosure
this.output.WriteLine("Starting " + i + " in Context=" + RuntimeContext.Current);
Assert.False(insideTask, $"Starting new task when I am already inside task of iteration {n}");
insideTask = true;
int k = n;
Thread.Sleep(100);
n = k + 1;
insideTask = false;
// ReSharper restore AccessToModifiedClosure
}).Ignore();
}
}), context);
// Pause to let things run
Thread.Sleep(1500);
// N should be 10, because all tasks should execute serially
Assert.True(n != 0, "Work items did not get executed");
Assert.Equal(10, n); // "Work items executed concurrently"
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task Sched_AC_WaitTest()
{
int n = 0;
bool insideTask = false;
UnitTestSchedulingContext context = new UnitTestSchedulingContext();
this.orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.performanceMetrics, this.loggerFactory);
var result = new TaskCompletionSource<bool>();
this.orleansTaskScheduler.QueueWorkItem(new ClosureWorkItem(() =>
{
var task1 = Task.Factory.StartNew(() =>
{
this.output.WriteLine("Starting 1");
Assert.False(insideTask, $"Starting new task when I am already inside task of iteration {n}");
insideTask = true;
this.output.WriteLine("===> 1a");
Thread.Sleep(1000); n = n + 3;
this.output.WriteLine("===> 1b");
insideTask = false;
});
var task2 = Task.Factory.StartNew(() =>
{
this.output.WriteLine("Starting 2");
Assert.False(insideTask, $"Starting new task when I am already inside task of iteration {n}");
insideTask = true;
this.output.WriteLine("===> 2a");
task1.Wait();
this.output.WriteLine("===> 2b");
n = n * 5;
this.output.WriteLine("===> 2c");
insideTask = false;
result.SetResult(true);
});
task1.Ignore();
task2.Ignore();
}), context);
var timeoutLimit = TimeSpan.FromMilliseconds(1500);
try
{
await result.Task.WithTimeout(timeoutLimit);
}
catch (TimeoutException)
{
Assert.True(false, "Result did not arrive before timeout " + timeoutLimit);
}
Assert.True(n != 0, "Work items did not get executed");
Assert.Equal(15, n); // "Work items executed out of order"
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public void Sched_AC_MainTurnWait_Test()
{
this.orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(new UnitTestSchedulingContext(), this.performanceMetrics, this.loggerFactory);
var promise = Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
});
promise.Wait();
}
private void SubProcess1(int n)
{
string msg = string.Format("1-{0} MainDone={1} inside Task {2}", n, this.mainDone, Task.CurrentId);
this.output.WriteLine("1 ===> " + msg);
Assert.True(this.mainDone, msg + " -- Main turn should be finished");
this.stageNum1 = n;
}
private void SubProcess2(int n)
{
string msg = string.Format("2-{0} MainDone={1} inside Task {2}", n, this.mainDone, Task.CurrentId);
this.output.WriteLine("2 ===> " + msg);
Assert.True(this.mainDone, msg + " -- Main turn should be finished");
this.stageNum2 = n;
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task Sched_AC_Turn_Execution_Order()
{
// Can we add a unit test that basicaly checks that any turn is indeed run till completion before any other turn?
// For example, you have a long running main turn and in the middle it spawns a lot of short CWs (on Done promise) and StartNew.
// You test that no CW/StartNew runs until the main turn is fully done. And run in stress.
UnitTestSchedulingContext context = new UnitTestSchedulingContext();
this.orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.performanceMetrics, this.loggerFactory);
var result1 = new TaskCompletionSource<bool>();
var result2 = new TaskCompletionSource<bool>();
this.orleansTaskScheduler.QueueWorkItem(new ClosureWorkItem(() =>
{
this.mainDone = false;
this.stageNum1 = this.stageNum2 = 0;
Task task1 = Task.Factory.StartNew(() => SubProcess1(11));
Task task2 = task1.ContinueWith((_) => SubProcess1(12));
Task task3 = task2.ContinueWith((_) => SubProcess1(13));
Task task4 = task3.ContinueWith((_) => { SubProcess1(14); result1.SetResult(true); });
task4.Ignore();
Task task21 = Task.CompletedTask.ContinueWith((_) => SubProcess2(21));
Task task22 = task21.ContinueWith((_) => { SubProcess2(22); result2.SetResult(true); });
task22.Ignore();
Thread.Sleep(TimeSpan.FromSeconds(1));
this.mainDone = true;
}), context);
try { await result1.Task.WithTimeout(TimeSpan.FromSeconds(3)); }
catch (TimeoutException) { Assert.True(false, "Timeout-1"); }
try { await result2.Task.WithTimeout(TimeSpan.FromSeconds(3)); }
catch (TimeoutException) { Assert.True(false, "Timeout-2"); }
Assert.NotEqual(0, this.stageNum1); // "Work items did not get executed-1"
Assert.NotEqual(0, this.stageNum2); // "Work items did not get executed-2"
Assert.Equal(14, this.stageNum1); // "Work items executed out of order-1"
Assert.Equal(22, this.stageNum2); // "Work items executed out of order-2"
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public void Sched_Task_Turn_Execution_Order()
{
// A unit test that checks that any turn is indeed run till completion before any other turn?
// For example, you have a long running main turn and in the middle it spawns a lot of short CWs (on Done promise) and StartNew.
// You test that no CW/StartNew runs until the main turn is fully done. And run in stress.
UnitTestSchedulingContext context = new UnitTestSchedulingContext();
OrleansTaskScheduler masterScheduler = this.orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.performanceMetrics, this.loggerFactory);
WorkItemGroup workItemGroup = this.orleansTaskScheduler.GetWorkItemGroup(context);
ActivationTaskScheduler activationScheduler = workItemGroup.TaskRunner;
this.mainDone = false;
this.stageNum1 = this.stageNum2 = 0;
var result1 = new TaskCompletionSource<bool>();
var result2 = new TaskCompletionSource<bool>();
Task wrapper = null;
Task finalTask1 = null;
Task finalPromise2 = null;
masterScheduler.QueueWorkItem(new ClosureWorkItem(() =>
{
Log(1, "Outer ClosureWorkItem " + Task.CurrentId + " starting");
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #0"
Log(2, "Starting wrapper Task");
wrapper = Task.Factory.StartNew(() =>
{
Log(3, "Inside wrapper Task Id=" + Task.CurrentId);
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #1"
// Execution chain #1
Log(4, "Wrapper Task Id=" + Task.CurrentId + " creating Task chain");
Task task1 = Task.Factory.StartNew(() =>
{
Log(5, "#11 Inside sub-Task Id=" + Task.CurrentId);
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #11"
SubProcess1(11);
});
Task task2 = task1.ContinueWith((Task task) =>
{
Log(6, "#12 Inside continuation Task Id=" + Task.CurrentId);
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #12"
if (task.IsFaulted) throw task.Exception.Flatten();
SubProcess1(12);
});
Task task3 = task2.ContinueWith(task =>
{
Log(7, "#13 Inside continuation Task Id=" + Task.CurrentId);
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #13"
if (task.IsFaulted) throw task.Exception.Flatten();
SubProcess1(13);
});
finalTask1 = task3.ContinueWith(task =>
{
Log(8, "#14 Inside final continuation Task Id=" + Task.CurrentId);
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #14"
if (task.IsFaulted) throw task.Exception.Flatten();
SubProcess1(14);
result1.SetResult(true);
});
// Execution chain #2
Log(9, "Wrapper Task " + Task.CurrentId + " creating AC chain");
Task promise2 = Task.Factory.StartNew(() =>
{
Log(10, "#21 Inside sub-Task Id=" + Task.CurrentId);
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #21"
SubProcess2(21);
});
finalPromise2 = promise2.ContinueWith((_) =>
{
Log(11, "#22 Inside final continuation Task Id=" + Task.CurrentId);
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #22"
SubProcess2(22);
result2.SetResult(true);
});
finalPromise2.Ignore();
Log(12, "Wrapper Task Id=" + Task.CurrentId + " sleeping #2");
Thread.Sleep(TimeSpan.FromSeconds(1));
Log(13, "Wrapper Task Id=" + Task.CurrentId + " finished");
});
Log(14, "Outer ClosureWorkItem Task Id=" + Task.CurrentId + " sleeping");
Thread.Sleep(TimeSpan.FromSeconds(1));
Log(15, "Outer ClosureWorkItem Task Id=" + Task.CurrentId + " awake");
Log(16, "Finished Outer ClosureWorkItem Task Id=" + wrapper.Id);
this.mainDone = true;
}), context);
Log(17, "Waiting for ClosureWorkItem to spawn wrapper Task");
for (int i = 0; i < 5 * WaitFactor; i++)
{
if (wrapper != null) break;
Thread.Sleep(TimeSpan.FromSeconds(1).Multiply(WaitFactor));
}
Assert.NotNull(wrapper); // Wrapper Task was not created
Log(18, "Waiting for wrapper Task Id=" + wrapper.Id + " to complete");
bool finished = wrapper.Wait(TimeSpan.FromSeconds(4 * WaitFactor));
Log(19, "Done waiting for wrapper Task Id=" + wrapper.Id + " Finished=" + finished);
if (!finished) throw new TimeoutException();
Assert.False(wrapper.IsFaulted, "Wrapper Task faulted: " + wrapper.Exception);
Assert.True(wrapper.IsCompleted, "Wrapper Task should be completed");
Log(20, "Waiting for TaskWorkItem to complete");
for (int i = 0; i < 15 * WaitFactor; i++)
{
if (this.mainDone) break;
Thread.Sleep(1000 * WaitFactor);
}
Log(21, "Done waiting for TaskWorkItem to complete MainDone=" + this.mainDone);
Assert.True(this.mainDone, "Main Task should be completed");
Assert.NotNull(finalTask1); // Task chain #1 not created
Assert.NotNull(finalPromise2); // Task chain #2 not created
Log(22, "Waiting for final task #1 to complete");
bool ok = finalTask1.Wait(TimeSpan.FromSeconds(4 * WaitFactor));
Log(23, "Done waiting for final task #1 complete Ok=" + ok);
if (!ok) throw new TimeoutException();
Assert.False(finalTask1.IsFaulted, "Final Task faulted: " + finalTask1.Exception);
Assert.True(finalTask1.IsCompleted, "Final Task completed");
Assert.True(result1.Task.Result, "Timeout-1");
Log(24, "Waiting for final promise #2 to complete");
finalPromise2.Wait(TimeSpan.FromSeconds(4 * WaitFactor));
Log(25, "Done waiting for final promise #2");
Assert.False(finalPromise2.IsFaulted, "Final Task faulted: " + finalPromise2.Exception);
Assert.True(finalPromise2.IsCompleted, "Final Task completed");
Assert.True(result2.Task.Result, "Timeout-2");
Assert.NotEqual(0, this.stageNum1); // "Work items did not get executed-1"
Assert.Equal(14, this.stageNum1); // "Work items executed out of order-1"
Assert.NotEqual(0, this.stageNum2); // "Work items did not get executed-2"
Assert.Equal(22, this.stageNum2); // "Work items executed out of order-2"
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public void Sched_AC_Current_TaskScheduler()
{
UnitTestSchedulingContext context = new UnitTestSchedulingContext();
OrleansTaskScheduler orleansTaskScheduler = orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.performanceMetrics, this.loggerFactory);
ActivationTaskScheduler activationScheduler = orleansTaskScheduler.GetWorkItemGroup(context).TaskRunner;
// RuntimeContext.InitializeThread(masterScheduler);
this.mainDone = false;
var result = new TaskCompletionSource<bool>();
Task wrapper = null;
Task finalPromise = null;
orleansTaskScheduler.QueueWorkItem(new ClosureWorkItem(() =>
{
Log(1, "Outer ClosureWorkItem " + Task.CurrentId + " starting");
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #0"
Log(2, "Starting wrapper Task");
wrapper = Task.Factory.StartNew(() =>
{
Log(3, "Inside wrapper Task Id=" + Task.CurrentId);
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #1"
Log(4, "Wrapper Task " + Task.CurrentId + " creating AC chain");
Task promise1 = Task.Factory.StartNew(() =>
{
Log(5, "#1 Inside AC Task Id=" + Task.CurrentId);
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #1"
SubProcess1(1);
});
Task promise2 = promise1.ContinueWith((_) =>
{
Log(6, "#2 Inside AC Task Id=" + Task.CurrentId);
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #2"
SubProcess1(2);
});
finalPromise = promise2.ContinueWith((_) =>
{
Log(7, "#3 Inside final AC Task Id=" + Task.CurrentId);
Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #3"
SubProcess1(3);
result.SetResult(true);
});
finalPromise.Ignore();
Log(8, "Wrapper Task Id=" + Task.CurrentId + " sleeping");
Thread.Sleep(TimeSpan.FromSeconds(1));
Log(9, "Wrapper Task Id=" + Task.CurrentId + " finished");
});
Log(10, "Outer ClosureWorkItem Task Id=" + Task.CurrentId + " sleeping");
Thread.Sleep(TimeSpan.FromSeconds(1));
Log(11, "Outer ClosureWorkItem Task Id=" + Task.CurrentId + " awake");
Log(12, "Finished Outer TaskWorkItem Task Id=" + wrapper.Id);
this.mainDone = true;
}), context);
Log(13, "Waiting for ClosureWorkItem to spawn wrapper Task");
for (int i = 0; i < 5 * WaitFactor; i++)
{
if (wrapper != null) break;
Thread.Sleep(TimeSpan.FromSeconds(1).Multiply(WaitFactor));
}
Assert.NotNull(wrapper); // Wrapper Task was not created
Log(14, "Waiting for wrapper Task Id=" + wrapper.Id + " to complete");
bool finished = wrapper.Wait(TimeSpan.FromSeconds(4 * WaitFactor));
Log(15, "Done waiting for wrapper Task Id=" + wrapper.Id + " Finished=" + finished);
if (!finished) throw new TimeoutException();
Assert.False(wrapper.IsFaulted, "Wrapper Task faulted: " + wrapper.Exception);
Assert.True(wrapper.IsCompleted, "Wrapper Task should be completed");
Log(16, "Waiting for TaskWorkItem to complete");
for (int i = 0; i < 15 * WaitFactor; i++)
{
if (this.mainDone) break;
Thread.Sleep(1000 * WaitFactor);
}
Log(17, "Done waiting for TaskWorkItem to complete MainDone=" + this.mainDone);
Assert.True(this.mainDone, "Main Task should be completed");
Assert.NotNull(finalPromise); // AC chain not created
Log(18, "Waiting for final AC promise to complete");
finalPromise.Wait(TimeSpan.FromSeconds(4 * WaitFactor));
Log(19, "Done waiting for final promise");
Assert.False(finalPromise.IsFaulted, "Final AC faulted: " + finalPromise.Exception);
Assert.True(finalPromise.IsCompleted, "Final AC completed");
Assert.True(result.Task.Result, "Timeout-1");
Assert.NotEqual(0, this.stageNum1); // "Work items did not get executed-1"
Assert.Equal(3, this.stageNum1); // "Work items executed out of order-1"
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public void Sched_AC_ContinueWith_1_Test()
{
UnitTestSchedulingContext context = new UnitTestSchedulingContext();
this.orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.performanceMetrics, this.loggerFactory);
var result = new TaskCompletionSource<bool>();
int n = 0;
// ReSharper disable AccessToModifiedClosure
this.orleansTaskScheduler.QueueWorkItem(new ClosureWorkItem(() =>
{
Task task1 = Task.Factory.StartNew(() => { this.output.WriteLine("===> 1a"); Thread.Sleep(OneSecond); n = n + 3; this.output.WriteLine("===> 1b"); });
Task task2 = task1.ContinueWith((_) => { n = n * 5; this.output.WriteLine("===> 2"); });
Task task3 = task2.ContinueWith((_) => { n = n / 5; this.output.WriteLine("===> 3"); });
Task task4 = task3.ContinueWith((_) => { n = n - 2; this.output.WriteLine("===> 4"); result.SetResult(true); });
task4.Ignore();
}), context);
// ReSharper restore AccessToModifiedClosure
Assert.True(result.Task.Wait(TwoSeconds));
Assert.True(n != 0, "Work items did not get executed");
Assert.Equal(1, n); // "Work items executed out of order"
}
[Fact, TestCategory("Functional"), TestCategory("AsynchronyPrimitives")]
public void Sched_Task_JoinAll()
{
var result = new TaskCompletionSource<bool>();
int n = 0;
Task<int>[] tasks = null;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
UnitTestSchedulingContext context = new UnitTestSchedulingContext();
this.orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.performanceMetrics, this.loggerFactory);
// ReSharper disable AccessToModifiedClosure
this.orleansTaskScheduler.QueueWorkItem(new ClosureWorkItem(() =>
{
Task<int> task1 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("===> 1a"); Thread.Sleep(OneSecond); n = n + 3; this.output.WriteLine("===> 1b"); return 1; });
Task<int> task2 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("===> 2a"); Thread.Sleep(OneSecond); n = n + 3; this.output.WriteLine("===> 2b"); return 2; });
Task<int> task3 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("===> 3a"); Thread.Sleep(OneSecond); n = n + 3; this.output.WriteLine("===> 3b"); return 3; });
Task<int> task4 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("===> 4a"); Thread.Sleep(OneSecond); n = n + 3; this.output.WriteLine("===> 4b"); return 4; });
tasks = new Task<int>[] {task1, task2, task3, task4};
result.SetResult(true);
}),context);
// ReSharper restore AccessToModifiedClosure
Assert.True(result.Task.Wait(TwoSeconds)); // Wait for main (one that creates tasks) work item to finish.
var promise = Task<int[]>.Factory.ContinueWhenAll(tasks, (res) =>
{
List<int> output = new List<int>();
int taskNum = 1;
foreach (var t in tasks)
{
Assert.True(t.IsCompleted, "Sub-Task completed");
Assert.False(t.IsFaulted, "Sub-Task faulted: " + t.Exception);
var val = t.Result;
Assert.Equal(taskNum, val); // "Value returned by Task " + taskNum
output.Add(val);
taskNum++;
}
int[] results = output.ToArray();
return results;
});
bool ok = promise.Wait(TimeSpan.FromSeconds(8));
if (!ok) throw new TimeoutException();
Assert.True(n != 0, "Work items did not get executed");
Assert.Equal(12, n); // "Not all work items executed"
long ms = stopwatch.ElapsedMilliseconds;
Assert.True(4000 <= ms && ms <= 5000, "Wait time out of range, expected between 4000 and 5000 milliseconds, was " + ms);
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public void Sched_AC_ContinueWith_2_OrleansSched()
{
this.orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(new UnitTestSchedulingContext(), this.performanceMetrics, this.loggerFactory);
var result1 = new TaskCompletionSource<bool>();
var result2 = new TaskCompletionSource<bool>();
bool failed1 = false;
bool failed2 = false;
Task task1 = Task.Factory.StartNew(() => { this.output.WriteLine("===> 1a"); Thread.Sleep(OneSecond); throw new ArgumentException(); });
Task task2 = task1.ContinueWith((Task t) =>
{
if (!t.IsFaulted) this.output.WriteLine("===> 2");
else
{
this.output.WriteLine("===> 3");
failed1 = true;
result1.SetResult(true);
}
});
Task task3 = task1.ContinueWith((Task t) =>
{
if (!t.IsFaulted) this.output.WriteLine("===> 4");
else
{
this.output.WriteLine("===> 5");
failed2 = true;
result2.SetResult(true);
}
});
task1.Ignore();
task2.Ignore();
task3.Ignore();
Assert.True(result1.Task.Wait(TwoSeconds), "First ContinueWith did not fire.");
Assert.True(result2.Task.Wait(TwoSeconds), "Second ContinueWith did not fire.");
Assert.True(failed1); // "First ContinueWith did not fire error handler."
Assert.True(failed2); // "Second ContinueWith did not fire error handler."
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public void Sched_Task_SchedulingContext()
{
UnitTestSchedulingContext context = new UnitTestSchedulingContext();
this.orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.performanceMetrics, this.loggerFactory);
ActivationTaskScheduler scheduler = this.orleansTaskScheduler.GetWorkItemGroup(context).TaskRunner;
var result = new TaskCompletionSource<bool>();
Task endOfChain = null;
int n = 0;
Task wrapper = new Task(() =>
{
CheckRuntimeContext(context);
// ReSharper disable AccessToModifiedClosure
Task task1 = Task.Factory.StartNew(() =>
{
this.output.WriteLine("===> 1a ");
CheckRuntimeContext(context);
Thread.Sleep(1000);
n = n + 3;
this.output.WriteLine("===> 1b");
CheckRuntimeContext(context);
});
Task task2 = task1.ContinueWith(task =>
{
this.output.WriteLine("===> 2");
CheckRuntimeContext(context);
n = n * 5;
});
Task task3 = task2.ContinueWith(task =>
{
this.output.WriteLine("===> 3");
n = n / 5;
CheckRuntimeContext(context);
});
Task task4 = task3.ContinueWith(task =>
{
this.output.WriteLine("===> 4");
n = n - 2;
result.SetResult(true);
CheckRuntimeContext(context);
});
// ReSharper restore AccessToModifiedClosure
endOfChain = task4.ContinueWith(task =>
{
this.output.WriteLine("Done Faulted={0}", task.IsFaulted);
CheckRuntimeContext(context);
Assert.False(task.IsFaulted, "Faulted with Exception=" + task.Exception);
});
});
wrapper.Start(scheduler);
bool ok = wrapper.Wait(TimeSpan.FromSeconds(1));
if (!ok) throw new TimeoutException();
Assert.False(wrapper.IsFaulted, "Wrapper Task Faulted with Exception=" + wrapper.Exception);
Assert.True(wrapper.IsCompleted, "Wrapper Task completed");
bool finished = result.Task.Wait(TimeSpan.FromSeconds(2));
Assert.NotNull(endOfChain); // End of chain Task created successfully
Assert.False(endOfChain.IsFaulted, "Task chain Faulted with Exception=" + endOfChain.Exception);
Assert.True(finished, "Wrapper Task completed ok");
Assert.True(n != 0, "Work items did not get executed");
Assert.Equal(1, n); // "Work items executed out of order"
}
private void Log(int level, string what)
{
this.output.WriteLine("#{0} - {1} -- Thread={2} Worker={3} TaskScheduler.Current={4}",
level, what,
Thread.CurrentThread.ManagedThreadId,
Thread.CurrentThread.Name,
TaskScheduler.Current);
}
private static void CheckRuntimeContext(ISchedulingContext context)
{
Assert.NotNull(RuntimeContext.Current); // Runtime context should not be null
Assert.NotNull(RuntimeContext.Current.ActivationContext); // Activation context should not be null
Assert.Equal(context, RuntimeContext.Current.ActivationContext); // "Activation context"
}
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// <p>Values that identify various data, texture, and buffer types that can be assigned to a shader variable.</p>
/// </summary>
/// <remarks>
/// <p>A call to the <strong><see cref="SharpDX.D3DCompiler.ShaderReflectionType.GetDescription"/></strong> method returns a <strong><see cref="SharpDX.D3DCompiler.ShaderVariableType"/></strong> value in the <strong>Type</strong> member of a <strong><see cref="SharpDX.D3DCompiler.ShaderTypeDescription"/></strong> structure.</p><p>The types in a structured buffer describe the structure of the elements in the buffer. The layout of these types generally match their C++ struct counterparts. The following examples show structured buffers:</p><pre><code>struct mystruct {float4 val; uint ind;}; RWStructuredBuffer<mystruct> rwbuf;
/// RWStructuredBuffer<float3> rwbuf2;</code></pre>
/// </remarks>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SHADER_VARIABLE_TYPE</unmanaged>
/// <unmanaged-short>D3D_SHADER_VARIABLE_TYPE</unmanaged-short>
public enum EffectParameterType : byte
{
/// <summary>
/// <dd> <p>The variable is a void reference.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_VOID</unmanaged>
/// <unmanaged-short>D3D_SVT_VOID</unmanaged-short>
Void = unchecked((int)0),
/// <summary>
/// <dd> <p>The variable is a boolean.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_BOOL</unmanaged>
/// <unmanaged-short>D3D_SVT_BOOL</unmanaged-short>
Bool = unchecked((int)1),
/// <summary>
/// <dd> <p>The variable is an integer.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_INT</unmanaged>
/// <unmanaged-short>D3D_SVT_INT</unmanaged-short>
Int = unchecked((int)2),
/// <summary>
/// <dd> <p>The variable is a floating-point number.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_FLOAT</unmanaged>
/// <unmanaged-short>D3D_SVT_FLOAT</unmanaged-short>
Float = unchecked((int)3),
/// <summary>
/// <dd> <p>The variable is a string.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_STRING</unmanaged>
/// <unmanaged-short>D3D_SVT_STRING</unmanaged-short>
String = unchecked((int)4),
/// <summary>
/// <dd> <p>The variable is a texture.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_TEXTURE</unmanaged>
/// <unmanaged-short>D3D_SVT_TEXTURE</unmanaged-short>
Texture = unchecked((int)5),
/// <summary>
/// <dd> <p>The variable is a 1D texture.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_TEXTURE1D</unmanaged>
/// <unmanaged-short>D3D_SVT_TEXTURE1D</unmanaged-short>
Texture1D = unchecked((int)6),
/// <summary>
/// <dd> <p>The variable is a 2D texture.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_TEXTURE2D</unmanaged>
/// <unmanaged-short>D3D_SVT_TEXTURE2D</unmanaged-short>
Texture2D = unchecked((int)7),
/// <summary>
/// <dd> <p>The variable is a 3D texture.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_TEXTURE3D</unmanaged>
/// <unmanaged-short>D3D_SVT_TEXTURE3D</unmanaged-short>
Texture3D = unchecked((int)8),
/// <summary>
/// <dd> <p>The variable is a texture cube.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_TEXTURECUBE</unmanaged>
/// <unmanaged-short>D3D_SVT_TEXTURECUBE</unmanaged-short>
TextureCube = unchecked((int)9),
/// <summary>
/// <dd> <p>The variable is a sampler.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_SAMPLER</unmanaged>
/// <unmanaged-short>D3D_SVT_SAMPLER</unmanaged-short>
Sampler = unchecked((int)10),
/// <summary>
/// <dd> <p>The variable is a sampler.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_SAMPLER1D</unmanaged>
/// <unmanaged-short>D3D_SVT_SAMPLER1D</unmanaged-short>
Sampler1D = unchecked((int)11),
/// <summary>
/// <dd> <p>The variable is a sampler.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_SAMPLER2D</unmanaged>
/// <unmanaged-short>D3D_SVT_SAMPLER2D</unmanaged-short>
Sampler2D = unchecked((int)12),
/// <summary>
/// <dd> <p>The variable is a sampler.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_SAMPLER3D</unmanaged>
/// <unmanaged-short>D3D_SVT_SAMPLER3D</unmanaged-short>
Sampler3D = unchecked((int)13),
/// <summary>
/// <dd> <p>The variable is a sampler.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_SAMPLERCUBE</unmanaged>
/// <unmanaged-short>D3D_SVT_SAMPLERCUBE</unmanaged-short>
SamplerCube = unchecked((int)14),
/// <summary>
/// <dd> <p>The variable is a pixel shader.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_PIXELSHADER</unmanaged>
/// <unmanaged-short>D3D_SVT_PIXELSHADER</unmanaged-short>
Pixelshader = unchecked((int)15),
/// <summary>
/// <dd> <p>The variable is a vertex shader.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_VERTEXSHADER</unmanaged>
/// <unmanaged-short>D3D_SVT_VERTEXSHADER</unmanaged-short>
Vertexshader = unchecked((int)16),
/// <summary>
/// <dd> <p>The variable is a pixel shader.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_PIXELFRAGMENT</unmanaged>
/// <unmanaged-short>D3D_SVT_PIXELFRAGMENT</unmanaged-short>
Pixelfragment = unchecked((int)17),
/// <summary>
/// <dd> <p>The variable is a vertex shader.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_VERTEXFRAGMENT</unmanaged>
/// <unmanaged-short>D3D_SVT_VERTEXFRAGMENT</unmanaged-short>
Vertexfragment = unchecked((int)18),
/// <summary>
/// <dd> <p>The variable is an unsigned integer.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_UINT</unmanaged>
/// <unmanaged-short>D3D_SVT_UINT</unmanaged-short>
UInt = unchecked((int)19),
/// <summary>
/// <dd> <p>The variable is an 8-bit unsigned integer.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_UINT8</unmanaged>
/// <unmanaged-short>D3D_SVT_UINT8</unmanaged-short>
UInt8 = unchecked((int)20),
/// <summary>
/// <dd> <p>The variable is a geometry shader.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_GEOMETRYSHADER</unmanaged>
/// <unmanaged-short>D3D_SVT_GEOMETRYSHADER</unmanaged-short>
Geometryshader = unchecked((int)21),
/// <summary>
/// <dd> <p>The variable is a rasterizer-state object.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_RASTERIZER</unmanaged>
/// <unmanaged-short>D3D_SVT_RASTERIZER</unmanaged-short>
Rasterizer = unchecked((int)22),
/// <summary>
/// <dd> <p>The variable is a depth-stencil-state object.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_DEPTHSTENCIL</unmanaged>
/// <unmanaged-short>D3D_SVT_DEPTHSTENCIL</unmanaged-short>
Depthstencil = unchecked((int)23),
/// <summary>
/// <dd> <p>The variable is a blend-state object.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_BLEND</unmanaged>
/// <unmanaged-short>D3D_SVT_BLEND</unmanaged-short>
Blend = unchecked((int)24),
/// <summary>
/// <dd> <p>The variable is a buffer.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_BUFFER</unmanaged>
/// <unmanaged-short>D3D_SVT_BUFFER</unmanaged-short>
Buffer = unchecked((int)25),
/// <summary>
/// <dd> <p>The variable is a constant buffer.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_CBUFFER</unmanaged>
/// <unmanaged-short>D3D_SVT_CBUFFER</unmanaged-short>
ConstantBuffer = unchecked((int)26),
/// <summary>
/// <dd> <p>The variable is a texture buffer.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_TBUFFER</unmanaged>
/// <unmanaged-short>D3D_SVT_TBUFFER</unmanaged-short>
TextureBuffer = unchecked((int)27),
/// <summary>
/// <dd> <p>The variable is a 1D-texture array.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_TEXTURE1DARRAY</unmanaged>
/// <unmanaged-short>D3D_SVT_TEXTURE1DARRAY</unmanaged-short>
Texture1DArray = unchecked((int)28),
/// <summary>
/// <dd> <p>The variable is a 2D-texture array.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_TEXTURE2DARRAY</unmanaged>
/// <unmanaged-short>D3D_SVT_TEXTURE2DARRAY</unmanaged-short>
Texture2DArray = unchecked((int)29),
/// <summary>
/// <dd> <p>The variable is a render-target view.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_RENDERTARGETVIEW</unmanaged>
/// <unmanaged-short>D3D_SVT_RENDERTARGETVIEW</unmanaged-short>
Rendertargetview = unchecked((int)30),
/// <summary>
/// <dd> <p>The variable is a depth-stencil view.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_DEPTHSTENCILVIEW</unmanaged>
/// <unmanaged-short>D3D_SVT_DEPTHSTENCILVIEW</unmanaged-short>
Depthstencilview = unchecked((int)31),
/// <summary>
/// <dd> <p>The variable is a 2D-multisampled texture.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_TEXTURE2DMS</unmanaged>
/// <unmanaged-short>D3D_SVT_TEXTURE2DMS</unmanaged-short>
Texture2DMultisampled = unchecked((int)32),
/// <summary>
/// <dd> <p>The variable is a 2D-multisampled-texture array.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_TEXTURE2DMSARRAY</unmanaged>
/// <unmanaged-short>D3D_SVT_TEXTURE2DMSARRAY</unmanaged-short>
Texture2DMultisampledArray = unchecked((int)33),
/// <summary>
/// <dd> <p>The variable is a texture-cube array.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_TEXTURECUBEARRAY</unmanaged>
/// <unmanaged-short>D3D_SVT_TEXTURECUBEARRAY</unmanaged-short>
TextureCubeArray = unchecked((int)34),
/// <summary>
/// <dd> <p>The variable holds a compiled hull-shader binary.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_HULLSHADER</unmanaged>
/// <unmanaged-short>D3D_SVT_HULLSHADER</unmanaged-short>
Hullshader = unchecked((int)35),
/// <summary>
/// <dd> <p>The variable holds a compiled domain-shader binary.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_DOMAINSHADER</unmanaged>
/// <unmanaged-short>D3D_SVT_DOMAINSHADER</unmanaged-short>
Domainshader = unchecked((int)36),
/// <summary>
/// <dd> <p>The variable is an interface.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_INTERFACE_POINTER</unmanaged>
/// <unmanaged-short>D3D_SVT_INTERFACE_POINTER</unmanaged-short>
InterfacePointer = unchecked((int)37),
/// <summary>
/// <dd> <p>The variable holds a compiled compute-shader binary.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_COMPUTESHADER</unmanaged>
/// <unmanaged-short>D3D_SVT_COMPUTESHADER</unmanaged-short>
Computeshader = unchecked((int)38),
/// <summary>
/// <dd> <p>The variable is a double precision (64-bit) floating-point number.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_DOUBLE</unmanaged>
/// <unmanaged-short>D3D_SVT_DOUBLE</unmanaged-short>
Double = unchecked((int)39),
/// <summary>
/// <dd> <p>The variable is a 1D read-and-write texture.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_RWTEXTURE1D</unmanaged>
/// <unmanaged-short>D3D_SVT_RWTEXTURE1D</unmanaged-short>
RWTexture1D = unchecked((int)40),
/// <summary>
/// <dd> <p>The variable is an array of 1D read-and-write textures.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_RWTEXTURE1DARRAY</unmanaged>
/// <unmanaged-short>D3D_SVT_RWTEXTURE1DARRAY</unmanaged-short>
RWTexture1DArray = unchecked((int)41),
/// <summary>
/// <dd> <p>The variable is a 2D read-and-write texture.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_RWTEXTURE2D</unmanaged>
/// <unmanaged-short>D3D_SVT_RWTEXTURE2D</unmanaged-short>
RWTexture2D = unchecked((int)42),
/// <summary>
/// <dd> <p>The variable is an array of 2D read-and-write textures.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_RWTEXTURE2DARRAY</unmanaged>
/// <unmanaged-short>D3D_SVT_RWTEXTURE2DARRAY</unmanaged-short>
RWTexture2DArray = unchecked((int)43),
/// <summary>
/// <dd> <p>The variable is a 3D read-and-write texture.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_RWTEXTURE3D</unmanaged>
/// <unmanaged-short>D3D_SVT_RWTEXTURE3D</unmanaged-short>
RWTexture3D = unchecked((int)44),
/// <summary>
/// <dd> <p>The variable is a read-and-write buffer.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_RWBUFFER</unmanaged>
/// <unmanaged-short>D3D_SVT_RWBUFFER</unmanaged-short>
RWBuffer = unchecked((int)45),
/// <summary>
/// <dd> <p>The variable is a byte-address buffer.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_BYTEADDRESS_BUFFER</unmanaged>
/// <unmanaged-short>D3D_SVT_BYTEADDRESS_BUFFER</unmanaged-short>
ByteAddressBuffer = unchecked((int)46),
/// <summary>
/// <dd> <p>The variable is a read-and-write byte-address buffer.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_RWBYTEADDRESS_BUFFER</unmanaged>
/// <unmanaged-short>D3D_SVT_RWBYTEADDRESS_BUFFER</unmanaged-short>
RWByteAddressBuffer = unchecked((int)47),
/// <summary>
/// <dd> <p>The variable is a structured buffer. </p> <p>For more information about structured buffer, see the <strong>Remarks</strong> section.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_STRUCTURED_BUFFER</unmanaged>
/// <unmanaged-short>D3D_SVT_STRUCTURED_BUFFER</unmanaged-short>
StructuredBuffer = unchecked((int)48),
/// <summary>
/// <dd> <p>The variable is a read-and-write structured buffer.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_RWSTRUCTURED_BUFFER</unmanaged>
/// <unmanaged-short>D3D_SVT_RWSTRUCTURED_BUFFER</unmanaged-short>
RWStructuredBuffer = unchecked((int)49),
/// <summary>
/// <dd> <p>The variable is an append structured buffer.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_APPEND_STRUCTURED_BUFFER</unmanaged>
/// <unmanaged-short>D3D_SVT_APPEND_STRUCTURED_BUFFER</unmanaged-short>
AppendStructuredBuffer = unchecked((int)50),
/// <summary>
/// <dd> <p>The variable is a consume structured buffer.</p> </dd>
/// </summary>
/// <msdn-id>ff728735</msdn-id>
/// <unmanaged>D3D_SVT_CONSUME_STRUCTURED_BUFFER</unmanaged>
/// <unmanaged-short>D3D_SVT_CONSUME_STRUCTURED_BUFFER</unmanaged-short>
ConsumeStructuredBuffer = unchecked((int)51),
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Net.Test.Common;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public abstract class ResponseStreamTest : HttpClientHandlerTestBase
{
public ResponseStreamTest(ITestOutputHelper output) : base(output) { }
public static IEnumerable<object[]> RemoteServersAndReadModes()
{
foreach (Configuration.Http.RemoteServer remoteServer in Configuration.Http.RemoteServers)
{
for (int i = 0; i < 8; i++)
{
yield return new object[] { remoteServer, i };
}
}
}
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(RemoteServersAndReadModes))]
public async Task GetStreamAsync_ReadToEnd_Success(Configuration.Http.RemoteServer remoteServer, int readMode)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
{
string customHeaderValue = Guid.NewGuid().ToString("N");
client.DefaultRequestHeaders.Add("X-ResponseStreamTest", customHeaderValue);
using (Stream stream = await client.GetStreamAsync(remoteServer.EchoUri))
{
var ms = new MemoryStream();
int bytesRead;
var buffer = new byte[10];
string responseBody;
// Read all of the response content in various ways
switch (readMode)
{
case 0:
// StreamReader.ReadToEnd
responseBody = new StreamReader(stream).ReadToEnd();
break;
case 1:
// StreamReader.ReadToEndAsync
responseBody = await new StreamReader(stream).ReadToEndAsync();
break;
case 2:
// Individual calls to Read(Array)
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
ms.Write(buffer, 0, bytesRead);
}
responseBody = Encoding.UTF8.GetString(ms.ToArray());
break;
case 3:
// Individual calls to ReadAsync(Array)
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
ms.Write(buffer, 0, bytesRead);
}
responseBody = Encoding.UTF8.GetString(ms.ToArray());
break;
case 4:
// Individual calls to Read(Span)
while ((bytesRead = stream.Read(new Span<byte>(buffer))) != 0)
{
ms.Write(buffer, 0, bytesRead);
}
responseBody = Encoding.UTF8.GetString(ms.ToArray());
break;
case 5:
// ReadByte
int byteValue;
while ((byteValue = stream.ReadByte()) != -1)
{
ms.WriteByte((byte)byteValue);
}
responseBody = Encoding.UTF8.GetString(ms.ToArray());
break;
case 6:
// CopyTo
stream.CopyTo(ms);
responseBody = Encoding.UTF8.GetString(ms.ToArray());
break;
case 7:
// CopyToAsync
await stream.CopyToAsync(ms);
responseBody = Encoding.UTF8.GetString(ms.ToArray());
break;
default:
throw new Exception($"Unexpected test mode {readMode}");
}
// Calling GetStreamAsync() means we don't have access to the HttpResponseMessage.
// So, we can't use the MD5 hash validation to verify receipt of the response body.
// For this test, we can use a simpler verification of a custom header echo'ing back.
_output.WriteLine(responseBody);
Assert.Contains(customHeaderValue, responseBody);
}
}
}
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task GetAsync_UseResponseHeadersReadAndCallLoadIntoBuffer_Success(Configuration.Http.RemoteServer remoteServer)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
using (HttpResponseMessage response = await client.GetAsync(remoteServer.EchoUri, HttpCompletionOption.ResponseHeadersRead))
{
await response.Content.LoadIntoBufferAsync();
string responseBody = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseBody);
TestHelper.VerifyResponseBody(
responseBody,
response.Content.Headers.ContentMD5,
false,
null);
}
}
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task GetAsync_UseResponseHeadersReadAndCopyToMemoryStream_Success(Configuration.Http.RemoteServer remoteServer)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
using (HttpResponseMessage response = await client.GetAsync(remoteServer.EchoUri, HttpCompletionOption.ResponseHeadersRead))
{
var memoryStream = new MemoryStream();
await response.Content.CopyToAsync(memoryStream);
memoryStream.Position = 0;
using (var reader = new StreamReader(memoryStream))
{
string responseBody = reader.ReadToEnd();
_output.WriteLine(responseBody);
TestHelper.VerifyResponseBody(
responseBody,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task GetStreamAsync_ReadZeroBytes_Success(Configuration.Http.RemoteServer remoteServer)
{
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
using (Stream stream = await client.GetStreamAsync(remoteServer.EchoUri))
{
Assert.Equal(0, stream.Read(new byte[1], 0, 0));
Assert.Equal(0, stream.Read(new Span<byte>(new byte[1], 0, 0)));
Assert.Equal(0, await stream.ReadAsync(new byte[1], 0, 0));
}
}
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(RemoteServersMemberData))]
public async Task ReadAsStreamAsync_Cancel_TaskIsCanceled(Configuration.Http.RemoteServer remoteServer)
{
var cts = new CancellationTokenSource();
using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer))
using (HttpResponseMessage response =
await client.GetAsync(remoteServer.EchoUri, HttpCompletionOption.ResponseHeadersRead))
using (Stream stream = await response.Content.ReadAsStreamAsync())
{
var buffer = new byte[2048];
Task task = stream.ReadAsync(buffer, 0, buffer.Length, cts.Token);
cts.Cancel();
// Verify that the task completed.
Assert.True(((IAsyncResult)task).AsyncWaitHandle.WaitOne(new TimeSpan(0, 5, 0)));
Assert.True(task.IsCompleted, "Task was not yet completed");
// Verify that the task completed successfully or is canceled.
if (IsWinHttpHandler)
{
// With WinHttpHandler, we may fault because canceling the task destroys the request handle
// which may randomly cause an ObjectDisposedException (or other exception).
Assert.True(
task.Status == TaskStatus.RanToCompletion ||
task.Status == TaskStatus.Canceled ||
task.Status == TaskStatus.Faulted);
}
else
{
if (task.IsFaulted)
{
// Propagate exception for debugging
task.GetAwaiter().GetResult();
}
Assert.True(
task.Status == TaskStatus.RanToCompletion ||
task.Status == TaskStatus.Canceled);
}
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "WinRT based Http stack ignores these errors")]
[Theory]
[InlineData(TransferType.ContentLength, TransferError.ContentLengthTooLarge)]
[InlineData(TransferType.Chunked, TransferError.MissingChunkTerminator)]
[InlineData(TransferType.Chunked, TransferError.ChunkSizeTooLarge)]
public async Task ReadAsStreamAsync_InvalidServerResponse_ThrowsIOException(
TransferType transferType,
TransferError transferError)
{
await StartTransferTypeAndErrorServer(transferType, transferError, async uri =>
{
await Assert.ThrowsAsync<IOException>(() => ReadAsStreamHelper(uri));
});
}
[Theory]
[InlineData(TransferType.None, TransferError.None)]
[InlineData(TransferType.ContentLength, TransferError.None)]
[InlineData(TransferType.Chunked, TransferError.None)]
public async Task ReadAsStreamAsync_ValidServerResponse_Success(
TransferType transferType,
TransferError transferError)
{
await StartTransferTypeAndErrorServer(transferType, transferError, async uri =>
{
await ReadAsStreamHelper(uri);
});
}
public enum TransferType
{
None = 0,
ContentLength,
Chunked
}
public enum TransferError
{
None = 0,
ContentLengthTooLarge,
ChunkSizeTooLarge,
MissingChunkTerminator
}
public static Task StartTransferTypeAndErrorServer(
TransferType transferType,
TransferError transferError,
Func<Uri, Task> clientFunc)
{
return LoopbackServer.CreateClientAndServerAsync(
clientFunc,
server => server.AcceptConnectionAsync(async connection =>
{
// Read past request headers.
await connection.ReadRequestHeaderAsync();
// Determine response transfer headers.
string transferHeader = null;
string content = "This is some response content.";
if (transferType == TransferType.ContentLength)
{
transferHeader = transferError == TransferError.ContentLengthTooLarge ?
$"Content-Length: {content.Length + 42}\r\n" :
$"Content-Length: {content.Length}\r\n";
}
else if (transferType == TransferType.Chunked)
{
transferHeader = "Transfer-Encoding: chunked\r\n";
}
// Write response header
TextWriter writer = connection.Writer;
await writer.WriteAsync("HTTP/1.1 200 OK\r\n").ConfigureAwait(false);
await writer.WriteAsync($"Date: {DateTimeOffset.UtcNow:R}\r\n").ConfigureAwait(false);
await writer.WriteAsync("Content-Type: text/plain\r\n").ConfigureAwait(false);
if (!string.IsNullOrEmpty(transferHeader))
{
await writer.WriteAsync(transferHeader).ConfigureAwait(false);
}
await writer.WriteAsync("\r\n").ConfigureAwait(false);
// Write response body
if (transferType == TransferType.Chunked)
{
string chunkSizeInHex = string.Format(
"{0:x}\r\n",
content.Length + (transferError == TransferError.ChunkSizeTooLarge ? 42 : 0));
await writer.WriteAsync(chunkSizeInHex).ConfigureAwait(false);
await writer.WriteAsync($"{content}\r\n").ConfigureAwait(false);
if (transferError != TransferError.MissingChunkTerminator)
{
await writer.WriteAsync("0\r\n\r\n").ConfigureAwait(false);
}
}
else
{
await writer.WriteAsync($"{content}").ConfigureAwait(false);
}
}));
}
private async Task ReadAsStreamHelper(Uri serverUri)
{
using (HttpClient client = CreateHttpClient())
{
using (var response = await client.GetAsync(
serverUri,
HttpCompletionOption.ResponseHeadersRead))
using (var stream = await response.Content.ReadAsStreamAsync())
{
var buffer = new byte[1];
while (await stream.ReadAsync(buffer, 0, 1) > 0) ;
}
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using org.swyn.foundation.utils;
using tdbgui;
namespace tdbadmin
{
/// <summary>
/// offer Form.
/// </summary>
public class FOffer : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox TDB_abgrp;
private System.Windows.Forms.Button TDB_ab_clr;
private System.Windows.Forms.Button TDB_ab_sel;
private System.Windows.Forms.Button TDB_ab_exit;
private System.Windows.Forms.Button TDB_ab_del;
private System.Windows.Forms.Button TDB_ab_upd;
private System.Windows.Forms.Button TDB_ab_ins;
private System.Windows.Forms.Label tdb_e_id;
private System.Windows.Forms.TextBox tdb_e_bez;
private System.Windows.Forms.TextBox tdb_e_text;
private System.Windows.Forms.Label tdb_l_text;
private System.Windows.Forms.Label tdb_l_bez;
private System.Windows.Forms.Label tdb_l_id;
private System.Windows.Forms.CheckBox Off_e_ishost;
private System.Windows.Forms.Label Off_l_dlt;
private System.Windows.Forms.ComboBox Off_e_parent;
private System.Windows.Forms.Label Off_l_parent;
private System.Windows.Forms.ComboBox Off_e_dlt;
private System.Windows.Forms.Label Off_l_ord;
private bool ishost;
private tdbgui.GUIoffer offer;
private System.Windows.Forms.TextBox tdb_e_code;
private System.Windows.Forms.Label tdb_l_code;
private ComboBox Off_e_act;
private Label Off_l_act;
private ComboBox Off_e_offtype;
private Label Off_l_offtype;
private Label Off_l_dur;
private NumericUpDown Off_e_ord;
private TextBox Off_e_location;
private Label Off_l_loc;
private ComboBox Off_e_to;
private Label Off_l_to;
private ComboBox Off_e_from;
private Label Off_l_from;
private Button Off_b_createserv;
private DateTimePicker Off_e_duration;
private CheckBox Off_e_onlytime;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public FOffer()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
offer = new tdbgui.GUIoffer();
ishost = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.Off_e_onlytime = new System.Windows.Forms.CheckBox();
this.Off_e_duration = new System.Windows.Forms.DateTimePicker();
this.Off_b_createserv = new System.Windows.Forms.Button();
this.Off_e_location = new System.Windows.Forms.TextBox();
this.Off_l_loc = new System.Windows.Forms.Label();
this.Off_e_to = new System.Windows.Forms.ComboBox();
this.Off_l_to = new System.Windows.Forms.Label();
this.Off_e_from = new System.Windows.Forms.ComboBox();
this.Off_l_from = new System.Windows.Forms.Label();
this.Off_l_dur = new System.Windows.Forms.Label();
this.Off_e_ord = new System.Windows.Forms.NumericUpDown();
this.Off_e_offtype = new System.Windows.Forms.ComboBox();
this.Off_l_offtype = new System.Windows.Forms.Label();
this.Off_e_act = new System.Windows.Forms.ComboBox();
this.Off_l_act = new System.Windows.Forms.Label();
this.tdb_e_code = new System.Windows.Forms.TextBox();
this.tdb_l_code = new System.Windows.Forms.Label();
this.Off_l_ord = new System.Windows.Forms.Label();
this.Off_e_dlt = new System.Windows.Forms.ComboBox();
this.Off_e_ishost = new System.Windows.Forms.CheckBox();
this.Off_l_dlt = new System.Windows.Forms.Label();
this.Off_e_parent = new System.Windows.Forms.ComboBox();
this.Off_l_parent = new System.Windows.Forms.Label();
this.tdb_e_id = new System.Windows.Forms.Label();
this.tdb_e_bez = new System.Windows.Forms.TextBox();
this.tdb_e_text = new System.Windows.Forms.TextBox();
this.tdb_l_text = new System.Windows.Forms.Label();
this.tdb_l_bez = new System.Windows.Forms.Label();
this.tdb_l_id = new System.Windows.Forms.Label();
this.TDB_abgrp = new System.Windows.Forms.GroupBox();
this.TDB_ab_clr = new System.Windows.Forms.Button();
this.TDB_ab_sel = new System.Windows.Forms.Button();
this.TDB_ab_exit = new System.Windows.Forms.Button();
this.TDB_ab_del = new System.Windows.Forms.Button();
this.TDB_ab_upd = new System.Windows.Forms.Button();
this.TDB_ab_ins = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.Off_e_ord)).BeginInit();
this.TDB_abgrp.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.Off_e_onlytime);
this.groupBox1.Controls.Add(this.Off_e_duration);
this.groupBox1.Controls.Add(this.Off_b_createserv);
this.groupBox1.Controls.Add(this.Off_e_location);
this.groupBox1.Controls.Add(this.Off_l_loc);
this.groupBox1.Controls.Add(this.Off_e_to);
this.groupBox1.Controls.Add(this.Off_l_to);
this.groupBox1.Controls.Add(this.Off_e_from);
this.groupBox1.Controls.Add(this.Off_l_from);
this.groupBox1.Controls.Add(this.Off_l_dur);
this.groupBox1.Controls.Add(this.Off_e_ord);
this.groupBox1.Controls.Add(this.Off_e_offtype);
this.groupBox1.Controls.Add(this.Off_l_offtype);
this.groupBox1.Controls.Add(this.Off_e_act);
this.groupBox1.Controls.Add(this.Off_l_act);
this.groupBox1.Controls.Add(this.tdb_e_code);
this.groupBox1.Controls.Add(this.tdb_l_code);
this.groupBox1.Controls.Add(this.Off_l_ord);
this.groupBox1.Controls.Add(this.Off_e_dlt);
this.groupBox1.Controls.Add(this.Off_e_ishost);
this.groupBox1.Controls.Add(this.Off_l_dlt);
this.groupBox1.Controls.Add(this.Off_e_parent);
this.groupBox1.Controls.Add(this.Off_l_parent);
this.groupBox1.Controls.Add(this.tdb_e_id);
this.groupBox1.Controls.Add(this.tdb_e_bez);
this.groupBox1.Controls.Add(this.tdb_e_text);
this.groupBox1.Controls.Add(this.tdb_l_text);
this.groupBox1.Controls.Add(this.tdb_l_bez);
this.groupBox1.Controls.Add(this.tdb_l_id);
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox1.Location = new System.Drawing.Point(0, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(620, 472);
this.groupBox1.TabIndex = 13;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Description";
//
// Off_e_onlytime
//
this.Off_e_onlytime.AutoSize = true;
this.Off_e_onlytime.Location = new System.Drawing.Point(497, 287);
this.Off_e_onlytime.Name = "Off_e_onlytime";
this.Off_e_onlytime.Size = new System.Drawing.Size(67, 17);
this.Off_e_onlytime.TabIndex = 35;
this.Off_e_onlytime.Text = "only time";
this.Off_e_onlytime.UseVisualStyleBackColor = true;
//
// Off_e_duration
//
this.Off_e_duration.CustomFormat = "dd HH:mm";
this.Off_e_duration.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
this.Off_e_duration.Location = new System.Drawing.Point(496, 264);
this.Off_e_duration.Name = "Off_e_duration";
this.Off_e_duration.ShowUpDown = true;
this.Off_e_duration.Size = new System.Drawing.Size(96, 20);
this.Off_e_duration.TabIndex = 34;
//
// Off_b_createserv
//
this.Off_b_createserv.Enabled = false;
this.Off_b_createserv.Location = new System.Drawing.Point(518, 393);
this.Off_b_createserv.Name = "Off_b_createserv";
this.Off_b_createserv.Size = new System.Drawing.Size(96, 23);
this.Off_b_createserv.TabIndex = 33;
this.Off_b_createserv.Text = "Create services";
this.Off_b_createserv.UseVisualStyleBackColor = true;
this.Off_b_createserv.Click += new System.EventHandler(this.Off_b_createserv_Click);
//
// Off_e_location
//
this.Off_e_location.Location = new System.Drawing.Point(136, 330);
this.Off_e_location.Name = "Off_e_location";
this.Off_e_location.Size = new System.Drawing.Size(456, 20);
this.Off_e_location.TabIndex = 31;
//
// Off_l_loc
//
this.Off_l_loc.Location = new System.Drawing.Point(8, 330);
this.Off_l_loc.Name = "Off_l_loc";
this.Off_l_loc.Size = new System.Drawing.Size(100, 23);
this.Off_l_loc.TabIndex = 32;
this.Off_l_loc.Text = "Check-In location";
//
// Off_e_to
//
this.Off_e_to.Location = new System.Drawing.Point(366, 356);
this.Off_e_to.Name = "Off_e_to";
this.Off_e_to.Size = new System.Drawing.Size(248, 21);
this.Off_e_to.TabIndex = 30;
//
// Off_l_to
//
this.Off_l_to.Location = new System.Drawing.Point(333, 359);
this.Off_l_to.Name = "Off_l_to";
this.Off_l_to.Size = new System.Drawing.Size(33, 23);
this.Off_l_to.TabIndex = 29;
this.Off_l_to.Text = "to:";
//
// Off_e_from
//
this.Off_e_from.Location = new System.Drawing.Point(60, 356);
this.Off_e_from.Name = "Off_e_from";
this.Off_e_from.Size = new System.Drawing.Size(248, 21);
this.Off_e_from.TabIndex = 28;
//
// Off_l_from
//
this.Off_l_from.Location = new System.Drawing.Point(8, 359);
this.Off_l_from.Name = "Off_l_from";
this.Off_l_from.Size = new System.Drawing.Size(46, 23);
this.Off_l_from.TabIndex = 27;
this.Off_l_from.Text = "From:";
//
// Off_l_dur
//
this.Off_l_dur.Location = new System.Drawing.Point(435, 266);
this.Off_l_dur.Name = "Off_l_dur";
this.Off_l_dur.Size = new System.Drawing.Size(47, 23);
this.Off_l_dur.TabIndex = 25;
this.Off_l_dur.Text = "Duration";
//
// Off_e_ord
//
this.Off_e_ord.Location = new System.Drawing.Point(136, 264);
this.Off_e_ord.Name = "Off_e_ord";
this.Off_e_ord.Size = new System.Drawing.Size(36, 20);
this.Off_e_ord.TabIndex = 24;
//
// Off_e_offtype
//
this.Off_e_offtype.Location = new System.Drawing.Point(136, 215);
this.Off_e_offtype.Name = "Off_e_offtype";
this.Off_e_offtype.Size = new System.Drawing.Size(248, 21);
this.Off_e_offtype.TabIndex = 23;
//
// Off_l_offtype
//
this.Off_l_offtype.Location = new System.Drawing.Point(8, 215);
this.Off_l_offtype.Name = "Off_l_offtype";
this.Off_l_offtype.Size = new System.Drawing.Size(104, 23);
this.Off_l_offtype.TabIndex = 22;
this.Off_l_offtype.Text = "Type";
//
// Off_e_act
//
this.Off_e_act.Location = new System.Drawing.Point(136, 287);
this.Off_e_act.Name = "Off_e_act";
this.Off_e_act.Size = new System.Drawing.Size(248, 21);
this.Off_e_act.TabIndex = 21;
//
// Off_l_act
//
this.Off_l_act.Location = new System.Drawing.Point(8, 287);
this.Off_l_act.Name = "Off_l_act";
this.Off_l_act.Size = new System.Drawing.Size(122, 23);
this.Off_l_act.TabIndex = 20;
this.Off_l_act.Text = "Default process action";
//
// tdb_e_code
//
this.tdb_e_code.Location = new System.Drawing.Point(136, 48);
this.tdb_e_code.Name = "tdb_e_code";
this.tdb_e_code.Size = new System.Drawing.Size(456, 20);
this.tdb_e_code.TabIndex = 18;
//
// tdb_l_code
//
this.tdb_l_code.Location = new System.Drawing.Point(8, 48);
this.tdb_l_code.Name = "tdb_l_code";
this.tdb_l_code.Size = new System.Drawing.Size(100, 23);
this.tdb_l_code.TabIndex = 19;
this.tdb_l_code.Text = "Code";
//
// Off_l_ord
//
this.Off_l_ord.Location = new System.Drawing.Point(8, 264);
this.Off_l_ord.Name = "Off_l_ord";
this.Off_l_ord.Size = new System.Drawing.Size(100, 23);
this.Off_l_ord.TabIndex = 16;
this.Off_l_ord.Text = "Ordering";
//
// Off_e_dlt
//
this.Off_e_dlt.Location = new System.Drawing.Point(136, 240);
this.Off_e_dlt.Name = "Off_e_dlt";
this.Off_e_dlt.Size = new System.Drawing.Size(248, 21);
this.Off_e_dlt.TabIndex = 15;
//
// Off_e_ishost
//
this.Off_e_ishost.Location = new System.Drawing.Point(432, 192);
this.Off_e_ishost.Name = "Off_e_ishost";
this.Off_e_ishost.Size = new System.Drawing.Size(104, 24);
this.Off_e_ishost.TabIndex = 14;
this.Off_e_ishost.Text = "Root offer ?";
this.Off_e_ishost.CheckedChanged += new System.EventHandler(this.Off_e_ishost_CheckedChanged);
//
// Off_l_dlt
//
this.Off_l_dlt.Location = new System.Drawing.Point(8, 240);
this.Off_l_dlt.Name = "Off_l_dlt";
this.Off_l_dlt.Size = new System.Drawing.Size(104, 23);
this.Off_l_dlt.TabIndex = 12;
this.Off_l_dlt.Text = "Supplier";
//
// Off_e_parent
//
this.Off_e_parent.Location = new System.Drawing.Point(136, 192);
this.Off_e_parent.Name = "Off_e_parent";
this.Off_e_parent.Size = new System.Drawing.Size(248, 21);
this.Off_e_parent.TabIndex = 11;
//
// Off_l_parent
//
this.Off_l_parent.Location = new System.Drawing.Point(8, 192);
this.Off_l_parent.Name = "Off_l_parent";
this.Off_l_parent.Size = new System.Drawing.Size(100, 23);
this.Off_l_parent.TabIndex = 10;
this.Off_l_parent.Text = "Parent offer";
//
// tdb_e_id
//
this.tdb_e_id.Location = new System.Drawing.Point(136, 24);
this.tdb_e_id.Name = "tdb_e_id";
this.tdb_e_id.Size = new System.Drawing.Size(64, 16);
this.tdb_e_id.TabIndex = 9;
//
// tdb_e_bez
//
this.tdb_e_bez.Location = new System.Drawing.Point(136, 72);
this.tdb_e_bez.Name = "tdb_e_bez";
this.tdb_e_bez.Size = new System.Drawing.Size(456, 20);
this.tdb_e_bez.TabIndex = 0;
//
// tdb_e_text
//
this.tdb_e_text.Location = new System.Drawing.Point(136, 96);
this.tdb_e_text.Multiline = true;
this.tdb_e_text.Name = "tdb_e_text";
this.tdb_e_text.Size = new System.Drawing.Size(456, 88);
this.tdb_e_text.TabIndex = 2;
//
// tdb_l_text
//
this.tdb_l_text.Location = new System.Drawing.Point(8, 128);
this.tdb_l_text.Name = "tdb_l_text";
this.tdb_l_text.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.tdb_l_text.Size = new System.Drawing.Size(100, 23);
this.tdb_l_text.TabIndex = 4;
this.tdb_l_text.Text = "Description";
//
// tdb_l_bez
//
this.tdb_l_bez.Location = new System.Drawing.Point(8, 72);
this.tdb_l_bez.Name = "tdb_l_bez";
this.tdb_l_bez.Size = new System.Drawing.Size(100, 23);
this.tdb_l_bez.TabIndex = 2;
this.tdb_l_bez.Text = "Title";
//
// tdb_l_id
//
this.tdb_l_id.Location = new System.Drawing.Point(8, 21);
this.tdb_l_id.Name = "tdb_l_id";
this.tdb_l_id.Size = new System.Drawing.Size(100, 23);
this.tdb_l_id.TabIndex = 1;
this.tdb_l_id.Text = "ID";
//
// TDB_abgrp
//
this.TDB_abgrp.Controls.Add(this.TDB_ab_clr);
this.TDB_abgrp.Controls.Add(this.TDB_ab_sel);
this.TDB_abgrp.Controls.Add(this.TDB_ab_exit);
this.TDB_abgrp.Controls.Add(this.TDB_ab_del);
this.TDB_abgrp.Controls.Add(this.TDB_ab_upd);
this.TDB_abgrp.Controls.Add(this.TDB_ab_ins);
this.TDB_abgrp.Dock = System.Windows.Forms.DockStyle.Bottom;
this.TDB_abgrp.Location = new System.Drawing.Point(0, 416);
this.TDB_abgrp.Name = "TDB_abgrp";
this.TDB_abgrp.Size = new System.Drawing.Size(620, 56);
this.TDB_abgrp.TabIndex = 15;
this.TDB_abgrp.TabStop = false;
this.TDB_abgrp.Text = "Actions";
//
// TDB_ab_clr
//
this.TDB_ab_clr.Dock = System.Windows.Forms.DockStyle.Right;
this.TDB_ab_clr.Location = new System.Drawing.Point(467, 16);
this.TDB_ab_clr.Name = "TDB_ab_clr";
this.TDB_ab_clr.Size = new System.Drawing.Size(75, 37);
this.TDB_ab_clr.TabIndex = 10;
this.TDB_ab_clr.Text = "Clear";
this.TDB_ab_clr.Click += new System.EventHandler(this.TDB_ab_clr_Click);
//
// TDB_ab_sel
//
this.TDB_ab_sel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.TDB_ab_sel.Dock = System.Windows.Forms.DockStyle.Left;
this.TDB_ab_sel.Location = new System.Drawing.Point(228, 16);
this.TDB_ab_sel.Name = "TDB_ab_sel";
this.TDB_ab_sel.Size = new System.Drawing.Size(80, 37);
this.TDB_ab_sel.TabIndex = 8;
this.TDB_ab_sel.Text = "Select";
this.TDB_ab_sel.UseVisualStyleBackColor = false;
this.TDB_ab_sel.Click += new System.EventHandler(this.TDB_ab_sel_Click);
//
// TDB_ab_exit
//
this.TDB_ab_exit.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.TDB_ab_exit.Dock = System.Windows.Forms.DockStyle.Right;
this.TDB_ab_exit.Location = new System.Drawing.Point(542, 16);
this.TDB_ab_exit.Name = "TDB_ab_exit";
this.TDB_ab_exit.Size = new System.Drawing.Size(75, 37);
this.TDB_ab_exit.TabIndex = 9;
this.TDB_ab_exit.Text = "Exit";
this.TDB_ab_exit.UseVisualStyleBackColor = false;
this.TDB_ab_exit.Click += new System.EventHandler(this.TDB_ab_exit_Click);
//
// TDB_ab_del
//
this.TDB_ab_del.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.TDB_ab_del.Dock = System.Windows.Forms.DockStyle.Left;
this.TDB_ab_del.Location = new System.Drawing.Point(153, 16);
this.TDB_ab_del.Name = "TDB_ab_del";
this.TDB_ab_del.Size = new System.Drawing.Size(75, 37);
this.TDB_ab_del.TabIndex = 7;
this.TDB_ab_del.Text = "Delete";
this.TDB_ab_del.UseVisualStyleBackColor = false;
this.TDB_ab_del.Click += new System.EventHandler(this.TDB_ab_del_Click);
//
// TDB_ab_upd
//
this.TDB_ab_upd.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.TDB_ab_upd.Dock = System.Windows.Forms.DockStyle.Left;
this.TDB_ab_upd.Location = new System.Drawing.Point(78, 16);
this.TDB_ab_upd.Name = "TDB_ab_upd";
this.TDB_ab_upd.Size = new System.Drawing.Size(75, 37);
this.TDB_ab_upd.TabIndex = 6;
this.TDB_ab_upd.Text = "Update";
this.TDB_ab_upd.UseVisualStyleBackColor = false;
this.TDB_ab_upd.Click += new System.EventHandler(this.TDB_ab_upd_Click);
//
// TDB_ab_ins
//
this.TDB_ab_ins.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.TDB_ab_ins.Dock = System.Windows.Forms.DockStyle.Left;
this.TDB_ab_ins.Location = new System.Drawing.Point(3, 16);
this.TDB_ab_ins.Name = "TDB_ab_ins";
this.TDB_ab_ins.Size = new System.Drawing.Size(75, 37);
this.TDB_ab_ins.TabIndex = 5;
this.TDB_ab_ins.Text = "Insert";
this.TDB_ab_ins.UseVisualStyleBackColor = false;
this.TDB_ab_ins.Click += new System.EventHandler(this.TDB_ab_ins_Click);
//
// FOffer
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(620, 472);
this.Controls.Add(this.TDB_abgrp);
this.Controls.Add(this.groupBox1);
this.Name = "FOffer";
this.Text = "Offer";
this.Load += new System.EventHandler(this.FOff_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.Off_e_ord)).EndInit();
this.TDB_abgrp.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
#region Form callbacks
private void TDB_ab_sel_Click(object sender, System.EventArgs e)
{
SelForm Fsel = new SelForm();
offer.Sel(Fsel.GetLV);
Fsel.Accept += new EventHandler(TDB_ab_sel_Click_Return);
Fsel.ShowDialog(this);
}
void TDB_ab_sel_Click_Return(object sender, EventArgs e)
{
int id = -1, rows = 0;
SelForm Fsel = (SelForm)sender;
id = Fsel.GetID;
offer.Get(id, ref rows);
tdb_e_id.Text = offer.ObjId.ToString();
tdb_e_bez.Text = offer.ObjBez;
tdb_e_text.Text = offer.ObjText;
tdb_e_code.Text = offer.ObjCode;
if (offer.ObjParentId == -1)
{
this.Off_e_parent.SelectedValue = -1;
this.Off_e_ishost.CheckState = CheckState.Checked;
this.Off_e_parent.Visible = false;
ishost = true;
this.Off_b_createserv.Enabled = true;
}
else
{
this.Off_e_parent.SelectedValue = offer.ObjParentId;
this.Off_e_ishost.CheckState = CheckState.Unchecked;
this.Off_e_parent.Visible = true;
ishost = false;
this.Off_b_createserv.Enabled = false;
}
Off_e_ord.Text = offer.ObjOrder.ToString();
this.Off_e_duration.Value = offer.ObjDuration;
this.Off_e_location.Text = offer.ObjLocation;
this.Off_e_dlt.SelectedValue = offer.ObjSuplier;
this.Off_e_to.SelectedValue = offer.ObjTo;
this.Off_e_from.SelectedValue = offer.ObjFrom;
this.Off_e_act.SelectedValue = offer.ObjAction;
this.Off_e_offtype.SelectedValue = offer.ObjType;
}
private void TDB_ab_exit_Click(object sender, System.EventArgs e)
{
Close();
}
private void TDB_ab_ins_Click(object sender, System.EventArgs e)
{
offer.InsUpd(true, tdb_e_bez.Text, tdb_e_text.Text, (int)this.Off_e_parent.SelectedValue,
tdb_e_code.Text, (int)this.Off_e_dlt.SelectedValue, (int)this.Off_e_offtype.SelectedValue,
this.Off_e_duration.Value, (int)this.Off_e_act.SelectedValue, (int)this.Off_e_from.SelectedValue,
(int)this.Off_e_to.SelectedValue, Convert.ToInt32(this.Off_e_ord.Text), Off_e_location.Text);
tdb_e_id.Text = offer.ObjId.ToString();
}
private void TDB_ab_upd_Click(object sender, System.EventArgs e)
{
offer.InsUpd(false, tdb_e_bez.Text, tdb_e_text.Text, (int)this.Off_e_parent.SelectedValue,
tdb_e_code.Text, (int)this.Off_e_dlt.SelectedValue, (int)this.Off_e_offtype.SelectedValue,
this.Off_e_duration.Value, (int)this.Off_e_act.SelectedValue, (int)this.Off_e_from.SelectedValue,
(int)this.Off_e_to.SelectedValue, Convert.ToInt32(this.Off_e_ord.Text), Off_e_location.Text);
}
private void TDB_ab_del_Click(object sender, System.EventArgs e)
{
int rows = 0;
offer.Get(Convert.ToInt32(tdb_e_id.Text), ref rows);
offer.Delete();
}
private void TDB_ab_clr_Click(object sender, System.EventArgs e)
{
tdb_e_id.Text = "";
tdb_e_bez.Text = "";
tdb_e_text.Text = "";
tdb_e_code.Text = "";
this.Off_e_ord.Text = "1";
this.Off_e_location.Text = "";
this.Off_e_to.Text = "";
this.Off_e_act.Text = "";
this.Off_e_from.Text = "";
this.Off_e_parent.Text = "";
this.Off_e_dlt.Text = "";
}
private void FOff_Load(object sender, System.EventArgs e)
{
// combos sup, act, offtype, tocity, fromcity, parentoffer
tdbgui.GUIsup S = new tdbgui.GUIsup();
S.SetCombo(this.Off_e_dlt);
tdbgui.GUIact A = new tdbgui.GUIact();
A.SetCombo(this.Off_e_act);
tdbgui.GUIofft OT = new tdbgui.GUIofft();
OT.SetCombo(this.Off_e_offtype);
tdbgui.GUIcity C1 = new tdbgui.GUIcity();
C1.SetCombo(this.Off_e_to);
tdbgui.GUIcity C2 = new tdbgui.GUIcity();
C2.SetCombo(this.Off_e_from);
tdbgui.GUIoffer P = new tdbgui.GUIoffer();
P.SetCombo(this.Off_e_parent);
}
private void Off_e_ishost_CheckedChanged(object sender, System.EventArgs e)
{
if (this.Off_e_ishost.CheckState == CheckState.Checked)
{
this.Off_e_parent.Visible = false;
ishost = true;
}
else
{
this.Off_e_parent.Visible = true;
ishost = false;
}
}
private void Off_b_createserv_Click(object sender, EventArgs e)
{
// only visible if it's a root offer object
FWcreateserv Fw = new FWcreateserv();
Fw.ObjOffer = offer;
Fw.doPages();
Fw.ShowDialog();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
internal class TestApp
{
private static long test_0_0(long num, AA init, AA zero)
{
return init.q;
}
private static long test_0_1(long num, AA init, AA zero)
{
zero.q = num;
return zero.q;
}
private static long test_0_2(long num, AA init, AA zero)
{
return init.q + zero.q;
}
private static long test_0_3(long num, AA init, AA zero)
{
return checked(init.q - zero.q);
}
private static long test_0_4(long num, AA init, AA zero)
{
zero.q += num; return zero.q;
}
private static long test_0_5(long num, AA init, AA zero)
{
zero.q += init.q; return zero.q;
}
private static long test_0_6(long num, AA init, AA zero)
{
if (init.q == num)
return 100;
else
return zero.q;
}
private static long test_0_7(long num, AA init, AA zero)
{
return init.q < num + 1 ? 100 : -1;
}
private static long test_0_8(long num, AA init, AA zero)
{
return (init.q > zero.q ? 1 : 0) + 99;
}
private static long test_0_9(long num, AA init, AA zero)
{
return (init.q ^ zero.q) | num;
}
private static long test_0_10(long num, AA init, AA zero)
{
zero.q |= init.q;
return zero.q & num;
}
private static long test_0_11(long num, AA init, AA zero)
{
return init.q >> (int)zero.q;
}
private static long test_0_12(long num, AA init, AA zero)
{
return AA.a_init[init.q].q;
}
private static long test_0_13(long num, AA init, AA zero)
{
return AA.aa_init[num - 100, (init.q | 1) - 2, 1 + zero.q].q;
}
private static long test_0_14(long num, AA init, AA zero)
{
object bb = init.q;
return (long)bb;
}
private static long test_0_15(long num, AA init, AA zero)
{
double dbl = init.q;
return (long)dbl;
}
private static long test_0_16(long num, AA init, AA zero)
{
return AA.call_target(init.q);
}
private static long test_0_17(long num, AA init, AA zero)
{
return AA.call_target_ref(ref init.q);
}
private static long test_1_0(long num, ref AA r_init, ref AA r_zero)
{
return r_init.q;
}
private static long test_1_1(long num, ref AA r_init, ref AA r_zero)
{
r_zero.q = num;
return r_zero.q;
}
private static long test_1_2(long num, ref AA r_init, ref AA r_zero)
{
return r_init.q + r_zero.q;
}
private static long test_1_3(long num, ref AA r_init, ref AA r_zero)
{
return checked(r_init.q - r_zero.q);
}
private static long test_1_4(long num, ref AA r_init, ref AA r_zero)
{
r_zero.q += num; return r_zero.q;
}
private static long test_1_5(long num, ref AA r_init, ref AA r_zero)
{
r_zero.q += r_init.q; return r_zero.q;
}
private static long test_1_6(long num, ref AA r_init, ref AA r_zero)
{
if (r_init.q == num)
return 100;
else
return r_zero.q;
}
private static long test_1_7(long num, ref AA r_init, ref AA r_zero)
{
return r_init.q < num + 1 ? 100 : -1;
}
private static long test_1_8(long num, ref AA r_init, ref AA r_zero)
{
return (r_init.q > r_zero.q ? 1 : 0) + 99;
}
private static long test_1_9(long num, ref AA r_init, ref AA r_zero)
{
return (r_init.q ^ r_zero.q) | num;
}
private static long test_1_10(long num, ref AA r_init, ref AA r_zero)
{
r_zero.q |= r_init.q;
return r_zero.q & num;
}
private static long test_1_11(long num, ref AA r_init, ref AA r_zero)
{
return r_init.q >> (int)r_zero.q;
}
private static long test_1_12(long num, ref AA r_init, ref AA r_zero)
{
return AA.a_init[r_init.q].q;
}
private static long test_1_13(long num, ref AA r_init, ref AA r_zero)
{
return AA.aa_init[num - 100, (r_init.q | 1) - 2, 1 + r_zero.q].q;
}
private static long test_1_14(long num, ref AA r_init, ref AA r_zero)
{
object bb = r_init.q;
return (long)bb;
}
private static long test_1_15(long num, ref AA r_init, ref AA r_zero)
{
double dbl = r_init.q;
return (long)dbl;
}
private static long test_1_16(long num, ref AA r_init, ref AA r_zero)
{
return AA.call_target(r_init.q);
}
private static long test_1_17(long num, ref AA r_init, ref AA r_zero)
{
return AA.call_target_ref(ref r_init.q);
}
private static long test_2_0(long num)
{
return AA.a_init[num].q;
}
private static long test_2_1(long num)
{
AA.a_zero[num].q = num;
return AA.a_zero[num].q;
}
private static long test_2_2(long num)
{
return AA.a_init[num].q + AA.a_zero[num].q;
}
private static long test_2_3(long num)
{
return checked(AA.a_init[num].q - AA.a_zero[num].q);
}
private static long test_2_4(long num)
{
AA.a_zero[num].q += num; return AA.a_zero[num].q;
}
private static long test_2_5(long num)
{
AA.a_zero[num].q += AA.a_init[num].q; return AA.a_zero[num].q;
}
private static long test_2_6(long num)
{
if (AA.a_init[num].q == num)
return 100;
else
return AA.a_zero[num].q;
}
private static long test_2_7(long num)
{
return AA.a_init[num].q < num + 1 ? 100 : -1;
}
private static long test_2_8(long num)
{
return (AA.a_init[num].q > AA.a_zero[num].q ? 1 : 0) + 99;
}
private static long test_2_9(long num)
{
return (AA.a_init[num].q ^ AA.a_zero[num].q) | num;
}
private static long test_2_10(long num)
{
AA.a_zero[num].q |= AA.a_init[num].q;
return AA.a_zero[num].q & num;
}
private static long test_2_11(long num)
{
return AA.a_init[num].q >> (int)AA.a_zero[num].q;
}
private static long test_2_12(long num)
{
return AA.a_init[AA.a_init[num].q].q;
}
private static long test_2_13(long num)
{
return AA.aa_init[num - 100, (AA.a_init[num].q | 1) - 2, 1 + AA.a_zero[num].q].q;
}
private static long test_2_14(long num)
{
object bb = AA.a_init[num].q;
return (long)bb;
}
private static long test_2_15(long num)
{
double dbl = AA.a_init[num].q;
return (long)dbl;
}
private static long test_2_16(long num)
{
return AA.call_target(AA.a_init[num].q);
}
private static long test_2_17(long num)
{
return AA.call_target_ref(ref AA.a_init[num].q);
}
private static long test_3_0(long num)
{
return AA.aa_init[0, num - 1, num / 100].q;
}
private static long test_3_1(long num)
{
AA.aa_zero[0, num - 1, num / 100].q = num;
return AA.aa_zero[0, num - 1, num / 100].q;
}
private static long test_3_2(long num)
{
return AA.aa_init[0, num - 1, num / 100].q + AA.aa_zero[0, num - 1, num / 100].q;
}
private static long test_3_3(long num)
{
return checked(AA.aa_init[0, num - 1, num / 100].q - AA.aa_zero[0, num - 1, num / 100].q);
}
private static long test_3_4(long num)
{
AA.aa_zero[0, num - 1, num / 100].q += num; return AA.aa_zero[0, num - 1, num / 100].q;
}
private static long test_3_5(long num)
{
AA.aa_zero[0, num - 1, num / 100].q += AA.aa_init[0, num - 1, num / 100].q; return AA.aa_zero[0, num - 1, num / 100].q;
}
private static long test_3_6(long num)
{
if (AA.aa_init[0, num - 1, num / 100].q == num)
return 100;
else
return AA.aa_zero[0, num - 1, num / 100].q;
}
private static long test_3_7(long num)
{
return AA.aa_init[0, num - 1, num / 100].q < num + 1 ? 100 : -1;
}
private static long test_3_8(long num)
{
return (AA.aa_init[0, num - 1, num / 100].q > AA.aa_zero[0, num - 1, num / 100].q ? 1 : 0) + 99;
}
private static long test_3_9(long num)
{
return (AA.aa_init[0, num - 1, num / 100].q ^ AA.aa_zero[0, num - 1, num / 100].q) | num;
}
private static long test_3_10(long num)
{
AA.aa_zero[0, num - 1, num / 100].q |= AA.aa_init[0, num - 1, num / 100].q;
return AA.aa_zero[0, num - 1, num / 100].q & num;
}
private static long test_3_11(long num)
{
return AA.aa_init[0, num - 1, num / 100].q >> (int)AA.aa_zero[0, num - 1, num / 100].q;
}
private static long test_3_12(long num)
{
return AA.a_init[AA.aa_init[0, num - 1, num / 100].q].q;
}
private static long test_3_13(long num)
{
return AA.aa_init[num - 100, (AA.aa_init[0, num - 1, num / 100].q | 1) - 2, 1 + AA.aa_zero[0, num - 1, num / 100].q].q;
}
private static long test_3_14(long num)
{
object bb = AA.aa_init[0, num - 1, num / 100].q;
return (long)bb;
}
private static long test_3_15(long num)
{
double dbl = AA.aa_init[0, num - 1, num / 100].q;
return (long)dbl;
}
private static long test_3_16(long num)
{
return AA.call_target(AA.aa_init[0, num - 1, num / 100].q);
}
private static long test_3_17(long num)
{
return AA.call_target_ref(ref AA.aa_init[0, num - 1, num / 100].q);
}
private static long test_4_0(long num)
{
return BB.f_init.q;
}
private static long test_4_1(long num)
{
BB.f_zero.q = num;
return BB.f_zero.q;
}
private static long test_4_2(long num)
{
return BB.f_init.q + BB.f_zero.q;
}
private static long test_4_3(long num)
{
return checked(BB.f_init.q - BB.f_zero.q);
}
private static long test_4_4(long num)
{
BB.f_zero.q += num; return BB.f_zero.q;
}
private static long test_4_5(long num)
{
BB.f_zero.q += BB.f_init.q; return BB.f_zero.q;
}
private static long test_4_6(long num)
{
if (BB.f_init.q == num)
return 100;
else
return BB.f_zero.q;
}
private static long test_4_7(long num)
{
return BB.f_init.q < num + 1 ? 100 : -1;
}
private static long test_4_8(long num)
{
return (BB.f_init.q > BB.f_zero.q ? 1 : 0) + 99;
}
private static long test_4_9(long num)
{
return (BB.f_init.q ^ BB.f_zero.q) | num;
}
private static long test_4_10(long num)
{
BB.f_zero.q |= BB.f_init.q;
return BB.f_zero.q & num;
}
private static long test_4_11(long num)
{
return BB.f_init.q >> (int)BB.f_zero.q;
}
private static long test_4_12(long num)
{
return AA.a_init[BB.f_init.q].q;
}
private static long test_4_13(long num)
{
return AA.aa_init[num - 100, (BB.f_init.q | 1) - 2, 1 + BB.f_zero.q].q;
}
private static long test_4_14(long num)
{
object bb = BB.f_init.q;
return (long)bb;
}
private static long test_4_15(long num)
{
double dbl = BB.f_init.q;
return (long)dbl;
}
private static long test_4_16(long num)
{
return AA.call_target(BB.f_init.q);
}
private static long test_4_17(long num)
{
return AA.call_target_ref(ref BB.f_init.q);
}
private static long test_5_0(long num)
{
return ((AA)AA.b_init).q;
}
private static long test_6_0(long num, TypedReference tr_init)
{
return __refvalue(tr_init, AA).q;
}
private static unsafe long test_7_0(long num, void* ptr_init, void* ptr_zero)
{
return (*((AA*)ptr_init)).q;
}
private static unsafe long test_7_1(long num, void* ptr_init, void* ptr_zero)
{
(*((AA*)ptr_zero)).q = num;
return (*((AA*)ptr_zero)).q;
}
private static unsafe long test_7_2(long num, void* ptr_init, void* ptr_zero)
{
return (*((AA*)ptr_init)).q + (*((AA*)ptr_zero)).q;
}
private static unsafe long test_7_3(long num, void* ptr_init, void* ptr_zero)
{
return checked((*((AA*)ptr_init)).q - (*((AA*)ptr_zero)).q);
}
private static unsafe long test_7_4(long num, void* ptr_init, void* ptr_zero)
{
(*((AA*)ptr_zero)).q += num; return (*((AA*)ptr_zero)).q;
}
private static unsafe long test_7_5(long num, void* ptr_init, void* ptr_zero)
{
(*((AA*)ptr_zero)).q += (*((AA*)ptr_init)).q; return (*((AA*)ptr_zero)).q;
}
private static unsafe long test_7_6(long num, void* ptr_init, void* ptr_zero)
{
if ((*((AA*)ptr_init)).q == num)
return 100;
else
return (*((AA*)ptr_zero)).q;
}
private static unsafe long test_7_7(long num, void* ptr_init, void* ptr_zero)
{
return (*((AA*)ptr_init)).q < num + 1 ? 100 : -1;
}
private static unsafe long test_7_8(long num, void* ptr_init, void* ptr_zero)
{
return ((*((AA*)ptr_init)).q > (*((AA*)ptr_zero)).q ? 1 : 0) + 99;
}
private static unsafe long test_7_9(long num, void* ptr_init, void* ptr_zero)
{
return ((*((AA*)ptr_init)).q ^ (*((AA*)ptr_zero)).q) | num;
}
private static unsafe long test_7_10(long num, void* ptr_init, void* ptr_zero)
{
(*((AA*)ptr_zero)).q |= (*((AA*)ptr_init)).q;
return (*((AA*)ptr_zero)).q & num;
}
private static unsafe long test_7_11(long num, void* ptr_init, void* ptr_zero)
{
return (*((AA*)ptr_init)).q >> (int)(*((AA*)ptr_zero)).q;
}
private static unsafe long test_7_12(long num, void* ptr_init, void* ptr_zero)
{
return AA.a_init[(*((AA*)ptr_init)).q].q;
}
private static unsafe long test_7_13(long num, void* ptr_init, void* ptr_zero)
{
return AA.aa_init[num - 100, ((*((AA*)ptr_init)).q | 1) - 2, 1 + (*((AA*)ptr_zero)).q].q;
}
private static unsafe long test_7_14(long num, void* ptr_init, void* ptr_zero)
{
object bb = (*((AA*)ptr_init)).q;
return (long)bb;
}
private static unsafe long test_7_15(long num, void* ptr_init, void* ptr_zero)
{
double dbl = (*((AA*)ptr_init)).q;
return (long)dbl;
}
private static unsafe long test_7_16(long num, void* ptr_init, void* ptr_zero)
{
return AA.call_target((*((AA*)ptr_init)).q);
}
private static unsafe long test_7_17(long num, void* ptr_init, void* ptr_zero)
{
return AA.call_target_ref(ref (*((AA*)ptr_init)).q);
}
private static unsafe int Main()
{
AA.reset();
if (test_0_0(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_0() failed.");
return 101;
}
AA.verify_all(); AA.reset();
if (test_0_1(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_1() failed.");
return 102;
}
AA.verify_all(); AA.reset();
if (test_0_2(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_2() failed.");
return 103;
}
AA.verify_all(); AA.reset();
if (test_0_3(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_3() failed.");
return 104;
}
AA.verify_all(); AA.reset();
if (test_0_4(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_4() failed.");
return 105;
}
AA.verify_all(); AA.reset();
if (test_0_5(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_5() failed.");
return 106;
}
AA.verify_all(); AA.reset();
if (test_0_6(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_6() failed.");
return 107;
}
AA.verify_all(); AA.reset();
if (test_0_7(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_7() failed.");
return 108;
}
AA.verify_all(); AA.reset();
if (test_0_8(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_8() failed.");
return 109;
}
AA.verify_all(); AA.reset();
if (test_0_9(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_9() failed.");
return 110;
}
AA.verify_all(); AA.reset();
if (test_0_10(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_10() failed.");
return 111;
}
AA.verify_all(); AA.reset();
if (test_0_11(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_11() failed.");
return 112;
}
AA.verify_all(); AA.reset();
if (test_0_12(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_12() failed.");
return 113;
}
AA.verify_all(); AA.reset();
if (test_0_13(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_13() failed.");
return 114;
}
AA.verify_all(); AA.reset();
if (test_0_14(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_14() failed.");
return 115;
}
AA.verify_all(); AA.reset();
if (test_0_15(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_15() failed.");
return 116;
}
AA.verify_all(); AA.reset();
if (test_0_16(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_16() failed.");
return 117;
}
AA.verify_all(); AA.reset();
if (test_0_17(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_17() failed.");
return 118;
}
AA.verify_all(); AA.reset();
if (test_1_0(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_0() failed.");
return 119;
}
AA.verify_all(); AA.reset();
if (test_1_1(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_1() failed.");
return 120;
}
AA.verify_all(); AA.reset();
if (test_1_2(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_2() failed.");
return 121;
}
AA.verify_all(); AA.reset();
if (test_1_3(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_3() failed.");
return 122;
}
AA.verify_all(); AA.reset();
if (test_1_4(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_4() failed.");
return 123;
}
AA.verify_all(); AA.reset();
if (test_1_5(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_5() failed.");
return 124;
}
AA.verify_all(); AA.reset();
if (test_1_6(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_6() failed.");
return 125;
}
AA.verify_all(); AA.reset();
if (test_1_7(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_7() failed.");
return 126;
}
AA.verify_all(); AA.reset();
if (test_1_8(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_8() failed.");
return 127;
}
AA.verify_all(); AA.reset();
if (test_1_9(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_9() failed.");
return 128;
}
AA.verify_all(); AA.reset();
if (test_1_10(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_10() failed.");
return 129;
}
AA.verify_all(); AA.reset();
if (test_1_11(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_11() failed.");
return 130;
}
AA.verify_all(); AA.reset();
if (test_1_12(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_12() failed.");
return 131;
}
AA.verify_all(); AA.reset();
if (test_1_13(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_13() failed.");
return 132;
}
AA.verify_all(); AA.reset();
if (test_1_14(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_14() failed.");
return 133;
}
AA.verify_all(); AA.reset();
if (test_1_15(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_15() failed.");
return 134;
}
AA.verify_all(); AA.reset();
if (test_1_16(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_16() failed.");
return 135;
}
AA.verify_all(); AA.reset();
if (test_1_17(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_17() failed.");
return 136;
}
AA.verify_all(); AA.reset();
if (test_2_0(100) != 100)
{
Console.WriteLine("test_2_0() failed.");
return 137;
}
AA.verify_all(); AA.reset();
if (test_2_1(100) != 100)
{
Console.WriteLine("test_2_1() failed.");
return 138;
}
AA.verify_all(); AA.reset();
if (test_2_2(100) != 100)
{
Console.WriteLine("test_2_2() failed.");
return 139;
}
AA.verify_all(); AA.reset();
if (test_2_3(100) != 100)
{
Console.WriteLine("test_2_3() failed.");
return 140;
}
AA.verify_all(); AA.reset();
if (test_2_4(100) != 100)
{
Console.WriteLine("test_2_4() failed.");
return 141;
}
AA.verify_all(); AA.reset();
if (test_2_5(100) != 100)
{
Console.WriteLine("test_2_5() failed.");
return 142;
}
AA.verify_all(); AA.reset();
if (test_2_6(100) != 100)
{
Console.WriteLine("test_2_6() failed.");
return 143;
}
AA.verify_all(); AA.reset();
if (test_2_7(100) != 100)
{
Console.WriteLine("test_2_7() failed.");
return 144;
}
AA.verify_all(); AA.reset();
if (test_2_8(100) != 100)
{
Console.WriteLine("test_2_8() failed.");
return 145;
}
AA.verify_all(); AA.reset();
if (test_2_9(100) != 100)
{
Console.WriteLine("test_2_9() failed.");
return 146;
}
AA.verify_all(); AA.reset();
if (test_2_10(100) != 100)
{
Console.WriteLine("test_2_10() failed.");
return 147;
}
AA.verify_all(); AA.reset();
if (test_2_11(100) != 100)
{
Console.WriteLine("test_2_11() failed.");
return 148;
}
AA.verify_all(); AA.reset();
if (test_2_12(100) != 100)
{
Console.WriteLine("test_2_12() failed.");
return 149;
}
AA.verify_all(); AA.reset();
if (test_2_13(100) != 100)
{
Console.WriteLine("test_2_13() failed.");
return 150;
}
AA.verify_all(); AA.reset();
if (test_2_14(100) != 100)
{
Console.WriteLine("test_2_14() failed.");
return 151;
}
AA.verify_all(); AA.reset();
if (test_2_15(100) != 100)
{
Console.WriteLine("test_2_15() failed.");
return 152;
}
AA.verify_all(); AA.reset();
if (test_2_16(100) != 100)
{
Console.WriteLine("test_2_16() failed.");
return 153;
}
AA.verify_all(); AA.reset();
if (test_2_17(100) != 100)
{
Console.WriteLine("test_2_17() failed.");
return 154;
}
AA.verify_all(); AA.reset();
if (test_3_0(100) != 100)
{
Console.WriteLine("test_3_0() failed.");
return 155;
}
AA.verify_all(); AA.reset();
if (test_3_1(100) != 100)
{
Console.WriteLine("test_3_1() failed.");
return 156;
}
AA.verify_all(); AA.reset();
if (test_3_2(100) != 100)
{
Console.WriteLine("test_3_2() failed.");
return 157;
}
AA.verify_all(); AA.reset();
if (test_3_3(100) != 100)
{
Console.WriteLine("test_3_3() failed.");
return 158;
}
AA.verify_all(); AA.reset();
if (test_3_4(100) != 100)
{
Console.WriteLine("test_3_4() failed.");
return 159;
}
AA.verify_all(); AA.reset();
if (test_3_5(100) != 100)
{
Console.WriteLine("test_3_5() failed.");
return 160;
}
AA.verify_all(); AA.reset();
if (test_3_6(100) != 100)
{
Console.WriteLine("test_3_6() failed.");
return 161;
}
AA.verify_all(); AA.reset();
if (test_3_7(100) != 100)
{
Console.WriteLine("test_3_7() failed.");
return 162;
}
AA.verify_all(); AA.reset();
if (test_3_8(100) != 100)
{
Console.WriteLine("test_3_8() failed.");
return 163;
}
AA.verify_all(); AA.reset();
if (test_3_9(100) != 100)
{
Console.WriteLine("test_3_9() failed.");
return 164;
}
AA.verify_all(); AA.reset();
if (test_3_10(100) != 100)
{
Console.WriteLine("test_3_10() failed.");
return 165;
}
AA.verify_all(); AA.reset();
if (test_3_11(100) != 100)
{
Console.WriteLine("test_3_11() failed.");
return 166;
}
AA.verify_all(); AA.reset();
if (test_3_12(100) != 100)
{
Console.WriteLine("test_3_12() failed.");
return 167;
}
AA.verify_all(); AA.reset();
if (test_3_13(100) != 100)
{
Console.WriteLine("test_3_13() failed.");
return 168;
}
AA.verify_all(); AA.reset();
if (test_3_14(100) != 100)
{
Console.WriteLine("test_3_14() failed.");
return 169;
}
AA.verify_all(); AA.reset();
if (test_3_15(100) != 100)
{
Console.WriteLine("test_3_15() failed.");
return 170;
}
AA.verify_all(); AA.reset();
if (test_3_16(100) != 100)
{
Console.WriteLine("test_3_16() failed.");
return 171;
}
AA.verify_all(); AA.reset();
if (test_3_17(100) != 100)
{
Console.WriteLine("test_3_17() failed.");
return 172;
}
AA.verify_all(); AA.reset();
if (test_4_0(100) != 100)
{
Console.WriteLine("test_4_0() failed.");
return 173;
}
AA.verify_all(); AA.reset();
if (test_4_1(100) != 100)
{
Console.WriteLine("test_4_1() failed.");
return 174;
}
AA.verify_all(); AA.reset();
if (test_4_2(100) != 100)
{
Console.WriteLine("test_4_2() failed.");
return 175;
}
AA.verify_all(); AA.reset();
if (test_4_3(100) != 100)
{
Console.WriteLine("test_4_3() failed.");
return 176;
}
AA.verify_all(); AA.reset();
if (test_4_4(100) != 100)
{
Console.WriteLine("test_4_4() failed.");
return 177;
}
AA.verify_all(); AA.reset();
if (test_4_5(100) != 100)
{
Console.WriteLine("test_4_5() failed.");
return 178;
}
AA.verify_all(); AA.reset();
if (test_4_6(100) != 100)
{
Console.WriteLine("test_4_6() failed.");
return 179;
}
AA.verify_all(); AA.reset();
if (test_4_7(100) != 100)
{
Console.WriteLine("test_4_7() failed.");
return 180;
}
AA.verify_all(); AA.reset();
if (test_4_8(100) != 100)
{
Console.WriteLine("test_4_8() failed.");
return 181;
}
AA.verify_all(); AA.reset();
if (test_4_9(100) != 100)
{
Console.WriteLine("test_4_9() failed.");
return 182;
}
AA.verify_all(); AA.reset();
if (test_4_10(100) != 100)
{
Console.WriteLine("test_4_10() failed.");
return 183;
}
AA.verify_all(); AA.reset();
if (test_4_11(100) != 100)
{
Console.WriteLine("test_4_11() failed.");
return 184;
}
AA.verify_all(); AA.reset();
if (test_4_12(100) != 100)
{
Console.WriteLine("test_4_12() failed.");
return 185;
}
AA.verify_all(); AA.reset();
if (test_4_13(100) != 100)
{
Console.WriteLine("test_4_13() failed.");
return 186;
}
AA.verify_all(); AA.reset();
if (test_4_14(100) != 100)
{
Console.WriteLine("test_4_14() failed.");
return 187;
}
AA.verify_all(); AA.reset();
if (test_4_15(100) != 100)
{
Console.WriteLine("test_4_15() failed.");
return 188;
}
AA.verify_all(); AA.reset();
if (test_4_16(100) != 100)
{
Console.WriteLine("test_4_16() failed.");
return 189;
}
AA.verify_all(); AA.reset();
if (test_4_17(100) != 100)
{
Console.WriteLine("test_4_17() failed.");
return 190;
}
AA.verify_all(); AA.reset();
if (test_5_0(100) != 100)
{
Console.WriteLine("test_5_0() failed.");
return 191;
}
AA.verify_all(); AA.reset();
if (test_6_0(100, __makeref(AA._init)) != 100)
{
Console.WriteLine("test_6_0() failed.");
return 192;
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_0(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_0() failed.");
return 193;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_1(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_1() failed.");
return 194;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_2(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_2() failed.");
return 195;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_3(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_3() failed.");
return 196;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_4(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_4() failed.");
return 197;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_5(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_5() failed.");
return 198;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_6(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_6() failed.");
return 199;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_7(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_7() failed.");
return 200;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_8(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_8() failed.");
return 201;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_9(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_9() failed.");
return 202;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_10(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_10() failed.");
return 203;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_11(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_11() failed.");
return 204;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_12(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_12() failed.");
return 205;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_13(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_13() failed.");
return 206;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_14(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_14() failed.");
return 207;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_15(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_15() failed.");
return 208;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_16(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_16() failed.");
return 209;
}
}
AA.verify_all(); AA.reset();
fixed (void* p_init = &AA._init, p_zero = &AA._zero)
{
if (test_7_17(100, p_init, p_zero) != 100)
{
Console.WriteLine("test_7_17() failed.");
return 210;
}
}
AA.verify_all(); Console.WriteLine("All tests passed.");
return 100;
}
}
| |
// 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,
// MERCHANTABILITY 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.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Logging;
using Microsoft.PythonTools.Project;
using Microsoft.PythonTools.Project.Web;
using Microsoft.VisualStudioTools.Project;
namespace Microsoft.PythonTools {
internal sealed class DiagnosticsProvider {
private readonly IServiceProvider _serviceProvider;
private static readonly IEnumerable<string> InterestingDteProperties = new[] {
"InterpreterId",
"InterpreterVersion",
"StartupFile",
"WorkingDirectory",
"PublishUrl",
"SearchPath",
"CommandLineArguments",
"InterpreterPath"
};
private static readonly IEnumerable<string> InterestingProjectProperties = new[] {
"ClusterRunEnvironment",
"ClusterPublishBeforeRun",
"ClusterWorkingDir",
"ClusterMpiExecCommand",
"ClusterAppCommand",
"ClusterAppArguments",
"ClusterDeploymentDir",
"ClusterTargetPlatform",
PythonWebLauncher.DebugWebServerTargetProperty,
PythonWebLauncher.DebugWebServerTargetTypeProperty,
PythonWebLauncher.DebugWebServerArgumentsProperty,
PythonWebLauncher.DebugWebServerEnvironmentProperty,
PythonWebLauncher.RunWebServerTargetProperty,
PythonWebLauncher.RunWebServerTargetTypeProperty,
PythonWebLauncher.RunWebServerArgumentsProperty,
PythonWebLauncher.RunWebServerEnvironmentProperty,
PythonWebPropertyPage.StaticUriPatternSetting,
PythonWebPropertyPage.StaticUriRewriteSetting,
PythonWebPropertyPage.WsgiHandlerSetting
};
private static readonly Regex InterestingApplicationLogEntries = new Regex(
@"^Application: (devenv\.exe|.+?Python.+?\.exe|ipy(64)?\.exe)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled
);
public DiagnosticsProvider(IServiceProvider serviceProvider) {
_serviceProvider = serviceProvider;
}
public void WriteLog(TextWriter writer, bool includeAnalysisLog) {
var pyService = _serviceProvider.GetPythonToolsService();
var pythonPathIsMasked = pyService.GeneralOptions.ClearGlobalPythonPath
? " (masked)"
: "";
var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));
var model = _serviceProvider.GetComponentModel();
var knownProviders = model.GetExtensions<IPythonInterpreterFactoryProvider>().ToArray();
var launchProviders = model.GetExtensions<IPythonLauncherProvider>().ToArray();
var inMemLogger = model.GetService<InMemoryLogger>();
writer.WriteLine("Projects: ");
var projects = dte.Solution.Projects;
foreach (EnvDTE.Project project in projects) {
string name;
try {
// Some projects will throw rather than give us a unique
// name. They are not ours, so we will ignore them.
name = project.UniqueName;
} catch (Exception ex) when (!ex.IsCriticalException()) {
bool isPythonProject = false;
try {
isPythonProject = Utilities.GuidEquals(PythonConstants.ProjectFactoryGuid, project.Kind);
} catch (Exception ex2) when (!ex2.IsCriticalException()) {
}
if (isPythonProject) {
// Actually, it was one of our projects, so we do care
// about the exception. We'll add it to the output,
// rather than crashing.
writer.WriteLine(" Project: " + ex.Message);
writer.WriteLine(" Kind: Python");
}
continue;
}
writer.WriteLine(" Project: " + name);
if (Utilities.GuidEquals(PythonConstants.ProjectFactoryGuid, project.Kind)) {
writer.WriteLine(" Kind: Python");
foreach (var prop in InterestingDteProperties) {
writer.WriteLine(" " + prop + ": " + GetProjectProperty(project, prop));
}
var pyProj = project.GetPythonProject();
if (pyProj != null) {
foreach (var prop in InterestingProjectProperties) {
var propValue = pyProj.GetProjectProperty(prop);
if (propValue != null) {
writer.WriteLine(" " + prop + ": " + propValue);
}
}
foreach (var factory in pyProj.InterpreterFactories) {
writer.WriteLine();
writer.WriteLine(" Interpreter: " + factory.Configuration.Description);
writer.WriteLine(" Id: " + factory.Configuration.Id);
writer.WriteLine(" Version: " + factory.Configuration.Version);
writer.WriteLine(" Arch: " + factory.Configuration.Architecture);
writer.WriteLine(" Prefix Path: " + (factory.Configuration.GetPrefixPath() ?? "(null)"));
writer.WriteLine(" Path: " + (factory.Configuration.InterpreterPath ?? "(null)"));
writer.WriteLine(" Windows Path: " + (factory.Configuration.GetWindowsInterpreterPath() ?? "(null)"));
writer.WriteLine(string.Format(" Path Env: {0}={1}{2}",
factory.Configuration.PathEnvironmentVariable ?? "(null)",
Environment.GetEnvironmentVariable(factory.Configuration.PathEnvironmentVariable ?? ""),
pythonPathIsMasked
));
}
}
} else {
writer.WriteLine(" Kind: " + project.Kind);
}
writer.WriteLine();
}
writer.WriteLine("Environments: ");
foreach (var provider in knownProviders.MaybeEnumerate()) {
writer.WriteLine(" " + provider.GetType().FullName);
foreach (var config in provider.GetInterpreterConfigurations()) {
writer.WriteLine(" Id: " + config.Id);
writer.WriteLine(" Factory: " + config.Description);
writer.WriteLine(" Version: " + config.Version);
writer.WriteLine(" Arch: " + config.Architecture);
writer.WriteLine(" Prefix Path: " + (config.GetPrefixPath() ?? "(null)"));
writer.WriteLine(" Path: " + (config.InterpreterPath ?? "(null)"));
writer.WriteLine(" Windows Path: " + (config.GetWindowsInterpreterPath() ?? "(null)"));
writer.WriteLine(" Path Env: " + (config.PathEnvironmentVariable ?? "(null)"));
writer.WriteLine();
}
}
writer.WriteLine("Launchers:");
foreach (var launcher in launchProviders.MaybeEnumerate()) {
writer.WriteLine(" Launcher: " + launcher.GetType().FullName);
writer.WriteLine(" " + launcher.Description);
writer.WriteLine(" " + launcher.Name);
writer.WriteLine();
}
writer.WriteLine("General Options:");
writer.WriteLine(" ClearGlobalPythonPath: {0}", pyService.GeneralOptions.ClearGlobalPythonPath);
writer.WriteLine(" ElevatePip: {0}", pyService.GeneralOptions.ElevatePip);
writer.WriteLine(" IndentationInconsistencySeverity: {0}", pyService.GeneralOptions.IndentationInconsistencySeverity);
writer.WriteLine(" InvalidEncodingWarning: {0}", pyService.GeneralOptions.InvalidEncodingWarning);
writer.WriteLine(" PromptForEnvCreate: {0}", pyService.GeneralOptions.PromptForEnvCreate);
writer.WriteLine(" PromptForPackageInstallation: {0}", pyService.GeneralOptions.PromptForPackageInstallation);
writer.WriteLine(" ShowOutputWindowForPackageInstallation: {0}", pyService.GeneralOptions.ShowOutputWindowForPackageInstallation);
writer.WriteLine(" ShowOutputWindowForVirtualEnvCreate: {0}", pyService.GeneralOptions.ShowOutputWindowForVirtualEnvCreate);
writer.WriteLine(" UnresolvedImportWarning: {0}", pyService.GeneralOptions.UnresolvedImportWarning);
writer.WriteLine(" UpdateSearchPathsWhenAddingLinkedFiles: {0}", pyService.GeneralOptions.UpdateSearchPathsWhenAddingLinkedFiles);
writer.WriteLine();
writer.WriteLine("Advanced Options:");
writer.WriteLine(" PasteRemovesReplPrompts: {0}", pyService.FormattingOptions.PasteRemovesReplPrompts);
writer.WriteLine();
writer.WriteLine("Debugger Options:");
writer.WriteLine(" BreakOnSystemExitZero: {0}", pyService.DebuggerOptions.BreakOnSystemExitZero);
writer.WriteLine(" DebugStdLib: {0}", pyService.DebuggerOptions.DebugStdLib);
writer.WriteLine(" PromptBeforeRunningWithBuildError: {0}", pyService.DebuggerOptions.PromptBeforeRunningWithBuildError);
writer.WriteLine(" ShowFunctionReturnValue: {0}", pyService.DebuggerOptions.ShowFunctionReturnValue);
writer.WriteLine(" TeeStandardOutput: {0}", pyService.DebuggerOptions.TeeStandardOutput);
writer.WriteLine(" WaitOnAbnormalExit: {0}", pyService.DebuggerOptions.WaitOnAbnormalExit);
writer.WriteLine(" WaitOnNormalExit: {0}", pyService.DebuggerOptions.WaitOnNormalExit);
writer.WriteLine();
writer.WriteLine("Conda Options:");
writer.WriteLine(" CustomCondaExecutablePath: {0}", pyService.CondaOptions.CustomCondaExecutablePath);
writer.WriteLine();
writer.WriteLine("Interactive Options:");
writer.WriteLine(" CompletionMode: {0}", pyService.InteractiveOptions.CompletionMode);
writer.WriteLine(" LiveCompletionsOnly: {0}", pyService.InteractiveOptions.LiveCompletionsOnly);
writer.WriteLine(" Scripts: {0}", pyService.InteractiveOptions.Scripts);
writer.WriteLine(" UseSmartHistory: {0}", pyService.InteractiveOptions.UseSmartHistory);
writer.WriteLine();
writer.WriteLine("Debug Interactive Options:");
writer.WriteLine(" CompletionMode: {0}", pyService.DebugInteractiveOptions.CompletionMode);
writer.WriteLine(" LiveCompletionsOnly: {0}", pyService.DebugInteractiveOptions.LiveCompletionsOnly);
writer.WriteLine(" Scripts: {0}", pyService.DebugInteractiveOptions.Scripts);
writer.WriteLine(" UseSmartHistory: {0}", pyService.DebugInteractiveOptions.UseSmartHistory);
writer.WriteLine();
try {
writer.WriteLine("Logged events/stats:");
writer.WriteLine(inMemLogger.ToString());
writer.WriteLine();
} catch (Exception ex) when (!ex.IsCriticalException()) {
writer.WriteLine(" Failed to access event log.");
writer.WriteLine(ex.ToString());
writer.WriteLine();
}
if (includeAnalysisLog) {
try {
writer.WriteLine("System events:");
var application = new EventLog("Application");
var lastWeek = DateTime.Now.Subtract(TimeSpan.FromDays(7));
foreach (var entry in application.Entries.Cast<EventLogEntry>()
.Where(e => e.InstanceId == 1026L) // .NET Runtime
.Where(e => e.TimeGenerated >= lastWeek)
.Where(e => InterestingApplicationLogEntries.IsMatch(e.Message))
.OrderByDescending(e => e.TimeGenerated)
) {
writer.WriteLine(string.Format("Time: {0:s}", entry.TimeGenerated));
using (var reader = new StringReader(entry.Message.TrimEnd())) {
for (var line = reader.ReadLine(); line != null; line = reader.ReadLine()) {
writer.WriteLine(line);
}
}
writer.WriteLine();
}
} catch (Exception ex) when (!ex.IsCriticalException()) {
writer.WriteLine(" Failed to access event log.");
writer.WriteLine(ex.ToString());
writer.WriteLine();
}
}
writer.WriteLine("Loaded assemblies:");
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().OrderBy(assem => assem.FullName)) {
AssemblyFileVersionAttribute assemFileVersion;
var error = "(null)";
try {
assemFileVersion = assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)
.OfType<AssemblyFileVersionAttribute>()
.FirstOrDefault();
} catch (Exception e) when (!e.IsCriticalException()) {
assemFileVersion = null;
error = string.Format("{0}: {1}", e.GetType().Name, e.Message);
}
writer.WriteLine(string.Format(" {0}, FileVersion={1}",
assembly.FullName,
assemFileVersion?.Version ?? error
));
}
writer.WriteLine();
}
private static string GetProjectProperty(EnvDTE.Project project, string name) {
try {
return project.Properties.Item(name)?.Value?.ToString() ?? "<undefined>";
} catch {
return "<undefined>";
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using OpenSim.Region.CoreModules.Framework.Monitoring.Alerts;
using OpenSim.Region.CoreModules.Framework.Monitoring.Monitors;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Framework.Monitoring
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MonitorModule")]
public class MonitorModule : INonSharedRegionModule
{
/// <summary>
/// Is this module enabled?
/// </summary>
public bool Enabled { get; private set; }
private Scene m_scene;
/// <summary>
/// These are monitors where we know the static details in advance.
/// </summary>
/// <remarks>
/// Dynamic monitors also exist (we don't know any of the details of what stats we get back here)
/// but these are currently hardcoded.
/// </remarks>
private readonly List<IMonitor> m_staticMonitors = new List<IMonitor>();
private readonly List<IAlert> m_alerts = new List<IAlert>();
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MonitorModule()
{
Enabled = true;
}
#region Implementation of INonSharedRegionModule
public void Initialise(IConfigSource source)
{
IConfig cnfg = source.Configs["Monitoring"];
if (cnfg != null)
Enabled = cnfg.GetBoolean("Enabled", true);
if (!Enabled)
return;
}
public void AddRegion(Scene scene)
{
if (!Enabled)
return;
m_scene = scene;
m_scene.AddCommand("General", this, "monitor report",
"monitor report",
"Returns a variety of statistics about the current region and/or simulator",
DebugMonitors);
MainServer.Instance.AddHTTPHandler("/monitorstats/" + m_scene.RegionInfo.RegionID, StatsPage);
MainServer.Instance.AddHTTPHandler(
"/monitorstats/" + Uri.EscapeDataString(m_scene.RegionInfo.RegionName), StatsPage);
AddMonitors();
RegisterStatsManagerRegionStatistics();
}
public void RemoveRegion(Scene scene)
{
if (!Enabled)
return;
MainServer.Instance.RemoveHTTPHandler("GET", "/monitorstats/" + m_scene.RegionInfo.RegionID);
MainServer.Instance.RemoveHTTPHandler("GET", "/monitorstats/" + Uri.EscapeDataString(m_scene.RegionInfo.RegionName));
UnRegisterStatsManagerRegionStatistics();
m_scene = null;
}
public void Close()
{
}
public string Name
{
get { return "Region Health Monitoring Module"; }
}
public void RegionLoaded(Scene scene)
{
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
public void AddMonitors()
{
m_staticMonitors.Add(new AgentCountMonitor(m_scene));
m_staticMonitors.Add(new ChildAgentCountMonitor(m_scene));
m_staticMonitors.Add(new GCMemoryMonitor());
m_staticMonitors.Add(new ObjectCountMonitor(m_scene));
m_staticMonitors.Add(new PhysicsFrameMonitor(m_scene));
m_staticMonitors.Add(new PhysicsUpdateFrameMonitor(m_scene));
m_staticMonitors.Add(new PWSMemoryMonitor());
m_staticMonitors.Add(new ThreadCountMonitor());
m_staticMonitors.Add(new TotalFrameMonitor(m_scene));
m_staticMonitors.Add(new EventFrameMonitor(m_scene));
m_staticMonitors.Add(new LandFrameMonitor(m_scene));
m_staticMonitors.Add(new LastFrameTimeMonitor(m_scene));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"TimeDilationMonitor",
"Time Dilation",
m => m.Scene.StatsReporter.LastReportedSimStats[0],
m => m.GetValue().ToString()));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"SimFPSMonitor",
"Sim FPS",
m => m.Scene.StatsReporter.LastReportedSimStats[1],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"PhysicsFPSMonitor",
"Physics FPS",
m => m.Scene.StatsReporter.LastReportedSimStats[2],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"AgentUpdatesPerSecondMonitor",
"Agent Updates",
m => m.Scene.StatsReporter.LastReportedSimStats[3],
m => string.Format("{0} per second", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"ActiveObjectCountMonitor",
"Active Objects",
m => m.Scene.StatsReporter.LastReportedSimStats[7],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"ActiveScriptsMonitor",
"Active Scripts",
m => m.Scene.StatsReporter.LastReportedSimStats[19],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"ScriptEventsPerSecondMonitor",
"Script Events",
m => m.Scene.StatsReporter.LastReportedSimStats[23],
m => string.Format("{0} per second", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"InPacketsPerSecondMonitor",
"In Packets",
m => m.Scene.StatsReporter.LastReportedSimStats[13],
m => string.Format("{0} per second", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"OutPacketsPerSecondMonitor",
"Out Packets",
m => m.Scene.StatsReporter.LastReportedSimStats[14],
m => string.Format("{0} per second", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"UnackedBytesMonitor",
"Unacked Bytes",
m => m.Scene.StatsReporter.LastReportedSimStats[15],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"PendingDownloadsMonitor",
"Pending Downloads",
m => m.Scene.StatsReporter.LastReportedSimStats[17],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"PendingUploadsMonitor",
"Pending Uploads",
m => m.Scene.StatsReporter.LastReportedSimStats[18],
m => string.Format("{0}", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"TotalFrameTimeMonitor",
"Total Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[8],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"NetFrameTimeMonitor",
"Net Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[9],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"PhysicsFrameTimeMonitor",
"Physics Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[10],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"SimulationFrameTimeMonitor",
"Simulation Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[12],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"AgentFrameTimeMonitor",
"Agent Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[16],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"ImagesFrameTimeMonitor",
"Images Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[11],
m => string.Format("{0} ms", m.GetValue())));
m_staticMonitors.Add(
new GenericMonitor(
m_scene,
"SpareFrameTimeMonitor",
"Spare Frame Time",
m => m.Scene.StatsReporter.LastReportedSimStats[38],
m => string.Format("{0} ms", m.GetValue())));
m_alerts.Add(new DeadlockAlert(m_staticMonitors.Find(x => x is LastFrameTimeMonitor) as LastFrameTimeMonitor));
foreach (IAlert alert in m_alerts)
{
alert.OnTriggerAlert += OnTriggerAlert;
}
}
public void DebugMonitors(string module, string[] args)
{
foreach (IMonitor monitor in m_staticMonitors)
{
MainConsole.Instance.OutputFormat(
"[MONITOR MODULE]: {0} reports {1} = {2}",
m_scene.RegionInfo.RegionName, monitor.GetFriendlyName(), monitor.GetFriendlyValue());
}
foreach (KeyValuePair<string, float> tuple in m_scene.StatsReporter.GetExtraSimStats())
{
MainConsole.Instance.OutputFormat(
"[MONITOR MODULE]: {0} reports {1} = {2}",
m_scene.RegionInfo.RegionName, tuple.Key, tuple.Value);
}
}
public void TestAlerts()
{
foreach (IAlert alert in m_alerts)
{
alert.Test();
}
}
public Hashtable StatsPage(Hashtable request)
{
// If request was for a specific monitor
// eg url/?monitor=Monitor.Name
if (request.ContainsKey("monitor"))
{
string monID = (string) request["monitor"];
foreach (IMonitor monitor in m_staticMonitors)
{
string elemName = monitor.ToString();
if (elemName.StartsWith(monitor.GetType().Namespace))
elemName = elemName.Substring(monitor.GetType().Namespace.Length + 1);
if (elemName == monID || monitor.ToString() == monID)
{
Hashtable ereply3 = new Hashtable();
ereply3["int_response_code"] = 404; // 200 OK
ereply3["str_response_string"] = monitor.GetValue().ToString();
ereply3["content_type"] = "text/plain";
return ereply3;
}
}
// FIXME: Arguably this should also be done with dynamic monitors but I'm not sure what the above code
// is even doing. Why are we inspecting the type of the monitor???
// No monitor with that name
Hashtable ereply2 = new Hashtable();
ereply2["int_response_code"] = 404; // 200 OK
ereply2["str_response_string"] = "No such monitor";
ereply2["content_type"] = "text/plain";
return ereply2;
}
string xml = "<data>";
foreach (IMonitor monitor in m_staticMonitors)
{
string elemName = monitor.GetName();
xml += "<" + elemName + ">" + monitor.GetValue().ToString() + "</" + elemName + ">";
// m_log.DebugFormat("[MONITOR MODULE]: {0} = {1}", elemName, monitor.GetValue());
}
foreach (KeyValuePair<string, float> tuple in m_scene.StatsReporter.GetExtraSimStats())
{
xml += "<" + tuple.Key + ">" + tuple.Value + "</" + tuple.Key + ">";
}
xml += "</data>";
Hashtable ereply = new Hashtable();
ereply["int_response_code"] = 200; // 200 OK
ereply["str_response_string"] = xml;
ereply["content_type"] = "text/xml";
return ereply;
}
void OnTriggerAlert(System.Type reporter, string reason, bool fatal)
{
m_log.Error("[Monitor] " + reporter.Name + " for " + m_scene.RegionInfo.RegionName + " reports " + reason + " (Fatal: " + fatal + ")");
}
private List<Stat> registeredStats = new List<Stat>();
private void MakeStat(string pName, string pUnitName, Action<Stat> act)
{
Stat tempStat = new Stat(pName, pName, pName, pUnitName, "scene", m_scene.RegionInfo.RegionName, StatType.Pull, act, StatVerbosity.Info);
StatsManager.RegisterStat(tempStat);
registeredStats.Add(tempStat);
}
private void RegisterStatsManagerRegionStatistics()
{
MakeStat("RootAgents", "avatars", (s) => { s.Value = m_scene.SceneGraph.GetRootAgentCount(); });
MakeStat("ChildAgents", "avatars", (s) => { s.Value = m_scene.SceneGraph.GetChildAgentCount(); });
MakeStat("TotalPrims", "objects", (s) => { s.Value = m_scene.SceneGraph.GetTotalObjectsCount(); });
MakeStat("ActivePrims", "objects", (s) => { s.Value = m_scene.SceneGraph.GetActiveObjectsCount(); });
MakeStat("ActiveScripts", "scripts", (s) => { s.Value = m_scene.SceneGraph.GetActiveScriptsCount(); });
MakeStat("TimeDilation", "sec/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[0]; });
MakeStat("SimFPS", "fps", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[1]; });
MakeStat("PhysicsFPS", "fps", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[2]; });
MakeStat("AgentUpdates", "updates/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[3]; });
MakeStat("FrameTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[8]; });
MakeStat("NetTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[9]; });
MakeStat("OtherTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[12]; });
MakeStat("PhysicsTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[10]; });
MakeStat("AgentTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[16]; });
MakeStat("ImageTime", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[11]; });
MakeStat("ScriptLines", "lines/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[20]; });
MakeStat("SimSpareMS", "ms/sec", (s) => { s.Value = m_scene.StatsReporter.LastReportedSimStats[21]; });
}
private void UnRegisterStatsManagerRegionStatistics()
{
foreach (Stat stat in registeredStats)
{
StatsManager.DeregisterStat(stat);
stat.Dispose();
}
registeredStats.Clear();
}
}
}
| |
using Microsoft.Data.Entity.Migrations;
namespace AllReady.Migrations
{
public partial class ActivityType : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity");
migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill");
migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill");
migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.AddColumn<int>(
name: "ActivityType",
table: "Activity",
nullable: false,
defaultValue: Models.EventType.Itinerary);
migrationBuilder.AddForeignKey(
name: "FK_Activity_Campaign_CampaignId",
table: "Activity",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ActivitySkill_Activity_ActivityId",
table: "ActivitySkill",
column: "ActivityId",
principalTable: "Activity",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ActivitySkill_Skill_SkillId",
table: "ActivitySkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Campaign_Organization_ManagingOrganizationId",
table: "Campaign",
column: "ManagingOrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Campaign_CampaignId",
table: "CampaignContact",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Contact_ContactId",
table: "CampaignContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Contact_ContactId",
table: "OrganizationContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Organization_OrganizationId",
table: "OrganizationContact",
column: "OrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_Skill_SkillId",
table: "TaskSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_AllReadyTask_TaskId",
table: "TaskSkill",
column: "TaskId",
principalTable: "AllReadyTask",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_Skill_SkillId",
table: "UserSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_ApplicationUser_UserId",
table: "UserSkill",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity");
migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill");
migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill");
migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropColumn(name: "ActivityType", table: "Activity");
migrationBuilder.AddForeignKey(
name: "FK_Activity_Campaign_CampaignId",
table: "Activity",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ActivitySkill_Activity_ActivityId",
table: "ActivitySkill",
column: "ActivityId",
principalTable: "Activity",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ActivitySkill_Skill_SkillId",
table: "ActivitySkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Campaign_Organization_ManagingOrganizationId",
table: "Campaign",
column: "ManagingOrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Campaign_CampaignId",
table: "CampaignContact",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Contact_ContactId",
table: "CampaignContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Contact_ContactId",
table: "OrganizationContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Organization_OrganizationId",
table: "OrganizationContact",
column: "OrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_Skill_SkillId",
table: "TaskSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_AllReadyTask_TaskId",
table: "TaskSkill",
column: "TaskId",
principalTable: "AllReadyTask",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_Skill_SkillId",
table: "UserSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_ApplicationUser_UserId",
table: "UserSkill",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
| |
namespace BLBTest
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.dataListBindingNavigator = new System.Windows.Forms.BindingNavigator(this.components);
this.bindingNavigatorAddNewItem = new System.Windows.Forms.ToolStripButton();
this.bindingNavigatorCountItem = new System.Windows.Forms.ToolStripLabel();
this.bindingNavigatorDeleteItem = new System.Windows.Forms.ToolStripButton();
this.bindingNavigatorMoveFirstItem = new System.Windows.Forms.ToolStripButton();
this.bindingNavigatorMovePreviousItem = new System.Windows.Forms.ToolStripButton();
this.bindingNavigatorSeparator = new System.Windows.Forms.ToolStripSeparator();
this.bindingNavigatorPositionItem = new System.Windows.Forms.ToolStripTextBox();
this.bindingNavigatorSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.bindingNavigatorMoveNextItem = new System.Windows.Forms.ToolStripButton();
this.bindingNavigatorMoveLastItem = new System.Windows.Forms.ToolStripButton();
this.bindingNavigatorSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.dataListBindingNavigatorSaveItem = new System.Windows.Forms.ToolStripButton();
this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this.dataListDataGridView = new System.Windows.Forms.DataGridView();
this.cancelButton = new System.Windows.Forms.Button();
this.toolStripButton2 = new System.Windows.Forms.ToolStripButton();
this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ItemName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataListBindingSource = new System.Windows.Forms.BindingSource(this.components);
((System.ComponentModel.ISupportInitialize)(this.dataListBindingNavigator)).BeginInit();
this.dataListBindingNavigator.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataListDataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dataListBindingSource)).BeginInit();
this.SuspendLayout();
//
// dataListBindingNavigator
//
this.dataListBindingNavigator.AddNewItem = this.bindingNavigatorAddNewItem;
this.dataListBindingNavigator.BindingSource = this.dataListBindingSource;
this.dataListBindingNavigator.CountItem = this.bindingNavigatorCountItem;
this.dataListBindingNavigator.DeleteItem = this.bindingNavigatorDeleteItem;
this.dataListBindingNavigator.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.bindingNavigatorMoveFirstItem,
this.bindingNavigatorMovePreviousItem,
this.bindingNavigatorSeparator,
this.bindingNavigatorPositionItem,
this.bindingNavigatorCountItem,
this.bindingNavigatorSeparator1,
this.bindingNavigatorMoveNextItem,
this.bindingNavigatorMoveLastItem,
this.bindingNavigatorSeparator2,
this.bindingNavigatorAddNewItem,
this.bindingNavigatorDeleteItem,
this.dataListBindingNavigatorSaveItem,
this.toolStripButton1,
this.toolStripButton2});
this.dataListBindingNavigator.Location = new System.Drawing.Point(0, 0);
this.dataListBindingNavigator.MoveFirstItem = this.bindingNavigatorMoveFirstItem;
this.dataListBindingNavigator.MoveLastItem = this.bindingNavigatorMoveLastItem;
this.dataListBindingNavigator.MoveNextItem = this.bindingNavigatorMoveNextItem;
this.dataListBindingNavigator.MovePreviousItem = this.bindingNavigatorMovePreviousItem;
this.dataListBindingNavigator.Name = "dataListBindingNavigator";
this.dataListBindingNavigator.PositionItem = this.bindingNavigatorPositionItem;
this.dataListBindingNavigator.Size = new System.Drawing.Size(533, 25);
this.dataListBindingNavigator.TabIndex = 0;
this.dataListBindingNavigator.Text = "bindingNavigator1";
//
// bindingNavigatorAddNewItem
//
this.bindingNavigatorAddNewItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.bindingNavigatorAddNewItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorAddNewItem.Image")));
this.bindingNavigatorAddNewItem.Name = "bindingNavigatorAddNewItem";
this.bindingNavigatorAddNewItem.RightToLeftAutoMirrorImage = true;
this.bindingNavigatorAddNewItem.Size = new System.Drawing.Size(23, 22);
this.bindingNavigatorAddNewItem.Text = "Add new";
//
// bindingNavigatorCountItem
//
this.bindingNavigatorCountItem.Name = "bindingNavigatorCountItem";
this.bindingNavigatorCountItem.Size = new System.Drawing.Size(36, 22);
this.bindingNavigatorCountItem.Text = "of {0}";
this.bindingNavigatorCountItem.ToolTipText = "Total number of items";
//
// bindingNavigatorDeleteItem
//
this.bindingNavigatorDeleteItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.bindingNavigatorDeleteItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorDeleteItem.Image")));
this.bindingNavigatorDeleteItem.Name = "bindingNavigatorDeleteItem";
this.bindingNavigatorDeleteItem.RightToLeftAutoMirrorImage = true;
this.bindingNavigatorDeleteItem.Size = new System.Drawing.Size(23, 22);
this.bindingNavigatorDeleteItem.Text = "Delete";
//
// bindingNavigatorMoveFirstItem
//
this.bindingNavigatorMoveFirstItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.bindingNavigatorMoveFirstItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveFirstItem.Image")));
this.bindingNavigatorMoveFirstItem.Name = "bindingNavigatorMoveFirstItem";
this.bindingNavigatorMoveFirstItem.RightToLeftAutoMirrorImage = true;
this.bindingNavigatorMoveFirstItem.Size = new System.Drawing.Size(23, 22);
this.bindingNavigatorMoveFirstItem.Text = "Move first";
//
// bindingNavigatorMovePreviousItem
//
this.bindingNavigatorMovePreviousItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.bindingNavigatorMovePreviousItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMovePreviousItem.Image")));
this.bindingNavigatorMovePreviousItem.Name = "bindingNavigatorMovePreviousItem";
this.bindingNavigatorMovePreviousItem.RightToLeftAutoMirrorImage = true;
this.bindingNavigatorMovePreviousItem.Size = new System.Drawing.Size(23, 22);
this.bindingNavigatorMovePreviousItem.Text = "Move previous";
//
// bindingNavigatorSeparator
//
this.bindingNavigatorSeparator.Name = "bindingNavigatorSeparator";
this.bindingNavigatorSeparator.Size = new System.Drawing.Size(6, 25);
//
// bindingNavigatorPositionItem
//
this.bindingNavigatorPositionItem.AccessibleName = "Position";
this.bindingNavigatorPositionItem.AutoSize = false;
this.bindingNavigatorPositionItem.Name = "bindingNavigatorPositionItem";
this.bindingNavigatorPositionItem.Size = new System.Drawing.Size(50, 21);
this.bindingNavigatorPositionItem.Text = "0";
this.bindingNavigatorPositionItem.ToolTipText = "Current position";
//
// bindingNavigatorSeparator1
//
this.bindingNavigatorSeparator1.Name = "bindingNavigatorSeparator1";
this.bindingNavigatorSeparator1.Size = new System.Drawing.Size(6, 25);
//
// bindingNavigatorMoveNextItem
//
this.bindingNavigatorMoveNextItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.bindingNavigatorMoveNextItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveNextItem.Image")));
this.bindingNavigatorMoveNextItem.Name = "bindingNavigatorMoveNextItem";
this.bindingNavigatorMoveNextItem.RightToLeftAutoMirrorImage = true;
this.bindingNavigatorMoveNextItem.Size = new System.Drawing.Size(23, 22);
this.bindingNavigatorMoveNextItem.Text = "Move next";
//
// bindingNavigatorMoveLastItem
//
this.bindingNavigatorMoveLastItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.bindingNavigatorMoveLastItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveLastItem.Image")));
this.bindingNavigatorMoveLastItem.Name = "bindingNavigatorMoveLastItem";
this.bindingNavigatorMoveLastItem.RightToLeftAutoMirrorImage = true;
this.bindingNavigatorMoveLastItem.Size = new System.Drawing.Size(23, 22);
this.bindingNavigatorMoveLastItem.Text = "Move last";
//
// bindingNavigatorSeparator2
//
this.bindingNavigatorSeparator2.Name = "bindingNavigatorSeparator2";
this.bindingNavigatorSeparator2.Size = new System.Drawing.Size(6, 25);
//
// dataListBindingNavigatorSaveItem
//
this.dataListBindingNavigatorSaveItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.dataListBindingNavigatorSaveItem.Enabled = false;
this.dataListBindingNavigatorSaveItem.Image = ((System.Drawing.Image)(resources.GetObject("dataListBindingNavigatorSaveItem.Image")));
this.dataListBindingNavigatorSaveItem.Name = "dataListBindingNavigatorSaveItem";
this.dataListBindingNavigatorSaveItem.Size = new System.Drawing.Size(23, 22);
this.dataListBindingNavigatorSaveItem.Text = "Save Data";
//
// toolStripButton1
//
this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image")));
this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton1.Name = "toolStripButton1";
this.toolStripButton1.Size = new System.Drawing.Size(82, 22);
this.toolStripButton1.Text = "Replace child 2";
this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click);
//
// dataListDataGridView
//
this.dataListDataGridView.AutoGenerateColumns = false;
this.dataListDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.dataGridViewTextBoxColumn1,
this.ItemName});
this.dataListDataGridView.DataSource = this.dataListBindingSource;
this.dataListDataGridView.Location = new System.Drawing.Point(12, 28);
this.dataListDataGridView.Name = "dataListDataGridView";
this.dataListDataGridView.Size = new System.Drawing.Size(428, 336);
this.dataListDataGridView.TabIndex = 1;
//
// cancelButton
//
this.cancelButton.Location = new System.Drawing.Point(446, 37);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 23);
this.cancelButton.TabIndex = 2;
this.cancelButton.Text = "Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
//
// toolStripButton2
//
this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image")));
this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton2.Name = "toolStripButton2";
this.toolStripButton2.Size = new System.Drawing.Size(43, 22);
this.toolStripButton2.Text = "Cancel";
this.toolStripButton2.Click += new System.EventHandler(this.toolStripButton2_Click);
//
// dataGridViewTextBoxColumn1
//
this.dataGridViewTextBoxColumn1.DataPropertyName = "Data";
this.dataGridViewTextBoxColumn1.HeaderText = "Data";
this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1";
//
// ItemName
//
this.ItemName.DataPropertyName = "Name";
this.ItemName.HeaderText = "Name";
this.ItemName.Name = "ItemName";
//
// dataListBindingSource
//
this.dataListBindingSource.DataSource = typeof(BLBTest.DataEdit);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(533, 376);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.dataListDataGridView);
this.Controls.Add(this.dataListBindingNavigator);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.dataListBindingNavigator)).EndInit();
this.dataListBindingNavigator.ResumeLayout(false);
this.dataListBindingNavigator.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataListDataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dataListBindingSource)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.BindingSource dataListBindingSource;
private System.Windows.Forms.BindingNavigator dataListBindingNavigator;
private System.Windows.Forms.ToolStripButton bindingNavigatorAddNewItem;
private System.Windows.Forms.ToolStripLabel bindingNavigatorCountItem;
private System.Windows.Forms.ToolStripButton bindingNavigatorDeleteItem;
private System.Windows.Forms.ToolStripButton bindingNavigatorMoveFirstItem;
private System.Windows.Forms.ToolStripButton bindingNavigatorMovePreviousItem;
private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator;
private System.Windows.Forms.ToolStripTextBox bindingNavigatorPositionItem;
private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator1;
private System.Windows.Forms.ToolStripButton bindingNavigatorMoveNextItem;
private System.Windows.Forms.ToolStripButton bindingNavigatorMoveLastItem;
private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator2;
private System.Windows.Forms.ToolStripButton dataListBindingNavigatorSaveItem;
private System.Windows.Forms.DataGridView dataListDataGridView;
private System.Windows.Forms.ToolStripButton toolStripButton1;
private System.Windows.Forms.DataGridViewTextBoxColumn NameCol;
private System.Windows.Forms.ToolStripButton toolStripButton2;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
private System.Windows.Forms.DataGridViewTextBoxColumn ItemName;
}
}
| |
// This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace Fungus
{
/// <summary>
/// class for a single condition. A list of this is used for multiple conditions.
/// </summary>
[System.Serializable]
public class ConditionExpression
{
[SerializeField] protected CompareOperator compareOperator;
[SerializeField] protected AnyVariableAndDataPair anyVar;
public virtual AnyVariableAndDataPair AnyVar { get { return anyVar; } }
public virtual CompareOperator CompareOperator { get { return compareOperator; } }
public ConditionExpression()
{
}
public ConditionExpression(CompareOperator op, AnyVariableAndDataPair variablePair)
{
compareOperator = op;
anyVar = variablePair;
}
}
public abstract class VariableCondition : Condition, ISerializationCallbackReceiver
{
public enum AnyOrAll
{
AnyOf_OR,//Use as a chain of ORs
AllOf_AND,//Use as a chain of ANDs
}
[Tooltip("Selecting AnyOf will result in true if at least one of the conditions is true. Selecting AllOF will result in true only when all the conditions are true.")]
[SerializeField] protected AnyOrAll anyOrAllConditions;
[SerializeField] protected List<ConditionExpression> conditions = new List<ConditionExpression>();
/// <summary>
/// Called when the script is loaded or a value is changed in the
/// inspector (Called in the editor only).
/// </summary>
public override void OnValidate()
{
base.OnValidate();
if (conditions == null)
{
conditions = new List<ConditionExpression>();
}
if (conditions.Count == 0)
{
conditions.Add(new ConditionExpression());
}
}
protected override bool EvaluateCondition()
{
if (conditions == null || conditions.Count == 0)
{
return false;
}
bool resultAny = false, resultAll = true;
foreach (ConditionExpression condition in conditions)
{
bool curResult = false;
if (condition.AnyVar == null)
{
resultAll &= curResult;
resultAny |= curResult;
continue;
}
condition.AnyVar.Compare(condition.CompareOperator, ref curResult);
resultAll &= curResult;
resultAny |= curResult;
}
if (anyOrAllConditions == AnyOrAll.AnyOf_OR) return resultAny;
return resultAll;
}
protected override bool HasNeededProperties()
{
if (conditions == null || conditions.Count == 0)
{
return false;
}
foreach (ConditionExpression condition in conditions)
{
if (condition.AnyVar == null || condition.AnyVar.variable == null)
{
return false;
}
}
return true;
}
public override string GetSummary()
{
if (!this.HasNeededProperties())
{
return "Error: No variable selected";
}
string connector = "";
if (anyOrAllConditions == AnyOrAll.AnyOf_OR)
{
connector = " <b>OR</b> ";
}
else
{
connector = " <b>AND</b> ";
}
StringBuilder summary = new StringBuilder("");
for (int i = 0; i < conditions.Count; i++)
{
summary.Append(conditions[i].AnyVar.variable.Key + " " +
VariableUtil.GetCompareOperatorDescription(conditions[i].CompareOperator) + " " +
conditions[i].AnyVar.GetDataDescription());
if (i < conditions.Count - 1)
{
summary.Append(connector);
}
}
return summary.ToString();
}
public override bool HasReference(Variable variable)
{
return anyVar.HasReference(variable);
}
#region Editor caches
#if UNITY_EDITOR
protected override void RefreshVariableCache()
{
base.RefreshVariableCache();
if (conditions != null)
{
foreach (var item in conditions)
{
item.AnyVar.RefreshVariableCacheHelper(GetFlowchart(), ref referencedVariables);
}
}
}
#endif
#endregion Editor caches
#region backwards compat
[HideInInspector]
[SerializeField] protected CompareOperator compareOperator;
[HideInInspector]
[SerializeField] protected AnyVariableAndDataPair anyVar;
[Tooltip("Variable to use in expression")]
[VariableProperty(AllVariableTypes.VariableAny.Any)]
[SerializeField] protected Variable variable;
[Tooltip("Boolean value to compare against")]
[SerializeField] protected BooleanData booleanData;
[Tooltip("Integer value to compare against")]
[SerializeField] protected IntegerData integerData;
[Tooltip("Float value to compare against")]
[SerializeField] protected FloatData floatData;
[Tooltip("String value to compare against")]
[SerializeField] protected StringDataMulti stringData;
[Tooltip("Animator value to compare against")]
[SerializeField] protected AnimatorData animatorData;
[Tooltip("AudioSource value to compare against")]
[SerializeField] protected AudioSourceData audioSourceData;
[Tooltip("Color value to compare against")]
[SerializeField] protected ColorData colorData;
[Tooltip("GameObject value to compare against")]
[SerializeField] protected GameObjectData gameObjectData;
[Tooltip("Material value to compare against")]
[SerializeField] protected MaterialData materialData;
[Tooltip("Object value to compare against")]
[SerializeField] protected ObjectData objectData;
[Tooltip("Rigidbody2D value to compare against")]
[SerializeField] protected Rigidbody2DData rigidbody2DData;
[Tooltip("Sprite value to compare against")]
[SerializeField] protected SpriteData spriteData;
[Tooltip("Texture value to compare against")]
[SerializeField] protected TextureData textureData;
[Tooltip("Transform value to compare against")]
[SerializeField] protected TransformData transformData;
[Tooltip("Vector2 value to compare against")]
[SerializeField] protected Vector2Data vector2Data;
[Tooltip("Vector3 value to compare against")]
[SerializeField] protected Vector3Data vector3Data;
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
if (variable != null)
{
anyVar.variable = variable;
if (variable.GetType() == typeof(BooleanVariable) && !booleanData.Equals(new BooleanData()))
{
anyVar.data.booleanData = booleanData;
booleanData = new BooleanData();
}
else if (variable.GetType() == typeof(IntegerVariable) && !integerData.Equals(new IntegerData()))
{
anyVar.data.integerData = integerData;
integerData = new IntegerData();
}
else if (variable.GetType() == typeof(FloatVariable) && !floatData.Equals(new FloatData()))
{
anyVar.data.floatData = floatData;
floatData = new FloatData();
}
else if (variable.GetType() == typeof(StringVariable) && !stringData.Equals(new StringDataMulti()))
{
anyVar.data.stringData.stringRef = stringData.stringRef;
anyVar.data.stringData.stringVal = stringData.stringVal;
stringData = new StringDataMulti();
}
else if (variable.GetType() == typeof(AnimatorVariable) && !animatorData.Equals(new AnimatorData()))
{
anyVar.data.animatorData = animatorData;
animatorData = new AnimatorData();
}
else if (variable.GetType() == typeof(AudioSourceVariable) && !audioSourceData.Equals(new AudioSourceData()))
{
anyVar.data.audioSourceData = audioSourceData;
audioSourceData = new AudioSourceData();
}
else if (variable.GetType() == typeof(ColorVariable) && !colorData.Equals(new ColorData()))
{
anyVar.data.colorData = colorData;
colorData = new ColorData();
}
else if (variable.GetType() == typeof(GameObjectVariable) && !gameObjectData.Equals(new GameObjectData()))
{
anyVar.data.gameObjectData = gameObjectData;
gameObjectData = new GameObjectData();
}
else if (variable.GetType() == typeof(MaterialVariable) && !materialData.Equals(new MaterialData()))
{
anyVar.data.materialData = materialData;
materialData = new MaterialData();
}
else if (variable.GetType() == typeof(ObjectVariable) && !objectData.Equals(new ObjectData()))
{
anyVar.data.objectData = objectData;
objectData = new ObjectData();
}
else if (variable.GetType() == typeof(Rigidbody2DVariable) && !rigidbody2DData.Equals(new Rigidbody2DData()))
{
anyVar.data.rigidbody2DData = rigidbody2DData;
rigidbody2DData = new Rigidbody2DData();
}
else if (variable.GetType() == typeof(SpriteVariable) && !spriteData.Equals(new SpriteData()))
{
anyVar.data.spriteData = spriteData;
spriteData = new SpriteData();
}
else if (variable.GetType() == typeof(TextureVariable) && !textureData.Equals(new TextureData()))
{
anyVar.data.textureData = textureData;
textureData = new TextureData();
}
else if (variable.GetType() == typeof(TransformVariable) && !transformData.Equals(new TransformData()))
{
anyVar.data.transformData = transformData;
transformData = new TransformData();
}
else if (variable.GetType() == typeof(Vector2Variable) && !vector2Data.Equals(new Vector2Data()))
{
anyVar.data.vector2Data = vector2Data;
vector2Data = new Vector2Data();
}
else if (variable.GetType() == typeof(Vector3Variable) && !vector3Data.Equals(new Vector3Data()))
{
anyVar.data.vector3Data = vector3Data;
vector3Data = new Vector3Data();
}
//moved to new anyvar storage, clear legacy.
variable = null;
}
// just checking for anyVar != null fails here. is any var being reintilaized somewhere?
if (anyVar != null && anyVar.variable != null)
{
ConditionExpression c = new ConditionExpression(compareOperator, anyVar);
if (!conditions.Contains(c))
{
conditions.Add(c);
}
anyVar = null;
variable = null;
}
}
#endregion backwards compat
}
}
| |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using StructureMap.Configuration.DSL;
using StructureMap.Pipeline;
using StructureMap.Pipeline.Lazy;
using StructureMap.TypeRules;
using StructureMap.Util;
namespace StructureMap.Graph
{
/// <summary>
/// Models the runtime configuration of a StructureMap Container
/// </summary>
public class PluginGraph : IPluginGraph, IFamilyCollection, IDisposable
{
private readonly ConcurrentDictionary<Type, PluginFamily> _families = new ConcurrentDictionary<Type, PluginFamily>();
private readonly IList<IFamilyPolicy> _policies = new List<IFamilyPolicy>();
private readonly ConcurrentDictionary<Type, bool> _missingTypes = new ConcurrentDictionary<Type, bool>();
private readonly List<Registry> _registries = new List<Registry>();
private readonly LifecycleObjectCache _singletonCache = new LifecycleObjectCache();
private readonly LightweightCache<string, PluginGraph> _profiles;
public TransientTracking TransientTracking = TransientTracking.DefaultNotTrackedAtRoot;
public string Name { get; set; }
/// <summary>
/// Specifies interception, construction selection, and setter usage policies
/// </summary>
public readonly Policies Policies;
/// <summary>
/// Holds a cache of concrete types that can be considered for closing generic interface
/// types
/// </summary>
public readonly IList<Type> ConnectedConcretions = new List<Type>();
/// <summary>
/// Creates a top level PluginGraph with the default policies
/// </summary>
/// <param name="profile"></param>
/// <returns></returns>
public static PluginGraph CreateRoot(string profile = null)
{
var graph = new PluginGraph();
graph.ProfileName = profile ?? "DEFAULT";
graph.Families[typeof(Func<>)].SetDefault(new FuncFactoryTemplate());
graph.Families[typeof(Func<,>)].SetDefault(new FuncWithArgFactoryTemplate());
graph.Families[typeof(Lazy<>)].SetDefault(new LazyFactoryTemplate());
return graph;
}
internal void addCloseGenericPolicyTo()
{
var policy = new CloseGenericFamilyPolicy(this);
AddFamilyPolicy(policy);
AddFamilyPolicy(new FuncBuildByNamePolicy());
AddFamilyPolicy(new EnumerableFamilyPolicy());
}
internal PluginGraph NewChild()
{
return new PluginGraph
{
Parent = this
};
}
internal PluginGraph ToNestedGraph()
{
return new PluginGraph
{
Parent = this,
ProfileName = ProfileName + " - Nested"
};
}
private PluginGraph()
{
Policies = new Policies(this);
_profiles =
new LightweightCache<string, PluginGraph>(name => new PluginGraph {ProfileName = name, Parent = this});
ProfileName = "DEFAULT";
}
public PluginGraph Parent { get; private set; }
/// <summary>
/// The profile name of this PluginGraph or "DEFAULT" if it is the top
/// </summary>
public string ProfileName { get; private set; }
/// <summary>
/// The cache for all singleton scoped objects
/// </summary>
public LifecycleObjectCache SingletonCache
{
get { return _singletonCache; }
}
/// <summary>
/// Fetch the PluginGraph for the named profile. Will
/// create a new one on the fly for unrecognized names.
/// Is case sensitive
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public PluginGraph Profile(string name)
{
return _profiles[name];
}
/// <summary>
/// All the currently known profiles
/// </summary>
public IEnumerable<PluginGraph> Profiles
{
get { return _profiles.ToArray(); }
}
IEnumerator IEnumerable.GetEnumerator()
{
return _families.Select(x => x.Value).ToArray().GetEnumerator();
}
IEnumerator<PluginFamily> IEnumerable<PluginFamily>.GetEnumerator()
{
return _families.Select(x => x.Value).ToArray().As<IEnumerable<PluginFamily>>().GetEnumerator();
}
PluginFamily IFamilyCollection.this[Type pluginType]
{
get
{
return _families.GetOrAdd(pluginType, type =>
{
var family = _policies.FirstValue(x => x.Build(type)) ?? new PluginFamily(type);
family.Owner = this;
return family;
});
}
set { _families[pluginType] = value; }
}
bool IFamilyCollection.Has(Type pluginType)
{
return _families.ContainsKey(pluginType);
}
/// <summary>
/// Add a new family policy that can create new PluginFamily's on demand
/// when there is no pre-existing family
/// </summary>
/// <param name="policy"></param>
public void AddFamilyPolicy(IFamilyPolicy policy)
{
_policies.Insert(0, policy);
}
/// <summary>
/// The list of Registry objects used to create this container
/// </summary>
internal List<Registry> Registries
{
get { return _registries; }
}
/// <summary>
/// Access to all the known PluginFamily members
/// </summary>
public IFamilyCollection Families => this;
/// <summary>
/// The top most PluginGraph. If this is the root, will return itself.
/// If a Profiled PluginGraph, returns its ultimate parent
/// </summary>
public PluginGraph Root
{
get { return Parent == null ? this : Parent.Root; }
}
internal bool IsRunningConfigure { get; set; }
/// <summary>
/// Adds the concreteType as an Instance of the pluginType
/// </summary>
/// <param name = "pluginType"></param>
/// <param name = "concreteType"></param>
public virtual void AddType(Type pluginType, Type concreteType)
{
Families[pluginType].AddType(concreteType);
}
/// <summary>
/// Adds the concreteType as an Instance of the pluginType with a name
/// </summary>
/// <param name = "pluginType"></param>
/// <param name = "concreteType"></param>
/// <param name = "name"></param>
public virtual void AddType(Type pluginType, Type concreteType, string name)
{
Families[pluginType].AddType(concreteType, name);
}
public readonly Queue<Registry> QueuedRegistries = new Queue<Registry>();
/// <summary>
/// Adds a Registry by type. Requires that the Registry class have a no argument
/// public constructor
/// </summary>
/// <param name="type"></param>
public void ImportRegistry(Type type)
{
var all = Registries.Concat(QueuedRegistries);
if (all.Any(x => x.GetType() == type)) return;
try
{
var registry = (Registry) Activator.CreateInstance(type);
QueuedRegistries.Enqueue(registry);
}
catch (Exception e)
{
throw new StructureMapException(
"Unable to create an instance for Registry type '{0}'. Please check the inner exception for details"
.ToFormat(type.GetFullName()), e);
}
}
public void ImportRegistry(Registry registry)
{
var all = Registries.Concat(QueuedRegistries).ToArray();
if (Registry.RegistryExists(all, registry)) return;
QueuedRegistries.Enqueue(registry);
}
public void AddFamily(PluginFamily family)
{
family.Owner = this;
_families[family.PluginType] = family;
}
public bool HasInstance(Type pluginType, string name)
{
if (!HasFamily(pluginType))
{
return false;
}
return Families[pluginType].GetInstance(name) != null;
}
internal PluginFamily FindExistingOrCreateFamily(Type pluginType)
{
if (_families.ContainsKey(pluginType)) return _families[pluginType];
var family = new PluginFamily(pluginType);
_families[pluginType] = family;
return family;
}
/// <summary>
/// Does a PluginFamily already exist for the pluginType? Will also test for open generic
/// definition of a generic closed type
/// </summary>
/// <param name="pluginType"></param>
/// <returns></returns>
public bool HasFamily(Type pluginType)
{
if (_families.ContainsKey(pluginType)) return true;
if (_missingTypes.ContainsKey(pluginType)) return false;
if (_policies.Where(x => x.AppliesToHasFamilyChecks).ToArray().Any(x => x.Build(pluginType) != null))
{
return true;
}
_missingTypes.AddOrUpdate(pluginType, true, (type, b) => true);
return false;
}
/// <summary>
/// Can this PluginGraph resolve a default instance
/// for the pluginType?
/// </summary>
/// <param name="pluginType"></param>
/// <returns></returns>
public bool HasDefaultForPluginType(Type pluginType)
{
if (!HasFamily(pluginType))
{
return false;
}
return Families[pluginType].GetDefaultInstance() != null;
}
/// <summary>
/// Removes a PluginFamily from this PluginGraph
/// and disposes that family and all of its Instance's
/// </summary>
/// <param name="pluginType"></param>
public void EjectFamily(Type pluginType)
{
if (_families.ContainsKey(pluginType))
{
PluginFamily family = null;
if (_families.TryRemove(pluginType, out family))
{
family.SafeDispose();
}
}
}
internal void EachInstance(Action<Type, Instance> action)
{
_families.Each(family => family.Value.Instances.Each(i => action(family.Value.PluginType, i)));
}
/// <summary>
/// Find a named instance for a given PluginType
/// </summary>
/// <param name="pluginType"></param>
/// <param name="name"></param>
/// <returns></returns>
public Instance FindInstance(Type pluginType, string name)
{
if (!HasFamily(pluginType)) return null;
return Families[pluginType].GetInstance(name);
}
/// <summary>
/// Returns every instance in the PluginGraph for the pluginType
/// </summary>
/// <param name="pluginType"></param>
/// <returns></returns>
public IEnumerable<Instance> AllInstances(Type pluginType)
{
if (HasFamily(pluginType))
{
return Families[pluginType].Instances;
}
return Enumerable.Empty<Instance>();
}
void IDisposable.Dispose()
{
_families.Each(
family =>
{
family.Value.Instances.Each(instance =>
{
_singletonCache.Eject(family.Value.PluginType, instance);
if (instance is IDisposable)
{
instance.SafeDispose();
}
});
});
_profiles.Each(x => x.SafeDispose());
_profiles.Clear();
var containerFamily = _families[typeof (IContainer)];
PluginFamily c;
_families.TryRemove(typeof (IContainer), out c);
containerFamily.RemoveAll();
_missingTypes.Clear();
_families.Each(x => x.SafeDispose());
_families.Clear();
}
internal void ClearTypeMisses()
{
_missingTypes.Clear();
}
}
public interface IFamilyCollection : IEnumerable<PluginFamily>
{
PluginFamily this[Type pluginType] { get; set; }
bool Has(Type pluginType);
}
}
| |
//
// DialogViewController.cs: drives MonoTouch.Dialog
//
// Author:
// Miguel de Icaza
//
//
using System;
using System.Collections.Generic;
using Foundation;
using UIKit;
using CoreGraphics;
using NSAction = global::System.Action;
namespace MonoTouch.Dialog
{
/// <summary>
/// The DialogViewController is the main entry point to use MonoTouch.Dialog,
/// it provides a simplified API to the UITableViewController.
/// </summary>
public class DialogViewController : UITableViewController
{
public UITableViewStyle Style = UITableViewStyle.Grouped;
public event Action<NSIndexPath> OnSelection;
#if !__TVOS__
UISearchBar searchBar;
#endif
UITableView tableView;
RootElement root;
bool pushing;
bool dirty;
bool reloading;
/// <summary>
/// The root element displayed by the DialogViewController, the value can be changed during runtime to update the contents.
/// </summary>
public RootElement Root {
get {
return root;
}
set {
if (root == value)
return;
if (root != null)
root.Dispose ();
root = value;
root.TableView = tableView;
ReloadData ();
}
}
EventHandler refreshRequested;
/// <summary>
/// If you assign a handler to this event before the view is shown, the
/// DialogViewController will have support for pull-to-refresh UI.
/// </summary>
public event EventHandler RefreshRequested {
add {
if (tableView != null)
throw new ArgumentException ("You should set the handler before the controller is shown");
refreshRequested += value;
}
remove {
refreshRequested -= value;
}
}
// If the value is true, we are enabled, used in the source for quick computation
bool enableSearch;
public bool EnableSearch {
get {
return enableSearch;
}
set {
if (enableSearch == value)
return;
// After MonoTouch 3.0, we can allow for the search to be enabled/disable
if (tableView != null)
throw new ArgumentException ("You should set EnableSearch before the controller is shown");
enableSearch = value;
}
}
// If set, we automatically scroll the content to avoid showing the search bar until
// the user manually pulls it down.
public bool AutoHideSearch { get; set; }
public string SearchPlaceholder { get; set; }
/// <summary>
/// Invoke this method to trigger a data refresh.
/// </summary>
/// <remarks>
/// This will invoke the RerfeshRequested event handler, the code attached to it
/// should start the background operation to fetch the data and when it completes
/// it should call ReloadComplete to restore the control state.
/// </remarks>
public void TriggerRefresh ()
{
TriggerRefresh (false);
}
void TriggerRefresh (bool showStatus)
{
if (refreshRequested == null)
return;
if (reloading)
return;
reloading = true;
refreshRequested (this, EventArgs.Empty);
}
/// <summary>
/// Invoke this method to signal that a reload has completed, this will update the UI accordingly.
/// </summary>
public void ReloadComplete ()
{
if (!reloading)
return;
reloading = false;
#if !__TVOS__
RefreshControl.EndRefreshing ();
#endif
}
/// <summary>
/// Controls whether the DialogViewController should auto rotate
/// </summary>
public bool Autorotate { get; set; }
#if !__TVOS__
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
return Autorotate || toInterfaceOrientation == UIInterfaceOrientation.Portrait;
}
public override void DidRotate (UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate (fromInterfaceOrientation);
//Fixes the RefreshView's size if it is shown during rotation
ReloadData ();
}
#endif
Section [] originalSections;
Element [][] originalElements;
/// <summary>
/// Allows caller to programatically activate the search bar and start the search process
/// </summary>
public void StartSearch ()
{
if (originalSections != null)
return;
#if !__TVOS__
searchBar.BecomeFirstResponder ();
#endif
originalSections = Root.Sections.ToArray ();
originalElements = new Element [originalSections.Length][];
for (int i = 0; i < originalSections.Length; i++)
originalElements [i] = originalSections [i].Elements.ToArray ();
}
/// <summary>
/// Allows the caller to programatically stop searching.
/// </summary>
public virtual void FinishSearch ()
{
if (originalSections == null)
return;
Root.Sections = new List<Section> (originalSections);
originalSections = null;
originalElements = null;
#if !__TVOS__
searchBar.ResignFirstResponder ();
#endif
ReloadData ();
}
public delegate void SearchTextEventHandler (object sender, SearchChangedEventArgs args);
public event SearchTextEventHandler SearchTextChanged;
public virtual void OnSearchTextChanged (string text)
{
if (SearchTextChanged != null)
SearchTextChanged (this, new SearchChangedEventArgs (text));
}
public void PerformFilter (string text)
{
if (originalSections == null)
return;
OnSearchTextChanged (text);
var newSections = new List<Section> ();
for (int sidx = 0; sidx < originalSections.Length; sidx++){
Section newSection = null;
var section = originalSections [sidx];
Element [] elements = originalElements [sidx];
for (int eidx = 0; eidx < elements.Length; eidx++){
if (elements [eidx].Matches (text)){
if (newSection == null){
newSection = new Section (section.Header, section.Footer){
FooterView = section.FooterView,
HeaderView = section.HeaderView
};
newSections.Add (newSection);
}
newSection.Add (elements [eidx]);
}
}
}
Root.Sections = newSections;
ReloadData ();
}
public virtual void SearchButtonClicked (string text)
{
}
class SearchDelegate : UISearchBarDelegate {
DialogViewController container;
public SearchDelegate (DialogViewController container)
{
this.container = container;
}
public override void OnEditingStarted (UISearchBar searchBar)
{
#if !__TVOS__
searchBar.ShowsCancelButton = true;
#endif
container.StartSearch ();
}
public override void OnEditingStopped (UISearchBar searchBar)
{
#if !__TVOS__
searchBar.ShowsCancelButton = false;
#endif
container.FinishSearch ();
}
public override void TextChanged (UISearchBar searchBar, string searchText)
{
container.PerformFilter (searchText ?? "");
}
#if !__TVOS__
public override void CancelButtonClicked (UISearchBar searchBar)
{
searchBar.ShowsCancelButton = false;
container.searchBar.Text = "";
container.FinishSearch ();
searchBar.ResignFirstResponder ();
}
#endif
public override void SearchButtonClicked (UISearchBar searchBar)
{
container.SearchButtonClicked (searchBar.Text);
}
}
public class Source : UITableViewSource {
const float yboundary = 65;
WeakReference<DialogViewController> container;
protected DialogViewController Container => container.TryGetTarget (out var result) ? result : null;
protected RootElement Root;
bool checkForRefresh;
public Source (DialogViewController container)
{
this.container = new WeakReference<DialogViewController> (container);
Root = container.root;
}
public override void AccessoryButtonTapped (UITableView tableView, NSIndexPath indexPath)
{
var section = Root.Sections [(int) indexPath.Section];
var element = (section.Elements [(int) indexPath.Row] as StyledStringElement);
if (element != null)
element.AccessoryTap ();
}
public override nint RowsInSection (UITableView tableview, nint section)
{
var s = Root.Sections [(int) section];
var count = s.Elements.Count;
return count;
}
public override nint NumberOfSections (UITableView tableView)
{
return Root.Sections.Count;
}
public override string TitleForHeader (UITableView tableView, nint section)
{
return Root.Sections [(int) section].Caption;
}
public override string TitleForFooter (UITableView tableView, nint section)
{
return Root.Sections [(int) section].Footer;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
var section = Root.Sections [(int) indexPath.Section];
var element = section.Elements [(int) indexPath.Row];
return element.GetCell (tableView);
}
public override void WillDisplay (UITableView tableView, UITableViewCell cell, NSIndexPath indexPath)
{
if (Root.NeedColorUpdate){
var section = Root.Sections [(int) indexPath.Section];
var element = section.Elements [(int) indexPath.Row];
var colorized = element as IColorizeBackground;
if (colorized != null)
colorized.WillDisplay (tableView, cell, indexPath);
}
}
public override void RowDeselected (UITableView tableView, NSIndexPath indexPath)
{
Container.Deselected (indexPath);
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
var onSelection = Container.OnSelection;
if (onSelection != null)
onSelection (indexPath);
Container.Selected (indexPath);
}
public override UIView GetViewForHeader (UITableView tableView, nint sectionIdx)
{
var section = Root.Sections [(int) sectionIdx];
return section.HeaderView;
}
public override nfloat GetHeightForHeader (UITableView tableView, nint sectionIdx)
{
var section = Root.Sections [(int) sectionIdx];
if (section.HeaderView == null)
return -1;
return section.HeaderView.Frame.Height;
}
public override UIView GetViewForFooter (UITableView tableView, nint sectionIdx)
{
var section = Root.Sections [(int) sectionIdx];
return section.FooterView;
}
public override nfloat GetHeightForFooter (UITableView tableView, nint sectionIdx)
{
var section = Root.Sections [(int) sectionIdx];
if (section.FooterView == null)
return -1;
return section.FooterView.Frame.Height;
}
public override void Scrolled (UIScrollView scrollView)
{
}
public override void DraggingStarted (UIScrollView scrollView)
{
}
public override void DraggingEnded (UIScrollView scrollView, bool willDecelerate)
{
}
}
//
// Performance trick, if we expose GetHeightForRow, the UITableView will
// probe *every* row for its size; Avoid this by creating a separate
// model that is used only when we have items that require resizing
//
public class SizingSource : Source {
public SizingSource (DialogViewController controller) : base (controller) {}
public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
{
var section = Root.Sections [(int) indexPath.Section];
var element = section.Elements [(int) indexPath.Row];
var sizable = element as IElementSizing;
if (sizable == null)
return (nfloat)tableView.RowHeight;
return sizable.GetHeight (tableView, indexPath);
}
}
/// <summary>
/// Activates a nested view controller from the DialogViewController.
/// If the view controller is hosted in a UINavigationController it
/// will push the result. Otherwise it will show it as a modal
/// dialog
/// </summary>
public void ActivateController (UIViewController controller)
{
dirty = true;
var parent = ParentViewController;
var nav = parent as UINavigationController;
// We can not push a nav controller into a nav controller
if (nav != null && !(controller is UINavigationController))
nav.PushViewController (controller, true);
else {
#if __TVOS__
PresentViewController (controller, true, null);
#else
PresentModalViewController (controller, true);
#endif
}
}
/// <summary>
/// Dismisses the view controller. It either pops or dismisses
/// based on the kind of container we are hosted in.
/// </summary>
public void DeactivateController (bool animated)
{
var parent = ParentViewController;
var nav = parent as UINavigationController;
if (nav != null)
nav.PopViewController (animated);
else {
#if __TVOS__
DismissViewController (animated, null);
#else
DismissModalViewController (animated);
#endif
}
}
void SetupSearch ()
{
#if __TVOS__
// Can't create a UISearchBar in tvOS, you can only use one from a UISearchController,
// which require bigger changes, so just skip this for now.
#else
if (enableSearch){
searchBar = new UISearchBar (new CGRect (0, 0, tableView.Bounds.Width, 44)) {
Delegate = new SearchDelegate (this)
};
if (SearchPlaceholder != null)
searchBar.Placeholder = this.SearchPlaceholder;
tableView.TableHeaderView = searchBar;
} else {
// Does not work with current Monotouch, will work with 3.0
// tableView.TableHeaderView = null;
}
#endif
}
public virtual void Deselected (NSIndexPath indexPath)
{
var section = root.Sections [(int) indexPath.Section];
var element = section.Elements [(int) indexPath.Row];
element.Deselected (this, tableView, indexPath);
}
public virtual void Selected (NSIndexPath indexPath)
{
var section = root.Sections [(int) indexPath.Section];
var element = section.Elements [(int) indexPath.Row];
element.Selected (this, tableView, indexPath);
}
public virtual UITableView MakeTableView (CGRect bounds, UITableViewStyle style)
{
return new UITableView (bounds, style);
}
public override void LoadView ()
{
tableView = MakeTableView (UIScreen.MainScreen.Bounds, Style);
tableView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin;
tableView.AutosizesSubviews = true;
if (root != null)
root.Prepare ();
UpdateSource ();
View = tableView;
SetupSearch ();
ConfigureTableView ();
if (root == null)
return;
root.TableView = tableView;
}
void ConfigureTableView ()
{
#if !__TVOS__
if (refreshRequested != null) {
RefreshControl = new UIRefreshControl ();
RefreshControl.AddTarget ((sender,args)=> TriggerRefresh (), UIControlEvent.ValueChanged);
return;
}
#endif
}
public event EventHandler ViewAppearing;
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
if (AutoHideSearch){
if (enableSearch){
if (TableView.ContentOffset.Y < 44)
TableView.ContentOffset = new CGPoint (0, 44);
}
}
if (root == null)
return;
root.Prepare ();
#if !__TVOS__
NavigationItem.HidesBackButton = !pushing;
#endif
if (root.Caption != null)
NavigationItem.Title = root.Caption;
if (dirty){
tableView.ReloadData ();
dirty = false;
}
if (ViewAppearing != null)
ViewAppearing (this, EventArgs.Empty);
}
public bool Pushing {
get {
return pushing;
}
set {
pushing = value;
#if !__TVOS__
if (NavigationItem != null)
NavigationItem.HidesBackButton = !pushing;
#endif
}
}
public virtual Source CreateSizingSource (bool unevenRows)
{
return unevenRows ? new SizingSource (this) : new Source (this);
}
Source TableSource;
void UpdateSource ()
{
if (root == null)
return;
TableSource = CreateSizingSource (root.UnevenRows);
tableView.Source = TableSource;
}
public void ReloadData ()
{
if (root == null)
return;
if(root.Caption != null)
NavigationItem.Title = root.Caption;
root.Prepare ();
if (tableView != null){
UpdateSource ();
tableView.ReloadData ();
}
dirty = false;
}
public event EventHandler ViewDisappearing;
[Obsolete ("Use the ViewDisappearing event instead")]
public event EventHandler ViewDissapearing {
add {
ViewDisappearing += value;
}
remove {
ViewDisappearing -= value;
}
}
public override void ViewWillDisappear (bool animated)
{
base.ViewWillDisappear (animated);
if (ViewDisappearing != null)
ViewDisappearing (this, EventArgs.Empty);
}
public DialogViewController (RootElement root) : base (UITableViewStyle.Grouped)
{
this.root = root;
}
public DialogViewController (UITableViewStyle style, RootElement root) : base (style)
{
Style = style;
this.root = root;
}
/// <summary>
/// Creates a new DialogViewController from a RootElement and sets the push status
/// </summary>
/// <param name="root">
/// The <see cref="RootElement"/> containing the information to render.
/// </param>
/// <param name="pushing">
/// A <see cref="System.Boolean"/> describing whether this is being pushed
/// (NavigationControllers) or not. If pushing is true, then the back button
/// will be shown, allowing the user to go back to the previous controller
/// </param>
public DialogViewController (RootElement root, bool pushing) : base (UITableViewStyle.Grouped)
{
this.pushing = pushing;
this.root = root;
}
public DialogViewController (UITableViewStyle style, RootElement root, bool pushing) : base (style)
{
Style = style;
this.pushing = pushing;
this.root = root;
}
public DialogViewController (IntPtr handle) : base(handle)
{
this.root = new RootElement ("");
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QuantConnect.Brokerages.Bitfinex.Messages;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Packets;
using QuantConnect.Securities;
using QuantConnect.Securities.Crypto;
using QuantConnect.Util;
using RestSharp;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Order = QuantConnect.Orders.Order;
namespace QuantConnect.Brokerages.Bitfinex
{
/// <summary>
/// Bitfinex Brokerage implementation
/// </summary>
public partial class BitfinexBrokerage
{
private const string ApiVersion = "v2";
private const string RestApiUrl = "https://api.bitfinex.com";
private const string WebSocketUrl = "wss://api.bitfinex.com/ws/2";
private LiveNodePacket _job;
private IAlgorithm _algorithm;
private readonly RateGate _restRateLimiter = new RateGate(10, TimeSpan.FromMinutes(1));
private readonly ConcurrentDictionary<int, decimal> _fills = new ConcurrentDictionary<int, decimal>();
private SymbolPropertiesDatabase _symbolPropertiesDatabase;
private IDataAggregator _aggregator;
// map Bitfinex ClientOrderId -> LEAN order (only used for orders submitted in PlaceOrder, not for existing orders)
private readonly ConcurrentDictionary<long, Order> _orderMap = new ConcurrentDictionary<long, Order>();
private readonly object _clientOrderIdLocker = new object();
private long _nextClientOrderId;
// map Bitfinex currency to LEAN currency
private Dictionary<string, string> _currencyMap;
/// <summary>
/// Locking object for the Ticks list in the data queue handler
/// </summary>
public readonly object TickLocker = new object();
/// <summary>
/// Constructor for brokerage
/// </summary>
public BitfinexBrokerage() : base("Bitfinex")
{
}
/// <summary>
/// Constructor for brokerage
/// </summary>
/// <param name="apiKey">api key</param>
/// <param name="apiSecret">api secret</param>
/// <param name="algorithm">the algorithm instance is required to retrieve account type</param>
/// <param name="priceProvider">The price provider for missing FX conversion rates</param>
/// <param name="aggregator">consolidate ticks</param>
/// <param name="job">The live job packet</param>
public BitfinexBrokerage(string apiKey, string apiSecret, IAlgorithm algorithm, IPriceProvider priceProvider, IDataAggregator aggregator, LiveNodePacket job)
: this(new WebSocketClientWrapper(), new RestClient(RestApiUrl), apiKey, apiSecret, algorithm, priceProvider, aggregator, job)
{
}
/// <summary>
/// Constructor for brokerage
/// </summary>
/// <param name="websocket">instance of websockets client</param>
/// <param name="restClient">instance of rest client</param>
/// <param name="apiKey">api key</param>
/// <param name="apiSecret">api secret</param>
/// <param name="algorithm">the algorithm instance is required to retrieve account type</param>
/// <param name="priceProvider">The price provider for missing FX conversion rates</param>
/// <param name="aggregator">consolidate ticks</param>
/// <param name="job">The live job packet</param>
public BitfinexBrokerage(IWebSocket websocket, IRestClient restClient, string apiKey, string apiSecret, IAlgorithm algorithm, IPriceProvider priceProvider, IDataAggregator aggregator, LiveNodePacket job)
: base("Bitfinex")
{
Initialize(
wssUrl: WebSocketUrl,
websocket: websocket,
restClient: restClient,
apiKey: apiKey,
apiSecret: apiSecret,
algorithm: algorithm,
aggregator: aggregator,
job: job
);
}
/// <summary>
/// Wss message handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected override void OnMessage(object sender, WebSocketMessage e)
{
OnMessageImpl(e);
}
/// <summary>
/// Subscribes to the authenticated channels (using an single streaming channel)
/// </summary>
public void SubscribeAuth()
{
if (string.IsNullOrEmpty(ApiKey) || string.IsNullOrEmpty(ApiSecret))
return;
var authNonce = GetNonce();
var authPayload = "AUTH" + authNonce;
var authSig = AuthenticationToken(authPayload);
WebSocket.Send(JsonConvert.SerializeObject(new
{
@event = "auth",
apiKey = ApiKey,
authNonce,
authPayload,
authSig
}));
Log.Trace("BitfinexBrokerage.SubscribeAuth(): Sent authentication request.");
}
/// <summary>
/// Should be empty, Bitfinex brokerage manages his public channels including subscribe/unsubscribe/reconnect methods using <see cref="BrokerageMultiWebSocketSubscriptionManager"/>
/// Not used in master
/// </summary>
/// <param name="symbols"></param>
protected override bool Subscribe(IEnumerable<Symbol> symbols)
{
return true;
}
/// <summary>
/// Initialize the instance of this class
/// </summary>
/// <param name="wssUrl">The web socket base url</param>
/// <param name="websocket">instance of websockets client</param>
/// <param name="restClient">instance of rest client</param>
/// <param name="apiKey">api key</param>
/// <param name="apiSecret">api secret</param>
/// <param name="algorithm">the algorithm instance is required to retrieve account type</param>
/// <param name="aggregator">the aggregator for consolidating ticks</param>
/// <param name="job">The live job packet</param>
private void Initialize(string wssUrl, IWebSocket websocket, IRestClient restClient, string apiKey,
string apiSecret, IAlgorithm algorithm, IDataAggregator aggregator, LiveNodePacket job)
{
if (IsInitialized)
{
return;
}
base.Initialize(wssUrl, websocket, restClient, apiKey, apiSecret);
_job = job;
SubscriptionManager = new BrokerageMultiWebSocketSubscriptionManager(
WebSocketUrl,
MaximumSymbolsPerConnection,
0,
null,
() => new BitfinexWebSocketWrapper(null),
Subscribe,
Unsubscribe,
OnDataMessage,
TimeSpan.Zero,
_connectionRateLimiter);
_symbolPropertiesDatabase = SymbolPropertiesDatabase.FromDataFolder();
_algorithm = algorithm;
_aggregator = aggregator;
// load currency map
using (var wc = new WebClient())
{
var json = wc.DownloadString("https://api-pub.bitfinex.com/v2/conf/pub:map:currency:sym");
var rows = JsonConvert.DeserializeObject<List<List<List<string>>>>(json)[0];
_currencyMap = rows
.ToDictionary(row => row[0], row => row[1].ToUpperInvariant());
}
WebSocket.Open += (sender, args) =>
{
SubscribeAuth();
};
}
private long GetNextClientOrderId()
{
lock (_clientOrderIdLocker)
{
// ensure unique id
var id = Convert.ToInt64(Time.DateTimeToUnixTimeStampMilliseconds(DateTime.UtcNow));
if (id > _nextClientOrderId)
{
_nextClientOrderId = id;
}
else
{
_nextClientOrderId++;
}
}
return _nextClientOrderId;
}
/// <summary>
/// Implementation of the OnMessage event
/// </summary>
/// <param name="e"></param>
private void OnMessageImpl(WebSocketMessage webSocketMessage)
{
var e = (WebSocketClientWrapper.TextMessage)webSocketMessage.Data;
try
{
var token = JToken.Parse(e.Message);
if (token is JArray)
{
var channel = token[0].ToObject<int>();
// heartbeat
if (token[1].Type == JTokenType.String && token[1].Value<string>() == "hb")
{
return;
}
// account information channel
if (channel == 0)
{
var term = token[1].ToObject<string>();
switch (term.ToLowerInvariant())
{
// order closed
case "oc":
OnOrderClose(token[2].ToObject<Messages.Order>());
return;
// trade execution update
case "tu":
EmitFillOrder(token[2].ToObject<TradeExecutionUpdate>());
return;
// notification
case "n":
var notification = token[2];
var status = notification[6].ToString();
if (status == "ERROR")
{
var errorMessage = notification[7].ToString();
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, $"Error: {errorMessage}"));
OnOrderError(notification[4].ToObject<Messages.Order>());
}
else if (status == "SUCCESS")
{
var type = notification[1].ToString();
if (type == "on-req")
{
OnOrderNew(notification[4].ToObject<Messages.Order>());
}
else if (type == "ou-req")
{
OnOrderUpdate(notification[4].ToObject<Messages.Order>());
}
}
return;
default:
return;
}
}
}
else if (token is JObject)
{
var raw = token.ToObject<BaseMessage>();
switch (raw.Event.ToLowerInvariant())
{
case "auth":
var auth = token.ToObject<AuthResponseMessage>();
var result = string.Equals(auth.Status, "OK", StringComparison.OrdinalIgnoreCase) ? "successful" : "failed";
Log.Trace($"BitfinexBrokerage.OnMessage: Subscribing to authenticated channels {result}");
return;
case "info":
case "ping":
return;
case "error":
var error = token.ToObject<ErrorMessage>();
Log.Error($"BitfinexBrokerage.OnMessage: {error.Level}: {error.Message}");
return;
default:
Log.Error($"BitfinexBrokerage.OnMessage: Unexpected message format: {e.Message}");
break;
}
}
}
catch (Exception exception)
{
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, $"Parsing wss message failed. Data: {e.Message} Exception: {exception}"));
throw;
}
}
private void OnOrderError(Messages.Order bitfinexOrder)
{
Order order;
if (_orderMap.TryGetValue(bitfinexOrder.ClientOrderId, out order))
{
OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero, "Bitfinex Order Event")
{
Status = OrderStatus.Invalid
});
}
}
private void OnOrderNew(Messages.Order bitfinexOrder)
{
if (bitfinexOrder.Status == "ACTIVE")
{
var brokerId = bitfinexOrder.Id.ToStringInvariant();
Order order;
if (_orderMap.TryGetValue(bitfinexOrder.ClientOrderId, out order))
{
if (CachedOrderIDs.ContainsKey(order.Id))
{
CachedOrderIDs[order.Id].BrokerId.Clear();
CachedOrderIDs[order.Id].BrokerId.Add(brokerId);
}
else
{
order.BrokerId.Add(brokerId);
CachedOrderIDs.TryAdd(order.Id, order);
}
OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero, "Bitfinex Order Event")
{
Status = OrderStatus.Submitted
});
}
}
}
private void OnOrderUpdate(Messages.Order bitfinexOrder)
{
if (bitfinexOrder.Status == "ACTIVE")
{
var brokerId = bitfinexOrder.Id.ToStringInvariant();
var order = CachedOrderIDs
.FirstOrDefault(o => o.Value.BrokerId.Contains(brokerId))
.Value;
if (order == null)
{
order = _algorithm.Transactions.GetOrderByBrokerageId(brokerId);
if (order == null)
{
Log.Error($"OnOrderUpdate(): order not found: BrokerId: {brokerId}");
return;
}
}
OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero, "Bitfinex Order Event")
{
Status = OrderStatus.UpdateSubmitted
});
}
}
private void OnOrderClose(Messages.Order bitfinexOrder)
{
if (bitfinexOrder.Status.StartsWith("CANCELED"))
{
var brokerId = bitfinexOrder.Id.ToStringInvariant();
var order = CachedOrderIDs
.FirstOrDefault(o => o.Value.BrokerId.Contains(brokerId))
.Value;
if (order == null)
{
order = _algorithm.Transactions.GetOrderByBrokerageId(brokerId);
if (order == null)
{
Log.Error($"OnOrderClose(): order not found: BrokerId: {brokerId}");
return;
}
}
else
{
Order outOrder;
CachedOrderIDs.TryRemove(order.Id, out outOrder);
}
if (bitfinexOrder.ClientOrderId > 0)
{
Order removed;
_orderMap.TryRemove(bitfinexOrder.ClientOrderId, out removed);
}
OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero, "Bitfinex Order Event")
{
Status = OrderStatus.Canceled
});
}
}
private void EmitFillOrder(TradeExecutionUpdate update)
{
try
{
var brokerId = update.OrderId.ToStringInvariant();
var order = CachedOrderIDs
.FirstOrDefault(o => o.Value.BrokerId.Contains(brokerId))
.Value;
if (order == null)
{
order = _algorithm.Transactions.GetOrderByBrokerageId(brokerId);
if (order == null)
{
Log.Error($"BitfinexBrokerage.EmitFillOrder(): order not found: BrokerId: {brokerId}");
return;
}
}
var symbol = _symbolMapper.GetLeanSymbol(update.Symbol, SecurityType.Crypto, Market.Bitfinex);
var fillPrice = update.ExecPrice;
var fillQuantity = update.ExecAmount;
var direction = fillQuantity < 0 ? OrderDirection.Sell : OrderDirection.Buy;
var updTime = Time.UnixMillisecondTimeStampToDateTime(update.MtsCreate);
var orderFee = new OrderFee(new CashAmount(Math.Abs(update.Fee), GetLeanCurrency(update.FeeCurrency)));
var status = OrderStatus.Filled;
if (fillQuantity != order.Quantity)
{
decimal totalFillQuantity;
_fills.TryGetValue(order.Id, out totalFillQuantity);
totalFillQuantity += fillQuantity;
_fills[order.Id] = totalFillQuantity;
status = totalFillQuantity == order.Quantity
? OrderStatus.Filled
: OrderStatus.PartiallyFilled;
}
if (_algorithm.BrokerageModel.AccountType == AccountType.Cash &&
order.Direction == OrderDirection.Buy)
{
var symbolProperties = _symbolPropertiesDatabase.GetSymbolProperties(symbol.ID.Market,
symbol,
symbol.SecurityType,
AccountBaseCurrency);
Crypto.DecomposeCurrencyPair(symbol, symbolProperties, out var baseCurrency, out var _);
if (orderFee.Value.Currency != baseCurrency)
{
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, "UnexpectedFeeCurrency", $"Unexpected fee currency {orderFee.Value.Currency} for symbol {symbol}. OrderId {order.Id}. BrokerageOrderId {brokerId}. " +
"This error can happen because your account is Margin type and Lean is configured to be Cash type or while using Cash type the Bitfinex account fee settings are set to 'Asset Trading Fee' and should be set to 'Currency Exchange Fee'."));
}
else
{
// fees are debited in the base currency, so we have to subtract them from the filled quantity
fillQuantity -= orderFee.Value.Amount;
orderFee = new ModifiedFillQuantityOrderFee(orderFee.Value);
}
}
var orderEvent = new OrderEvent
(
order.Id, symbol, updTime, status,
direction, fillPrice, fillQuantity,
orderFee, $"Bitfinex Order Event {direction}"
);
// if the order is closed, we no longer need it in the active order list
if (status == OrderStatus.Filled)
{
Order outOrder;
CachedOrderIDs.TryRemove(order.Id, out outOrder);
decimal ignored;
_fills.TryRemove(order.Id, out ignored);
var clientOrderId = _orderMap.FirstOrDefault(x => x.Value.BrokerId.Contains(brokerId)).Key;
if (clientOrderId > 0)
{
_orderMap.TryRemove(clientOrderId, out outOrder);
}
}
OnOrderEvent(orderEvent);
}
catch (Exception e)
{
Log.Error(e);
throw;
}
}
private string GetLeanCurrency(string brokerageCurrency)
{
string currency;
if (!_currencyMap.TryGetValue(brokerageCurrency.ToUpperInvariant(), out currency))
{
currency = brokerageCurrency.ToUpperInvariant();
}
return currency;
}
/// <summary>
/// Emit stream tick
/// </summary>
/// <param name="tick"></param>
private void EmitTick(Tick tick)
{
lock (TickLocker)
{
_aggregator.Update(tick);
}
}
/// <summary>
/// Should be empty. <see cref="BrokerageMultiWebSocketSubscriptionManager"/> manages each <see cref="BitfinexWebSocketWrapper"/> individually
/// </summary>
/// <returns></returns>
protected override IEnumerable<Symbol> GetSubscribed() => new List<Symbol>();
}
}
| |
using CongressCollector.Models.Cleaned;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace CongressCollector.Models.Original
{
[XmlRoot(ElementName = "sourceSystem")]
public class SourceSystem
{
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "code")]
public string Code { get; set; }
}
[XmlRoot(ElementName = "link")]
public class Link
{
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "url")]
public string Url { get; set; }
}
[XmlRoot(ElementName = "links")]
public class Links : IItemized<Link>
{
[XmlElement(ElementName = "link")]
public List<Link> Items { get; set; }
}
[XmlRoot(ElementName = "item")]
public class Item
{
[XmlElement(ElementName = "calendar")]
public string Calendar { get; set; }
[XmlElement(ElementName = "sourceSystem")]
public SourceSystem SourceSystem { get; set; }
[XmlElement(ElementName = "text")]
public string Text { get; set; }
[XmlElement(ElementName = "actionDate")]
public string ActionDate { get; set; }
[XmlElement(ElementName = "type")]
public string Type { get; set; }
[XmlElement(ElementName = "links")]
public Links Links { get; set; }
[XmlElement(ElementName = "actionCode")]
public string ActionCode { get; set; }
[XmlElement(ElementName = "actionTime")]
public string ActionTime { get; set; }
[XmlElement(ElementName = "committee")]
public Committee Committee { get; set; }
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "state")]
public string State { get; set; }
[XmlElement(ElementName = "bioguideId")]
public string BioguideId { get; set; }
[XmlElement(ElementName = "party")]
public string Party { get; set; }
[XmlElement(ElementName = "middleName")]
public string MiddleName { get; set; }
[XmlElement(ElementName = "fullName")]
public string FullName { get; set; }
[XmlElement(ElementName = "lastName")]
public string LastName { get; set; }
[XmlElement(ElementName = "firstName")]
public string FirstName { get; set; }
[XmlElement(ElementName = "url")]
public string Url { get; set; }
[XmlElement(ElementName = "pubDate")]
public string PubDate { get; set; }
[XmlElement(ElementName = "title")]
public string Title { get; set; }
[XmlElement(ElementName = "number")]
public string Number { get; set; }
[XmlElement(ElementName = "byRequestType")]
public string ByRequestType { get; set; }
[XmlElement(ElementName = "identifiers")]
public Identifiers Identifiers { get; set; }
[XmlElement(ElementName = "district")]
public string District { get; set; }
[XmlElement(ElementName = "chamber")]
public string Chamber { get; set; }
[XmlElement(ElementName = "activities")]
public Activities Activities { get; set; }
[XmlElement(ElementName = "systemCode")]
public string SystemCode { get; set; }
[XmlElement(ElementName = "subcommittees")]
public Subcommittees Subcommittees { get; set; }
[XmlElement(ElementName = "sponsorshipDate")]
public string SponsorshipDate { get; set; }
[XmlElement(ElementName = "isOriginalCosponsor")]
public string IsOriginalCosponsor { get; set; }
[XmlElement(ElementName = "sponsorshipWithdrawnDate")]
public string SponsorshipWithdrawnDate { get; set; }
[XmlElement(ElementName = "latestTitle")]
public string LatestTitle { get; set; }
[XmlElement(ElementName = "relationshipDetails")]
public RelationshipDetails RelationshipDetails { get; set; }
[XmlElement(ElementName = "congress")]
public string Congress { get; set; }
[XmlElement(ElementName = "latestAction")]
public LatestAction LatestAction { get; set; }
[XmlElement(ElementName = "updateDate")]
public string UpdateDate { get; set; }
[XmlElement(ElementName = "actionDesc")]
public string ActionDesc { get; set; }
[XmlElement(ElementName = "versionCode")]
public string VersionCode { get; set; }
[XmlElement(ElementName = "lastSummaryUpdateDate")]
public string LastSummaryUpdateDate { get; set; }
[XmlElement(ElementName = "titleType")]
public string TitleType { get; set; }
[XmlElement(ElementName = "parentTitleType")]
public string ParentTitleType { get; set; }
[XmlElement(ElementName = "chamberCode")]
public string ChamberCode { get; set; }
[XmlElement(ElementName = "chamberName")]
public string ChamberName { get; set; }
[XmlElement(ElementName = "date")]
public string Date { get; set; }
[XmlElement(ElementName = "identifiedBy")]
public string IdentifiedBy { get; set; }
}
[XmlRoot(ElementName = "committee")]
public class Committee
{
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "systemCode")]
public string SystemCode { get; set; }
}
[XmlRoot(ElementName = "actionTypeCounts")]
public class ActionTypeCounts
{
[XmlElement(ElementName = "measureLaidBeforeSenate")]
public string MeasureLaidBeforeSenate { get; set; }
[XmlElement(ElementName = "passageOfAMeasure")]
public string PassageOfAMeasure { get; set; }
[XmlElement(ElementName = "ruleForConsiderationOfBillReportedToHouse")]
public string RuleForConsiderationOfBillReportedToHouse { get; set; }
[XmlElement(ElementName = "motionToWaiveMeasure")]
public string MotionToWaiveMeasure { get; set; }
[XmlElement(ElementName = "introducedInTheHouse")]
public string IntroducedInTheHouse { get; set; }
[XmlElement(ElementName = "motionToReconsiderResults")]
public string MotionToReconsiderResults { get; set; }
[XmlElement(ElementName = "passedAgreedToInHouse")]
public string PassedAgreedToInHouse { get; set; }
[XmlElement(ElementName = "pointOfOrderMeasure")]
public string PointOfOrderMeasure { get; set; }
[XmlElement(ElementName = "placeholderTextForE")]
public string PlaceholderTextForE { get; set; }
[XmlElement(ElementName = "presentedToPresident")]
public string PresentedToPresident { get; set; }
[XmlElement(ElementName = "introducedInSenate")]
public string IntroducedInSenate { get; set; }
[XmlElement(ElementName = "motionForPreviousQuestion")]
public string MotionForPreviousQuestion { get; set; }
[XmlElement(ElementName = "becamePublicLaw")]
public string BecamePublicLaw { get; set; }
[XmlElement(ElementName = "considerationByHouse")]
public string ConsiderationByHouse { get; set; }
[XmlElement(ElementName = "passedAgreedToInSenate")]
public string PassedAgreedToInSenate { get; set; }
[XmlElement(ElementName = "introducedInHouse")]
public string IntroducedInHouse { get; set; }
[XmlElement(ElementName = "placeholderTextForH")]
public string PlaceholderTextForH { get; set; }
[XmlElement(ElementName = "generalDebate")]
public string GeneralDebate { get; set; }
[XmlElement(ElementName = "placeholderTextForHL")]
public string PlaceholderTextForHL { get; set; }
[XmlElement(ElementName = "passedSenate")]
public string PassedSenate { get; set; }
[XmlElement(ElementName = "billReferralsAggregate")]
public string BillReferralsAggregate { get; set; }
[XmlElement(ElementName = "sentToHouse")]
public string SentToHouse { get; set; }
[XmlElement(ElementName = "billReferrals")]
public string BillReferrals { get; set; }
[XmlElement(ElementName = "houseAmendmentOffered")]
public string HouseAmendmentOffered { get; set; }
[XmlElement(ElementName = "pointOfOrderAmendment")]
public string PointOfOrderAmendment { get; set; }
[XmlElement(ElementName = "motionToWaiveAmendment")]
public string MotionToWaiveAmendment { get; set; }
[XmlElement(ElementName = "senateAmendmentProposedOnTheFloor")]
public string SenateAmendmentProposedOnTheFloor { get; set; }
[XmlElement(ElementName = "senateAmendmentSubmitted")]
public string SenateAmendmentSubmitted { get; set; }
[XmlElement(ElementName = "amendmentProposed")]
public string AmendmentProposed { get; set; }
[XmlElement(ElementName = "rollCallVotesOnAmendmentsInSenate")]
public string RollCallVotesOnAmendmentsInSenate { get; set; }
[XmlElement(ElementName = "rulingInSenate")]
public string RulingInSenate { get; set; }
[XmlElement(ElementName = "senateAmendmentNotAgreedTo")]
public string SenateAmendmentNotAgreedTo { get; set; }
[XmlElement(ElementName = "amendmentNotAgreedTo")]
public string AmendmentNotAgreedTo { get; set; }
}
[XmlRoot(ElementName = "actionByCounts")]
public class ActionByCounts
{
[XmlElement(ElementName = "senate")]
public string Senate { get; set; }
[XmlElement(ElementName = "houseOfRepresentatives")]
public string HouseOfRepresentatives { get; set; }
}
[XmlRoot(ElementName = "actions")]
public class Actions : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
[XmlElement(ElementName = "actionTypeCounts")]
public ActionTypeCounts ActionTypeCounts { get; set; }
[XmlElement(ElementName = "actionByCounts")]
public ActionByCounts ActionByCounts { get; set; }
[XmlElement(ElementName = "count")]
public string Count { get; set; }
[XmlElement(ElementName = "actions")]
public Actions InnerActions { get; set; }
}
[XmlRoot(ElementName = "cosponsors")]
public class Cosponsors : IItemized<Item>
{
[XmlElement(ElementName = "totalCount")]
public string TotalCount { get; set; }
[XmlElement(ElementName = "currentCount")]
public string CurrentCount { get; set; }
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "sponsors")]
public class Sponsors : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "amendments")]
public class Amendments : IItemized<Amendment>
{
[XmlElement(ElementName = "amendment")]
public List<Amendment> Items { get; set; }
}
[XmlRoot(ElementName = "amendedBill")]
public class AmendedBill
{
[XmlElement(ElementName = "originChamberCode")]
public string OriginChamberCode { get; set; }
[XmlElement(ElementName = "congress")]
public string Congress { get; set; }
[XmlElement(ElementName = "number")]
public string Number { get; set; }
[XmlElement(ElementName = "originChamber")]
public string OriginChamber { get; set; }
[XmlElement(ElementName = "title")]
public string Title { get; set; }
[XmlElement(ElementName = "type")]
public string Type { get; set; }
}
[XmlRoot(ElementName = "amendment")]
public class Amendment
{
[XmlElement(ElementName = "description")]
public List<string> Description { get; set; }
[XmlElement(ElementName = "congress")]
public List<string> Congress { get; set; }
[XmlElement(ElementName = "number")]
public List<string> Number { get; set; }
[XmlElement(ElementName = "titles")]
public Titles Titles { get; set; }
[XmlElement(ElementName = "cosponsors")]
public Cosponsors Cosponsors { get; set; }
[XmlElement(ElementName = "sponsors")]
public Sponsors Sponsors { get; set; }
[XmlElement(ElementName = "purpose")]
public List<string> Purpose { get; set; }
[XmlElement(ElementName = "updateDate")]
public string UpdateDate { get; set; }
[XmlElement(ElementName = "type")]
public List<string> Type { get; set; }
[XmlElement(ElementName = "notes")]
public Notes Notes { get; set; }
[XmlElement(ElementName = "proposedDate")]
public string ProposedDate { get; set; }
[XmlElement(ElementName = "amendments")]
public Amendments Amendments { get; set; }
[XmlElement(ElementName = "submittedDate")]
public string SubmittedDate { get; set; }
[XmlElement(ElementName = "createDate")]
public string CreateDate { get; set; }
[XmlElement(ElementName = "actions")]
public Actions Actions { get; set; }
[XmlElement(ElementName = "amendedAmendment")]
public AmendedAmendment AmendedAmendment { get; set; }
[XmlElement(ElementName = "links")]
public Links Links { get; set; }
[XmlElement(ElementName = "amendedBill")]
public AmendedBill AmendedBill { get; set; }
[XmlElement(ElementName = "chamber")]
public string Chamber { get; set; }
[XmlElement(ElementName = "latestAction")]
public LatestAction LatestAction { get; set; }
}
[XmlRoot(ElementName = "amendedAmendment")]
public class AmendedAmendment
{
[XmlElement(ElementName = "purpose")]
public string Purpose { get; set; }
[XmlElement(ElementName = "number")]
public string Number { get; set; }
[XmlElement(ElementName = "congress")]
public string Congress { get; set; }
[XmlElement(ElementName = "type")]
public string Type { get; set; }
[XmlElement(ElementName = "description")]
public string Description { get; set; }
}
[XmlRoot(ElementName = "titles")]
public class Titles : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "latestAction")]
public class LatestAction
{
[XmlElement(ElementName = "actionDate")]
public string ActionDate { get; set; }
[XmlElement(ElementName = "text")]
public string Text { get; set; }
[XmlElement(ElementName = "links")]
public Links Links { get; set; }
[XmlElement(ElementName = "actionTime")]
public string ActionTime { get; set; }
}
[XmlRoot(ElementName = "cboCostEstimates")]
public class CboCostEstimates : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "laws")]
public class Laws : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "legislativeSubjects")]
public class LegislativeSubjects : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "policyArea")]
public class PolicyArea
{
[XmlElement(ElementName = "name")]
public string Name { get; set; }
}
[XmlRoot(ElementName = "billSubjects")]
public class BillSubjects
{
[XmlElement(ElementName = "legislativeSubjects")]
public LegislativeSubjects LegislativeSubjects { get; set; }
[XmlElement(ElementName = "policyArea")]
public PolicyArea PolicyArea { get; set; }
}
[XmlRoot(ElementName = "subjects")]
public class Subjects
{
[XmlElement(ElementName = "billSubjects")]
public BillSubjects BillSubjects { get; set; }
}
[XmlRoot(ElementName = "identifiers")]
public class Identifiers
{
[XmlElement(ElementName = "lisID")]
public string LISID { get; set; }
[XmlElement(ElementName = "bioguideId")]
public string BioguideId { get; set; }
[XmlElement(ElementName = "gpoId")]
public string GPOID { get; set; }
}
[XmlRoot(ElementName = "activities")]
public class Activities : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "subcommittees")]
public class Subcommittees : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "billCommittees")]
public class BillCommittees : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "committees")]
public class Committees
{
[XmlElement(ElementName = "billCommittees")]
public BillCommittees BillCommittees { get; set; }
}
[XmlRoot(ElementName = "recordedVote")]
public class RecordedVote
{
[XmlElement(ElementName = "fullActionName")]
public string FullActionName { get; set; }
[XmlElement(ElementName = "date")]
public string Date { get; set; }
[XmlElement(ElementName = "rollNumber")]
public string RollNumber { get; set; }
[XmlElement(ElementName = "congress")]
public string Congress { get; set; }
[XmlElement(ElementName = "chamber")]
public string Chamber { get; set; }
[XmlElement(ElementName = "url")]
public string Url { get; set; }
[XmlElement(ElementName = "sessionNumber")]
public string SessionNumber { get; set; }
}
[XmlRoot(ElementName = "recordedVotes")]
public class RecordedVotes : IItemized<RecordedVote>
{
[XmlElement(ElementName = "recordedVote")]
public List<RecordedVote> Items { get; set; }
}
[XmlRoot(ElementName = "relationshipDetails")]
public class RelationshipDetails : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "relatedBills")]
public class RelatedBills : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "billSummaries")]
public class BillSummaries : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "summaries")]
public class Summaries
{
[XmlElement(ElementName = "billSummaries")]
public BillSummaries BillSummaries { get; set; }
}
[XmlRoot(ElementName = "bill")]
public class Bill
{
[XmlElement(ElementName = "billNumber")]
public string BillNumber { get; set; }
[XmlElement(ElementName = "congress")]
public string Congress { get; set; }
[XmlElement(ElementName = "originChamber")]
public string OriginChamber { get; set; }
[XmlElement(ElementName = "constitutionalAuthorityStatementText")]
public string ConstitutionalAuthorityStatementText { get; set; }
[XmlElement(ElementName = "actions")]
public Actions Actions { get; set; }
[XmlElement(ElementName = "amendments")]
public Amendments Amendments { get; set; }
[XmlElement(ElementName = "cboCostEstimates")]
public CboCostEstimates CboCostEstimates { get; set; }
[XmlElement(ElementName = "committeeReports")]
public CommitteeReports CommitteeReports { get; set; }
[XmlElement(ElementName = "laws")]
public Laws Laws { get; set; }
[XmlElement(ElementName = "createDate")]
public string CreateDate { get; set; }
[XmlElement(ElementName = "latestAction")]
public LatestAction LatestAction { get; set; }
[XmlElement(ElementName = "subjects")]
public Subjects Subjects { get; set; }
[XmlElement(ElementName = "title")]
public string Title { get; set; }
[XmlElement(ElementName = "sponsors")]
public Sponsors Sponsors { get; set; }
[XmlElement(ElementName = "committees")]
public Committees Committees { get; set; }
[XmlElement(ElementName = "updateDate")]
public string UpdateDate { get; set; }
[XmlElement(ElementName = "notes")]
public Notes Notes { get; set; }
[XmlElement(ElementName = "recordedVotes")]
public RecordedVotes RecordedVotes { get; set; }
[XmlElement(ElementName = "billType")]
public string BillType { get; set; }
[XmlElement(ElementName = "cosponsors")]
public Cosponsors Cosponsors { get; set; }
[XmlElement(ElementName = "relatedBills")]
public RelatedBills RelatedBills { get; set; }
[XmlElement(ElementName = "summaries")]
public Summaries Summaries { get; set; }
[XmlElement(ElementName = "introducedDate")]
public string IntroducedDate { get; set; }
[XmlElement(ElementName = "titles")]
public Titles Titles { get; set; }
[XmlElement(ElementName = "policyArea")]
public PolicyArea PolicyArea { get; set; }
[XmlElement(ElementName = "calendarNumbers")]
public CalendarNumbers CalendarNumbers { get; set; }
}
[XmlRoot(ElementName = "committeeReports")]
public class CommitteeReports : IItemized<CommitteeReport>
{
[XmlElement(ElementName = "committeeReport")]
public List<CommitteeReport> Items { get; set; }
}
[XmlRoot(ElementName = "committeeReport")]
public class CommitteeReport
{
[XmlElement(ElementName = "citation")]
public string Citation { get; set; }
}
[XmlRoot(ElementName = "notes")]
public class Notes : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "calendarNumbers")]
public class CalendarNumbers : IItemized<Item>
{
[XmlElement(ElementName = "item")]
public List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "dublinCore")]
public class DublinCore
{
[XmlElement(ElementName = "format", Namespace = "http://purl.org/dc/elements/1.1/")]
public string Format { get; set; }
[XmlElement(ElementName = "language", Namespace = "http://purl.org/dc/elements/1.1/")]
public string Language { get; set; }
[XmlElement(ElementName = "rights", Namespace = "http://purl.org/dc/elements/1.1/")]
public string Rights { get; set; }
[XmlElement(ElementName = "contributor", Namespace = "http://purl.org/dc/elements/1.1/")]
public string Contributor { get; set; }
[XmlElement(ElementName = "description", Namespace = "http://purl.org/dc/elements/1.1/")]
public string Description { get; set; }
[XmlAttribute(AttributeName = "dc", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Dc { get; set; }
}
[XmlRoot(ElementName = "billStatus")]
public class BillStatus
{
[XmlElement(ElementName = "bill")]
public Bill Bill { get; set; }
[XmlElement(ElementName = "dublinCore")]
public DublinCore DublinCore { get; set; }
}
}
| |
// 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.Globalization;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
[Trait("connection", "tcp")]
public static class ExceptionTest
{
// data value and server consts
private const string badServer = "NotAServer";
private const string sqlsvrBadConn = "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.";
private const string logonFailedErrorMessage = "Login failed for user '{0}'.";
private const string execReaderFailedMessage = "ExecuteReader requires an open and available Connection. The connection's current state is closed.";
private const string warningNoiseMessage = "The full-text search condition contained noise word(s).";
private const string warningInfoMessage = "Test of info messages";
private const string orderIdQuery = "select orderid from orders where orderid < 10250";
#if MANAGED_SNI
[CheckConnStrSetupFact]
public static void NonWindowsIntAuthFailureTest()
{
string connectionString = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { IntegratedSecurity = true }).ConnectionString;
Assert.Throws<NotSupportedException>(() => new SqlConnection(connectionString).Open());
// Should not receive any exception when using IntAuth=false
connectionString = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { IntegratedSecurity = false }).ConnectionString;
new SqlConnection(connectionString).Open();
}
#endif
[CheckConnStrSetupFact]
public static void WarningTest()
{
Action<object, SqlInfoMessageEventArgs> warningCallback =
(object sender, SqlInfoMessageEventArgs imevent) =>
{
for (int i = 0; i < imevent.Errors.Count; i++)
{
Assert.True(imevent.Errors[i].Message.Contains(warningInfoMessage), "FAILED: WarningTest Callback did not contain correct message.");
}
};
SqlInfoMessageEventHandler handler = new SqlInfoMessageEventHandler(warningCallback);
using (SqlConnection sqlConnection = new SqlConnection((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { Pooling = false }).ConnectionString))
{
sqlConnection.InfoMessage += handler;
sqlConnection.Open();
SqlCommand cmd = new SqlCommand(string.Format("PRINT N'{0}'", warningInfoMessage), sqlConnection);
cmd.ExecuteNonQuery();
sqlConnection.InfoMessage -= handler;
cmd.ExecuteNonQuery();
}
}
[CheckConnStrSetupFact]
public static void WarningsBeforeRowsTest()
{
bool hitWarnings = false;
int iteration = 0;
Action<object, SqlInfoMessageEventArgs> warningCallback =
(object sender, SqlInfoMessageEventArgs imevent) =>
{
for (int i = 0; i < imevent.Errors.Count; i++)
{
Assert.True(imevent.Errors[i].Message.Contains(warningNoiseMessage), "FAILED: WarningsBeforeRowsTest Callback did not contain correct message. Failed in loop iteration: " + iteration);
}
hitWarnings = true;
};
SqlInfoMessageEventHandler handler = new SqlInfoMessageEventHandler(warningCallback);
SqlConnection sqlConnection = new SqlConnection(DataTestUtility.TcpConnStr);
sqlConnection.InfoMessage += handler;
sqlConnection.Open();
foreach (string orderClause in new string[] { "", " order by FirstName" })
{
foreach (bool messagesOnErrors in new bool[] { true, false })
{
iteration++;
sqlConnection.FireInfoMessageEventOnUserErrors = messagesOnErrors;
// These queries should return warnings because AND here is a noise word.
SqlCommand cmd = new SqlCommand("select FirstName from Northwind.dbo.Employees where contains(FirstName, '\"Anne AND\"')" + orderClause, sqlConnection);
using (SqlDataReader reader = cmd.ExecuteReader())
{
Assert.True(reader.HasRows, "FAILED: SqlDataReader.HasRows is not correct (should be TRUE)");
bool receivedRows = false;
while (reader.Read())
{
receivedRows = true;
}
Assert.True(receivedRows, "FAILED: Should have received rows from this query.");
Assert.True(hitWarnings, "FAILED: Should have received warnings from this query");
}
hitWarnings = false;
cmd.CommandText = "select FirstName from Northwind.dbo.Employees where contains(FirstName, '\"NotARealPerson AND\"')" + orderClause;
using (SqlDataReader reader = cmd.ExecuteReader())
{
Assert.False(reader.HasRows, "FAILED: SqlDataReader.HasRows is not correct (should be FALSE)");
bool receivedRows = false;
while (reader.Read())
{
receivedRows = true;
}
Assert.False(receivedRows, "FAILED: Should have NOT received rows from this query.");
Assert.True(hitWarnings, "FAILED: Should have received warnings from this query");
}
}
}
sqlConnection.Close();
}
[CheckConnStrSetupFact]
public static void ExceptionTests()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
// tests improper server name thrown from constructor of tdsparser
SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), sqlsvrBadConn, VerifyException);
// tests incorrect password - thrown from the adapter
badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { Password = string.Empty };
string errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID);
VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14));
// tests incorrect database name - exception thrown from adapter
badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { InitialCatalog = "NotADatabase" };
errorMessage = string.Format(CultureInfo.InvariantCulture, "Cannot open database \"{0}\" requested by the login. The login failed.", badBuilder.InitialCatalog);
SqlException firstAttemptException = VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 2, 4060, 1, 11));
// tests incorrect user name - exception thrown from adapter
badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { UserID = "NotAUser" };
errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID);
VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14));
}
[CheckConnStrSetupFact]
public static void VariousExceptionTests()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
// Test 1 - A
SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString))
{
using (SqlCommand command = sqlConnection.CreateCommand())
{
command.CommandText = orderIdQuery;
VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage);
}
}
// Test 1 - B
badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { Password = string.Empty };
using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString))
{
string errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID);
VerifyConnectionFailure<SqlException>(() => sqlConnection.Open(), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14));
}
}
[CheckConnStrSetupFact]
public static void IndependentConnectionExceptionTest()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString))
{
// Test 1
VerifyConnectionFailure<SqlException>(() => sqlConnection.Open(), sqlsvrBadConn, VerifyException);
// Test 2
using (SqlCommand command = new SqlCommand(orderIdQuery, sqlConnection))
{
VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage);
}
}
}
private static void GenerateConnectionException(string connectionString)
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (SqlCommand command = sqlConnection.CreateCommand())
{
command.CommandText = orderIdQuery;
command.ExecuteReader();
}
}
}
private static TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage, Func<TException, bool> exVerifier) where TException : Exception
{
TException ex = Assert.Throws<TException>(connectAction);
Assert.True(ex.Message.Contains(expectedExceptionMessage), string.Format("FAILED: SqlException did not contain expected error message. Actual message: {0}", ex.Message));
Assert.True(exVerifier(ex), "FAILED: Exception verifier failed on the exception.");
return ex;
}
private static TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage) where TException : Exception
{
return VerifyConnectionFailure<TException>(connectAction, expectedExceptionMessage, (ex) => true);
}
private static bool VerifyException(SqlException exception)
{
VerifyException(exception, 1);
return true;
}
private static bool VerifyException(SqlException exception, int count, int? errorNumber = null, int? errorState = null, int? severity = null)
{
// Verify that there are the correct number of errors in the exception
Assert.True(exception.Errors.Count == count, string.Format("FAILED: Incorrect number of errors. Expected: {0}. Actual: {1}.", count, exception.Errors.Count));
// Ensure that all errors have an error-level severity
for (int i = 0; i < count; i++)
{
Assert.True(exception.Errors[i].Class >= 10, "FAILED: verification of Exception! Exception contains a warning!");
}
// Check the properties of the exception populated by the server are correct
if (errorNumber.HasValue)
{
Assert.True(errorNumber.Value == exception.Number, string.Format("FAILED: Error number of exception is incorrect. Expected: {0}. Actual: {1}.", errorNumber.Value, exception.Number));
}
if (errorState.HasValue)
{
Assert.True(errorState.Value == exception.State, string.Format("FAILED: Error state of exception is incorrect. Expected: {0}. Actual: {1}.", errorState.Value, exception.State));
}
if (severity.HasValue)
{
Assert.True(severity.Value == exception.Class, string.Format("FAILED: Severity of exception is incorrect. Expected: {0}. Actual: {1}.", severity.Value, exception.Class));
}
if ((errorNumber.HasValue) && (errorState.HasValue) && (severity.HasValue))
{
string detailsText = string.Format("Error Number:{0},State:{1},Class:{2}", errorNumber.Value, errorState.Value, severity.Value);
Assert.True(exception.ToString().Contains(detailsText), string.Format("FAILED: SqlException.ToString does not contain the error number, state and severity information"));
}
// verify that the this[] function on the collection works, as well as the All function
SqlError[] errors = new SqlError[exception.Errors.Count];
exception.Errors.CopyTo(errors, 0);
Assert.True((errors[0].Message).Equals(exception.Errors[0].Message), string.Format("FAILED: verification of Exception! ErrorCollection indexer/CopyTo resulted in incorrect value."));
return true;
}
}
}
| |
/*
* 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 autoscaling-2011-01-01.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.AutoScaling
{
/// <summary>
/// Constants used for properties of type LifecycleState.
/// </summary>
public class LifecycleState : ConstantClass
{
/// <summary>
/// Constant Detached for LifecycleState
/// </summary>
public static readonly LifecycleState Detached = new LifecycleState("Detached");
/// <summary>
/// Constant Detaching for LifecycleState
/// </summary>
public static readonly LifecycleState Detaching = new LifecycleState("Detaching");
/// <summary>
/// Constant EnteringStandby for LifecycleState
/// </summary>
public static readonly LifecycleState EnteringStandby = new LifecycleState("EnteringStandby");
/// <summary>
/// Constant InService for LifecycleState
/// </summary>
public static readonly LifecycleState InService = new LifecycleState("InService");
/// <summary>
/// Constant Pending for LifecycleState
/// </summary>
public static readonly LifecycleState Pending = new LifecycleState("Pending");
/// <summary>
/// Constant PendingProceed for LifecycleState
/// </summary>
public static readonly LifecycleState PendingProceed = new LifecycleState("Pending:Proceed");
/// <summary>
/// Constant PendingWait for LifecycleState
/// </summary>
public static readonly LifecycleState PendingWait = new LifecycleState("Pending:Wait");
/// <summary>
/// Constant Quarantined for LifecycleState
/// </summary>
public static readonly LifecycleState Quarantined = new LifecycleState("Quarantined");
/// <summary>
/// Constant Standby for LifecycleState
/// </summary>
public static readonly LifecycleState Standby = new LifecycleState("Standby");
/// <summary>
/// Constant Terminated for LifecycleState
/// </summary>
public static readonly LifecycleState Terminated = new LifecycleState("Terminated");
/// <summary>
/// Constant Terminating for LifecycleState
/// </summary>
public static readonly LifecycleState Terminating = new LifecycleState("Terminating");
/// <summary>
/// Constant TerminatingProceed for LifecycleState
/// </summary>
public static readonly LifecycleState TerminatingProceed = new LifecycleState("Terminating:Proceed");
/// <summary>
/// Constant TerminatingWait for LifecycleState
/// </summary>
public static readonly LifecycleState TerminatingWait = new LifecycleState("Terminating:Wait");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public LifecycleState(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static LifecycleState FindValue(string value)
{
return FindValue<LifecycleState>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator LifecycleState(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ScalingActivityStatusCode.
/// </summary>
public class ScalingActivityStatusCode : ConstantClass
{
/// <summary>
/// Constant Cancelled for ScalingActivityStatusCode
/// </summary>
public static readonly ScalingActivityStatusCode Cancelled = new ScalingActivityStatusCode("Cancelled");
/// <summary>
/// Constant Failed for ScalingActivityStatusCode
/// </summary>
public static readonly ScalingActivityStatusCode Failed = new ScalingActivityStatusCode("Failed");
/// <summary>
/// Constant InProgress for ScalingActivityStatusCode
/// </summary>
public static readonly ScalingActivityStatusCode InProgress = new ScalingActivityStatusCode("InProgress");
/// <summary>
/// Constant MidLifecycleAction for ScalingActivityStatusCode
/// </summary>
public static readonly ScalingActivityStatusCode MidLifecycleAction = new ScalingActivityStatusCode("MidLifecycleAction");
/// <summary>
/// Constant PreInService for ScalingActivityStatusCode
/// </summary>
public static readonly ScalingActivityStatusCode PreInService = new ScalingActivityStatusCode("PreInService");
/// <summary>
/// Constant Successful for ScalingActivityStatusCode
/// </summary>
public static readonly ScalingActivityStatusCode Successful = new ScalingActivityStatusCode("Successful");
/// <summary>
/// Constant WaitingForELBConnectionDraining for ScalingActivityStatusCode
/// </summary>
public static readonly ScalingActivityStatusCode WaitingForELBConnectionDraining = new ScalingActivityStatusCode("WaitingForELBConnectionDraining");
/// <summary>
/// Constant WaitingForInstanceId for ScalingActivityStatusCode
/// </summary>
public static readonly ScalingActivityStatusCode WaitingForInstanceId = new ScalingActivityStatusCode("WaitingForInstanceId");
/// <summary>
/// Constant WaitingForInstanceWarmup for ScalingActivityStatusCode
/// </summary>
public static readonly ScalingActivityStatusCode WaitingForInstanceWarmup = new ScalingActivityStatusCode("WaitingForInstanceWarmup");
/// <summary>
/// Constant WaitingForSpotInstanceId for ScalingActivityStatusCode
/// </summary>
public static readonly ScalingActivityStatusCode WaitingForSpotInstanceId = new ScalingActivityStatusCode("WaitingForSpotInstanceId");
/// <summary>
/// Constant WaitingForSpotInstanceRequestId for ScalingActivityStatusCode
/// </summary>
public static readonly ScalingActivityStatusCode WaitingForSpotInstanceRequestId = new ScalingActivityStatusCode("WaitingForSpotInstanceRequestId");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ScalingActivityStatusCode(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ScalingActivityStatusCode FindValue(string value)
{
return FindValue<ScalingActivityStatusCode>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ScalingActivityStatusCode(string value)
{
return FindValue(value);
}
}
}
| |
// 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 Test.Utilities;
using Xunit;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureXSLTScriptExecutionAnalyzerTests : DiagnosticAnalyzerTestBase
{
private readonly string _CA3076LoadInsecureConstructedMessage = MicrosoftNetFrameworkAnalyzersResources.XslCompiledTransformLoadInsecureConstructedMessage;
private DiagnosticResult GetCA3076LoadInsecureConstructedCSharpResultAt(int line, int column, string name)
{
return GetCSharpResultAt(line, column, CA3076RuleId, string.Format(_CA3076LoadInsecureConstructedMessage, name));
}
private DiagnosticResult GetCA3076LoadInsecureConstructedBasicResultAt(int line, int column, string name)
{
return GetBasicResultAt(line, column, CA3076RuleId, string.Format(_CA3076LoadInsecureConstructedMessage, name));
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
var resolver = new XmlUrlResolver();
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}",
GetCA3076LoadInsecureConstructedCSharpResultAt(13, 13, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Dim xslCompiledTransform As New XslCompiledTransform()
Dim resolver = New XmlUrlResolver()
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace",
GetCA3076LoadInsecureConstructedBasicResultAt(10, 13, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNonSecureResolverInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
var resolver = new XmlUrlResolver();
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}",
GetCA3076LoadInsecureConstructedCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
Dim resolver = New XmlUrlResolver()
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadInsecureConstructedBasicResultAt(11, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNonSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
var resolver = new XmlUrlResolver();
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}",
GetCA3076LoadInsecureConstructedCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
Dim resolver = New XmlUrlResolver()
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadInsecureConstructedBasicResultAt(12, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNonSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
var resolver = new XmlUrlResolver();
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}",
GetCA3076LoadInsecureConstructedCSharpResultAt(16, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
Dim resolver = New XmlUrlResolver()
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadInsecureConstructedBasicResultAt(14, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNullResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
xslCompiledTransform.Load(""testStylesheet"", settings, null);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Dim xslCompiledTransform As New XslCompiledTransform()
xslCompiledTransform.Load("""", settings, Nothing)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructDefaultAndNonSecureResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.Default;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.[Default]
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructTrustedXsltAndNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.TrustedXslt;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}",
GetCA3076LoadCSharpResultAt(13, 13, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.TrustedXslt
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(10, 13, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructTrustedXsltAndNonSecureResolverInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.TrustedXslt;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.TrustedXslt
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(11, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructTrustedXsltAndNonSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.TrustedXslt;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.TrustedXslt
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(12, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructTrustedXsltAndNonSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.TrustedXslt;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}",
GetCA3076LoadCSharpResultAt(16, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.TrustedXslt
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(14, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToFalseAndNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}",
GetCA3076LoadCSharpResultAt(13, 13, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(10, 13, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToFalseAndNonSecureResolverInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(11, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToFalseAndNonSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(12, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToFalseAndNonSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}",
GetCA3076LoadCSharpResultAt(16, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(14, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverInTryBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverInCatchBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverInFinallyBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverAsyncAwaitShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}",
GetCA3076LoadCSharpResultAt(13, 13, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(10, 13, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(11, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(12, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}",
GetCA3076LoadCSharpResultAt(16, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(14, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverAsyncAwaitShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private async Task TestMethod(XsltSettings settings, XmlResolver resolver)
{
await Task.Run(() =>
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
});
}
private async void TestMethod2()
{
await TestMethod(null, null);
}
}
}",
GetCA3076LoadCSharpResultAt(16, 17, "Run")
);
VerifyBasic(@"
Imports System.Threading.Tasks
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Async Function TestMethod(settings As XsltSettings, resolver As XmlResolver) As Task
Await Task.Run(Function()
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod(Nothing, Nothing)
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(12, 13, "Run")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverInTryBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverInCatchBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverInFinallyBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch { throw; }
finally
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverAsyncAwaitShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private async Task TestMethod(XsltSettings settings, XmlResolver resolver)
{
await Task.Run(() =>
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
});
}
private async void TestMethod2()
{
await TestMethod(null, null);
}
}
}"
);
VerifyBasic(@"
Imports System.Threading.Tasks
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Async Function TestMethod(settings As XsltSettings, resolver As XmlResolver) As Task
Await Task.Run(Function()
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod(Nothing, Nothing)
End Sub
End Class
End Namespace");
}
}
}
| |
using EngineLayer;
using EngineLayer.Calibration;
using EngineLayer.ClassicSearch;
using EngineLayer.FdrAnalysis;
using FlashLFQ;
using IO.MzML;
using MassSpectrometry;
using MzLibUtil;
using Nett;
using Proteomics;
using Proteomics.Fragmentation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UsefulProteomicsDatabases;
namespace TaskLayer
{
public class CalibrationTask : MetaMorpheusTask
{
public CalibrationTask() : base(MyTask.Calibrate)
{
CommonParameters = new CommonParameters(
productMassTolerance: new PpmTolerance(25),
precursorMassTolerance: new PpmTolerance(15),
trimMsMsPeaks: false,
doPrecursorDeconvolution: false
);
CalibrationParameters = new CalibrationParameters();
}
public CalibrationParameters CalibrationParameters { get; set; }
protected override MyTaskResults RunSpecific(string OutputFolder, List<DbForTask> dbFilenameList, List<string> currentRawFileList, string taskId, FileSpecificParameters[] fileSettingsList)
{
LoadModifications(taskId, out var variableModifications, out var fixedModifications, out var localizeableModificationTypes);
// load proteins
List<Protein> proteinList = LoadProteins(taskId, dbFilenameList, true, DecoyType.Reverse, localizeableModificationTypes, CommonParameters);
// write prose settings
ProseCreatedWhileRunning.Append("The following calibration settings were used: ");
ProseCreatedWhileRunning.Append("protease = " + CommonParameters.DigestionParams.Protease + "; ");
ProseCreatedWhileRunning.Append("maximum missed cleavages = " + CommonParameters.DigestionParams.MaxMissedCleavages + "; ");
ProseCreatedWhileRunning.Append("minimum peptide length = " + CommonParameters.DigestionParams.MinPeptideLength + "; ");
ProseCreatedWhileRunning.Append(CommonParameters.DigestionParams.MaxPeptideLength == int.MaxValue ?
"maximum peptide length = unspecified; " :
"maximum peptide length = " + CommonParameters.DigestionParams.MaxPeptideLength + "; ");
ProseCreatedWhileRunning.Append("initiator methionine behavior = " + CommonParameters.DigestionParams.InitiatorMethionineBehavior + "; ");
ProseCreatedWhileRunning.Append("fixed modifications = " + string.Join(", ", fixedModifications.Select(m => m.IdWithMotif)) + "; ");
ProseCreatedWhileRunning.Append("variable modifications = " + string.Join(", ", variableModifications.Select(m => m.IdWithMotif)) + "; ");
ProseCreatedWhileRunning.Append("max mods per peptide = " + CommonParameters.DigestionParams.MaxModsForPeptide + "; ");
ProseCreatedWhileRunning.Append("max modification isoforms = " + CommonParameters.DigestionParams.MaxModificationIsoforms + "; ");
ProseCreatedWhileRunning.Append("precursor mass tolerance = " + CommonParameters.PrecursorMassTolerance + "; ");
ProseCreatedWhileRunning.Append("product mass tolerance = " + CommonParameters.ProductMassTolerance + ". ");
ProseCreatedWhileRunning.Append("The combined search database contained " + proteinList.Count(p => !p.IsDecoy) + " non-decoy protein entries including " + proteinList.Count(p => p.IsContaminant) + " contaminant sequences. ");
// start the calibration task
Status("Calibrating...", new List<string> { taskId });
MyTaskResults = new MyTaskResults(this)
{
NewSpectra = new List<string>(),
NewFileSpecificTomls = new List<string>()
};
var myFileManager = new MyFileManager(true);
List<string> unsuccessfullyCalibratedFilePaths = new List<string>();
for (int spectraFileIndex = 0; spectraFileIndex < currentRawFileList.Count; spectraFileIndex++)
{
if (GlobalVariables.StopLoops) { break; }
bool couldNotFindEnoughDatapoints = false;
// get filename stuff
var originalUncalibratedFilePath = currentRawFileList[spectraFileIndex];
var originalUncalibratedFilenameWithoutExtension = Path.GetFileNameWithoutExtension(originalUncalibratedFilePath);
string calibratedFilePath = Path.Combine(OutputFolder, originalUncalibratedFilenameWithoutExtension + CalibSuffix + ".mzML");
// mark the file as in-progress
StartingDataFile(originalUncalibratedFilePath, new List<string> { taskId, "Individual Spectra Files", originalUncalibratedFilePath });
CommonParameters combinedParams = SetAllFileSpecificCommonParams(CommonParameters, fileSettingsList[spectraFileIndex]);
// load the file
Status("Loading spectra file...", new List<string> { taskId, "Individual Spectra Files" });
var myMsDataFile = myFileManager.LoadFile(originalUncalibratedFilePath, CommonParameters);
// get datapoints to fit calibration function to
Status("Acquiring calibration data points...", new List<string> { taskId, "Individual Spectra Files" });
DataPointAquisitionResults acquisitionResults = null;
for (int i = 1; i <= 5; i++)
{
acquisitionResults = GetDataAcquisitionResults(myMsDataFile, originalUncalibratedFilePath, variableModifications, fixedModifications, proteinList, taskId, combinedParams, combinedParams.PrecursorMassTolerance, combinedParams.ProductMassTolerance);
// enough data points to calibrate?
if (acquisitionResults.Psms.Count >= NumRequiredPsms && acquisitionResults.Ms1List.Count > NumRequiredMs1Datapoints && acquisitionResults.Ms2List.Count > NumRequiredMs2Datapoints)
{
break;
}
if (i == 1) // failed round 1
{
CommonParameters.PrecursorMassTolerance = new PpmTolerance(20);
CommonParameters.ProductMassTolerance = new PpmTolerance(50);
}
else if (i == 2) // failed round 2
{
CommonParameters.PrecursorMassTolerance = new PpmTolerance(30);
CommonParameters.ProductMassTolerance = new PpmTolerance(100);
}
else if (i == 3) // failed round 3
{
CommonParameters.PrecursorMassTolerance = new PpmTolerance(40);
CommonParameters.ProductMassTolerance = new PpmTolerance(150);
}
else // failed round 4
{
if (acquisitionResults.Psms.Count < NumRequiredPsms)
{
Warn("Calibration failure! Could not find enough high-quality PSMs. Required " + NumRequiredPsms + ", saw " + acquisitionResults.Psms.Count);
}
if (acquisitionResults.Ms1List.Count < NumRequiredMs1Datapoints)
{
Warn("Calibration failure! Could not find enough MS1 datapoints. Required " + NumRequiredMs1Datapoints + ", saw " + acquisitionResults.Ms1List.Count);
}
if (acquisitionResults.Ms2List.Count < NumRequiredMs2Datapoints)
{
Warn("Calibration failure! Could not find enough MS2 datapoints. Required " + NumRequiredMs2Datapoints + ", saw " + acquisitionResults.Ms2List.Count);
}
couldNotFindEnoughDatapoints = true;
FinishedDataFile(originalUncalibratedFilePath, new List<string> { taskId, "Individual Spectra Files", originalUncalibratedFilePath });
break;
}
Warn("Could not find enough PSMs to calibrate with; opening up tolerances to " +
Math.Round(CommonParameters.PrecursorMassTolerance.Value, 2) + " ppm precursor and " +
Math.Round(CommonParameters.ProductMassTolerance.Value, 2) + " ppm product");
}
if (couldNotFindEnoughDatapoints)
{
unsuccessfullyCalibratedFilePaths.Add(Path.GetFileNameWithoutExtension(currentRawFileList[spectraFileIndex]));
ReportProgress(new ProgressEventArgs(100, "Failed to calibrate!", new List<string> { taskId, "Individual Spectra Files", originalUncalibratedFilenameWithoutExtension }));
continue;
}
// stats before calibration
int prevPsmCount = acquisitionResults.Psms.Count;
double preCalibrationPrecursorErrorIqr = acquisitionResults.PsmPrecursorIqrPpmError;
double preCalibrationProductErrorIqr = acquisitionResults.PsmProductIqrPpmError;
// generate calibration function and shift data points
Status("Calibrating...", new List<string> { taskId, "Individual Spectra Files" });
CalibrationEngine engine = new CalibrationEngine(myMsDataFile, acquisitionResults, CommonParameters, FileSpecificParameters, new List<string> { taskId, "Individual Spectra Files", originalUncalibratedFilenameWithoutExtension });
engine.Run();
//update file
myMsDataFile = engine.CalibratedDataFile;
// do another search to evaluate calibration results
Status("Post-calibration search...", new List<string> { taskId, "Individual Spectra Files" });
acquisitionResults = GetDataAcquisitionResults(myMsDataFile, originalUncalibratedFilePath, variableModifications, fixedModifications, proteinList, taskId, combinedParams, combinedParams.PrecursorMassTolerance, combinedParams.ProductMassTolerance);
//generate calibration function and shift data points AGAIN because it's fast and contributes new data
Status("Calibrating...", new List<string> { taskId, "Individual Spectra Files" });
engine = new CalibrationEngine(myMsDataFile, acquisitionResults, CommonParameters, FileSpecificParameters, new List<string> { taskId, "Individual Spectra Files", originalUncalibratedFilenameWithoutExtension });
engine.Run();
//update file
myMsDataFile = engine.CalibratedDataFile;
// write the calibrated mzML file
MzmlMethods.CreateAndWriteMyMzmlWithCalibratedSpectra(myMsDataFile, calibratedFilePath, CalibrationParameters.WriteIndexedMzml);
myFileManager.DoneWithFile(originalUncalibratedFilePath);
// stats after calibration
int postCalibrationPsmCount = acquisitionResults.Psms.Count;
double postCalibrationPrecursorErrorIqr = acquisitionResults.PsmPrecursorIqrPpmError;
double postCalibrationProductErrorIqr = acquisitionResults.PsmProductIqrPpmError;
// did the data improve? (not used for anything yet...)
bool improvement = ImprovGlobal(preCalibrationPrecursorErrorIqr, preCalibrationProductErrorIqr, prevPsmCount, postCalibrationPsmCount, postCalibrationPrecursorErrorIqr, postCalibrationProductErrorIqr);
// write toml settings for the calibrated file
var newTomlFileName = Path.Combine(OutputFolder, originalUncalibratedFilenameWithoutExtension + CalibSuffix + ".toml");
var fileSpecificParams = new FileSpecificParameters();
// carry over file-specific parameters from the uncalibrated file to the calibrated one
if (fileSettingsList[spectraFileIndex] != null)
{
fileSpecificParams = fileSettingsList[spectraFileIndex].Clone();
}
//suggest 4 * interquartile range as the ppm tolerance
fileSpecificParams.PrecursorMassTolerance = new PpmTolerance((4.0 * postCalibrationPrecursorErrorIqr) + Math.Abs(acquisitionResults.PsmPrecursorMedianPpmError));
fileSpecificParams.ProductMassTolerance = new PpmTolerance((4.0 * postCalibrationProductErrorIqr) + Math.Abs(acquisitionResults.PsmProductMedianPpmError));
Toml.WriteFile(fileSpecificParams, newTomlFileName, tomlConfig);
FinishedWritingFile(newTomlFileName, new List<string> { taskId, "Individual Spectra Files", originalUncalibratedFilenameWithoutExtension });
// finished calibrating this file
FinishedWritingFile(calibratedFilePath, new List<string> { taskId, "Individual Spectra Files", originalUncalibratedFilenameWithoutExtension });
MyTaskResults.NewSpectra.Add(calibratedFilePath);
MyTaskResults.NewFileSpecificTomls.Add(newTomlFileName);
FinishedDataFile(originalUncalibratedFilePath, new List<string> { taskId, "Individual Spectra Files", originalUncalibratedFilePath });
ReportProgress(new ProgressEventArgs(100, "Done!", new List<string> { taskId, "Individual Spectra Files", originalUncalibratedFilenameWithoutExtension }));
}
// re-write experimental design (if it has been defined) with new calibrated file names
string assumedPathToExperDesign = Directory.GetParent(currentRawFileList.First()).FullName;
assumedPathToExperDesign = Path.Combine(assumedPathToExperDesign, GlobalVariables.ExperimentalDesignFileName);
if (File.Exists(assumedPathToExperDesign))
{
WriteNewExperimentalDesignFile(assumedPathToExperDesign, OutputFolder, currentRawFileList, unsuccessfullyCalibratedFilePaths);
}
// finished calibrating all files for the task
ReportProgress(new ProgressEventArgs(100, "Done!", new List<string> { taskId, "Individual Spectra Files" }));
return MyTaskResults;
}
private readonly int NumRequiredPsms = 20;
private readonly int NumRequiredMs1Datapoints = 50;
private readonly int NumRequiredMs2Datapoints = 100;
public const string CalibSuffix = "-calib";
private bool ImprovGlobal(double prevPrecTol, double prevProdTol, int prevPsmCount, int thisRoundPsmCount, double thisRoundPrecTol, double thisRoundProdTol)
{
if (thisRoundPsmCount > prevPsmCount)
{
return true;
}
var precRatio = thisRoundPrecTol / prevPrecTol;
var prodRatio = thisRoundProdTol / prevProdTol;
if (thisRoundPsmCount == prevPsmCount)
{
return precRatio + prodRatio < 2; // Take any improvement in ratios
}
var countRatio = (double)thisRoundPsmCount / prevPsmCount;
return countRatio > 0.9 && precRatio + prodRatio < 1.8;
}
private DataPointAquisitionResults GetDataAcquisitionResults(MsDataFile myMsDataFile, string currentDataFile, List<Modification> variableModifications, List<Modification> fixedModifications, List<Protein> proteinList, string taskId, CommonParameters combinedParameters, Tolerance initPrecTol, Tolerance initProdTol)
{
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(currentDataFile);
MassDiffAcceptor searchMode = initPrecTol is PpmTolerance ?
(MassDiffAcceptor)new SinglePpmAroundZeroSearchMode(initPrecTol.Value) :
new SingleAbsoluteAroundZeroSearchMode(initPrecTol.Value);
var listOfSortedms2Scans = GetMs2Scans(myMsDataFile, currentDataFile, combinedParameters).OrderBy(b => b.PrecursorMass).ToArray();
PeptideSpectralMatch[] allPsmsArray = new PeptideSpectralMatch[listOfSortedms2Scans.Length];
Log("Searching with searchMode: " + searchMode, new List<string> { taskId, "Individual Spectra Files", fileNameWithoutExtension });
Log("Searching with productMassTolerance: " + initProdTol, new List<string> { taskId, "Individual Spectra Files", fileNameWithoutExtension });
bool writeSpectralLibrary = false;
new ClassicSearchEngine(allPsmsArray, listOfSortedms2Scans, variableModifications, fixedModifications, null, null, null, proteinList, searchMode, combinedParameters,
FileSpecificParameters, null, new List<string> { taskId, "Individual Spectra Files", fileNameWithoutExtension }, writeSpectralLibrary).Run();
List<PeptideSpectralMatch> allPsms = allPsmsArray.Where(b => b != null).ToList();
allPsms = allPsms.OrderByDescending(b => b.Score)
.ThenBy(b => b.PeptideMonisotopicMass.HasValue ? Math.Abs(b.ScanPrecursorMass - b.PeptideMonisotopicMass.Value) : double.MaxValue)
.GroupBy(b => (b.FullFilePath, b.ScanNumber, b.PeptideMonisotopicMass)).Select(b => b.First()).ToList();
new FdrAnalysisEngine(allPsms, searchMode.NumNotches, CommonParameters, FileSpecificParameters, new List<string> { taskId, "Individual Spectra Files", fileNameWithoutExtension }).Run();
List<PeptideSpectralMatch> goodIdentifications = allPsms.Where(b => b.FdrInfo.QValueNotch < 0.001 && !b.IsDecoy && b.FullSequence != null).ToList();
if (!goodIdentifications.Any())
{
return new DataPointAquisitionResults(null, new List<PeptideSpectralMatch>(), new List<LabeledDataPoint>(), new List<LabeledDataPoint>(), 0, 0, 0, 0);
}
//get the deconvoluted ms2scans for the good identifications
List<Ms2ScanWithSpecificMass> goodScans = new List<Ms2ScanWithSpecificMass>();
List<PeptideSpectralMatch> unfilteredPsms = allPsmsArray.ToList();
foreach (PeptideSpectralMatch psm in goodIdentifications)
{
goodScans.Add(listOfSortedms2Scans[unfilteredPsms.IndexOf(psm)]);
}
DataPointAquisitionResults currentResult = (DataPointAquisitionResults)new DataPointAcquisitionEngine(
goodIdentifications,
goodScans,
myMsDataFile,
initPrecTol,
initProdTol,
CalibrationParameters.MinMS1IsotopicPeaksNeededForConfirmedIdentification,
CommonParameters,
FileSpecificParameters,
new List<string> { taskId, "Individual Spectra Files", fileNameWithoutExtension }).Run();
return currentResult;
}
private static void WriteNewExperimentalDesignFile(string pathToOldExperDesign, string outputFolder, List<string> originalUncalibratedFileNamesWithExtension,
List<string> unsuccessfullyCalibratedFilePaths)
{
var oldExperDesign = ExperimentalDesign.ReadExperimentalDesign(pathToOldExperDesign, originalUncalibratedFileNamesWithExtension, out var errors);
if (errors.Any())
{
foreach (var error in errors)
{
Warn(error);
}
return;
}
var newExperDesign = new List<SpectraFileInfo>();
foreach (var uncalibratedSpectraFile in oldExperDesign)
{
var originalUncalibratedFilePath = uncalibratedSpectraFile.FullFilePathWithExtension;
var originalUncalibratedFilenameWithoutExtension = GlobalVariables.GetFilenameWithoutExtension(originalUncalibratedFilePath);
string calibratedFilePath = Path.Combine(outputFolder, originalUncalibratedFilenameWithoutExtension + CalibSuffix + ".mzML");
var calibratedSpectraFile = new SpectraFileInfo(calibratedFilePath,
uncalibratedSpectraFile.Condition, uncalibratedSpectraFile.BiologicalReplicate, uncalibratedSpectraFile.TechnicalReplicate, uncalibratedSpectraFile.Fraction);
if (unsuccessfullyCalibratedFilePaths.Contains(uncalibratedSpectraFile.FullFilePathWithExtension))
{
newExperDesign.Add(uncalibratedSpectraFile);
}
else
{
newExperDesign.Add(calibratedSpectraFile);
}
}
ExperimentalDesign.WriteExperimentalDesignToFile(newExperDesign);
}
}
}
| |
// 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.Linq;
using System.Reflection.Internal;
using System.Text;
using Xunit;
namespace System.Reflection.Metadata.Tests
{
public class MemoryBlockTests
{
[Fact]
public unsafe void Utf8NullTerminatedStringStartsWithAsciiPrefix()
{
byte[] heap;
fixed (byte* heapPtr = (heap = new byte[] { 0 }))
{
Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, ""));
}
fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("Hello World!\0")))
{
Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix("Hello ".Length, "World"));
Assert.False(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix("Hello ".Length, "World?"));
}
fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("x\0")))
{
Assert.False(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, "xyz"));
Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, "x"));
}
// bad metadata (#String heap is not nul-terminated):
fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("abcx")))
{
Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(3, "x"));
Assert.False(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(3, "xyz"));
}
}
[Fact]
public unsafe void EncodingLightUpHasSucceededAndTestsStillPassWithPortableFallbackAsWell()
{
Assert.True(EncodingHelper.TestOnly_LightUpEnabled); // tests run on desktop only right now.
try
{
// Re-run them with forced portable implementation.
EncodingHelper.TestOnly_LightUpEnabled = false;
DefaultDecodingFallbackMatchesBcl();
DecodingSuccessMatchesBcl();
DecoderIsUsedCorrectly();
LightUpTrickFromDifferentAssemblyWorks();
}
finally
{
EncodingHelper.TestOnly_LightUpEnabled = true;
}
}
[Fact]
public unsafe void DefaultDecodingFallbackMatchesBcl()
{
byte[] buffer;
int bytesRead;
var decoder = MetadataStringDecoder.DefaultUTF8;
// dangling lead byte
fixed (byte* ptr = (buffer = new byte[] { 0xC0 }))
{
string s = new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, null, decoder, out bytesRead);
Assert.Equal("\uFFFD", new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, null, decoder, out bytesRead));
Assert.Equal(s, Encoding.UTF8.GetString(buffer));
Assert.Equal(buffer.Length, bytesRead);
s = new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, Encoding.UTF8.GetBytes("Hello"), decoder, out bytesRead);
Assert.Equal("Hello\uFFFD", s);
Assert.Equal(s, "Hello" + Encoding.UTF8.GetString(buffer));
Assert.Equal(buffer.Length, bytesRead);
Assert.Equal("\uFFFD", new MemoryBlock(ptr, buffer.Length).PeekUtf8(0, buffer.Length));
}
// overlong encoding
fixed (byte* ptr = (buffer = new byte[] { (byte)'a', 0xC0, 0xAF, (byte)'b', 0x0 }))
{
var block = new MemoryBlock(ptr, buffer.Length);
Assert.Equal("a\uFFFD\uFFFDb", block.PeekUtf8NullTerminated(0, null, decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
}
// TODO: There are a bunch more error cases of course, but this is enough to break the old code
// and we now just call the BCL, so from a white box perspective, we needn't get carried away.
}
[Fact]
public unsafe void DecodingSuccessMatchesBcl()
{
var utf8 = Encoding.GetEncoding("utf-8", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
byte[] buffer;
int bytesRead;
string str = "\u4F60\u597D. Comment \u00E7a va?";
var decoder = MetadataStringDecoder.DefaultUTF8;
fixed (byte* ptr = (buffer = utf8.GetBytes(str)))
{
Assert.Equal(str, new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, null, decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
Assert.Equal(str + str, new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, buffer, decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
Assert.Equal(str, new MemoryBlock(ptr, buffer.Length).PeekUtf8(0, buffer.Length));
}
// To cover to big to pool case.
str = String.Concat(Enumerable.Repeat(str, 10000));
fixed (byte* ptr = (buffer = utf8.GetBytes(str)))
{
Assert.Equal(str, new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, null, decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
Assert.Equal(str + str, new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, buffer, decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
Assert.Equal(str, new MemoryBlock(ptr, buffer.Length).PeekUtf8(0, buffer.Length));
}
}
[Fact]
public unsafe void LightUpTrickFromDifferentAssemblyWorks()
{
// This is a trick to use our portable light up outside the reader assembly (that
// I will use in Roslyn). Check that it works with encoding other than UTF8 and that it
// validates arguments like the real thing.
var decoder = new MetadataStringDecoder(Encoding.Unicode);
Assert.Throws<ArgumentNullException>(() => decoder.GetString(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => decoder.GetString((byte*)1, -1));
byte[] bytes;
fixed (byte* ptr = (bytes = Encoding.Unicode.GetBytes("\u00C7a marche tr\u00E8s bien.")))
{
Assert.Equal("\u00C7a marche tr\u00E8s bien.", decoder.GetString(ptr, bytes.Length));
}
}
unsafe delegate string GetString(byte* bytes, int count);
sealed class CustomDecoder : MetadataStringDecoder
{
private GetString _getString;
public CustomDecoder(Encoding encoding, GetString getString)
: base(encoding)
{
_getString = getString;
}
public override unsafe string GetString(byte* bytes, int byteCount)
{
return _getString(bytes, byteCount);
}
}
[Fact]
public unsafe void DecoderIsUsedCorrectly()
{
byte* ptr = null;
byte[] buffer = null;
int bytesRead;
bool prefixed = false;
var decoder = new CustomDecoder(
Encoding.UTF8,
(bytes, byteCount) =>
{
Assert.True(ptr != null);
Assert.True(prefixed != (ptr == bytes));
Assert.Equal(prefixed ? "PrefixTest".Length : "Test".Length, byteCount);
string s = Encoding.UTF8.GetString(bytes, byteCount);
Assert.Equal(s, prefixed ? "PrefixTest" : "Test");
return "Intercepted";
}
);
fixed (byte* fixedPtr = (buffer = Encoding.UTF8.GetBytes("Test")))
{
ptr = fixedPtr;
Assert.Equal("Intercepted", new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, null, decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
prefixed = true;
Assert.Equal("Intercepted", new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, Encoding.UTF8.GetBytes("Prefix"), decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
}
// decoder will fail to intercept because we don't bother calling it for empty strings.
Assert.Same(String.Empty, new MemoryBlock(null, 0).PeekUtf8NullTerminated(0, null, decoder, out bytesRead));
Assert.Equal(0, bytesRead);
Assert.Same(String.Empty, new MemoryBlock(null, 0).PeekUtf8NullTerminated(0, new byte[0], decoder, out bytesRead));
Assert.Equal(0, bytesRead);
}
private unsafe void TestComparisons(string heapValue, int offset, string value, bool unicode = false, bool ignoreCase = false)
{
byte[] heap;
MetadataStringDecoder decoder = MetadataStringDecoder.DefaultUTF8;
fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes(heapValue)))
{
var block = new MemoryBlock(heapPtr, heap.Length);
string heapSubstr = GetStringHeapValue(heapValue, offset);
// compare:
if (!unicode)
{
int actualCmp = block.CompareUtf8NullTerminatedStringWithAsciiString(offset, value);
int expectedCmp = StringComparer.Ordinal.Compare(heapSubstr, value);
Assert.Equal(Math.Sign(expectedCmp), Math.Sign(actualCmp));
}
if (!ignoreCase)
{
TestComparison(block, offset, value, heapSubstr, decoder, ignoreCase: true);
}
TestComparison(block, offset, value, heapSubstr, decoder, ignoreCase);
}
}
private static unsafe void TestComparison(MemoryBlock block, int offset, string value, string heapSubstr, MetadataStringDecoder decoder, bool ignoreCase)
{
// equals:
bool actualEq = block.Utf8NullTerminatedEquals(offset, value, decoder, terminator: '\0', ignoreCase: ignoreCase);
bool expectedEq = string.Equals(heapSubstr, value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
Assert.Equal(expectedEq, actualEq);
// starts with:
bool actualSW = block.Utf8NullTerminatedStartsWith(offset, value, decoder, terminator: '\0', ignoreCase: ignoreCase);
bool expectedSW = heapSubstr.StartsWith(value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
Assert.Equal(actualSW, expectedSW);
}
[Fact]
public unsafe void ComparisonToInvalidByteSequenceMatchesFallback()
{
MetadataStringDecoder decoder = MetadataStringDecoder.DefaultUTF8;
// dangling lead byte
byte[] buffer;
fixed (byte* ptr = (buffer = new byte[] { 0xC0 }))
{
var block = new MemoryBlock(ptr, buffer.Length);
Assert.False(block.Utf8NullTerminatedStartsWith(0, new string((char)0xC0, 1), decoder, terminator: '\0', ignoreCase: false));
Assert.False(block.Utf8NullTerminatedEquals(0, new string((char)0xC0, 1), decoder, terminator: '\0', ignoreCase: false));
Assert.True(block.Utf8NullTerminatedStartsWith(0, "\uFFFD", decoder, terminator: '\0', ignoreCase: false));
Assert.True(block.Utf8NullTerminatedEquals(0, "\uFFFD", decoder, terminator: '\0', ignoreCase: false));
}
// overlong encoding
fixed (byte* ptr = (buffer = new byte[] { (byte)'a', 0xC0, 0xAF, (byte)'b', 0x0 }))
{
var block = new MemoryBlock(ptr, buffer.Length);
Assert.False(block.Utf8NullTerminatedStartsWith(0, "a\\", decoder, terminator: '\0', ignoreCase: false));
Assert.False(block.Utf8NullTerminatedEquals(0, "a\\b", decoder, terminator: '\0', ignoreCase: false));
Assert.True(block.Utf8NullTerminatedStartsWith(0, "a\uFFFD", decoder, terminator: '\0', ignoreCase: false));
Assert.True(block.Utf8NullTerminatedEquals(0, "a\uFFFD\uFFFDb", decoder, terminator: '\0', ignoreCase: false));
}
}
private string GetStringHeapValue(string heapValue, int offset)
{
int heapEnd = heapValue.IndexOf('\0');
return (heapEnd < 0) ? heapValue.Substring(offset) : heapValue.Substring(offset, heapEnd - offset);
}
[Fact]
public void Utf8NullTerminatedString_Comparisons()
{
TestComparisons("\0", 0, "");
TestComparisons("Foo\0", 0, "Foo");
TestComparisons("Foo\0", 1, "oo");
TestComparisons("Foo\0", 1, "oops");
TestComparisons("Foo", 1, "oo");
TestComparisons("Foo", 1, "oops");
TestComparisons("x", 1, "");
TestComparisons("hello\0", 0, "h");
TestComparisons("hello\0", 0, "he");
TestComparisons("hello\0", 0, "hel");
TestComparisons("hello\0", 0, "hell");
TestComparisons("hello\0", 0, "hello");
TestComparisons("hello\0", 0, "hello!");
TestComparisons("IVector`1\0", 0, "IVectorView`1");
TestComparisons("IVector`1\0", 0, "IVector");
TestComparisons("IVectorView`1\0", 0, "IVector`1");
TestComparisons("Matrix\0", 0, "Matrix3D");
TestComparisons("Matrix3D\0", 0, "Matrix");
TestComparisons("\u1234\0", 0, "\u1234", unicode: true);
TestComparisons("a\u1234\0", 0, "a", unicode: true);
TestComparisons("\u1001\u1002\u1003\0", 0, "\u1001\u1002", unicode: true);
TestComparisons("\u1001a\u1002\u1003\0", 0, "\u1001a\u1002", unicode: true);
TestComparisons("\u1001\u1002\u1003\0", 0, "\u1001a\u1002", unicode: true);
TestComparisons("\uD808\uDF45abc\0", 0, "\uD808\uDF45", unicode: true);
TestComparisons("abc\u1234", 0, "abc\u1234", unicode: true);
TestComparisons("abc\u1234", 0, "abc\u1235", unicode: true);
TestComparisons("abc\u1234", 0, "abcd", unicode: true);
TestComparisons("abcd", 0, "abc\u1234", unicode: true);
TestComparisons("AAaa\0", 0, "aAAa");
TestComparisons("A\0", 0, "a", ignoreCase: true);
TestComparisons("AAaa\0", 0, "aAAa", ignoreCase: true);
TestComparisons("matrix3d\0", 0, "Matrix3D", ignoreCase: true);
}
[Fact]
public unsafe void Utf8NullTerminatedFastCompare()
{
byte[] heap;
MetadataStringDecoder decoder = MetadataStringDecoder.DefaultUTF8;
const bool HonorCase = false;
const bool IgnoreCase = true;
const char terminator_0 = '\0';
const char terminator_F = 'F';
const char terminator_X = 'X';
const char terminator_x = 'x';
fixed (byte* heapPtr = (heap = new byte[] { (byte)'F', 0, (byte)'X', (byte)'Y', /* U+12345 (\ud808\udf45) */ 0xf0, 0x92, 0x8d, 0x85 }))
{
var block = new MemoryBlock(heapPtr, heap.Length);
TestUtf8NullTerminatedFastCompare(block, 0, terminator_0, "F", 0, HonorCase, MemoryBlock.FastComparisonResult.Equal, 1);
TestUtf8NullTerminatedFastCompare(block, 0, terminator_0, "f", 0, IgnoreCase, MemoryBlock.FastComparisonResult.Equal, 1);
TestUtf8NullTerminatedFastCompare(block, 0, terminator_F, "", 0, IgnoreCase, MemoryBlock.FastComparisonResult.Equal, 0);
TestUtf8NullTerminatedFastCompare(block, 0, terminator_F, "*", 1, IgnoreCase, MemoryBlock.FastComparisonResult.Equal, 1);
TestUtf8NullTerminatedFastCompare(block, 0, terminator_0, "FF", 0, HonorCase, MemoryBlock.FastComparisonResult.TextStartsWithBytes, 1);
TestUtf8NullTerminatedFastCompare(block, 0, terminator_0, "fF", 0, IgnoreCase, MemoryBlock.FastComparisonResult.TextStartsWithBytes, 1);
TestUtf8NullTerminatedFastCompare(block, 0, terminator_0, "F\0", 0, HonorCase, MemoryBlock.FastComparisonResult.TextStartsWithBytes, 1);
TestUtf8NullTerminatedFastCompare(block, 0, terminator_X, "F\0", 0, HonorCase, MemoryBlock.FastComparisonResult.TextStartsWithBytes, 1);
TestUtf8NullTerminatedFastCompare(block, 2, terminator_0, "X", 0, HonorCase, MemoryBlock.FastComparisonResult.BytesStartWithText, 1);
TestUtf8NullTerminatedFastCompare(block, 2, terminator_0, "x", 0, IgnoreCase, MemoryBlock.FastComparisonResult.BytesStartWithText, 1);
TestUtf8NullTerminatedFastCompare(block, 2, terminator_x, "XY", 0, IgnoreCase, MemoryBlock.FastComparisonResult.BytesStartWithText, 2);
TestUtf8NullTerminatedFastCompare(block, 3, terminator_0, "yZ", 0, IgnoreCase, MemoryBlock.FastComparisonResult.Unequal, 1);
TestUtf8NullTerminatedFastCompare(block, 4, terminator_0, "a", 0, HonorCase, MemoryBlock.FastComparisonResult.Unequal, 0);
TestUtf8NullTerminatedFastCompare(block, 4, terminator_0, "\ud808", 0, HonorCase, MemoryBlock.FastComparisonResult.Inconclusive, 0);
TestUtf8NullTerminatedFastCompare(block, 4, terminator_0, "\ud808\udf45", 0, HonorCase, MemoryBlock.FastComparisonResult.Inconclusive, 0);
}
}
private void TestUtf8NullTerminatedFastCompare(
MemoryBlock block,
int offset,
char terminator,
string comparand,
int comparandOffset,
bool ignoreCase,
MemoryBlock.FastComparisonResult expectedResult,
int expectedFirstDifferenceIndex)
{
int actualFirstDifferenceIndex;
var actualResult = block.Utf8NullTerminatedFastCompare(offset, comparand, comparandOffset, out actualFirstDifferenceIndex, terminator, ignoreCase);
Assert.Equal(expectedResult, actualResult);
Assert.Equal(expectedFirstDifferenceIndex, actualFirstDifferenceIndex);
}
private unsafe void TestSearch(string heapValue, int offset, string[] values)
{
byte[] heap;
fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes(heapValue)))
{
int actual = new MemoryBlock(heapPtr, heap.Length).BinarySearch(values, offset);
string heapSubstr = GetStringHeapValue(heapValue, offset);
int expected = Array.BinarySearch(values, heapSubstr);
Assert.Equal(expected, actual);
}
}
[Fact]
public void BinarySearch()
{
TestSearch("a\0", 0, new string[0]);
TestSearch("a\0", 0, new[] { "b" });
TestSearch("b\0", 0, new[] { "b" });
TestSearch("c\0", 0, new[] { "b" });
TestSearch("a\0", 0, new[] { "b", "d" });
TestSearch("b\0", 0, new[] { "b", "d" });
TestSearch("c\0", 0, new[] { "b", "d" });
TestSearch("d\0", 0, new[] { "b", "d" });
TestSearch("e\0", 0, new[] { "b", "d" });
TestSearch("a\0", 0, new[] { "b", "d", "f" });
TestSearch("b\0", 0, new[] { "b", "d", "f" });
TestSearch("c\0", 0, new[] { "b", "d", "f" });
TestSearch("d\0", 0, new[] { "b", "d", "f" });
TestSearch("e\0", 0, new[] { "b", "d", "f" });
TestSearch("f\0", 0, new[] { "b", "d", "f" });
TestSearch("g\0", 0, new[] { "b", "d", "f" });
TestSearch("a\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("b\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("c\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("d\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("e\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("f\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("g\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("m\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("n\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("z\0", 0, new[] { "b", "d", "f", "m" });
}
[Fact]
public unsafe void BuildPtrTable_SmallRefs()
{
const int rowSize = 4;
const int secondColumnOffset = 2;
var table = new byte[]
{
0xAA, 0xAA, 0x05, 0x00,
0xBB, 0xBB, 0x04, 0x00,
0xCC, 0xCC, 0x02, 0x01,
0xDD, 0xDD, 0x02, 0x00,
0xEE, 0xEE, 0x01, 0x01,
};
int rowCount = table.Length / rowSize;
fixed (byte* tablePtr = table)
{
var block = new MemoryBlock(tablePtr, table.Length);
Assert.Equal(0x0004, block.PeekReference(6, smallRefSize: true));
var actual = block.BuildPtrTable(rowCount, rowSize, secondColumnOffset, isReferenceSmall: true);
var expected = new int[] { 4, 2, 1, 5, 3 };
Assert.Equal(expected, actual);
}
}
[Fact]
public unsafe void BuildPtrTable_LargeRefs()
{
const int rowSize = 6;
const int secondColumnOffset = 2;
var table = new byte[]
{
0xAA, 0xAA, 0x10, 0x00, 0x05, 0x00,
0xBB, 0xBB, 0x10, 0x00, 0x04, 0x00,
0xCC, 0xCC, 0x10, 0x00, 0x02, 0x01,
0xDD, 0xDD, 0x10, 0x00, 0x02, 0x00,
0xEE, 0xEE, 0x10, 0x00, 0x01, 0x01,
};
int rowCount = table.Length / rowSize;
fixed (byte* tablePtr = table)
{
var block = new MemoryBlock(tablePtr, table.Length);
Assert.Equal(0x00040010, block.PeekReference(8, smallRefSize: false));
var actual = block.BuildPtrTable(rowCount, rowSize, secondColumnOffset, isReferenceSmall: false);
var expected = new int[] { 4, 2, 1, 5, 3 };
Assert.Equal(expected, actual);
}
}
[Fact]
public unsafe void PeekReference()
{
var table = new byte[]
{
0xff, 0xff, 0xff, 0x00, // offset 0
0xff, 0xff, 0xff, 0x01, // offset 4
0xff, 0xff, 0xff, 0x1f, // offset 8
0xff, 0xff, 0xff, 0x2f, // offset 12
0xff, 0xff, 0xff, 0xff, // offset 16
};
fixed (byte* tablePtr = table)
{
var block = new MemoryBlock(tablePtr, table.Length);
Assert.Equal(0x0000ffff, block.PeekReference(0, smallRefSize: true));
Assert.Equal(0x0000ffff, block.PeekHeapReference(0, smallRefSize: true));
Assert.Equal(0x0000ffffu, block.PeekReferenceUnchecked(0, smallRefSize: true));
Assert.Equal(0x00ffffff, block.PeekReference(0, smallRefSize: false));
Assert.Throws<BadImageFormatException>(() => block.PeekReference(4, smallRefSize: false));
Assert.Throws<BadImageFormatException>(() => block.PeekReference(16, smallRefSize: false));
Assert.Equal(0x1fffffff, block.PeekHeapReference(8, smallRefSize: false));
Assert.Throws<BadImageFormatException>(() => block.PeekHeapReference(12, smallRefSize: false));
Assert.Throws<BadImageFormatException>(() => block.PeekHeapReference(16, smallRefSize: false));
Assert.Equal(0x01ffffffu, block.PeekReferenceUnchecked(4, smallRefSize: false));
Assert.Equal(0x1fffffffu, block.PeekReferenceUnchecked(8, smallRefSize: false));
Assert.Equal(0x2fffffffu, block.PeekReferenceUnchecked(12, smallRefSize: false));
Assert.Equal(0xffffffffu, block.PeekReferenceUnchecked(16, smallRefSize: false));
}
}
}
}
| |
// Copyright (c) Massive Pixel. All Rights Reserved. Licensed under the MIT License (MIT). See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Sancho.DOM.Model;
using Sancho.XAMLParser;
using Sancho.XAMLParser.Interfaces;
using Serilog;
using Xamarin.Forms;
namespace Sancho.DOM.XamarinForms
{
public partial class XamlDOMCreator : IXamlDOM
{
IXamlServices xamlServices;
public object Root { get; private set; }
public TargetPlatform Platform { get; set; }
Dictionary<XamlNode, object> nodeToElementMapper = new Dictionary<XamlNode, object>();
public XamlDOMCreator()
{
Log.Verbose($"{nameof(XamlDOMCreator)} created");
}
public XamlDOMCreator(IXamlServices services)
{
xamlServices = services;
Log.Verbose($"{nameof(XamlDOMCreator)} created");
}
public void AddNode(XamlNode node)
{
Log.Verbose("Adding node {node}", node);
if (node == null)
{
Log.Warning("Cannot add null node");
return;
}
Root = null;
nodeToElementMapper = new Dictionary<XamlNode, object>();
AddChild(null, node);
if (Root != null)
{
// now apply markup extensions
ApplyMarkupExtensions(nodeToElementMapper.FirstOrDefault(x => x.Value == Root).Key);
}
}
void ApplyMarkupExtensions(XamlNode node, XamlNode parent = null)
{
if (node == null) return;
foreach (var child in node.Children)
ApplyMarkupExtensions(child, node);
foreach (var prop in node.Properties)
{
if (!(prop is XamlStringProperty))
continue;
var value = prop.GetString();
if (value.StartsWith("{", StringComparison.Ordinal))
{
var element = nodeToElementMapper[node];
var p = element.GetType().GetRuntimeProperty(prop.Name);
if (p == null)
{
Log.Warning($"No property {prop.Name} found under {element.GetType().FullName}");
return;
}
ParseMarkupExtension(element, p, value);
}
}
}
void AddChild(object parent, XamlNode node)
{
var element = CreateNode(node, parent);
if (parent == null)
{
Log.Debug("Setting {node} as root", element);
Root = element;
}
else if (element is View)
{
Log.Debug("Adding {element} as child to parent", element);
AddToParent(parent, (View)element);
}
else if (element is Setter)
{
if (parent is Style)
((Style)parent).Setters.Add((Setter)element);
}
else if (element is ResourceDictionary)
{
if (parent is VisualElement)
{
Log.Debug("Adding resource dictionary to parent page");
((VisualElement)parent).Resources = (ResourceDictionary)element;
}
}
}
void AddToParent(object parent, View view)
{
if (parent == null || view == null)
{
Log.Warning("Both parent and view must be non null");
return;
}
var contentProp = ReflectionHelpers.GetContentProperty(parent.GetType());
if (contentProp != null)
{
Log.Debug($"Content property {contentProp.Name} found for {{parent}}", parent);
if (typeof(IList<View>).GetTypeInfo().IsAssignableFrom(contentProp.PropertyType.GetTypeInfo()))
{
Log.Debug("Content property is a list");
var list = contentProp.GetValue(parent) as IList<View>;
list?.Add(view);
}
else if (typeof(View).GetTypeInfo().IsAssignableFrom(contentProp.PropertyType.GetTypeInfo()))
{
Log.Debug("Content property is a single View");
contentProp.SetValue(parent, view);
}
else
{
Log.Warning($"Unknown content property type '{contentProp.PropertyType.FullName}'");
}
}
else
{
Log.Warning("Cannot add {view} under {parent} as parent doesn't contain content property", view, parent);
}
}
void ApplyProperty(object parent, XamlProperty xamlProperty)
{
if (parent == null)
{
Log.Warning("Parent is null");
return;
}
if (xamlProperty == null)
{
Log.Warning("Property is null");
return;
}
if (string.IsNullOrWhiteSpace(xamlProperty.Name))
{
Log.Verbose("Unnamed property is probably a content value");
if (xamlProperty is XamlStringProperty)
{
Log.Debug("Setting string content property");
var contentProp = ReflectionHelpers.GetContentProperty(parent.GetType());
if (contentProp == null)
{
Log.Warning($"No content property for {parent.GetType().FullName}");
}
else if (contentProp.PropertyType != typeof(string))
{
Log.Warning($"Content property should be string, it is {contentProp.PropertyType.FullName}");
}
else
{
Log.Debug($"Setting content property value {xamlProperty.GetString()}");
contentProp.SetValue(parent, xamlProperty.GetString());
}
}
else if (xamlProperty is XamlNodesProperty)
{
Log.Debug("Setting nodes content property");
var nodes = xamlProperty.GetNodes();
if (!nodes.Any())
{
Log.Warning("No nodes found under {property}", xamlProperty);
}
else if (nodes.Any())
{
foreach (var node in nodes)
{
var view = CreateNode(node) as View;
if (view != null)
AddToParent(parent, view);
}
}
}
else
{
Log.Warning($"Unsupported property type {xamlProperty.GetType().FullName}");
}
}
else if (xamlProperty.Name.Contains("."))
{
Log.Debug("Setting attached {property}", xamlProperty);
HandleAttachedProperty(parent, xamlProperty.Name, xamlProperty.GetString());
}
else
{
Log.Debug("Setting regular {property}", xamlProperty);
HandleProperty(parent, xamlProperty);
}
}
void HandleProperty(object parent, XamlProperty xamlProperty)
{
if (parent == null)
{
Log.Warning("Parent shouldn't be bull");
return;
}
if (xamlProperty == null)
{
Log.Warning("Property shouldn't be null");
return;
}
var prop = parent.GetType().GetRuntimeProperty(xamlProperty.Name);
if (prop == null)
{
Log.Warning($"No property {xamlProperty.Name} found under {parent.GetType().FullName}");
return;
}
Log.Verbose("Found property {prop}", prop);
if (xamlProperty is XamlStringProperty)
{
Log.Debug("Setting string attribute");
Apply(parent, prop, xamlProperty.GetString());
}
else if (xamlProperty is XamlNodesProperty)
{
Log.Debug("Setting object attribute");
var values = xamlProperty.GetNodes()
.Select(node => CreateNode(node))
.Where(v => v != null)
.ToList();
if (!values.Any())
{
Log.Debug($"No values found for property {prop.Name}");
return;
}
if (prop.PropertyType == typeof(ResourceDictionary))
{
var resDict = values.OfType<ResourceDictionary>().FirstOrDefault();
if (resDict != null)
{
Log.Debug($"Setting resource dictionary to parent {parent.GetType().FullName}");
prop.SetValue(parent, resDict);
}
}
else if (typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(prop.PropertyType.GetTypeInfo()))
{
Log.Debug("Target property is a an IEnumerable");
var propValue = prop.GetValue(parent);
if (propValue == null)
{
Log.Debug($"Property {prop.Name} is null, try creating it");
try
{
prop.SetValue(parent, propValue = Activator.CreateInstance(prop.PropertyType));
}
catch
{
Log.Warning($"Unable to set property {prop.Name} with new instance of {prop.PropertyType.FullName}");
}
}
if (propValue != null)
{
var addMethod = prop.PropertyType
.GetRuntimeMethods()
.FirstOrDefault(m => m.Name == "Add");
if (addMethod == null)
{
Log.Warning($"Cannot find Add method for {prop.PropertyType.FullName}");
return;
}
foreach (var value in values)
{
try
{
addMethod.Invoke(propValue, new[] { value });
}
catch (Exception ex)
{
Log.Error(ex, $"Unable to add {{value}} to property {prop.Name}", value);
}
}
}
}
else
{
var value = values.First();
Log.Debug($"Setting single {{value}} for property {prop.Name}", value);
if (prop.PropertyType.GetTypeInfo().IsAssignableFrom(value.GetType().GetTypeInfo()))
{
Log.Verbose($"Setting {prop.Name}");
prop.SetValue(parent, values[0]);
}
else if (value?.GetType()?.Name?.StartsWith("OnPlatform") == true)
{
Log.Verbose("Setting OnPlatform property");
if (Platform == TargetPlatform.iOS)
{
var platprop = value.GetType()
.GetRuntimeProperty(nameof(OnPlatform<int>.iOS));
if (platprop != null)
{
var platformValue = platprop.GetValue(value);
prop.SetValue(parent, platformValue);
}
}
else
{
Log.Warning($"Platform {Platform} is not supported");
}
}
else
{
Log.Warning($"Value type {value.GetType().FullName} is not compatible with {prop.PropertyType.FullName}");
}
}
}
}
object CreateNode(XamlNode node, object parent = null)
{
var element = CreateNodeInternal(node, parent);
if (element != null)
nodeToElementMapper.Add(node, element);
return element;
}
object CreateNodeInternal(XamlNode node, object parent = null)
{
if (node == null)
{
Log.Warning("Cannot create node from null value");
return null;
}
if (node.Name == "DataTemplate")
{
Log.Debug("Creating DataTemplate");
var dt = new DataTemplate(() =>
{
if (node.Children.Any())
return CreateNode(node.Children.FirstOrDefault());
return null;
});
return dt;
}
var type = ReflectionHelpers.GetType(node.Name);
if (type == null)
{
Log.Information($"{node.Name} not found in View types");
type = ReflectionHelpers.GetAllType(node.Name);
if (type == null)
Log.Information($"{node.Name} not found in all types");
}
if (type != null)
{
Log.Debug($"Found type for {node.Name}");
object element = null;
// special case for certain types
var typeConverter = ReflectionHelpers.GetTypeConverter(type);
if (typeConverter != null && node.Properties.Any(p => p.IsContent))
{
Log.Debug($"Node {{node}} is constructed via type converter {typeConverter.GetType().FullName}", node);
element = typeConverter.ConvertFromInvariantString(node.Properties.First(p => p.IsContent).GetString());
}
if (type == typeof(Style))
{
var targetTypeProp = node.Properties
.OfType<XamlStringProperty>()
.FirstOrDefault(p => p.Name == nameof(Style.TargetType));
if (targetTypeProp == null)
{
Log.Error($"Invalid style, missing TargetType property");
return null;
}
var targetType = ReflectionHelpers.GetType(targetTypeProp.GetString());
if (targetType == null)
{
Log.Error($"Invalid target type for style: '{targetTypeProp.GetString()}'");
return null;
}
Log.Debug($"Creating style for target type {targetType.FullName}");
element = Activator.CreateInstance(type, new[] { targetType });
}
if (element == null)
{
element = Activator.CreateInstance(type);
}
if (element is Setter)
{
var propertyProp = node.Properties.FirstOrDefault(p => p.Name == nameof(Setter.Property));
BindableProperty setterProp = null;
if (propertyProp != null)
{
if (parent is Style)
{
var targetType = ((Style)parent).TargetType;
setterProp = targetType.GetRuntimeFields()
.Select(field => field.GetValue(null))
.OfType<BindableProperty>()
.FirstOrDefault(bp => bp.PropertyName == propertyProp.GetString());
if (setterProp != null)
((Setter)element).Property = setterProp;
}
}
var valueProp = node.Properties
.FirstOrDefault(p => p.Name == nameof(Setter.Value));
if (valueProp != null && setterProp != null)
{
typeConverter = setterProp.DeclaringType
.GetRuntimeProperty(setterProp.PropertyName)
.IfNotNull(p => ReflectionHelpers.GetTypeConverterForProperty(p));
var value = valueProp.GetString();
object converted;
if (typeConverter != null)
{
converted = typeConverter.ConvertFromInvariantString(value);
((Setter)element).Value = converted;
}
else if (Parse(setterProp.ReturnType, value, out converted))
{
((Setter)element).Value = converted;
}
}
}
else
{
foreach (var prop in node.Properties)
ApplyProperty(element, prop);
}
foreach (var child in node.Children)
{
if (element is ResourceDictionary)
{
var key = child.Properties
.FirstOrDefault(p => p.Name == "Key")
.IfNotNull(p =>
{
if (p is XamlStringProperty)
return p.GetString();
return null;
});
var value = CreateNode(child);
if (key == null)
{
Log.Error("Adding static resource without a key!");
}
else if (value == null)
{
Log.Error("Adding static resource with null value!");
}
else
{
Log.Debug($"Adding static resource {key} to resource dictionary");
element.Cast<ResourceDictionary>()
.Add(key, value);
}
}
else
{
AddChild(element, child);
}
}
return element;
}
if (node.Name == "OnPlatform")
{
Log.Debug("Creating OnPlatform Node");
// find generic OnPlatform type
type = ReflectionHelpers.AllTypes.FirstOrDefault(t => t.Key.Contains("OnPlatform")).Value;
var typeArgumentProperty = node.Properties.FirstOrDefault(p => p.Name == "TypeArguments");
if (typeArgumentProperty == null)
{
Log.Error("Missing explicit type argument in OnPlatform node");
}
else if (typeArgumentProperty != null)
{
var typeArgumentTypeName = typeArgumentProperty.GetString();
var typeArgument = ReflectionHelpers.GetType(typeArgumentTypeName) ??
ReflectionHelpers.GetAllType(typeArgumentTypeName);
if (typeArgument == null)
{
Log.Error($"Unable to find type for {typeArgumentTypeName}");
}
else
{
// create concrete type in the form OnPlatform<Type>
type = type.MakeGenericType(new[] { typeArgument });
var element = Activator.CreateInstance(type);
// apply all child properties
foreach (var prop in node.Properties)
{
ApplyProperty(element, prop);
}
return element;
}
}
}
Log.Debug($"Unable to create from {node.Name}");
return null;
}
public void HandleAttachedProperty(object o, string property, string value)
{
if (o == null)
{
Log.Warning("Target object is null");
return;
}
if (string.IsNullOrWhiteSpace(property))
{
Log.Warning("Invalid property name.");
return;
}
if (string.IsNullOrWhiteSpace(value))
{
Log.Warning("Ignoring null value for property");
return;
}
var parts = property.Split(new[] { '.' });
if (parts.Length != 2)
{
Log.Error($"Invalid attached property '{property}'");
return;
}
Type owner = ReflectionHelpers.GetType(parts[0]);
if (owner == null)
{
Log.Error($"Owner type for attached property '{parts[0]}' not found");
return;
}
var methods = owner.GetTypeInfo().DeclaredMethods;
var method = methods.FirstOrDefault(x => x.Name == $"Set{parts[1]}");
if (method == null)
{
Log.Error($"Cannot find setter method for attached property '{parts[1]}' on type '{parts[0]}'");
return;
}
var parameters = method.GetParameters();
if (parameters.Length != 2)
{
Log.Error($"Invalid number of arguments for method '{method.Name}': got {parameters.Length}, expected 2");
return;
}
if (!parameters[0].ParameterType.GetTypeInfo().IsAssignableFrom(o.GetType().GetTypeInfo()))
{
Log.Error($"Setter method expected '{parameters[0].ParameterType.FullName}', provided object was of type '{o.GetType().FullName}'");
return;
}
object parsed;
if (!Parse(parameters[1].ParameterType, value, out parsed))
{
Log.Error($"Cannot parse value '{value}' for attached property {property}");
return;
}
if (parsed == null)
{
Log.Error($"Ignoring null values for attached property {property}");
return;
}
if (!parameters[1].ParameterType.GetTypeInfo().IsAssignableFrom(parsed.GetType().GetTypeInfo()))
{
Log.Error($"Invalid parsed value type. Expected '{parameters[1].ParameterType.FullName}', got '{parsed.GetType().FullName}'");
return;
}
try
{
method.Invoke(null, new object[] { o, parsed });
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//#define COLLECT_PERFORMANCE_DATA_FOR_CONTROLLER
namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
public sealed class Controller
{
//
// State
//
private readonly TypeSystemForCodeTransformation m_typeSystem;
private readonly CallsDataBase m_callsDatabase;
private readonly LinkedList< PhaseDriver > m_phases;
private PhaseDriver m_currentPhase;
//
// Constructor Methods
//
public Controller( TypeSystemForCodeTransformation typeSystem, List<String> phases )
{
m_typeSystem = typeSystem;
m_callsDatabase = new CallsDataBase( );
m_phases = new LinkedList<PhaseDriver>( );
//--//
var lst = new List<PhaseDriver>( );
CreatePhaseDrivers( lst, phases );
var orderingForward = HashTableFactory.NewWithReferenceEquality<PhaseDriver, List<PhaseDriver>>( );
var orderingBackward = HashTableFactory.NewWithReferenceEquality<PhaseDriver, List<PhaseDriver>>( );
CollectPhaseOrderingConstraints( lst, orderingForward, orderingBackward );
ValidateConstraints( lst, orderingForward );
SortPhaseDrivers( lst, orderingBackward );
DumpPhaseOrdering( );
}
public Controller( TypeSystemForCodeTransformation typeSystem ) : this( typeSystem, null )
{
}
//
// Helper Methods
//
private void CreatePhaseDrivers( List<PhaseDriver> lst, List<String> userDisabledPhases )
{
var assembly = System.Reflection.Assembly.GetCallingAssembly();
foreach(Type t in assembly.GetTypes())
{
if(t.IsAbstract == false && t.IsSubclassOf( typeof(PhaseDriver) ))
{
bool fDisabled = false;
// check if this phase appears in the list crafted by the user
if( userDisabledPhases != null && userDisabledPhases.Count > 0 )
{
foreach( var p in userDisabledPhases )
{
if(t.Name == p)
{
fDisabled = true;
break;
}
}
}
// check if phase has been disabled through attribute
if( !fDisabled )
{
// check that this phase is not disabled
// disabled phases cannot run
var e = t.CustomAttributes.GetEnumerator( );
while( e.MoveNext( ) )
{
if( e.Current.AttributeType == typeof( PhaseDisabledAttribute ) )
{
fDisabled = true;
break;
}
}
}
var phase = (PhaseDriver)Activator.CreateInstance(t, this);
phase.Disabled = fDisabled;
lst.Add(phase);
}
}
}
private static void CollectPhaseOrderingConstraints( List < PhaseDriver > lst ,
GrowOnlyHashTable< PhaseDriver, List< PhaseDriver > > orderingForward ,
GrowOnlyHashTable< PhaseDriver, List< PhaseDriver > > orderingBackward )
{
foreach(var phase in lst)
{
var phaseAfter = FindPhaseByType( lst, phase.ExecuteAfter );
if(phaseAfter != null)
{
HashTableWithListFactory.AddUnique( orderingForward , phaseAfter, phase );
HashTableWithListFactory.AddUnique( orderingBackward, phase , phaseAfter );
}
var phaseBefore = FindPhaseByType( lst, phase.ExecuteBefore );
if(phaseBefore != null)
{
HashTableWithListFactory.AddUnique( orderingForward , phase , phaseBefore );
HashTableWithListFactory.AddUnique( orderingBackward, phaseBefore, phase );
}
}
}
private static void ValidateConstraints( List < PhaseDriver > lst ,
GrowOnlyHashTable< PhaseDriver, List< PhaseDriver > > orderingForward )
{
var set = SetFactory.NewWithReferenceEquality< PhaseDriver >();
foreach(var phase in lst)
{
set.Clear();
if(FindOrderingLoop( orderingForward, set, phase, phase ))
{
throw TypeConsistencyErrorException.Create( "Found loop in phase ordering constraints" );
}
}
}
private static bool FindOrderingLoop( GrowOnlyHashTable< PhaseDriver, List< PhaseDriver > > ordering ,
GrowOnlySet < PhaseDriver > set ,
PhaseDriver phaseStart ,
PhaseDriver phase )
{
set.Insert( phase );
List< PhaseDriver > lst;
if(ordering.TryGetValue( phase, out lst ))
{
foreach(var phaseNext in lst)
{
if(phaseNext == phaseStart)
{
return true;
}
if(FindOrderingLoop( ordering, set, phaseStart, phaseNext ))
{
return true;
}
}
}
return false;
}
private void SortPhaseDrivers( List < PhaseDriver > lst ,
GrowOnlyHashTable< PhaseDriver, List< PhaseDriver > > orderingBackward )
{
//
// Keep looking for a phase that doesn't have any pending predecessors.
// This is guaranteed to make progress, since we have already proved there are no loops.
//
while(lst.Count > 0)
{
foreach(var phase in lst)
{
List< PhaseDriver > lstPredecessors;
bool fAdd = true;
if(orderingBackward.TryGetValue( phase, out lstPredecessors ))
{
foreach(var phasePredecessor in lstPredecessors)
{
if(phasePredecessor.m_node == null)
{
//
// Predecessor not inserted, can't add to the list.
//
fAdd = false;
break;
}
}
}
if(fAdd)
{
phase.m_node = m_phases.AddLast( phase );
lst.Remove( phase );
break;
}
}
}
}
private void DumpPhaseOrdering()
{
Console.WriteLine("");
Console.WriteLine("Phase Ordering:");
foreach(var phase in m_phases)
{
if (phase.Disabled)
{
var color = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(" {0}: {1} (Disabled)", phase.PhaseIndex, phase);
Console.ForegroundColor = color;
}
else
{
Console.WriteLine(" {0}: {1}", phase.PhaseIndex, phase);
}
}
Console.WriteLine( "" );
Console.WriteLine( "" );
}
//--//
public void ExecuteSteps( bool fGenerateImageOnly = false )
{
Console.WriteLine( "Compiling..." );
Console.WriteLine( "" );
//
// 1) Expand the Call Closure to include all the overrides of virtual methods.
// Question: should we wait until we know all the types used by the application?
//
// 2) For all the ForceDevirtualization types, find the implementation. Virtual calls should be changed to normal calls.
// Question: should we use a ClassExtension-like mechanism? Not for now.
//
// 3) ImplicitInstance == you cannot create objects for this type. For now, it's not-implemented!
//
// 4) ForceDevirtualization = there should be only one subclass used by the application
// => keep track of referenced types, marking some types as unavailable. For now, we could simplify and abort on multiple sub-classes.
//
RegisterPhases();
m_currentPhase = m_phases.First.Value;
while(m_currentPhase != null)
{
if(fGenerateImageOnly && ((m_currentPhase is Phases.GenerateImage) == false))
{
m_currentPhase = m_currentPhase.NextPhase;
continue;
}
if(m_currentPhase.Disabled)
{
var color = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine( "Skipping phase: {0}", m_currentPhase );
Console.ForegroundColor = color;
m_currentPhase = m_currentPhase.NextPhase;
continue;
}
using(new Transformations.ExecutionTiming( m_currentPhase.ToString() ))
{
m_typeSystem.NotifyCompilationPhaseInner( m_currentPhase );
#if COLLECT_PERFORMANCE_DATA_FOR_CONTROLLER
PerformanceCounters.ContextualTiming timing = new PerformanceCounters.ContextualTiming();
timing.Start( this, string.Format( "Phase__{0}", m_currentPhase ) );
#endif
var nextPhase = m_currentPhase.Execute();
#if COLLECT_PERFORMANCE_DATA_FOR_CONTROLLER
timing.Stop();
#endif
if(nextPhase != null)
{
foreach(var phase in m_phases)
{
phase.ValidatePhaseMovement( m_currentPhase, nextPhase );
}
}
m_currentPhase = nextPhase;
}
}
}
private void RegisterPhases()
{
var cache = m_typeSystem.GetEnvironmentService< IR.CompilationSteps.DelegationCache >();
cache.Register( new Handlers.MethodTransformations() );
cache.Register( new Handlers.ProtectRequiredEntities() );
cache.Register( new Handlers.WellKnownFieldHandlers() );
cache.Register( new Handlers.WellKnownMethodHandlers() );
cache.Register( new Handlers.OperatorHandlers_HighLevel() );
cache.Register( new Handlers.OperatorHandlers_HighLevelToMidLevel() );
cache.Register( new Handlers.OperatorHandlers_FromImplicitToExplicitExceptions() );
cache.Register( new Handlers.OperatorHandlers_ReferenceCountingGarbageCollection() );
cache.Register( new Handlers.OperatorHandlers_ConvertUnsupportedOperatorsToMethodCalls() );
cache.Register( new Handlers.OperatorHandlers_ExpandAggregateTypes() );
cache.Register( new Handlers.OperatorHandlers_MidLevelToLowLevel() );
cache.Register( new Handlers.Optimizations() );
m_typeSystem.PlatformAbstraction.RegisterForNotifications( m_typeSystem, cache );
m_typeSystem.CallingConvention .RegisterForNotifications( m_typeSystem, cache );
}
//--//
internal T FindPhase< T >() where T : PhaseDriver
{
return (T)FindPhaseByType( typeof(T) );
}
internal PhaseDriver FindPhaseByType( Type type )
{
return FindPhaseByType( m_phases, type );
}
private static PhaseDriver FindPhaseByType( IEnumerable< PhaseDriver > lst ,
Type type )
{
if(type != null)
{
foreach(var phase in lst)
{
if(phase.GetType() == type)
{
return phase;
}
}
}
return null;
}
//--//
//
// Access Methods
//
internal TypeSystemForCodeTransformation TypeSystem
{
get
{
return m_typeSystem;
}
}
internal CallsDataBase CallsDatabase
{
get
{
return m_callsDatabase;
}
}
public GrowOnlyHashTable< MethodRepresentation, GrowOnlySet< object > > EntitiesReferencedByMethods
{
get
{
CHECKS.ASSERT( m_currentPhase.PhaseIndex > FindPhase< Phases.ComputeCallsClosure >().PhaseIndex, "Cannot access EntitiesReferencedByMethods property at phase {0}!", m_currentPhase );
var phase = this.FindPhase< Phases.ComputeCallsClosure >();
return phase.EntitiesReferencedByMethods;
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//-----------------------------------------------------------------------------
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics.SymbolStore;
namespace Microsoft.Cci.Pdb
{
internal class PdbFile
{
private PdbFile() // This class can't be instantiated.
{
}
static void LoadGuidStream(BitAccess bits, out Guid doctype, out Guid language, out Guid vendor)
{
bits.ReadGuid(out language);
bits.ReadGuid(out vendor);
bits.ReadGuid(out doctype);
}
static Dictionary<string, int> LoadNameIndex(BitAccess bits)
{
Dictionary<string, int> result = new Dictionary<string, int>();
int ver;
int sig;
int age;
Guid guid;
bits.ReadInt32(out ver); // 0..3 Version
bits.ReadInt32(out sig); // 4..7 Signature
bits.ReadInt32(out age); // 8..11 Age
bits.ReadGuid(out guid); // 12..27 GUID
//if (ver != 20000404) {
// throw new PdbDebugException("Unsupported PDB Stream version {0}", ver);
//}
// Read string buffer.
int buf;
bits.ReadInt32(out buf); // 28..31 Bytes of Strings
int beg = bits.Position;
int nxt = bits.Position + buf;
bits.Position = nxt;
// Read map index.
int cnt; // n+0..3 hash size.
int max; // n+4..7 maximum ni.
bits.ReadInt32(out cnt);
bits.ReadInt32(out max);
BitSet present = new BitSet(bits);
BitSet deleted = new BitSet(bits);
if (!deleted.IsEmpty)
{
throw new PdbDebugException("Unsupported PDB deleted bitset is not empty.");
}
int j = 0;
for (int i = 0; i < max; i++)
{
if (present.IsSet(i))
{
int ns;
int ni;
bits.ReadInt32(out ns);
bits.ReadInt32(out ni);
string name;
int saved = bits.Position;
bits.Position = beg + ns;
bits.ReadCString(out name);
bits.Position = saved;
result.Add(name.ToUpperInvariant(), ni);
j++;
}
}
if (j != cnt)
{
throw new PdbDebugException("Count mismatch. ({0} != {1})", j, cnt);
}
return result;
}
static IntHashTable LoadNameStream(BitAccess bits)
{
IntHashTable ht = new IntHashTable();
uint sig;
int ver;
bits.ReadUInt32(out sig); // 0..3 Signature
bits.ReadInt32(out ver); // 4..7 Version
// Read (or skip) string buffer.
int buf;
bits.ReadInt32(out buf); // 8..11 Bytes of Strings
if (sig != 0xeffeeffe || ver != 1)
{
throw new PdbDebugException("Unsupported Name Stream version. " +
"(sig={0:x8}, ver={1})",
sig, ver);
}
int beg = bits.Position;
int nxt = bits.Position + buf;
bits.Position = nxt;
// Read hash table.
int siz;
bits.ReadInt32(out siz); // n+0..3 Number of hash buckets.
nxt = bits.Position;
for (int i = 0; i < siz; i++)
{
int ni;
string name;
bits.ReadInt32(out ni);
if (ni != 0)
{
int saved = bits.Position;
bits.Position = beg + ni;
bits.ReadCString(out name);
bits.Position = saved;
ht.Add(ni, name);
}
}
bits.Position = nxt;
return ht;
}
private static PdbFunction match = new PdbFunction();
private static int FindFunction(PdbFunction[] funcs, ushort sec, uint off)
{
match.segment = sec;
match.address = off;
return Array.BinarySearch(funcs, match, PdbFunction.byAddress);
}
static void LoadManagedLines(PdbFunction[] funcs,
IntHashTable names,
BitAccess bits,
MsfDirectory dir,
Dictionary<string, int> nameIndex,
PdbReader reader,
uint limit,
Dictionary<string, PdbSource> sourceCache)
{
Array.Sort(funcs, PdbFunction.byAddressAndToken);
int begin = bits.Position;
IntHashTable checks = ReadSourceFileInfo(bits, limit, names, dir, nameIndex, reader, sourceCache);
// Read the lines next.
bits.Position = begin;
while (bits.Position < limit)
{
int sig;
int siz;
bits.ReadInt32(out sig);
bits.ReadInt32(out siz);
int endSym = bits.Position + siz;
switch ((DEBUG_S_SUBSECTION)sig)
{
case DEBUG_S_SUBSECTION.LINES:
{
CV_LineSection sec;
bits.ReadUInt32(out sec.off);
bits.ReadUInt16(out sec.sec);
bits.ReadUInt16(out sec.flags);
bits.ReadUInt32(out sec.cod);
int funcIndex = FindFunction(funcs, sec.sec, sec.off);
if (funcIndex < 0) break;
var func = funcs[funcIndex];
if (func.lines == null)
{
while (funcIndex > 0)
{
var f = funcs[funcIndex - 1];
if (f.lines != null || f.segment != sec.sec || f.address != sec.off) break;
func = f;
funcIndex--;
}
}
else
{
while (funcIndex < funcs.Length - 1 && func.lines != null)
{
var f = funcs[funcIndex + 1];
if (f.segment != sec.sec || f.address != sec.off) break;
func = f;
funcIndex++;
}
}
if (func.lines != null) break;
// Count the line blocks.
int begSym = bits.Position;
int blocks = 0;
while (bits.Position < endSym)
{
CV_SourceFile file;
bits.ReadUInt32(out file.index);
bits.ReadUInt32(out file.count);
bits.ReadUInt32(out file.linsiz); // Size of payload.
int linsiz = (int)file.count * (8 + ((sec.flags & 1) != 0 ? 4 : 0));
bits.Position += linsiz;
blocks++;
}
func.lines = new PdbLines[blocks];
int block = 0;
bits.Position = begSym;
while (bits.Position < endSym)
{
CV_SourceFile file;
bits.ReadUInt32(out file.index);
bits.ReadUInt32(out file.count);
bits.ReadUInt32(out file.linsiz); // Size of payload.
PdbSource src = (PdbSource)checks[(int)file.index];
PdbLines tmp = new PdbLines(src, file.count);
func.lines[block++] = tmp;
PdbLine[] lines = tmp.lines;
int plin = bits.Position;
int pcol = bits.Position + 8 * (int)file.count;
for (int i = 0; i < file.count; i++)
{
CV_Line line;
CV_Column column = new CV_Column();
bits.Position = plin + 8 * i;
bits.ReadUInt32(out line.offset);
bits.ReadUInt32(out line.flags);
uint lineBegin = line.flags & (uint)CV_Line_Flags.linenumStart;
uint delta = (line.flags & (uint)CV_Line_Flags.deltaLineEnd) >> 24;
//bool statement = ((line.flags & (uint)CV_Line_Flags.fStatement) == 0);
if ((sec.flags & 1) != 0)
{
bits.Position = pcol + 4 * i;
bits.ReadUInt16(out column.offColumnStart);
bits.ReadUInt16(out column.offColumnEnd);
}
lines[i] = new PdbLine(line.offset,
lineBegin,
column.offColumnStart,
lineBegin + delta,
column.offColumnEnd);
}
}
break;
}
}
bits.Position = endSym;
}
}
static void LoadFuncsFromDbiModule(BitAccess bits,
DbiModuleInfo info,
IntHashTable names,
ArrayList funcList,
bool readStrings,
MsfDirectory dir,
Dictionary<string, int> nameIndex,
PdbReader reader,
System.Compiler.Metadata.Reader ilreader,
Dictionary<string,PdbSource> sourceCache
)
{
PdbFunction[] funcs = null;
bits.Position = 0;
int sig;
bits.ReadInt32(out sig);
if (sig != 4)
{
throw new PdbDebugException("Invalid signature. (sig={0})", sig);
}
bits.Position = 4;
// Console.WriteLine("{0}:", info.moduleName);
funcs = PdbFunction.LoadManagedFunctions(/*info.moduleName,*/
bits, (uint)info.cbSyms,
readStrings, ilreader);
if (funcs != null)
{
bits.Position = info.cbSyms + info.cbOldLines;
LoadManagedLines(funcs, names, bits, dir, nameIndex, reader,
(uint)(info.cbSyms + info.cbOldLines + info.cbLines),
sourceCache);
for (int i = 0; i < funcs.Length; i++)
{
funcList.Add(funcs[i]);
}
}
}
static void LoadDbiStream(BitAccess bits,
out DbiModuleInfo[] modules,
out DbiDbgHdr header,
bool readStrings)
{
DbiHeader dh = new DbiHeader(bits);
header = new DbiDbgHdr();
//if (dh.sig != -1 || dh.ver != 19990903) {
// throw new PdbException("Unsupported DBI Stream version, sig={0}, ver={1}",
// dh.sig, dh.ver);
//}
// Read gpmod section.
ArrayList modList = new ArrayList();
int end = bits.Position + dh.gpmodiSize;
while (bits.Position < end)
{
DbiModuleInfo mod = new DbiModuleInfo(bits, readStrings);
modList.Add(mod);
}
if (bits.Position != end)
{
throw new PdbDebugException("Error reading DBI stream, pos={0} != {1}",
bits.Position, end);
}
if (modList.Count > 0)
{
modules = (DbiModuleInfo[])modList.ToArray(typeof(DbiModuleInfo));
}
else
{
modules = null;
}
// Skip the Section Contribution substream.
bits.Position += dh.secconSize;
// Skip the Section Map substream.
bits.Position += dh.secmapSize;
// Skip the File Info substream.
bits.Position += dh.filinfSize;
// Skip the TSM substream.
bits.Position += dh.tsmapSize;
// Skip the EC substream.
bits.Position += dh.ecinfoSize;
// Read the optional header.
end = bits.Position + dh.dbghdrSize;
if (dh.dbghdrSize > 0)
{
header = new DbiDbgHdr(bits);
}
bits.Position = end;
}
internal static PdbFunction[] LoadFunctions(Stream read, out Dictionary<uint, PdbTokenLine> tokenToSourceMapping, out string sourceServerData,
System.Compiler.Metadata.Reader ilreader)
{
tokenToSourceMapping = new Dictionary<uint, PdbTokenLine>();
BitAccess bits = new BitAccess(512 * 1024);
PdbFileHeader head = new PdbFileHeader(read, bits);
PdbReader reader = new PdbReader(read, head.pageSize);
MsfDirectory dir = new MsfDirectory(reader, head, bits);
DbiModuleInfo[] modules = null;
DbiDbgHdr header;
Dictionary<string, PdbSource> sourceCache = new Dictionary<string, PdbSource>();
dir.streams[1].Read(reader, bits);
Dictionary<string, int> nameIndex = LoadNameIndex(bits);
int nameStream;
if (!nameIndex.TryGetValue("/NAMES", out nameStream))
{
throw new NoNameStreamPdbException();
}
dir.streams[nameStream].Read(reader, bits);
IntHashTable names = LoadNameStream(bits);
int srcsrvStream;
if (!nameIndex.TryGetValue("SRCSRV", out srcsrvStream))
sourceServerData = string.Empty;
else
{
DataStream dataStream = dir.streams[srcsrvStream];
byte[] bytes = new byte[dataStream.contentSize];
dataStream.Read(reader, bits);
sourceServerData = bits.ReadBString(bytes.Length);
}
dir.streams[3].Read(reader, bits);
LoadDbiStream(bits, out modules, out header, true);
ArrayList funcList = new ArrayList();
if (modules != null)
{
for (int m = 0; m < modules.Length; m++)
{
var module = modules[m];
if (module.stream > 0)
{
dir.streams[module.stream].Read(reader, bits);
if (module.moduleName == "TokenSourceLineInfo")
{
LoadTokenToSourceInfo(bits, module, names, dir, nameIndex, reader, tokenToSourceMapping, sourceCache);
continue;
}
LoadFuncsFromDbiModule(bits, module, names, funcList, true, dir, nameIndex, reader, ilreader, sourceCache);
}
}
}
PdbFunction[] funcs = (PdbFunction[])funcList.ToArray(typeof(PdbFunction));
// After reading the functions, apply the token remapping table if it exists.
if (header.snTokenRidMap != 0 && header.snTokenRidMap != 0xffff)
{
uint[] ridMap = new uint[dir.streams[header.snTokenRidMap].Length / 4];
dir.streams[header.snTokenRidMap].Read(reader, bits);
bits.ReadUInt32(ridMap);
foreach (PdbFunction func in funcs)
{
func.MapTokens(ridMap, ilreader);
}
}
else
{
foreach (PdbFunction func in funcs)
{
func.MapTokens(null, ilreader);
}
}
//
Array.Sort(funcs, PdbFunction.byAddressAndToken);
//Array.Sort(funcs, PdbFunction.byToken);
return funcs;
}
internal static uint[] LoadRemapTable(Stream read)
{
//tokenToSourceMapping = new Dictionary<uint, PdbTokenLine>();
BitAccess bits = new BitAccess(512 * 1024);
PdbFileHeader head = new PdbFileHeader(read, bits);
PdbReader reader = new PdbReader(read, head.pageSize);
MsfDirectory dir = new MsfDirectory(reader, head, bits);
DbiModuleInfo[] modules = null;
DbiDbgHdr header;
dir.streams[1].Read(reader, bits);
Dictionary<string, int> nameIndex = LoadNameIndex(bits);
int nameStream;
if (!nameIndex.TryGetValue("/NAMES", out nameStream))
{
throw new NoNameStreamPdbException();
}
dir.streams[nameStream].Read(reader, bits);
IntHashTable names = LoadNameStream(bits);
int srcsrvStream;
string sourceServerData;
if (!nameIndex.TryGetValue("SRCSRV", out srcsrvStream))
sourceServerData = string.Empty;
else
{
DataStream dataStream = dir.streams[srcsrvStream];
byte[] bytes = new byte[dataStream.contentSize];
dataStream.Read(reader, bits);
sourceServerData = bits.ReadBString(bytes.Length);
}
dir.streams[3].Read(reader, bits);
LoadDbiStream(bits, out modules, out header, true);
#if SKIP_THIS
ArrayList funcList = new ArrayList();
if (modules != null)
{
for (int m = 0; m < modules.Length; m++)
{
var module = modules[m];
if (module.stream > 0)
{
dir.streams[module.stream].Read(reader, bits);
if (module.moduleName == "TokenSourceLineInfo")
{
LoadTokenToSourceInfo(bits, module, names, dir, nameIndex, reader, tokenToSourceMapping);
continue;
}
LoadFuncsFromDbiModule(bits, module, names, funcList, true, dir, nameIndex, reader, ilreader);
}
}
}
PdbFunction[] funcs = (PdbFunction[])funcList.ToArray(typeof(PdbFunction));
#endif
// After reading the functions, apply the token remapping table if it exists.
if (header.snTokenRidMap != 0 && header.snTokenRidMap != 0xffff)
{
uint[] ridMap = new uint[dir.streams[header.snTokenRidMap].Length / 4];
dir.streams[header.snTokenRidMap].Read(reader, bits);
bits.ReadUInt32(ridMap);
return ridMap;
}
return null;
}
private static void LoadTokenToSourceInfo(BitAccess bits, DbiModuleInfo module, IntHashTable names, MsfDirectory dir,
Dictionary<string, int> nameIndex, PdbReader reader, Dictionary<uint, PdbTokenLine> tokenToSourceMapping,
Dictionary<string, PdbSource> sourceCache)
{
bits.Position = 0;
int sig;
bits.ReadInt32(out sig);
if (sig != 4)
{
throw new PdbDebugException("Invalid signature. (sig={0})", sig);
}
bits.Position = 4;
while (bits.Position < module.cbSyms)
{
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec)
{
case SYM.S_OEM:
OemSymbol oem;
bits.ReadGuid(out oem.idOem);
bits.ReadUInt32(out oem.typind);
// internal byte[] rgl; // user data, force 4-byte alignment
if (oem.idOem == PdbFunction.msilMetaData)
{
string name = bits.ReadString();
if (name == "TSLI")
{
uint token;
uint file_id;
uint line;
uint column;
uint endLine;
uint endColumn;
bits.ReadUInt32(out token);
bits.ReadUInt32(out file_id);
bits.ReadUInt32(out line);
bits.ReadUInt32(out column);
bits.ReadUInt32(out endLine);
bits.ReadUInt32(out endColumn);
PdbTokenLine tokenLine;
if (!tokenToSourceMapping.TryGetValue(token, out tokenLine))
tokenToSourceMapping.Add(token, new PdbTokenLine(token, file_id, line, column, endLine, endColumn));
else
{
while (tokenLine.nextLine != null) tokenLine = tokenLine.nextLine;
tokenLine.nextLine = new PdbTokenLine(token, file_id, line, column, endLine, endColumn);
}
}
bits.Position = stop;
break;
}
else
{
throw new PdbDebugException("OEM section: guid={0} ti={1}",
oem.idOem, oem.typind);
// bits.Position = stop;
}
case SYM.S_END:
bits.Position = stop;
break;
default:
//Console.WriteLine("{0,6}: {1:x2} {2}",
// bits.Position, rec, (SYM)rec);
bits.Position = stop;
break;
}
}
bits.Position = module.cbSyms + module.cbOldLines;
int limit = module.cbSyms + module.cbOldLines + module.cbLines;
IntHashTable sourceFiles = ReadSourceFileInfo(bits, (uint)limit, names, dir, nameIndex, reader, sourceCache);
foreach (var tokenLine in tokenToSourceMapping.Values)
{
tokenLine.sourceFile = (PdbSource)sourceFiles[(int)tokenLine.file_id];
}
}
private static IntHashTable ReadSourceFileInfo(BitAccess bits, uint limit, IntHashTable names, MsfDirectory dir,
Dictionary<string, int> nameIndex, PdbReader reader, Dictionary<string, PdbSource> sourceCache)
{
IntHashTable checks = new IntHashTable();
int begin = bits.Position;
while (bits.Position < limit)
{
int sig;
int siz;
bits.ReadInt32(out sig);
bits.ReadInt32(out siz);
int place = bits.Position;
int endSym = bits.Position + siz;
switch ((DEBUG_S_SUBSECTION)sig)
{
case DEBUG_S_SUBSECTION.FILECHKSMS:
while (bits.Position < endSym)
{
CV_FileCheckSum chk;
int ni = bits.Position - place;
bits.ReadUInt32(out chk.name);
bits.ReadUInt8(out chk.len);
bits.ReadUInt8(out chk.type);
string name = (string)names[(int)chk.name];
PdbSource src;
if (!sourceCache.TryGetValue(name, out src))
{
int guidStream;
Guid doctypeGuid = SymDocumentType.Text;
Guid languageGuid = Guid.Empty;
Guid vendorGuid = Guid.Empty;
if (nameIndex.TryGetValue("/SRC/FILES/" + name.ToUpperInvariant(), out guidStream))
{
var guidBits = new BitAccess(0x100);
dir.streams[guidStream].Read(reader, guidBits);
LoadGuidStream(guidBits, out doctypeGuid, out languageGuid, out vendorGuid);
}
src = new PdbSource(/*(uint)ni,*/ name, doctypeGuid, languageGuid, vendorGuid);
sourceCache.Add(name, src);
}
checks.Add(ni, src);
bits.Position += chk.len;
bits.Align(4);
}
bits.Position = endSym;
break;
default:
bits.Position = endSym;
break;
}
}
return checks;
}
internal static Dictionary<uint, PdbFunction> LoadFunctionMap(FileStream inputStream, out Dictionary<uint, PdbTokenLine> tokenToSourceMapping, out string sourceServerData, System.Compiler.Metadata.Reader reader)
{
var funcs = LoadFunctions(inputStream, out tokenToSourceMapping, out sourceServerData, reader);
var result = new Dictionary<uint, PdbFunction>(funcs.Length+10);
foreach (PdbFunction pdbFunction in funcs)
result[pdbFunction.token] = pdbFunction;
return result;
}
}
}
| |
namespace Microsoft.Azure.Management.Dns
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// RecordSetsOperations operations.
/// </summary>
internal partial class RecordSetsOperations : IServiceOperations<DnsManagementClient>, IRecordSetsOperations
{
/// <summary>
/// Initializes a new instance of the RecordSetsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal RecordSetsOperations(DnsManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DnsManagementClient
/// </summary>
public DnsManagementClient Client { get; private set; }
/// <summary>
/// Updates a RecordSet within a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of Zone.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RecordSet>> UpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (relativeRecordSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "relativeRecordSetName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("relativeRecordSetName", relativeRecordSetName);
tracingParameters.Add("recordType", recordType);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("ifNoneMatch", ifNoneMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/{recordType}/{relativeRecordSetName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{relativeRecordSetName}", relativeRecordSetName);
_url = _url.Replace("{recordType}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(recordType, this.Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (ifNoneMatch != null)
{
if (_httpRequest.Headers.Contains("If-None-Match"))
{
_httpRequest.Headers.Remove("If-None-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RecordSet>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<RecordSet>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or Updates a RecordSet within a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of Recordset.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RecordSet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (relativeRecordSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "relativeRecordSetName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("relativeRecordSetName", relativeRecordSetName);
tracingParameters.Add("recordType", recordType);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("ifNoneMatch", ifNoneMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/{recordType}/{relativeRecordSetName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{relativeRecordSetName}", relativeRecordSetName);
_url = _url.Replace("{recordType}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(recordType, this.Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (ifNoneMatch != null)
{
if (_httpRequest.Headers.Contains("If-None-Match"))
{
_httpRequest.Headers.Remove("If-None-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RecordSet>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<RecordSet>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<RecordSet>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Removes a RecordSet from a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='ifMatch'>
/// Defines the If-Match condition. The delete operation will be performed
/// only if the ETag of the zone on the server matches this value.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. The delete operation will be
/// performed only if the ETag of the zone on the server does not match this
/// value.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (relativeRecordSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "relativeRecordSetName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("relativeRecordSetName", relativeRecordSetName);
tracingParameters.Add("recordType", recordType);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("ifNoneMatch", ifNoneMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/{recordType}/{relativeRecordSetName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{relativeRecordSetName}", relativeRecordSetName);
_url = _url.Replace("{recordType}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(recordType, this.Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (ifNoneMatch != null)
{
if (_httpRequest.Headers.Contains("If-None-Match"))
{
_httpRequest.Headers.Remove("If-None-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a RecordSet.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RecordSet>> GetWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (relativeRecordSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "relativeRecordSetName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("relativeRecordSetName", relativeRecordSetName);
tracingParameters.Add("recordType", recordType);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/{recordType}/{relativeRecordSetName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{relativeRecordSetName}", relativeRecordSetName);
_url = _url.Replace("{recordType}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(recordType, this.Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RecordSet>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<RecordSet>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the RecordSets of a specified type in a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// The name of the zone from which to enumerate RecordsSets.
/// </param>
/// <param name='recordType'>
/// The type of record sets to enumerate. Possible values include: 'A',
/// 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='top'>
/// Query parameters. If null is passed returns the default number of zones.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RecordSet>>> ListByTypeWithHttpMessagesAsync(string resourceGroupName, string zoneName, RecordType recordType, string top = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("recordType", recordType);
tracingParameters.Add("top", top);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByType", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/{recordType}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{recordType}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(recordType, this.Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", Uri.EscapeDataString(top)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RecordSet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<RecordSet>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all RecordSets in a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// The name of the zone from which to enumerate RecordSets.
/// </param>
/// <param name='top'>
/// Query parameters. If null is passed returns the default number of zones.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RecordSet>>> ListAllInResourceGroupWithHttpMessagesAsync(string resourceGroupName, string zoneName, string top = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("top", top);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllInResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/recordsets").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", Uri.EscapeDataString(top)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RecordSet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<RecordSet>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the RecordSets of a specified type in a DNS zone.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RecordSet>>> ListByTypeNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByTypeNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RecordSet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<RecordSet>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all RecordSets in a DNS zone.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RecordSet>>> ListAllInResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllInResourceGroupNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RecordSet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<RecordSet>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System.Collections.Generic;
namespace UnityEngine.AI
{
public enum CollectObjects
{
All = 0,
Volume = 1,
Children = 2,
}
[ExecuteInEditMode]
[DefaultExecutionOrder(-102)]
[AddComponentMenu("Navigation/NavMeshSurface", 30)]
[HelpURL("https://github.com/Unity-Technologies/NavMeshComponents#documentation-draft")]
public class NavMeshSurface : MonoBehaviour
{
[SerializeField]
int m_AgentTypeID;
public int agentTypeID { get { return m_AgentTypeID; } set { m_AgentTypeID = value; } }
[SerializeField]
CollectObjects m_CollectObjects = CollectObjects.All;
public CollectObjects collectObjects { get { return m_CollectObjects; } set { m_CollectObjects = value; } }
[SerializeField]
Vector3 m_Size = new Vector3(10.0f, 10.0f, 10.0f);
public Vector3 size { get { return m_Size; } set { m_Size = value; } }
[SerializeField]
Vector3 m_Center = new Vector3(0, 2.0f, 0);
public Vector3 center { get { return m_Center; } set { m_Center = value; } }
[SerializeField]
LayerMask m_LayerMask = ~0;
public LayerMask layerMask { get { return m_LayerMask; } set { m_LayerMask = value; } }
[SerializeField]
NavMeshCollectGeometry m_UseGeometry = NavMeshCollectGeometry.RenderMeshes;
public NavMeshCollectGeometry useGeometry { get { return m_UseGeometry; } set { m_UseGeometry = value; } }
[SerializeField]
int m_DefaultArea;
public int defaultArea { get { return m_DefaultArea; } set { m_DefaultArea = value; } }
[SerializeField]
bool m_IgnoreNavMeshAgent = true;
public bool ignoreNavMeshAgent { get { return m_IgnoreNavMeshAgent; } set { m_IgnoreNavMeshAgent = value; } }
[SerializeField]
bool m_IgnoreNavMeshObstacle = true;
public bool ignoreNavMeshObstacle { get { return m_IgnoreNavMeshObstacle; } set { m_IgnoreNavMeshObstacle = value; } }
[SerializeField]
bool m_OverrideTileSize;
public bool overrideTileSize { get { return m_OverrideTileSize; } set { m_OverrideTileSize = value; } }
[SerializeField]
int m_TileSize = 256;
public int tileSize { get { return m_TileSize; } set { m_TileSize = value; } }
[SerializeField]
bool m_OverrideVoxelSize;
public bool overrideVoxelSize { get { return m_OverrideVoxelSize; } set { m_OverrideVoxelSize = value; } }
[SerializeField]
float m_VoxelSize;
public float voxelSize { get { return m_VoxelSize; } set { m_VoxelSize = value; } }
// Currently not supported advanced options
[SerializeField]
bool m_BuildHeightMesh;
public bool buildHeightMesh { get { return m_BuildHeightMesh; } set { m_BuildHeightMesh = value; } }
// Reference to whole scene navmesh data asset.
[UnityEngine.Serialization.FormerlySerializedAs("m_BakedNavMeshData")]
[SerializeField]
NavMeshData m_NavMeshData;
public NavMeshData navMeshData { get { return m_NavMeshData; } set { m_NavMeshData = value; } }
// Do not serialize - runtime only state.
NavMeshDataInstance m_NavMeshDataInstance;
Vector3 m_LastPosition = Vector3.zero;
Quaternion m_LastRotation = Quaternion.identity;
static readonly List<NavMeshSurface> s_NavMeshSurfaces = new List<NavMeshSurface>();
public static List<NavMeshSurface> activeSurfaces
{
get { return s_NavMeshSurfaces; }
}
void OnEnable()
{
Register(this);
AddData();
}
void OnDisable()
{
RemoveData();
Unregister(this);
}
public void AddData()
{
if (m_NavMeshDataInstance.valid)
return;
if (m_NavMeshData != null)
{
m_NavMeshDataInstance = NavMesh.AddNavMeshData(m_NavMeshData, transform.position, transform.rotation);
m_NavMeshDataInstance.owner = this;
}
m_LastPosition = transform.position;
m_LastRotation = transform.rotation;
}
public void RemoveData()
{
m_NavMeshDataInstance.Remove();
m_NavMeshDataInstance = new NavMeshDataInstance();
}
public NavMeshBuildSettings GetBuildSettings()
{
var buildSettings = NavMesh.GetSettingsByID(m_AgentTypeID);
if (buildSettings.agentTypeID == -1)
{
Debug.LogWarning("No build settings for agent type ID " + agentTypeID, this);
buildSettings.agentTypeID = m_AgentTypeID;
}
if (overrideTileSize)
{
buildSettings.overrideTileSize = true;
buildSettings.tileSize = tileSize;
}
if (overrideVoxelSize)
{
buildSettings.overrideVoxelSize = true;
buildSettings.voxelSize = voxelSize;
}
return buildSettings;
}
public void BuildNavMesh()
{
var sources = CollectSources();
// Use unscaled bounds - this differs in behaviour from e.g. collider components.
// But is similar to reflection probe - and since navmesh data has no scaling support - it is the right choice here.
var sourcesBounds = new Bounds(m_Center, Abs(m_Size));
if (m_CollectObjects == CollectObjects.All || m_CollectObjects == CollectObjects.Children)
{
sourcesBounds = CalculateWorldBounds(sources);
}
var data = NavMeshBuilder.BuildNavMeshData(GetBuildSettings(),
sources, sourcesBounds, transform.position, transform.rotation);
if (data != null)
{
data.name = gameObject.name;
RemoveData();
m_NavMeshData = data;
if (isActiveAndEnabled)
AddData();
}
}
public AsyncOperation UpdateNavMesh(NavMeshData data)
{
var sources = CollectSources();
// Use unscaled bounds - this differs in behaviour from e.g. collider components.
// But is similar to reflection probe - and since navmesh data has no scaling support - it is the right choice here.
var sourcesBounds = new Bounds(m_Center, Abs(m_Size));
if (m_CollectObjects == CollectObjects.All || m_CollectObjects == CollectObjects.Children)
sourcesBounds = CalculateWorldBounds(sources);
return NavMeshBuilder.UpdateNavMeshDataAsync(data, GetBuildSettings(), sources, sourcesBounds);
}
static void Register(NavMeshSurface surface)
{
if (s_NavMeshSurfaces.Count == 0)
NavMesh.onPreUpdate += UpdateActive;
if (!s_NavMeshSurfaces.Contains(surface))
s_NavMeshSurfaces.Add(surface);
}
static void Unregister(NavMeshSurface surface)
{
s_NavMeshSurfaces.Remove(surface);
if (s_NavMeshSurfaces.Count == 0)
NavMesh.onPreUpdate -= UpdateActive;
}
static void UpdateActive()
{
for (var i = 0; i < s_NavMeshSurfaces.Count; ++i)
s_NavMeshSurfaces[i].UpdateDataIfTransformChanged();
}
void AppendModifierVolumes(ref List<NavMeshBuildSource> sources)
{
// Modifiers
List<NavMeshModifierVolume> modifiers;
if (m_CollectObjects == CollectObjects.Children)
{
modifiers = new List<NavMeshModifierVolume>(GetComponentsInChildren<NavMeshModifierVolume>());
modifiers.RemoveAll(x => !x.isActiveAndEnabled);
}
else
{
modifiers = NavMeshModifierVolume.activeModifiers;
}
foreach (var m in modifiers)
{
if ((m_LayerMask & (1 << m.gameObject.layer)) == 0)
continue;
if (!m.AffectsAgentType(m_AgentTypeID))
continue;
var mcenter = m.transform.TransformPoint(m.center);
var scale = m.transform.lossyScale;
var msize = new Vector3(m.size.x * Mathf.Abs(scale.x), m.size.y * Mathf.Abs(scale.y), m.size.z * Mathf.Abs(scale.z));
var src = new NavMeshBuildSource();
src.shape = NavMeshBuildSourceShape.ModifierBox;
src.transform = Matrix4x4.TRS(mcenter, m.transform.rotation, Vector3.one);
src.size = msize;
src.area = m.area;
sources.Add(src);
}
}
List<NavMeshBuildSource> CollectSources()
{
var sources = new List<NavMeshBuildSource>();
var markups = new List<NavMeshBuildMarkup>();
List<NavMeshModifier> modifiers;
if (m_CollectObjects == CollectObjects.Children)
{
modifiers = new List<NavMeshModifier>(GetComponentsInChildren<NavMeshModifier>());
modifiers.RemoveAll(x => !x.isActiveAndEnabled);
}
else
{
modifiers = NavMeshModifier.activeModifiers;
}
foreach (var m in modifiers)
{
if ((m_LayerMask & (1 << m.gameObject.layer)) == 0)
continue;
if (!m.AffectsAgentType(m_AgentTypeID))
continue;
var markup = new NavMeshBuildMarkup();
markup.root = m.transform;
markup.overrideArea = m.overrideArea;
markup.area = m.area;
markup.ignoreFromBuild = m.ignoreFromBuild;
markups.Add(markup);
}
if (m_CollectObjects == CollectObjects.All)
{
NavMeshBuilder.CollectSources(null, m_LayerMask, m_UseGeometry, m_DefaultArea, markups, sources);
}
else if (m_CollectObjects == CollectObjects.Children)
{
NavMeshBuilder.CollectSources(transform, m_LayerMask, m_UseGeometry, m_DefaultArea, markups, sources);
}
else if (m_CollectObjects == CollectObjects.Volume)
{
Matrix4x4 localToWorld = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
var worldBounds = GetWorldBounds(localToWorld, new Bounds(m_Center, m_Size));
NavMeshBuilder.CollectSources(worldBounds, m_LayerMask, m_UseGeometry, m_DefaultArea, markups, sources);
}
if (m_IgnoreNavMeshAgent)
sources.RemoveAll((x) => (x.component != null && x.component.gameObject.GetComponent<NavMeshAgent>() != null));
if (m_IgnoreNavMeshObstacle)
sources.RemoveAll((x) => (x.component != null && x.component.gameObject.GetComponent<NavMeshObstacle>() != null));
AppendModifierVolumes(ref sources);
return sources;
}
static Vector3 Abs(Vector3 v)
{
return new Vector3(Mathf.Abs(v.x), Mathf.Abs(v.y), Mathf.Abs(v.z));
}
static Bounds GetWorldBounds(Matrix4x4 mat, Bounds bounds)
{
var absAxisX = Abs(mat.MultiplyVector(Vector3.right));
var absAxisY = Abs(mat.MultiplyVector(Vector3.up));
var absAxisZ = Abs(mat.MultiplyVector(Vector3.forward));
var worldPosition = mat.MultiplyPoint(bounds.center);
var worldSize = absAxisX * bounds.size.x + absAxisY * bounds.size.y + absAxisZ * bounds.size.z;
return new Bounds(worldPosition, worldSize);
}
Bounds CalculateWorldBounds(List<NavMeshBuildSource> sources)
{
// Use the unscaled matrix for the NavMeshSurface
Matrix4x4 worldToLocal = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
worldToLocal = worldToLocal.inverse;
var result = new Bounds();
foreach (var src in sources)
{
switch (src.shape)
{
case NavMeshBuildSourceShape.Mesh:
{
var m = src.sourceObject as Mesh;
result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, m.bounds));
break;
}
case NavMeshBuildSourceShape.Terrain:
{
// Terrain pivot is lower/left corner - shift bounds accordingly
var t = src.sourceObject as TerrainData;
result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, new Bounds(0.5f * t.size, t.size)));
break;
}
case NavMeshBuildSourceShape.Box:
case NavMeshBuildSourceShape.Sphere:
case NavMeshBuildSourceShape.Capsule:
case NavMeshBuildSourceShape.ModifierBox:
result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, new Bounds(Vector3.zero, src.size)));
break;
}
}
// Inflate the bounds a bit to avoid clipping co-planar sources
result.Expand(0.1f);
return result;
}
bool HasTransformChanged()
{
if (m_LastPosition != transform.position) return true;
if (m_LastRotation != transform.rotation) return true;
return false;
}
void UpdateDataIfTransformChanged()
{
if (HasTransformChanged())
{
RemoveData();
AddData();
}
}
#if UNITY_EDITOR
bool UnshareNavMeshAsset()
{
// Nothing to unshare
if (m_NavMeshData == null)
return false;
// Prefab parent owns the asset reference
var prefabType = UnityEditor.PrefabUtility.GetPrefabType(this);
if (prefabType == UnityEditor.PrefabType.Prefab)
return false;
// An instance can share asset reference only with its prefab parent
var prefab = UnityEditor.PrefabUtility.GetPrefabParent(this) as NavMeshSurface;
if (prefab != null && prefab.navMeshData == navMeshData)
return false;
// Don't allow referencing an asset that's assigned to another surface
for (var i = 0; i < s_NavMeshSurfaces.Count; ++i)
{
var surface = s_NavMeshSurfaces[i];
if (surface != this && surface.m_NavMeshData == m_NavMeshData)
return true;
}
// Asset is not referenced by known surfaces
return false;
}
void OnValidate()
{
if (UnshareNavMeshAsset())
{
Debug.LogWarning("Duplicating NavMeshSurface does not duplicate the referenced navmesh data", this);
m_NavMeshData = null;
}
var settings = NavMesh.GetSettingsByID(m_AgentTypeID);
if (settings.agentTypeID != -1)
{
// When unchecking the override control, revert to automatic value.
const float kMinVoxelSize = 0.01f;
if (!m_OverrideVoxelSize)
m_VoxelSize = settings.agentRadius / 3.0f;
if (m_VoxelSize < kMinVoxelSize)
m_VoxelSize = kMinVoxelSize;
// When unchecking the override control, revert to default value.
const int kMinTileSize = 16;
const int kMaxTileSize = 1024;
const int kDefaultTileSize = 256;
if (!m_OverrideTileSize)
m_TileSize = kDefaultTileSize;
// Make sure tilesize is in sane range.
if (m_TileSize < kMinTileSize)
m_TileSize = kMinTileSize;
if (m_TileSize > kMaxTileSize)
m_TileSize = kMaxTileSize;
}
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.SessionState;
using Common.Logging;
using SharpBrake.Serialization;
namespace SharpBrake
{
/// <summary>
/// Responsible for building the notice that is sent to Airbrake.
/// </summary>
public class AirbrakeNoticeBuilder
{
private readonly AirbrakeConfiguration configuration;
private readonly ILog log;
private AirbrakeServerEnvironment environment;
private AirbrakeNotifier notifier;
/// <summary>
/// Initializes a new instance of the <see cref="AirbrakeNoticeBuilder"/> class.
/// </summary>
public AirbrakeNoticeBuilder()
: this(new AirbrakeConfiguration())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AirbrakeNoticeBuilder"/> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
public AirbrakeNoticeBuilder(AirbrakeConfiguration configuration)
{
if (configuration == null)
throw new ArgumentNullException("configuration");
this.configuration = configuration;
this.log = LogManager.GetLogger(GetType());
}
/// <summary>
/// Gets the configuration.
/// </summary>
public AirbrakeConfiguration Configuration
{
get { return this.configuration; }
}
/// <summary>
/// Gets the notifier.
/// </summary>
public AirbrakeNotifier Notifier
{
get
{
return this.notifier ?? (this.notifier = new AirbrakeNotifier
{
Name = "SharpBrake",
Url = "https://github.com/asbjornu/SharpBrake",
Version = typeof(AirbrakeNotice).Assembly.GetName().Version.ToString()
});
}
}
/// <summary>
/// Gets the server environment.
/// </summary>
public AirbrakeServerEnvironment ServerEnvironment
{
get
{
string env = this.configuration.EnvironmentName;
return this.environment ?? (this.environment = new AirbrakeServerEnvironment(env)
{
ProjectRoot = this.configuration.ProjectRoot,
AppVersion = this.configuration.AppVersion,
});
}
}
/// <summary>
/// Creates a <see cref="AirbrakeError"/> from the the specified exception.
/// </summary>
/// <param name="exception">The exception.</param>
/// <returns>
/// A <see cref="AirbrakeError"/>, created from the the specified exception.
/// </returns>
public AirbrakeError ErrorFromException(Exception exception)
{
if (exception == null)
throw new ArgumentNullException("exception");
this.log.Debug(f => f("{0}.Notice({1})", GetType(), exception.GetType()), exception);
MethodBase catchingMethod;
var backtrace = BuildBacktrace(exception, out catchingMethod);
var error = Activator.CreateInstance<AirbrakeError>();
error.CatchingMethod = catchingMethod;
error.Class = exception.GetType().FullName;
error.Message = exception.GetType().Name + ": " + exception.Message;
error.Backtrace = backtrace;
return error;
}
/// <summary>
/// Creates a <see cref="AirbrakeNotice"/> from the the specified error.
/// </summary>
/// <param name="error">The error.</param>
/// <returns></returns>
public AirbrakeNotice Notice(AirbrakeError error)
{
this.log.Debug(f => f("{0}.Notice({1})", GetType(), error));
var notice = new AirbrakeNotice
{
ApiKey = Configuration.ApiKey,
Error = error,
Notifier = Notifier,
ServerEnvironment = ServerEnvironment,
};
MethodBase catchingMethod = (error != null)
? error.CatchingMethod
: null;
AddContextualInformation(notice, catchingMethod);
return notice;
}
/// <summary>
/// Creates a <see cref="AirbrakeNotice"/> from the the specified exception.
/// </summary>
/// <param name="exception">The exception.</param>
/// <returns>
/// A <see cref="AirbrakeNotice"/>, created from the the specified exception.
/// </returns>
public AirbrakeNotice Notice(Exception exception)
{
if (exception == null)
throw new ArgumentNullException("exception");
this.log.Info(f => f("{0}.Notice({1})", GetType(), exception.GetType()), exception);
AirbrakeError error = ErrorFromException(exception);
return Notice(error);
}
private void AddContextualInformation(AirbrakeNotice notice, MethodBase catchingMethod)
{
var component = String.Empty;
var action = String.Empty;
if ((notice.Error != null) && (notice.Error.Backtrace != null) && notice.Error.Backtrace.Any())
{
// TODO: We should perhaps check whether the topmost back trace is in fact a Controller+Action by performing some sort of heuristic (searching for "Controller" etc.). @asbjornu
var backtrace = notice.Error.Backtrace.First();
action = backtrace.Method;
component = backtrace.File;
}
else if (catchingMethod != null)
{
action = catchingMethod.Name;
if (catchingMethod.DeclaringType != null)
component = catchingMethod.DeclaringType.FullName;
}
var request = new AirbrakeRequest("http://example.com/", component)
{
Action = action
};
var cgiData = new List<AirbrakeVar>
{
new AirbrakeVar("Environment.MachineName", Environment.MachineName),
new AirbrakeVar("Environment.OSversion", Environment.OSVersion),
new AirbrakeVar("Environment.Version", Environment.Version)
};
var parameters = new List<AirbrakeVar>();
var session = new List<AirbrakeVar>();
var httpContext = HttpContext.Current;
if (httpContext != null)
{
var httpRequest = httpContext.Request;
request.Url = httpRequest.Url.ToString();
cgiData.AddRange(BuildVars(httpRequest.Headers));
cgiData.AddRange(BuildVars(httpRequest.Cookies));
parameters.AddRange(BuildVars(httpRequest.Params));
session.AddRange(BuildVars(httpContext.Session));
if (httpContext.User != null)
cgiData.Add(new AirbrakeVar("User.Identity.Name", httpContext.User.Identity.Name));
var browser = httpRequest.Browser;
if (browser != null)
{
cgiData.Add(new AirbrakeVar("Browser.Browser", browser.Browser));
cgiData.Add(new AirbrakeVar("Browser.ClrVersion", browser.ClrVersion));
cgiData.Add(new AirbrakeVar("Browser.Cookies", browser.Cookies));
cgiData.Add(new AirbrakeVar("Browser.Crawler", browser.Crawler));
cgiData.Add(new AirbrakeVar("Browser.EcmaScriptVersion", browser.EcmaScriptVersion));
cgiData.Add(new AirbrakeVar("Browser.JavaApplets", browser.JavaApplets));
cgiData.Add(new AirbrakeVar("Browser.MajorVersion", browser.MajorVersion));
cgiData.Add(new AirbrakeVar("Browser.MinorVersion", browser.MinorVersion));
cgiData.Add(new AirbrakeVar("Browser.Platform", browser.Platform));
cgiData.Add(new AirbrakeVar("Browser.W3CDomVersion", browser.W3CDomVersion));
}
}
request.CgiData = cgiData.ToArray();
request.Params = parameters.Any() ? parameters.ToArray() : null;
request.Session = session.Any() ? session.ToArray() : null;
notice.Request = request;
}
private AirbrakeTraceLine[] BuildBacktrace(Exception exception, out MethodBase catchingMethod)
{
Assembly assembly = Assembly.GetExecutingAssembly();
if (assembly.EntryPoint == null)
assembly = Assembly.GetCallingAssembly();
if (assembly.EntryPoint == null)
assembly = Assembly.GetEntryAssembly();
catchingMethod = assembly == null
? null
: assembly.EntryPoint;
List<AirbrakeTraceLine> lines = new List<AirbrakeTraceLine>();
var stackTrace = new StackTrace(exception, true);
StackFrame[] frames = stackTrace.GetFrames();
if (frames == null || frames.Length == 0)
{
// Airbrake requires that at least one line is present in the XML.
AirbrakeTraceLine line = new AirbrakeTraceLine("none", 0);
lines.Add(line);
return lines.ToArray();
}
foreach (StackFrame frame in frames)
{
MethodBase method = frame.GetMethod();
catchingMethod = method;
int lineNumber = frame.GetFileLineNumber();
if (lineNumber == 0)
{
this.log.Debug(f => f("No line number found in {0}, using IL offset instead.", method));
lineNumber = frame.GetILOffset();
}
string file = frame.GetFileName();
if (String.IsNullOrEmpty(file))
{
// ReSharper disable ConditionIsAlwaysTrueOrFalse
file = method.ReflectedType != null
? method.ReflectedType.FullName
: "(unknown)";
// ReSharper restore ConditionIsAlwaysTrueOrFalse
}
AirbrakeTraceLine line = new AirbrakeTraceLine(file, lineNumber)
{
Method = method.Name
};
lines.Add(line);
}
return lines.ToArray();
}
private IEnumerable<AirbrakeVar> BuildVars(HttpCookieCollection cookies)
{
if ((cookies == null) || (cookies.Count == 0))
{
this.log.Debug(f => f("No cookies to build vars from."));
return new AirbrakeVar[0];
}
return from key in cookies.Keys.Cast<string>()
where !String.IsNullOrEmpty(key)
let cookie = cookies[key]
let value = cookie != null ? cookie.Value : null
where !String.IsNullOrEmpty(value)
select new AirbrakeVar(key, value);
}
private IEnumerable<AirbrakeVar> BuildVars(NameValueCollection formData)
{
if ((formData == null) || (formData.Count == 0))
{
this.log.Debug(f => f("No form data to build vars from."));
return new AirbrakeVar[0];
}
return from key in formData.AllKeys
where !String.IsNullOrEmpty(key)
let value = configuration.ParamFilters.Any(f => key.ToLower().Contains(f)) ? "[FILTERED]" : formData[key]
where !String.IsNullOrEmpty(value)
select new AirbrakeVar(key, value);
}
private IEnumerable<AirbrakeVar> BuildVars(HttpSessionState session)
{
if ((session == null) || (session.Count == 0))
{
this.log.Debug(f => f("No session to build vars from."));
return new AirbrakeVar[0];
}
return from key in session.Keys.Cast<string>()
where !String.IsNullOrEmpty(key)
let v = session[key]
let value = v != null ? v.ToString() : null
where !String.IsNullOrEmpty(value)
select new AirbrakeVar(key, value);
}
}
}
| |
using IL2CPU.API;
using IL2CPU.API.Attribs;
using Cosmos.Debug.Kernel;
using XSharp;
using XSharp.Assembler;
namespace Cosmos.Debug.Kernel.Plugs.Asm
{
[Plug(Target = typeof(Debugger))]
public static class DebuggerAsm
{
[PlugMethod(Assembler = typeof(DebugBreak))]
public static void Break(Debugger aThis) { }
[PlugMethod(Assembler = typeof(DebugDoSend))]
public static void DoSend(string aText) { }
[PlugMethod(Assembler = typeof(DebugDoSendNumber))]
public static void DoSendNumber(int aNumber) { }
[PlugMethod(Assembler = typeof(DebugDoSendNumber))]
public static void DoSendNumber(uint aNumber) { }
[PlugMethod(Assembler = typeof(DebugDoSendLongNumber))]
public static void DoSendNumber(long aNumber) { }
[PlugMethod(Assembler = typeof(DebugDoSendLongNumber))]
public static void DoSendNumber(ulong aNumber) { }
[PlugMethod(Assembler = typeof(DebugDoSendComplexNumber))]
public static void DoSendNumber(float aNumber) { }
[PlugMethod(Assembler = typeof(DebugDoSendComplexLongNumber))]
public static void DoSendNumber(double aNumber) { }
[PlugMethod(Assembler = typeof(DebugSendMessageBox))]
public static unsafe void SendMessageBox(Debugger aThis, int aLength, char* aText) { }
[PlugMethod(Assembler = typeof(DebugSendPtr))]
public static unsafe void SendPtr(Debugger aThis, object aPtr) { }
[PlugMethod(Assembler = typeof(DebugSendChannelCommand))]
public static unsafe void SendChannelCommand(byte aChannel, byte aCommand, int aByteCount, byte* aData) { }
[PlugMethod(Assembler = typeof(DebugSendChannelCommandNoData))]
public static unsafe void SendChannelCommand(byte aChannel, byte aCommand) { }
[PlugMethod(Assembler = typeof(DoBochsBreak))]
public static void DoBochsBreak() { }
[Inline]
public static void SendKernelPanic(uint id)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("push dword [EBP + 8]");
new LiteralAssemblerCode("xchg bx, bx");
new LiteralAssemblerCode("Call DebugStub_SendKernelPanic");
new LiteralAssemblerCode("add ESP, 4");
new LiteralAssemblerCode("%endif");
}
[PlugMethod(Assembler = typeof(DoRealHalt))]
public static void DoRealHalt() { }
//[PlugMethod(Assembler = typeof(DebugTraceOff))]
//public static void TraceOff() { }
//[PlugMethod(Assembler = typeof(DebugTraceOn))]
//public static void TraceOn() { }
}
//TODO: Make a new plug attrib that assembly plug methods dont need
// an empty stub also, its just extra fluff - although they allow signature matching
// Maybe could merge this into the same unit as the plug
public class DebugTraceOff : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("pushad");
new LiteralAssemblerCode("Call DebugStub_TraceOff");
new LiteralAssemblerCode("popad");
new LiteralAssemblerCode("%endif");
}
}
public class DebugTraceOn : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("pushad");
new LiteralAssemblerCode("Call DebugStub_TraceOn");
new LiteralAssemblerCode("popad");
new LiteralAssemblerCode("%endif");
}
}
/// <summary>
/// Assembler for SendChannelCommand
/// </summary>
/// <remarks>
/// AL contains channel
/// BL contains command
/// ECX contains number of bytes to send as command data
/// ESI contains data start pointer
/// </remarks>
public class DebugSendChannelCommand : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("mov AL, [EBP + 20]");
new LiteralAssemblerCode("mov BL, [EBP + 16]");
new LiteralAssemblerCode("mov ECX, [EBP + 12]");
new LiteralAssemblerCode("mov ESI, [EBP + 8]");
new LiteralAssemblerCode("call DebugStub_SendCommandOnChannel");
new LiteralAssemblerCode("%endif");
}
}
/// <summary>
/// Assembler for SendChannelCommandNoData
/// </summary>
/// <remarks>
/// AL contains channel
/// BL contains command
/// ECX contains number of bytes to send as command data
/// ESI contains data start pointer
/// </remarks>
public class DebugSendChannelCommandNoData : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("mov AL, [EBP + 12]");
new LiteralAssemblerCode("mov BL, [EBP + 8]");
new LiteralAssemblerCode("mov ECX, 0");
new LiteralAssemblerCode("mov ESI, EBP");
new LiteralAssemblerCode("call DebugStub_SendCommandOnChannel");
new LiteralAssemblerCode("%endif");
}
}
public class DebugBreak : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("mov dword [DebugStub_DebugBreakOnNextTrace], 1");
new LiteralAssemblerCode("%endif");
}
}
/// <summary>
/// Assembler for DoSend
/// </summary>
/// <remarks>
/// EBP + 12 contains length
/// EBP + 8 contains first char pointer
/// </remarks>
public class DebugDoSend : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
XS.Label(".BeforeArgumentsPrepare");
new LiteralAssemblerCode("mov EBX, [EBP + 12]");
new LiteralAssemblerCode("push dword [EBX + 12]");
new LiteralAssemblerCode("add EBX, 16");
new LiteralAssemblerCode("push dword EBX");
XS.Label(".BeforeCall");
new LiteralAssemblerCode("Call DebugStub_SendText");
new LiteralAssemblerCode("add ESP, 8");
new LiteralAssemblerCode("%endif");
}
}
public class DebugDoSendNumber : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("push dword [EBP + 8]");
new LiteralAssemblerCode("Call DebugStub_SendSimpleNumber");
new LiteralAssemblerCode("add ESP, 4");
new LiteralAssemblerCode("%endif");
}
}
public class DebugDoSendLongNumber : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("push dword [EBP + 12]");
new LiteralAssemblerCode("push dword [EBP + 8]");
new LiteralAssemblerCode("Call DebugStub_SendSimpleLongNumber");
new LiteralAssemblerCode("add ESP, 8");
new LiteralAssemblerCode("%endif");
}
}
public class DebugDoSendComplexNumber : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("push dword [EBP + 8]");
new LiteralAssemblerCode("Call DebugStub_SendComplexNumber");
new LiteralAssemblerCode("add ESP, 4");
new LiteralAssemblerCode("%endif");
}
}
public class DebugDoSendComplexLongNumber : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("push dword [EBP + 12]");
new LiteralAssemblerCode("push dword [EBP + 8]");
new LiteralAssemblerCode("Call DebugStub_SendComplexLongNumber");
new LiteralAssemblerCode("add ESP, 8");
new LiteralAssemblerCode("%endif");
}
}
public class DebugSendMessageBox : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("pushad");
new LiteralAssemblerCode("Call DebugStub_SendMessageBox");
new LiteralAssemblerCode("popad");
new LiteralAssemblerCode("%endif");
}
}
public class DebugSendPtr : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("pushad");
new LiteralAssemblerCode("Call DebugStub_SendPtr");
new LiteralAssemblerCode("popad");
new LiteralAssemblerCode("%endif");
}
}
public class DoBochsBreak : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
XS.Exchange(XSRegisters.BX, XSRegisters.BX);
}
}
public class DoRealHalt : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
XS.DisableInterrupts();
// bochs magic break
//Exchange(BX, BX);
XS.Halt();
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace Revit.SDK.Samples.MaterialProperties.CS
{
/// <summary>
/// Summary description for MaterialPropFrm.
/// </summary>
public class MaterialPropertiesForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Label typeLable;
private System.Windows.Forms.ComboBox typeComboBox;
private System.Windows.Forms.ComboBox subTypeComboBox;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button applyButton;
private System.Windows.Forms.Button changeButton;
private System.Windows.Forms.DataGrid parameterDataGrid;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private MaterialPropertiesForm()
{
}
/// <summary>
/// material properties from
/// </summary>
/// <param name="dataBuffer">material properties from Revit</param>
public MaterialPropertiesForm(MaterialProperties dataBuffer)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
parameterDataGrid.PreferredColumnWidth = parameterDataGrid.Width / 2 - 2;
m_dataBuffer = dataBuffer;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private MaterialProperties m_dataBuffer = null;
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.typeLable = new System.Windows.Forms.Label();
this.typeComboBox = new System.Windows.Forms.ComboBox();
this.subTypeComboBox = new System.Windows.Forms.ComboBox();
this.parameterDataGrid = new System.Windows.Forms.DataGrid();
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.applyButton = new System.Windows.Forms.Button();
this.changeButton = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.parameterDataGrid)).BeginInit();
this.SuspendLayout();
//
// typeLable
//
this.typeLable.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.typeLable.Location = new System.Drawing.Point(24, 16);
this.typeLable.Name = "typeLable";
this.typeLable.Size = new System.Drawing.Size(80, 23);
this.typeLable.TabIndex = 0;
this.typeLable.Text = "Material Type:";
//
// typeComboBox
//
this.typeComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.typeComboBox.Location = new System.Drawing.Point(112, 16);
this.typeComboBox.Name = "typeComboBox";
this.typeComboBox.Size = new System.Drawing.Size(264, 21);
this.typeComboBox.TabIndex = 2;
this.typeComboBox.SelectedIndexChanged += new System.EventHandler(this.typeComboBox_SelectedIndexChanged);
//
// subTypeComboBox
//
this.subTypeComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.subTypeComboBox.Location = new System.Drawing.Point(112, 48);
this.subTypeComboBox.MaxDropDownItems = 30;
this.subTypeComboBox.Name = "subTypeComboBox";
this.subTypeComboBox.Size = new System.Drawing.Size(264, 21);
this.subTypeComboBox.TabIndex = 3;
this.subTypeComboBox.SelectedIndexChanged += new System.EventHandler(this.subTypeComboBox_SelectedIndexChanged);
//
// parameterDataGrid
//
this.parameterDataGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.parameterDataGrid.CaptionVisible = false;
this.parameterDataGrid.DataMember = "";
this.parameterDataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.parameterDataGrid.Location = new System.Drawing.Point(16, 88);
this.parameterDataGrid.Name = "parameterDataGrid";
this.parameterDataGrid.ReadOnly = true;
this.parameterDataGrid.RowHeadersVisible = false;
this.parameterDataGrid.Size = new System.Drawing.Size(480, 380);
this.parameterDataGrid.TabIndex = 4;
//
// okButton
//
this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.okButton.Location = new System.Drawing.Point(104, 480);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23);
this.okButton.TabIndex = 5;
this.okButton.Text = "&OK";
this.okButton.Click += new System.EventHandler(this.okButton_Click);
//
// cancelButton
//
this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cancelButton.Location = new System.Drawing.Point(192, 480);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 23);
this.cancelButton.TabIndex = 6;
this.cancelButton.Text = "&Cancel";
this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
//
// applyButton
//
this.applyButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.applyButton.Location = new System.Drawing.Point(280, 480);
this.applyButton.Name = "applyButton";
this.applyButton.Size = new System.Drawing.Size(75, 23);
this.applyButton.TabIndex = 7;
this.applyButton.Text = "&Apply";
this.applyButton.Click += new System.EventHandler(this.applyButton_Click);
//
// changeButton
//
this.changeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.changeButton.Location = new System.Drawing.Point(368, 480);
this.changeButton.Name = "changeButton";
this.changeButton.Size = new System.Drawing.Size(128, 23);
this.changeButton.TabIndex = 8;
this.changeButton.Text = "Change &Unit Weight";
this.changeButton.Click += new System.EventHandler(this.changeButton_Click);
//
// MaterialPropertiesForm
//
this.AcceptButton = this.okButton;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.cancelButton;
this.ClientSize = new System.Drawing.Size(512, 512);
this.Controls.Add(this.changeButton);
this.Controls.Add(this.applyButton);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.okButton);
this.Controls.Add(this.parameterDataGrid);
this.Controls.Add(this.subTypeComboBox);
this.Controls.Add(this.typeComboBox);
this.Controls.Add(this.typeLable);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "MaterialPropertiesForm";
this.ShowInTaskbar = false;
this.Text = "Material Properties";
this.Load += new System.EventHandler(this.MaterialPropFrm_Load);
((System.ComponentModel.ISupportInitialize)(this.parameterDataGrid)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MaterialPropFrm_Load(object sender, System.EventArgs e)
{
LoadCurrentMaterial();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void typeComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
if ((MaterialType)typeComboBox.SelectedIndex == MaterialType.Steel)
{
applyButton.Enabled = true;
changeButton.Enabled = true;
subTypeComboBox.Enabled = true;
subTypeComboBox.DataSource = m_dataBuffer.SteelCollection;
subTypeComboBox.DisplayMember = "MaterialName";
subTypeComboBox.ValueMember = "Material";
parameterDataGrid.DataSource = m_dataBuffer.GetParameterTable(subTypeComboBox.SelectedValue, (MaterialType)typeComboBox.SelectedIndex);
}
else if ((MaterialType)typeComboBox.SelectedIndex == MaterialType.Concrete)
{
applyButton.Enabled = true;
changeButton.Enabled = true;
subTypeComboBox.Enabled = true;
subTypeComboBox.DataSource = m_dataBuffer.ConcreteCollection;
subTypeComboBox.DisplayMember = "MaterialName";
subTypeComboBox.ValueMember = "Material";
parameterDataGrid.DataSource = m_dataBuffer.GetParameterTable(subTypeComboBox.SelectedValue, (MaterialType)typeComboBox.SelectedIndex);
}
else
{
applyButton.Enabled = false;
changeButton.Enabled = false;
subTypeComboBox.DataSource = new ArrayList();
subTypeComboBox.Enabled = false;
parameterDataGrid.DataSource = new DataTable();
}
}
/// <summary>
/// change the content in datagrid according to selected material type
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void subTypeComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (null != subTypeComboBox.SelectedValue)
{
m_dataBuffer.UpdateMaterial(subTypeComboBox.SelectedValue);
}
parameterDataGrid.DataSource = m_dataBuffer.GetParameterTable(subTypeComboBox.SelectedValue, (MaterialType)typeComboBox.SelectedIndex);
}
/// <summary>
/// close form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cancelButton_Click(object sender, System.EventArgs e)
{
this.Close();
}
/// <summary>
/// set selected element's material to current selection and close form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void okButton_Click(object sender, System.EventArgs e)
{
if (null != subTypeComboBox.SelectedValue)
{
m_dataBuffer.UpdateMaterial(subTypeComboBox.SelectedValue);
m_dataBuffer.SetMaterial();
}
this.Close();
}
/// <summary>
/// set selected element's material to current selection
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void applyButton_Click(object sender, System.EventArgs e)
{
if (null != subTypeComboBox.SelectedValue)
{
m_dataBuffer.UpdateMaterial(subTypeComboBox.SelectedValue);
m_dataBuffer.SetMaterial();
}
}
/// <summary>
/// change unit weight all instances of the elements that use this material
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void changeButton_Click(object sender, System.EventArgs e)
{
MessageBox.Show("This will change the unit weight of all instances that use this material in current document.");
if (!m_dataBuffer.ChangeUnitWeight())
{
MessageBox.Show("Failed to change the unit weight.");
return;
}
LoadCurrentMaterial();
}
/// <summary>
/// update display data to selected element's material
/// </summary>
private void LoadCurrentMaterial()
{
typeComboBox.DataSource = m_dataBuffer.MaterialTypes;
typeComboBox.SelectedIndex = (int)m_dataBuffer.CurrentType;
if (null == m_dataBuffer.CurrentMaterial || (m_dataBuffer.CurrentType != MaterialType.Steel
&& m_dataBuffer.CurrentType != MaterialType.Concrete))
{
return;
}
Autodesk.Revit.DB.Material tmp = m_dataBuffer.CurrentMaterial as Autodesk.Revit.DB.Material;
if (null == tmp)
return;
subTypeComboBox.SelectedValue = tmp;
parameterDataGrid.DataSource = m_dataBuffer.GetParameterTable(subTypeComboBox.SelectedValue, (MaterialType)typeComboBox.SelectedIndex);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>AdGroupCriterion</c> resource.</summary>
public sealed partial class AdGroupCriterionName : gax::IResourceName, sys::IEquatable<AdGroupCriterionName>
{
/// <summary>The possible contents of <see cref="AdGroupCriterionName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}</c>
/// .
/// </summary>
CustomerAdGroupCriterion = 1,
}
private static gax::PathTemplate s_customerAdGroupCriterion = new gax::PathTemplate("customers/{customer_id}/adGroupCriteria/{ad_group_id_criterion_id}");
/// <summary>Creates a <see cref="AdGroupCriterionName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AdGroupCriterionName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AdGroupCriterionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AdGroupCriterionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AdGroupCriterionName"/> with the pattern
/// <c>customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AdGroupCriterionName"/> constructed from the provided ids.</returns>
public static AdGroupCriterionName FromCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) =>
new AdGroupCriterionName(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupCriterionName"/> with pattern
/// <c>customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdGroupCriterionName"/> with pattern
/// <c>customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}</c>.
/// </returns>
public static string Format(string customerId, string adGroupId, string criterionId) =>
FormatCustomerAdGroupCriterion(customerId, adGroupId, criterionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupCriterionName"/> with pattern
/// <c>customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdGroupCriterionName"/> with pattern
/// <c>customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}</c>.
/// </returns>
public static string FormatCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) =>
s_customerAdGroupCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="AdGroupCriterionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adGroupCriterionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AdGroupCriterionName"/> if successful.</returns>
public static AdGroupCriterionName Parse(string adGroupCriterionName) => Parse(adGroupCriterionName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AdGroupCriterionName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupCriterionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AdGroupCriterionName"/> if successful.</returns>
public static AdGroupCriterionName Parse(string adGroupCriterionName, bool allowUnparsed) =>
TryParse(adGroupCriterionName, allowUnparsed, out AdGroupCriterionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdGroupCriterionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adGroupCriterionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdGroupCriterionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adGroupCriterionName, out AdGroupCriterionName result) =>
TryParse(adGroupCriterionName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdGroupCriterionName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupCriterionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdGroupCriterionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adGroupCriterionName, bool allowUnparsed, out AdGroupCriterionName result)
{
gax::GaxPreconditions.CheckNotNull(adGroupCriterionName, nameof(adGroupCriterionName));
gax::TemplatedResourceName resourceName;
if (s_customerAdGroupCriterion.TryParseName(adGroupCriterionName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerAdGroupCriterion(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(adGroupCriterionName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private AdGroupCriterionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string criterionId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AdGroupId = adGroupId;
CriterionId = criterionId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AdGroupCriterionName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
public AdGroupCriterionName(string customerId, string adGroupId, string criterionId) : this(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdGroupId { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerAdGroupCriterion: return s_customerAdGroupCriterion.Expand(CustomerId, $"{AdGroupId}~{CriterionId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AdGroupCriterionName);
/// <inheritdoc/>
public bool Equals(AdGroupCriterionName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AdGroupCriterionName a, AdGroupCriterionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AdGroupCriterionName a, AdGroupCriterionName b) => !(a == b);
}
public partial class AdGroupCriterion
{
/// <summary>
/// <see cref="AdGroupCriterionName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal AdGroupCriterionName ResourceNameAsAdGroupCriterionName
{
get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupCriterionName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property.
/// </summary>
internal AdGroupName AdGroupAsAdGroupName
{
get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true);
set => AdGroup = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupCriterionLabelName"/>-typed view over the <see cref="Labels"/> resource name property.
/// </summary>
internal gax::ResourceNameList<AdGroupCriterionLabelName> LabelsAsAdGroupCriterionLabelNames
{
get => new gax::ResourceNameList<AdGroupCriterionLabelName>(Labels, s => string.IsNullOrEmpty(s) ? null : AdGroupCriterionLabelName.Parse(s, allowUnparsed: true));
}
}
}
| |
/*
* Copyright (c) 2006-2016, openmetaverse.co
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.InteropServices;
using System.Globalization;
namespace OpenMetaverse
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Quaternion : IEquatable<Quaternion>
{
/// <summary>X value</summary>
public float X;
/// <summary>Y value</summary>
public float Y;
/// <summary>Z value</summary>
public float Z;
/// <summary>W value</summary>
public float W;
#region Constructors
public Quaternion(float x, float y, float z, float w)
{
X = x;
Y = y;
Z = z;
W = w;
}
public Quaternion(Vector3 vectorPart, float scalarPart)
{
X = vectorPart.X;
Y = vectorPart.Y;
Z = vectorPart.Z;
W = scalarPart;
}
/// <summary>
/// Build a quaternion from normalized float values
/// </summary>
/// <param name="x">X value from -1.0 to 1.0</param>
/// <param name="y">Y value from -1.0 to 1.0</param>
/// <param name="z">Z value from -1.0 to 1.0</param>
public Quaternion(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
float xyzsum = 1 - X * X - Y * Y - Z * Z;
W = (xyzsum > 0) ? (float)Math.Sqrt(xyzsum) : 0;
}
/// <summary>
/// Constructor, builds a quaternion object from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing four four-byte floats</param>
/// <param name="pos">Offset in the byte array to start reading at</param>
/// <param name="normalized">Whether the source data is normalized or
/// not. If this is true 12 bytes will be read, otherwise 16 bytes will
/// be read.</param>
public Quaternion(byte[] byteArray, int pos, bool normalized)
{
X = Y = Z = W = 0;
FromBytes(byteArray, pos, normalized);
}
public Quaternion(Quaternion q)
{
X = q.X;
Y = q.Y;
Z = q.Z;
W = q.W;
}
#endregion Constructors
#region Public Methods
public bool ApproxEquals(Quaternion quat, float tolerance)
{
Quaternion diff = this - quat;
return (diff.LengthSquared() <= tolerance * tolerance);
}
public float Length()
{
return (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W);
}
public float LengthSquared()
{
return (X * X + Y * Y + Z * Z + W * W);
}
/// <summary>
/// Normalizes the quaternion
/// </summary>
public void Normalize()
{
this = Normalize(this);
}
/// <summary>
/// Builds a quaternion object from a byte array
/// </summary>
/// <param name="byteArray">The source byte array</param>
/// <param name="pos">Offset in the byte array to start reading at</param>
/// <param name="normalized">Whether the source data is normalized or
/// not. If this is true 12 bytes will be read, otherwise 16 bytes will
/// be read.</param>
public void FromBytes(byte[] byteArray, int pos, bool normalized)
{
if (!normalized)
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[16];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 16);
Array.Reverse(conversionBuffer, 0, 4);
Array.Reverse(conversionBuffer, 4, 4);
Array.Reverse(conversionBuffer, 8, 4);
Array.Reverse(conversionBuffer, 12, 4);
X = BitConverter.ToSingle(conversionBuffer, 0);
Y = BitConverter.ToSingle(conversionBuffer, 4);
Z = BitConverter.ToSingle(conversionBuffer, 8);
W = BitConverter.ToSingle(conversionBuffer, 12);
}
else
{
// Little endian architecture
X = BitConverter.ToSingle(byteArray, pos);
Y = BitConverter.ToSingle(byteArray, pos + 4);
Z = BitConverter.ToSingle(byteArray, pos + 8);
W = BitConverter.ToSingle(byteArray, pos + 12);
}
}
else
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[16];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 12);
Array.Reverse(conversionBuffer, 0, 4);
Array.Reverse(conversionBuffer, 4, 4);
Array.Reverse(conversionBuffer, 8, 4);
X = BitConverter.ToSingle(conversionBuffer, 0);
Y = BitConverter.ToSingle(conversionBuffer, 4);
Z = BitConverter.ToSingle(conversionBuffer, 8);
}
else
{
// Little endian architecture
X = BitConverter.ToSingle(byteArray, pos);
Y = BitConverter.ToSingle(byteArray, pos + 4);
Z = BitConverter.ToSingle(byteArray, pos + 8);
}
float xyzsum = 1f - X * X - Y * Y - Z * Z;
W = (xyzsum > 0f) ? (float)Math.Sqrt(xyzsum) : 0f;
}
}
/// <summary>
/// Normalize this quaternion and serialize it to a byte array
/// </summary>
/// <returns>A 12 byte array containing normalized X, Y, and Z floating
/// point values in order using little endian byte ordering</returns>
public byte[] GetBytes()
{
byte[] bytes = new byte[12];
ToBytes(bytes, 0);
return bytes;
}
/// <summary>
/// Writes the raw bytes for this quaternion to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 12 bytes before the end of the array</param>
public void ToBytes(byte[] dest, int pos)
{
float norm = (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W);
if (norm != 0f)
{
norm = 1f / norm;
float x, y, z;
if (W >= 0f)
{
x = X; y = Y; z = Z;
}
else
{
x = -X; y = -Y; z = -Z;
}
Buffer.BlockCopy(BitConverter.GetBytes(norm * x), 0, dest, pos + 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(norm * y), 0, dest, pos + 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes(norm * z), 0, dest, pos + 8, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(dest, pos + 0, 4);
Array.Reverse(dest, pos + 4, 4);
Array.Reverse(dest, pos + 8, 4);
}
}
else
{
throw new InvalidOperationException(String.Format(
"Quaternion {0} normalized to zero", ToString()));
}
}
/// <summary>
/// Convert this quaternion to euler angles
/// </summary>
/// <param name="roll">X euler angle</param>
/// <param name="pitch">Y euler angle</param>
/// <param name="yaw">Z euler angle</param>
public void GetEulerAngles(out float roll, out float pitch, out float yaw)
{
roll = 0f;
pitch = 0f;
yaw = 0f;
Quaternion t = new Quaternion(this.X * this.X, this.Y * this.Y, this.Z * this.Z, this.W * this.W);
float m = (t.X + t.Y + t.Z + t.W);
if (Math.Abs(m) < 0.001d) return;
float n = 2 * (this.Y * this.W + this.X * this.Z);
float p = m * m - n * n;
if (p > 0f)
{
roll = (float)Math.Atan2(2.0f * (this.X * this.W - this.Y * this.Z), (-t.X - t.Y + t.Z + t.W));
pitch = (float)Math.Atan2(n, Math.Sqrt(p));
yaw = (float)Math.Atan2(2.0f * (this.Z * this.W - this.X * this.Y), t.X - t.Y - t.Z + t.W);
}
else if (n > 0f)
{
roll = 0f;
pitch = (float)(Math.PI / 2d);
yaw = (float)Math.Atan2((this.Z * this.W + this.X * this.Y), 0.5f - t.X - t.Y);
}
else
{
roll = 0f;
pitch = -(float)(Math.PI / 2d);
yaw = (float)Math.Atan2((this.Z * this.W + this.X * this.Y), 0.5f - t.X - t.Z);
}
//float sqx = X * X;
//float sqy = Y * Y;
//float sqz = Z * Z;
//float sqw = W * W;
//// Unit will be a correction factor if the quaternion is not normalized
//float unit = sqx + sqy + sqz + sqw;
//double test = X * Y + Z * W;
//if (test > 0.499f * unit)
//{
// // Singularity at north pole
// yaw = 2f * (float)Math.Atan2(X, W);
// pitch = (float)Math.PI / 2f;
// roll = 0f;
//}
//else if (test < -0.499f * unit)
//{
// // Singularity at south pole
// yaw = -2f * (float)Math.Atan2(X, W);
// pitch = -(float)Math.PI / 2f;
// roll = 0f;
//}
//else
//{
// yaw = (float)Math.Atan2(2f * Y * W - 2f * X * Z, sqx - sqy - sqz + sqw);
// pitch = (float)Math.Asin(2f * test / unit);
// roll = (float)Math.Atan2(2f * X * W - 2f * Y * Z, -sqx + sqy - sqz + sqw);
//}
}
/// <summary>
/// Convert this quaternion to an angle around an axis
/// </summary>
/// <param name="axis">Unit vector describing the axis</param>
/// <param name="angle">Angle around the axis, in radians</param>
public void GetAxisAngle(out Vector3 axis, out float angle)
{
Quaternion q = Normalize(this);
float sin = (float)Math.Sqrt(1.0f - q.W * q.W);
if (sin >= 0.001)
{
float invSin = 1.0f / sin;
if (q.W < 0) invSin = -invSin;
axis = new Vector3(q.X, q.Y, q.Z) * invSin;
angle = 2.0f * (float)Math.Acos(q.W);
if (angle > Math.PI)
angle = 2.0f * (float)Math.PI - angle;
}
else
{
axis = Vector3.UnitX;
angle = 0f;
}
}
#endregion Public Methods
#region Static Methods
public static Quaternion Add(Quaternion quaternion1, Quaternion quaternion2)
{
quaternion1.X += quaternion2.X;
quaternion1.Y += quaternion2.Y;
quaternion1.Z += quaternion2.Z;
quaternion1.W += quaternion2.W;
return quaternion1;
}
/// <summary>
/// Returns the conjugate (spatial inverse) of a quaternion
/// </summary>
public static Quaternion Conjugate(Quaternion quaternion)
{
quaternion.X = -quaternion.X;
quaternion.Y = -quaternion.Y;
quaternion.Z = -quaternion.Z;
return quaternion;
}
/// <summary>
/// Build a quaternion from an axis and an angle of rotation around
/// that axis
/// </summary>
public static Quaternion CreateFromAxisAngle(float axisX, float axisY, float axisZ, float angle)
{
Vector3 axis = new Vector3(axisX, axisY, axisZ);
return CreateFromAxisAngle(axis, angle);
}
/// <summary>
/// Build a quaternion from an axis and an angle of rotation around
/// that axis
/// </summary>
/// <param name="axis">Axis of rotation</param>
/// <param name="angle">Angle of rotation</param>
public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle)
{
Quaternion q;
axis = Vector3.Normalize(axis);
angle *= 0.5f;
float c = (float)Math.Cos(angle);
float s = (float)Math.Sin(angle);
q.X = axis.X * s;
q.Y = axis.Y * s;
q.Z = axis.Z * s;
q.W = c;
return Quaternion.Normalize(q);
}
/// <summary>
/// Creates a quaternion from a vector containing roll, pitch, and yaw
/// in radians
/// </summary>
/// <param name="eulers">Vector representation of the euler angles in
/// radians</param>
/// <returns>Quaternion representation of the euler angles</returns>
public static Quaternion CreateFromEulers(Vector3 eulers)
{
return CreateFromEulers(eulers.X, eulers.Y, eulers.Z);
}
/// <summary>
/// Creates a quaternion from roll, pitch, and yaw euler angles in
/// radians
/// </summary>
/// <param name="roll">X angle in radians</param>
/// <param name="pitch">Y angle in radians</param>
/// <param name="yaw">Z angle in radians</param>
/// <returns>Quaternion representation of the euler angles</returns>
public static Quaternion CreateFromEulers(float roll, float pitch, float yaw)
{
if (roll > Utils.TWO_PI || pitch > Utils.TWO_PI || yaw > Utils.TWO_PI)
throw new ArgumentException("Euler angles must be in radians");
double atCos = Math.Cos(roll / 2f);
double atSin = Math.Sin(roll / 2f);
double leftCos = Math.Cos(pitch / 2f);
double leftSin = Math.Sin(pitch / 2f);
double upCos = Math.Cos(yaw / 2f);
double upSin = Math.Sin(yaw / 2f);
double atLeftCos = atCos * leftCos;
double atLeftSin = atSin * leftSin;
return new Quaternion(
(float)(atSin * leftCos * upCos + atCos * leftSin * upSin),
(float)(atCos * leftSin * upCos - atSin * leftCos * upSin),
(float)(atLeftCos * upSin + atLeftSin * upCos),
(float)(atLeftCos * upCos - atLeftSin * upSin)
);
}
public static Quaternion CreateFromRotationMatrix(Matrix4 matrix)
{
float num8 = (matrix.M11 + matrix.M22) + matrix.M33;
Quaternion quaternion = new Quaternion();
if (num8 > 0f)
{
float num = (float)Math.Sqrt((double)(num8 + 1f));
quaternion.W = num * 0.5f;
num = 0.5f / num;
quaternion.X = (matrix.M23 - matrix.M32) * num;
quaternion.Y = (matrix.M31 - matrix.M13) * num;
quaternion.Z = (matrix.M12 - matrix.M21) * num;
return quaternion;
}
if ((matrix.M11 >= matrix.M22) && (matrix.M11 >= matrix.M33))
{
float num7 = (float)Math.Sqrt((double)(((1f + matrix.M11) - matrix.M22) - matrix.M33));
float num4 = 0.5f / num7;
quaternion.X = 0.5f * num7;
quaternion.Y = (matrix.M12 + matrix.M21) * num4;
quaternion.Z = (matrix.M13 + matrix.M31) * num4;
quaternion.W = (matrix.M23 - matrix.M32) * num4;
return quaternion;
}
if (matrix.M22 > matrix.M33)
{
float num6 = (float)Math.Sqrt((double)(((1f + matrix.M22) - matrix.M11) - matrix.M33));
float num3 = 0.5f / num6;
quaternion.X = (matrix.M21 + matrix.M12) * num3;
quaternion.Y = 0.5f * num6;
quaternion.Z = (matrix.M32 + matrix.M23) * num3;
quaternion.W = (matrix.M31 - matrix.M13) * num3;
return quaternion;
}
float num5 = (float)Math.Sqrt((double)(((1f + matrix.M33) - matrix.M11) - matrix.M22));
float num2 = 0.5f / num5;
quaternion.X = (matrix.M31 + matrix.M13) * num2;
quaternion.Y = (matrix.M32 + matrix.M23) * num2;
quaternion.Z = 0.5f * num5;
quaternion.W = (matrix.M12 - matrix.M21) * num2;
return quaternion;
}
public static Quaternion Divide(Quaternion q1, Quaternion q2)
{
return Quaternion.Inverse(q1) * q2;
}
public static float Dot(Quaternion q1, Quaternion q2)
{
return (q1.X * q2.X) + (q1.Y * q2.Y) + (q1.Z * q2.Z) + (q1.W * q2.W);
}
/// <summary>
/// Conjugates and renormalizes a vector
/// </summary>
public static Quaternion Inverse(Quaternion quaternion)
{
float norm = quaternion.LengthSquared();
if (norm == 0f)
{
quaternion.X = quaternion.Y = quaternion.Z = quaternion.W = 0f;
}
else
{
float oonorm = 1f / norm;
quaternion = Conjugate(quaternion);
quaternion.X *= oonorm;
quaternion.Y *= oonorm;
quaternion.Z *= oonorm;
quaternion.W *= oonorm;
}
return quaternion;
}
/// <summary>
/// Spherical linear interpolation between two quaternions
/// </summary>
public static Quaternion Slerp(Quaternion q1, Quaternion q2, float amount)
{
float angle = Dot(q1, q2);
if (angle < 0f)
{
q1 *= -1f;
angle *= -1f;
}
float scale;
float invscale;
if ((angle + 1f) > 0.05f)
{
if ((1f - angle) >= 0.05f)
{
// slerp
float theta = (float)Math.Acos(angle);
float invsintheta = 1f / (float)Math.Sin(theta);
scale = (float)Math.Sin(theta * (1f - amount)) * invsintheta;
invscale = (float)Math.Sin(theta * amount) * invsintheta;
}
else
{
// lerp
scale = 1f - amount;
invscale = amount;
}
}
else
{
q2.X = -q1.Y;
q2.Y = q1.X;
q2.Z = -q1.W;
q2.W = q1.Z;
scale = (float)Math.Sin(Utils.PI * (0.5f - amount));
invscale = (float)Math.Sin(Utils.PI * amount);
}
return (q1 * scale) + (q2 * invscale);
}
public static Quaternion Subtract(Quaternion quaternion1, Quaternion quaternion2)
{
quaternion1.X -= quaternion2.X;
quaternion1.Y -= quaternion2.Y;
quaternion1.Z -= quaternion2.Z;
quaternion1.W -= quaternion2.W;
return quaternion1;
}
public static Quaternion Multiply(Quaternion a, Quaternion b)
{
return new Quaternion(
a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y,
a.W * b.Y + a.Y * b.W + a.Z * b.X - a.X * b.Z,
a.W * b.Z + a.Z * b.W + a.X * b.Y - a.Y * b.X,
a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z
);
}
public static Quaternion Multiply(Quaternion quaternion, float scaleFactor)
{
quaternion.X *= scaleFactor;
quaternion.Y *= scaleFactor;
quaternion.Z *= scaleFactor;
quaternion.W *= scaleFactor;
return quaternion;
}
public static Quaternion Negate(Quaternion quaternion)
{
quaternion.X = -quaternion.X;
quaternion.Y = -quaternion.Y;
quaternion.Z = -quaternion.Z;
quaternion.W = -quaternion.W;
return quaternion;
}
public static Quaternion Normalize(Quaternion q)
{
const float MAG_THRESHOLD = 0.0000001f;
float mag = q.Length();
// Catch very small rounding errors when normalizing
if (mag > MAG_THRESHOLD)
{
float oomag = 1f / mag;
q.X *= oomag;
q.Y *= oomag;
q.Z *= oomag;
q.W *= oomag;
}
else
{
q.X = 0f;
q.Y = 0f;
q.Z = 0f;
q.W = 1f;
}
return q;
}
public static Quaternion Parse(string val)
{
char[] splitChar = { ',' };
string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar);
if (split.Length == 3)
{
return new Quaternion(
float.Parse(split[0].Trim(), Utils.EnUsCulture),
float.Parse(split[1].Trim(), Utils.EnUsCulture),
float.Parse(split[2].Trim(), Utils.EnUsCulture));
}
else
{
return new Quaternion(
float.Parse(split[0].Trim(), Utils.EnUsCulture),
float.Parse(split[1].Trim(), Utils.EnUsCulture),
float.Parse(split[2].Trim(), Utils.EnUsCulture),
float.Parse(split[3].Trim(), Utils.EnUsCulture));
}
}
public static bool TryParse(string val, out Quaternion result)
{
try
{
result = Parse(val);
return true;
}
catch (Exception)
{
result = new Quaternion();
return false;
}
}
#endregion Static Methods
#region Overrides
public override bool Equals(object obj)
{
return (obj is Quaternion) ? this == (Quaternion)obj : false;
}
public bool Equals(Quaternion other)
{
return W == other.W
&& X == other.X
&& Y == other.Y
&& Z == other.Z;
}
public override int GetHashCode()
{
return (X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode());
}
public override string ToString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W);
}
/// <summary>
/// Get a string representation of the quaternion elements with up to three
/// decimal digits and separated by spaces only
/// </summary>
/// <returns>Raw string representation of the quaternion</returns>
public string ToRawString()
{
CultureInfo enUs = new CultureInfo("en-us");
enUs.NumberFormat.NumberDecimalDigits = 3;
return String.Format(enUs, "{0} {1} {2} {3}", X, Y, Z, W);
}
#endregion Overrides
#region Operators
public static bool operator ==(Quaternion quaternion1, Quaternion quaternion2)
{
return quaternion1.Equals(quaternion2);
}
public static bool operator !=(Quaternion quaternion1, Quaternion quaternion2)
{
return !(quaternion1 == quaternion2);
}
public static Quaternion operator +(Quaternion quaternion1, Quaternion quaternion2)
{
return Add(quaternion1, quaternion2);
}
public static Quaternion operator -(Quaternion quaternion)
{
return Negate(quaternion);
}
public static Quaternion operator -(Quaternion quaternion1, Quaternion quaternion2)
{
return Subtract(quaternion1, quaternion2);
}
public static Quaternion operator *(Quaternion a, Quaternion b)
{
return Multiply(a, b);
}
public static Quaternion operator *(Quaternion quaternion, float scaleFactor)
{
return Multiply(quaternion, scaleFactor);
}
public static Quaternion operator /(Quaternion quaternion1, Quaternion quaternion2)
{
return Divide(quaternion1, quaternion2);
}
#endregion Operators
/// <summary>A quaternion with a value of 0,0,0,1</summary>
public readonly static Quaternion Identity = new Quaternion(0f, 0f, 0f, 1f);
}
}
| |
using Tibia.Addresses;
namespace Tibia
{
public partial class Version
{
public static void SetVersion810and811()
{
BattleList.Start = 0x613BD0;
BattleList.End = 0x619990;
BattleList.StepCreatures = 0xA0;
BattleList.MaxCreatures = 100;
Client.StartTime = 0x76D90C;
Client.XTeaKey = 0x768C7C;
Client.SocketStruct = 0x768C50;
Client.SendPointer = 0x597600;
Client.FrameRatePointer = 0x76CE0C;
Client.FrameRateCurrentOffset = 0x00;
Client.FrameRateLimitOffset = 0x58;
Client.MultiClient = 0;//?
Client.Status = 0x76C2C8;
Client.SafeMode = 0x76909C;
Client.FollowMode = Client.SafeMode + 4;
Client.AttackMode = Client.FollowMode + 4;
Client.ActionState = 0x76C328;
//Client.CurrentWindow = 0x61E984;
Client.LastMSGAuthor = Client.LastMSGText - 0x28;
Client.LastMSGText = 0x76DB78;
Client.StatusbarText = 0x76D928;
Client.StatusbarTime = Client.StatusbarText - 4;
Client.ClickId = 0x76C364;
Client.ClickCount = Client.ClickId + 4;
Client.ClickZ = Client.ClickId - 0x68;
Client.SeeId = Client.ClickId + 12;
Client.SeeCount = Client.SeeId + 4;
Client.SeeZ = Client.SeeId - 0x68;
Client.SeeText = 0x76DB50;
Client.LoginServerStart = 0x763BB8;
Client.StepLoginServer = 112;
Client.DistancePort = 100;
Client.MaxLoginServers = 10;
Client.RSA = 0x597610;
Client.LoginCharList = 0x76C28C;
Client.LoginCharListLength = 0x76C290;
Client.GameWindowRectPointer = 0x12D624;
Client.DatPointer = 0x768C9C;
Client.DialogPointer = 0x61E984;
Client.DialogLeft = 0x14;
Client.DialogTop = 0x18;
Client.DialogWidth = 0x1C;
Client.DialogHeight = 0x20;
Client.DialogCaption = 0x50;
Client.LoginAccountNum = 0x76C2C0;
Client.LoginAccount = 0x76C2B4;
Client.LoginPassword = 0x76C294;
Client.LoginPatch = 0x47935E;
Client.LoginPatch2 = 0x47A2B3;
Client.LoginPatchOrig = new byte[] { 0xE8, 0x0D, 0x1D, 0x09, 0x00 };
Client.LoginPatchOrig2 = new byte[] { 0xE8, 0xC8, 0x15, 0x09, 0x00 };
Container.Start = 0x61C0D0;
Container.End = 0x61DF90;
Container.StepContainer = 492;
Container.StepSlot = 12;
Container.MaxContainers = 16;
Container.MaxStack = 100;
Container.DistanceIsOpen = 0;
Container.DistanceId = 4;
Container.DistanceName = 16;
Container.DistanceVolume = 48;
Container.DistanceAmount = 56;
Container.DistanceItemId = 60;
Container.DistanceItemCount = 64;
Creature.DistanceId = 0;
Creature.DistanceType = 3;
Creature.DistanceName = 4;
Creature.DistanceX = 36;
Creature.DistanceY = 40;
Creature.DistanceZ = 44;
Creature.DistanceScreenOffsetHoriz = 48;
Creature.DistanceScreenOffsetVert = 52;
Creature.DistanceIsWalking = 76;
Creature.DistanceWalkSpeed = 140;
Creature.DistanceDirection = 80;
Creature.DistanceIsVisible = 144;
Creature.DistanceBlackSquare = 128;
Creature.DistanceLight = 120;
Creature.DistanceLightColor = 124;
Creature.DistanceHPBar = 136;
Creature.DistanceSkull = 148;
Creature.DistanceParty = 152;
Creature.DistanceOutfit = 96;
Creature.DistanceColorHead = 100;
Creature.DistanceColorBody = 104;
Creature.DistanceColorLegs = 108;
Creature.DistanceColorFeet = 112;
Creature.DistanceAddon = 116;
DatItem.StepItems = 0x4C;
DatItem.Width = 0;
DatItem.Height = 4;
DatItem.MaxSizeInPixels = 8;
DatItem.Layers = 12;
DatItem.PatternX = 16;
DatItem.PatternY = 20;
DatItem.PatternDepth = 24;
DatItem.Phase = 28;
DatItem.Sprite = 32;
DatItem.Flags = 36;
DatItem.CanLookAt = 0;
DatItem.WalkSpeed = 40;
DatItem.TextLimit = 44;
DatItem.LightRadius = 48;
DatItem.LightColor = 52;
DatItem.ShiftX = 56;
DatItem.ShiftY = 60;
DatItem.WalkHeight = 64;
DatItem.Automap = 68;
DatItem.LensHelp = 72;
Hotkey.SendAutomaticallyStart = 0x769298;
Hotkey.SendAutomaticallyStep = 0x01;
Hotkey.TextStart = 0x7692C0;
Hotkey.TextStep = 0x100;
Hotkey.ObjectStart = 0x769208;
Hotkey.ObjectStep = 0x04;
Hotkey.ObjectUseTypeStart = 0x7690E8;
Hotkey.ObjectUseTypeStep = 0x04;
Hotkey.MaxHotkeys = 36;
Map.MapPointer = 0x6234D8;
Map.StepTile = 172;
Map.StepTileObject = 12;
Map.DistanceTileObjectCount = 0;
Map.DistanceTileObjects = 4;
Map.DistanceObjectId = 0;
Map.DistanceObjectData = 4;
Map.DistanceObjectDataEx = 8;
Map.MaxTileObjects = 13;
Map.MaxX = 18;
Map.MaxY = 14;
Map.MaxZ = 8;
Map.MaxTiles = 2016;
Map.ZAxisDefault = 7;
Map.PlayerTile = 0x3E3A08;
Map.NameSpy1 = 0x4DF469;
Map.NameSpy2 = 0x004DF473;
Map.NameSpy1Default = 19061;
Map.NameSpy2Default = 16501;
Map.LevelSpy1 = 0x4E115A;
Map.LevelSpy2 = 0x4E125F;
Map.LevelSpy3 = 0x4E12E0;
Map.LevelSpyPtr = 0x61B608;
Map.LevelSpyAdd2 = 0x25D8;
Map.RevealInvisible1 = 0x453AF3;
Map.RevealInvisible2 = 0x4DE734;
Player.Flags = 0x00613AF8;
Player.Experience = 0x00613B64;
Player.Id = Player.Experience + 12;
Player.Health = Player.Experience + 8;
Player.HealthMax = Player.Experience + 4;
Player.Level = Player.Experience - 4;
Player.MagicLevel = Player.Experience - 8;
Player.LevelPercent = Player.Experience - 12;
Player.MagicLevelPercent = Player.Experience - 16;
Player.Mana = Player.Experience - 20;
Player.ManaMax = Player.Experience - 24;
Player.Soul = Player.Experience - 28;
Player.Stamina = Player.Experience - 32;
Player.Capacity = Player.Experience - 36;
Player.FistPercent = 0x00613AFC;
Player.ClubPercent = Player.FistPercent + 4;
Player.SwordPercent = Player.FistPercent + 8;
Player.AxePercent = Player.FistPercent + 12;
Player.DistancePercent = Player.FistPercent + 16;
Player.ShieldingPercent = Player.FistPercent + 20;
Player.FishingPercent = Player.FistPercent + 24;
Player.Fist = Player.FistPercent + 28;
Player.Club = Player.FistPercent + 32;
Player.Sword = Player.FistPercent + 36;
Player.Axe = Player.FistPercent + 40;
Player.Distance = Player.FistPercent + 44;
Player.Shielding = Player.FistPercent + 48;
Player.Fishing = Player.FistPercent + 52;
Player.SlotHead = 0x61C058;
Player.SlotNeck = Player.SlotHead + 12;
Player.SlotBackpack = Player.SlotHead + 24;
Player.SlotArmor = Player.SlotHead + 36;
Player.SlotRight = Player.SlotHead + 48;
Player.SlotLeft = Player.SlotHead + 60;
Player.SlotLegs = Player.SlotHead + 72;
Player.SlotFeet = Player.SlotHead + 84;
Player.SlotRing = Player.SlotHead + 96;
Player.SlotAmmo = Player.SlotHead + 108;
Player.MaxSlots = 10;
Player.DistanceSlotCount = 4;
Player.CurrentTileToGo = 0x613B78;
Player.TilesToGo = 0x613B7C;
Player.GoToX = 0x613BB4;
Player.GoToY = Player.GoToX - 4;
Player.GoToZ = Player.GoToX - 8;
Player.RedSquare = 0x613B3C;
Player.GreenSquare = Player.RedSquare - 4;
Player.WhiteSquare = Player.GreenSquare - 8;
Player.AccessN = 0x766DF4;
Player.AccessS = 0x766DC4;
Player.TargetId = Player.RedSquare;
Player.TargetBattlelistId = Player.TargetId - 8;
Player.TargetBattlelistType = Player.TargetId - 5;
Player.TargetType = Player.TargetId + 3;
Player.Z = 0x61E9C0;
TextDisplay.PrintName = 0x4E228A;
TextDisplay.PrintFPS = 0x44E753;
TextDisplay.ShowFPS = 0x611874;
TextDisplay.PrintTextFunc = 0x4A3C00;
TextDisplay.NopFPS = 0x44E68F;
Vip.Start = 0x611890;
Vip.End = 0x612128;
Vip.StepPlayers = 0x2C;
Vip.MaxPlayers = 100;
Vip.DistanceId = 0;
Vip.DistanceName = 4;
Vip.DistanceStatus = 34;
Vip.DistanceIcon = 40;
}
}
}
| |
#region Copyright
//
// This framework is based on log4j see http://jakarta.apache.org/log4j
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.Collections;
using System.Data;
using System.Reflection;
using log4net.helpers;
using log4net.Layout;
using log4net.spi;
namespace log4net.Appender
{
/// <summary>
/// Appender that logs to a database.
/// </summary>
/// <remarks>
/// <para>
/// <see cref="ADONetAppender"/> appends logging events to a table within a
/// database. The appender can be configured to specify the connection
/// string by setting the <see cref="ConnectionString"/> property.
/// The connection type (provider) can be specified by setting the <see cref="ConnectionType"/>
/// property. For more information on database connection strings for
/// your specific database see <a href="http://www.connectionstrings.com/">http://www.connectionstrings.com/</a>.
/// </para>
/// <para>
/// Records are written into the database either using a prepared
/// statement or a stored procedure. The <see cref="CommandType"/> property
/// is set to <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>) to specify a prepared statement
/// or to <see cref="System.Data.CommandType.StoredProcedure"/> (<c>System.Data.CommandType.StoredProcedure</c>) to specify a stored
/// procedure.
/// </para>
/// <para>
/// The prepared statement text or the name of the stored procedure
/// must be set in the <see cref="CommandText"/> property.
/// </para>
/// <para>
/// The prepared statement or stored procedure can take a number
/// of parameters. Parameters are added using the <see cref="AddParameter"/>
/// method. This adds a single <see cref="ADONetAppenderParameter"/> to the
/// ordered list of parameters. The <see cref="ADONetAppenderParameter"/>
/// type may be subclassed if required to provide database specific
/// functionality. The <see cref="ADONetAppenderParameter"/> specifies
/// the parameter name, database type, size, and how the value should
/// be generated using a <see cref="ILayout"/>.
/// </para>
/// </remarks>
/// <example>
/// An example of a SQL Server table that could be logged to:
/// <code>
/// CREATE TABLE [dbo].[Log] (
/// [ID] [int] IDENTITY (1, 1) NOT NULL ,
/// [Date] [datetime] NOT NULL ,
/// [Thread] [varchar] (255) NOT NULL ,
/// [Level] [varchar] (20) NOT NULL ,
/// [Logger] [varchar] (255) NOT NULL ,
/// [Message] [varchar] (4000) NOT NULL
/// ) ON [PRIMARY]
/// </code>
/// </example>
/// <example>
/// An example configuration to log to the above table:
/// <code>
/// <appender name="ADONetAppender_SqlServer" type="log4net.Appender.ADONetAppender" >
/// <param name="ConnectionType" value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
/// <param name="ConnectionString" value="data source=GUINNESS;initial catalog=test_log4net;integrated security=false;persist security info=True;User ID=sa;Password=sql" />
/// <param name="CommandText" value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
/// <param name="Parameter">
/// <param name="ParameterName" value="@log_date" />
/// <param name="DbType" value="DateTime" />
/// <param name="Layout" type="log4net.Layout.PatternLayout">
/// <param name="ConversionPattern" value="%d{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
/// </param>
/// </param>
/// <param name="Parameter">
/// <param name="ParameterName" value="@thread" />
/// <param name="DbType" value="String" />
/// <param name="Size" value="255" />
/// <param name="Layout" type="log4net.Layout.PatternLayout">
/// <param name="ConversionPattern" value="%t" />
/// </param>
/// </param>
/// <param name="Parameter">
/// <param name="ParameterName" value="@log_level" />
/// <param name="DbType" value="String" />
/// <param name="Size" value="50" />
/// <param name="Layout" type="log4net.Layout.PatternLayout">
/// <param name="ConversionPattern" value="%p" />
/// </param>
/// </param>
/// <param name="Parameter">
/// <param name="ParameterName" value="@logger" />
/// <param name="DbType" value="String" />
/// <param name="Size" value="255" />
/// <param name="Layout" type="log4net.Layout.PatternLayout">
/// <param name="ConversionPattern" value="%c" />
/// </param>
/// </param>
/// <param name="Parameter">
/// <param name="ParameterName" value="@message" />
/// <param name="DbType" value="String" />
/// <param name="Size" value="4000" />
/// <param name="Layout" type="log4net.Layout.PatternLayout">
/// <param name="ConversionPattern" value="%m" />
/// </param>
/// </param>
/// </appender>
/// </code>
/// </example>
public class ADONetAppender : BufferingAppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ADONetAppender" /> class.
/// </summary>
public ADONetAppender()
{
m_connectionType = "System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
m_useTransactions = true;
m_commandType = System.Data.CommandType.Text;
m_parameters = new ArrayList();
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the database connection string that is used to connect to
/// the database.
/// </summary>
/// <value>
/// The database connection string used to connect to the database.
/// </value>
/// <remarks>
/// <para>
/// The connections string is specific to the connection type.
/// See <see cref="ConnectionType"/> for more information.
/// </para>
/// </remarks>
/// <example>Connection string for MS Access via ODBC:
/// <code>"DSN=MS Access Database;UID=admin;PWD=;SystemDB=C:\\data\\System.mdw;SafeTransactions = 0;FIL=MS Access;DriverID = 25;DBQ=C:\\data\\train33.mdb"</code>
/// </example>
/// <example>Another connection string for MS Access via ODBC:
/// <code>"Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\\Work\\cvs_root\\log4net-1.2\\access.mdb;UID=;PWD=;"</code>
/// </example>
/// <example>Connection string for MS Access via OLE DB:
/// <code>"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Work\\cvs_root\\log4net-1.2\\access.mdb;User Id=;Password=;"</code>
/// </example>
public string ConnectionString
{
get { return m_connectionString; }
set { m_connectionString = value; }
}
/// <summary>
/// Gets or sets the type name of the <see cref="IDbConnection"/> connection
/// that should be created.
/// </summary>
/// <value>
/// The type name of the <see cref="IDbConnection"/> connection.
/// </value>
/// <remarks>
/// <para>
/// The type name of the ADO.NET provider to use.
/// </para>
/// <para>
/// The default is to use the OLE DB provider.
/// </para>
/// </remarks>
/// <example>Use the OLE DB Provider. This is the default value.
/// <code>System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code>
/// </example>
/// <example>Use the MS SQL Server Provider.
/// <code>System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code>
/// </example>
/// <example>Use the ODBC Provider.
/// <code>Microsoft.Data.Odbc.OdbcConnection,Microsoft.Data.Odbc,version=1.0.3300.0,publicKeyToken=b77a5c561934e089,culture=neutral</code>
/// This is an optional package that you can download from
/// <a href="http://msdn.microsoft.com/downloads">http://msdn.microsoft.com/downloads</a>
/// search for <b>ODBC .NET Data Provider</b>.
/// </example>
public string ConnectionType
{
get { return m_connectionType; }
set { m_connectionType = value; }
}
/// <summary>
/// Gets or sets the command text that is used to insert logging events
/// into the database.
/// </summary>
/// <value>
/// The command text used to insert logging events into the database.
/// </value>
/// <remarks>
/// <para>
/// Either the text of the prepared statement or the
/// name of the stored procedure to execute to write into
/// the database.
/// </para>
/// <para>
/// The <see cref="CommandType"/> property determines if
/// this text is a prepared statement or a stored procedure.
/// </para>
/// </remarks>
public string CommandText
{
get { return m_commandText; }
set { m_commandText = value; }
}
/// <summary>
/// Gets or sets the command type to execute.
/// </summary>
/// <value>
/// The command type to execute.
/// </value>
/// <remarks>
/// <para>
/// This value may be either <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>) to specify
/// that the <see cref="CommandText"/> is a prepared statement to execute,
/// or <see cref="System.Data.CommandType.StoredProcedure"/> (<c>System.Data.CommandType.StoredProcedure</c>) to specify that the
/// <see cref="CommandText"/> property is the name of a stored procedure
/// to execute.
/// </para>
/// <para>
/// The default value is <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>).
/// </para>
/// </remarks>
public CommandType CommandType
{
get { return m_commandType; }
set { m_commandType = value; }
}
/// <summary>
/// Gets or sets a value that indicates whether transactions should be used
/// to insert logging events in the database.
/// </summary>
/// <value>
/// <c>true</c> if transactions should be used to insert logging events in
/// the database, otherwisr <c>false</c>. The default value is <c>true</c>.
/// </value>
public bool UseTransactions
{
get { return m_useTransactions; }
set { m_useTransactions = value; }
}
#endregion // Public Instance Properties
#region Protected Instance Properties
/// <summary>
/// Gets or sets the underlying <see cref="IDbConnection" />.
/// </summary>
/// <value>
/// The underlying <see cref="IDbConnection" />.
/// </value>
/// <remarks>
/// <see cref="ADONetAppender" /> creates a <see cref="IDbConnection" /> to insert
/// logging events into a database. Classes deriving from <see cref="ADONetAppender" />
/// can use this property to get or set this <see cref="IDbConnection" />. Use the
/// underlying <see cref="IDbConnection" /> returned from <see cref="Connection" /> if
/// you require access beyond that which <see cref="ADONetAppender" /> provides.
/// </remarks>
protected IDbConnection Connection
{
get { return this.m_dbConnection; }
set { this.m_dbConnection = value; }
}
#endregion // Protected Instance Properties
#region Implementation of IOptionHandler
/// <summary>
/// Initialise the appender based on the options set
/// </summary>
override public void ActivateOptions()
{
base.ActivateOptions();
InitializeDatabaseConnection();
// Are we using a command object
if (m_commandText != null && m_commandText.Length > 0)
{
m_usePreparedCommand = true;
// Create the command object
InitializeDatabaseCommand();
}
else
{
m_usePreparedCommand = false;
}
}
#endregion
#region Override implementation of AppenderSkeleton
/// <summary>
/// Override the parent method to close the database
/// </summary>
override public void OnClose()
{
base.OnClose();
if (m_dbCommand != null)
{
m_dbCommand.Dispose();
m_dbCommand = null;
}
if (m_dbConnection != null)
{
m_dbConnection.Close();
m_dbConnection = null;
}
}
#endregion
#region Override implementation of BufferingAppenderSkeleton
/// <summary>
/// Inserts the events into the database.
/// </summary>
/// <param name="events">The events to insert into the database.</param>
override protected void SendBuffer(LoggingEvent[] events)
{
// Check that the connection exists and is open
if (m_dbConnection != null && m_dbConnection.State == ConnectionState.Open)
{
if (m_useTransactions)
{
// Create transaction
// NJC - Do this on 2 lines because it can confuse the debugger
IDbTransaction dbTran = null;
dbTran = m_dbConnection.BeginTransaction();
try
{
SendBuffer(dbTran, events);
// commit transaction
dbTran.Commit();
}
catch(Exception ex)
{
// rollback the transaction
try
{
dbTran.Rollback();
}
catch(Exception)
{
}
// Can't insert into the database. That's a bad thing
ErrorHandler.Error("Exception while writing to database", ex);
}
}
else
{
// Send without transaction
SendBuffer(null, events);
}
}
}
#endregion // Override implementation of BufferingAppenderSkeleton
#region Public Instance Methods
/// <summary>
/// Adds a parameter to the command.
/// </summary>
/// <param name="parameter">The parameter to add to the command.</param>
/// <remarks>
/// <para>
/// Adds a parameter to the ordered list of command parameters.
/// </para>
/// </remarks>
public void AddParameter(ADONetAppenderParameter parameter)
{
m_parameters.Add(parameter);
}
#endregion // Public Instance Methods
#region Protected Instance Methods
/// <summary>
/// Writes the events to the database using the transaction specified.
/// </summary>
/// <param name="dbTran">The transaction that the events will be executed under.</param>
/// <param name="events">The array of events to insert into the database.</param>
/// <remarks>
/// The transaction argument can be <c>null</c> if the appender has been
/// configured not to use transactions. See <see cref="UseTransactions"/>
/// property for more information.
/// </remarks>
virtual protected void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)
{
if (m_usePreparedCommand)
{
// Send buffer using the prepared command object
if (m_dbCommand != null)
{
if (dbTran != null)
{
m_dbCommand.Transaction = dbTran;
}
// run for all events
foreach(LoggingEvent e in events)
{
// Set the parameter values
foreach(ADONetAppenderParameter param in m_parameters)
{
param.FormatValue(m_dbCommand, e);
}
// Execute the query
m_dbCommand.ExecuteNonQuery();
}
}
}
else
{
// create a new command
using(IDbCommand dbCmd = m_dbConnection.CreateCommand())
{
if (dbTran != null)
{
dbCmd.Transaction = dbTran;
}
// run for all events
foreach(LoggingEvent e in events)
{
// Get the command text from the Layout
string logStatement = GetLogStatement(e);
LogLog.Debug("ADOAppender: LogStatement ["+logStatement+"]");
dbCmd.CommandText = logStatement;
dbCmd.ExecuteNonQuery();
}
}
}
}
/// <summary>
/// Formats the log message into database statement text.
/// </summary>
/// <param name="logEvent">The event being logged.</param>
/// <remarks>
/// This method can be overridden by subclasses to provide
/// more control over the format of the database statement.
/// </remarks>
/// <returns>
/// Text that can be passed to a <see cref="System.Data.IDbCommand"/>.
/// </returns>
virtual protected string GetLogStatement(LoggingEvent logEvent)
{
if (Layout == null)
{
ErrorHandler.Error("ADOAppender: No Layout specified.");
return "";
}
else
{
return Layout.Format(logEvent);
}
}
/// <summary>
/// Connects to the database.
/// </summary>
virtual protected void InitializeDatabaseConnection()
{
try
{
// Create the connection object
m_dbConnection = (IDbConnection)Activator.CreateInstance(ResolveConnectionType());
// Set the connection string
m_dbConnection.ConnectionString = m_connectionString;
// Open the database connection
m_dbConnection.Open();
}
catch (System.Exception e)
{
// Sadly, your connection string is bad.
ErrorHandler.Error("Could not open database connection [" + m_connectionString + "]", e);
}
}
/// <summary>
/// Retrieves the class type of the ADO.NET provider.
/// </summary>
virtual protected Type ResolveConnectionType()
{
try
{
return Type.GetType(m_connectionType, true);
}
catch(Exception ex)
{
ErrorHandler.Error("Failed to load connection type ["+m_connectionType+"]", ex);
throw;
}
}
/// <summary>
/// Prepares the database command and initialize the parameters.
/// </summary>
virtual protected void InitializeDatabaseCommand()
{
try
{
// Create the command object
m_dbCommand = m_dbConnection.CreateCommand();
// Set the command string
m_dbCommand.CommandText = m_commandText;
// Set the command type
m_dbCommand.CommandType = m_commandType;
}
catch (System.Exception e)
{
ErrorHandler.Error("Could not create database command ["+m_commandText+"]", e);
if (m_dbCommand != null)
{
try
{
m_dbCommand.Dispose();
}
catch
{
}
m_dbCommand = null;
}
}
if (m_dbCommand != null)
{
try
{
foreach(ADONetAppenderParameter param in m_parameters)
{
try
{
param.Prepare(m_dbCommand);
}
catch(System.Exception e)
{
ErrorHandler.Error("Could not add database command parameter ["+param.ParameterName+"]", e);
throw;
}
}
}
catch
{
try
{
m_dbCommand.Dispose();
}
catch
{
}
m_dbCommand = null;
}
}
if (m_dbCommand != null)
{
try
{
// Prepare the command statement.
m_dbCommand.Prepare();
}
catch (System.Exception e)
{
ErrorHandler.Error("Could not prepare database command ["+m_commandText+"]", e);
try
{
m_dbCommand.Dispose();
}
catch
{
}
m_dbCommand = null;
}
}
}
#endregion // Protected Instance Methods
#region Private Instance Fields
/// <summary>
/// The <see cref="IDbConnection" /> that will be used
/// to insert logging events into a database.
/// </summary>
private IDbConnection m_dbConnection;
/// <summary>
/// The database command.
/// </summary>
private IDbCommand m_dbCommand;
/// <summary>
/// Flag to indicate if we are using a command object
/// </summary>
private bool m_usePreparedCommand;
/// <summary>
/// Database connection string.
/// </summary>
private string m_connectionString;
/// <summary>
/// String type name of the <see cref="IDbConnection"/> type name.
/// </summary>
private string m_connectionType;
/// <summary>
/// The text of the command.
/// </summary>
private string m_commandText;
/// <summary>
/// The command type.
/// </summary>
private CommandType m_commandType;
/// <summary>
/// Incicats whether to use Utransactions when writing to the
/// database.
/// </summary>
private bool m_useTransactions;
/// <summary>
/// The list of <see cref="ADONetAppenderParameter"/> objects.
/// </summary>
/// <remarks>
/// The list of <see cref="ADONetAppenderParameter"/> objects.
/// </remarks>
private ArrayList m_parameters;
#endregion // Private Instance Fields
}
/// <summary>
/// Parameter type used by the <see cref="ADONetAppender"/>.
/// </summary>
/// <remarks>
/// <para>
/// This class provides the basic database parameter properties
/// as defined by the <see cref="System.Data.IDbDataParameter"/> interface.
/// </para>
/// <para>This type can be subclassed to provide database specific
/// functionality. The two methods that are called externally are
/// <see cref="Prepare"/> and <see cref="FormatValue"/>.
/// </para>
/// </remarks>
public class ADONetAppenderParameter
{
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ADONetAppenderParameter" />
/// class.
/// </summary>
public ADONetAppenderParameter()
{
m_precision = 0;
m_scale = 0;
m_size = 0;
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the name of this parameter.
/// </summary>
/// <value>
/// The name of this parameter.
/// </value>
public string ParameterName
{
get { return m_parameterName; }
set { m_parameterName = value; }
}
/// <summary>
/// Gets or sets the database type for this parameter.
/// </summary>
/// <value>
/// The database type for this parameter.
/// </value>
public DbType DbType
{
get { return m_dbType; }
set { m_dbType = value; }
}
/// <summary>
/// Gets or sets the precision for this parameter.
/// </summary>
/// <value>
/// The precision for this parameter.
/// </value>
public byte Precision
{
get { return m_precision; }
set { m_precision = value; }
}
/// <summary>
/// Gets or sets the scale for this parameter.
/// </summary>
/// <value>
/// The scale for this parameter.
/// </value>
public byte Scale
{
get { return m_scale; }
set { m_scale = value; }
}
/// <summary>
/// Gets or sets the size for this parameter.
/// </summary>
/// <value>
/// The size for this parameter.
/// </value>
public int Size
{
get { return m_size; }
set { m_size = value; }
}
/// <summary>
/// Gets or sets the <see cref="IRawLayout"/> to use to
/// render the logging event into an object for this
/// parameter.
/// </summary>
/// <value>
/// The <see cref="IRawLayout"/> used to render the
/// logging event into an object for this parameter.
/// </value>
public IRawLayout Layout
{
get { return m_layout; }
set { m_layout = value; }
}
#endregion // Public Instance Properties
#region Public Instance Methods
/// <summary>
/// Prepare the specified database command object.
/// </summary>
/// <param name="command">The command to prepare.</param>
/// <remarks>
/// <para>
/// Prepares the database command object by adding
/// this parameter to its collection of parameters.
/// </para>
/// </remarks>
virtual public void Prepare(IDbCommand command)
{
// Create a new parameter
IDbDataParameter param = command.CreateParameter();
// Set the parameter properties
param.ParameterName = m_parameterName;
param.DbType = m_dbType;
if (m_precision != 0)
{
param.Precision = m_precision;
}
if (m_scale != 0)
{
param.Scale = m_scale;
}
if (m_size != 0)
{
param.Size = m_size;
}
// Add the parameter to the collection of params
command.Parameters.Add(param);
}
/// <summary>
/// Renders the logging event and set the parameter value in the command.
/// </summary>
/// <param name="command">The command containing the parameter.</param>
/// <param name="loggingEvent">The event to be rendered.</param>
/// <remarks>
/// <para>
/// Renders the logging event using this parameters layout
/// object. Sets the value of the parameter on the command object.
/// </para>
/// </remarks>
virtual public void FormatValue(IDbCommand command, LoggingEvent loggingEvent)
{
// Lookup the parameter
IDbDataParameter param = (IDbDataParameter)command.Parameters[m_parameterName];
param.Value = Layout.Format(loggingEvent);
}
#endregion // Public Instance Methods
#region Private Instance Fields
/// <summary>
/// The name of this parameter.
/// </summary>
private string m_parameterName;
/// <summary>
/// The database type for this parameter.
/// </summary>
private DbType m_dbType;
/// <summary>
/// The precision for this parameter.
/// </summary>
private byte m_precision;
/// <summary>
/// The scale for this parameter.
/// </summary>
private byte m_scale;
/// <summary>
/// The size for this parameter.
/// </summary>
private int m_size;
/// <summary>
/// The <see cref="IRawLayout"/> to use to render the
/// logging event into an object for this parameter.
/// </summary>
private IRawLayout m_layout;
#endregion // Private Instance Fields
}
}
| |
using System;
using NLog;
using ServiceStack.Logging;
namespace ServiceStack.Logging.NLogger
{
/// <summary>
/// Wrapper over the NLog 2.0 beta and above logger
/// </summary>
public class NLogLogger : ServiceStack.Logging.ILog
{
private readonly NLog.Logger log;
public NLogLogger(string typeName)
{
log = NLog.LogManager.GetLogger(typeName);
}
/// <summary>
/// Initializes a new instance of the <see cref="NLogLogger"/> class.
/// </summary>
/// <param name="type">The type.</param>
public NLogLogger(Type type)
{
log = NLog.LogManager.GetLogger(UseFullTypeNames ? type.FullName : type.Name);
}
public static bool UseFullTypeNames { get; set; }
public bool IsDebugEnabled { get { return log.IsDebugEnabled; } }
public bool IsInfoEnabled { get { return log.IsInfoEnabled; } }
public bool IsWarnEnabled { get { return log.IsWarnEnabled; } }
public bool IsErrorEnabled { get { return log.IsErrorEnabled; } }
public bool IsFatalEnabled { get { return log.IsFatalEnabled; } }
/// <summary>
/// Logs a Debug message.
/// </summary>
/// <param name="message">The message.</param>
public void Debug(object message)
{
if (IsDebugEnabled)
Write(LogLevel.Debug, message.ToString());
}
/// <summary>
/// Logs a Debug message and exception.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public void Debug(object message, Exception exception)
{
if(IsDebugEnabled)
Write(LogLevel.Debug,exception,message.ToString());
}
/// <summary>
/// Logs a Debug format message.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The args.</param>
public void DebugFormat(string format, params object[] args)
{
if (IsDebugEnabled)
Write(LogLevel.Debug, format, args);
}
/// <summary>
/// Logs a Error message.
/// </summary>
/// <param name="message">The message.</param>
public void Error(object message)
{
if (IsErrorEnabled)
Write(LogLevel.Error,message.ToString());
}
/// <summary>
/// Logs a Error message and exception.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public void Error(object message, Exception exception)
{
if (IsErrorEnabled)
Write(LogLevel.Error, exception, message.ToString());
}
/// <summary>
/// Logs a Error format message.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The args.</param>
public void ErrorFormat(string format, params object[] args)
{
if (IsErrorEnabled)
Write(LogLevel.Error,format,args);
}
/// <summary>
/// Logs a Fatal message.
/// </summary>
/// <param name="message">The message.</param>
public void Fatal(object message)
{
if (IsFatalEnabled)
Write(LogLevel.Fatal,message.ToString());
}
/// <summary>
/// Logs a Fatal message and exception.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public void Fatal(object message, Exception exception)
{
if (IsFatalEnabled)
Write(LogLevel.Fatal, exception, message.ToString());
}
/// <summary>
/// Logs a Error format message.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The args.</param>
public void FatalFormat(string format, params object[] args)
{
if (IsFatalEnabled)
Write(LogLevel.Fatal, format, args);
}
/// <summary>
/// Logs an Info message and exception.
/// </summary>
/// <param name="message">The message.</param>
public void Info(object message)
{
if (IsInfoEnabled)
Write(LogLevel.Info,message.ToString());
}
/// <summary>
/// Logs an Info message and exception.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public void Info(object message, Exception exception)
{
if (IsInfoEnabled)
Write(LogLevel.Info,exception,message.ToString());
}
/// <summary>
/// Logs an Info format message.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The args.</param>
public void InfoFormat(string format, params object[] args)
{
if (IsInfoEnabled)
Write(LogLevel.Info, format, args);
}
/// <summary>
/// Logs a Warning message.
/// </summary>
/// <param name="message">The message.</param>
public void Warn(object message)
{
if (IsWarnEnabled)
Write(LogLevel.Warn,message.ToString());
}
/// <summary>
/// Logs a Warning message and exception.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public void Warn(object message, Exception exception)
{
if (IsWarnEnabled)
Write(LogLevel.Warn,exception,message.ToString());
}
/// <summary>
/// Logs a Warning format message.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The args.</param>
public void WarnFormat(string format, params object[] args)
{
if (IsWarnEnabled)
Write(LogLevel.Warn, format, args);
}
private void Write(LogLevel level, string format, params object[] args)
{
//preserve call site info - see here: http://stackoverflow.com/questions/3947136/problem-matching-specific-nlog-logger-name
var logEventInfo = new LogEventInfo(level, log.Name, null, format, args);
log.Log(typeof(NLogLogger), logEventInfo);
}
private void Write(LogLevel level, Exception exception, string format, params object[] args)
{
var exceptionEventInfo = new LogEventInfo(level, log.Name, null, format, args, exception);
log.Log(typeof(NLogLogger), exceptionEventInfo);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using Palaso.Code;
using Palaso.Xml;
namespace Palaso.WritingSystems
{
/// <summary>
/// This class forms the bases for managing collections of WritingSystemDefinitions. WritingSystemDefinitions
/// can be registered and then retrieved and deleted by Id. The preferred use when editting a WritingSystemDefinition stored
/// in the WritingSystemRepository is to Get the WritingSystemDefinition in question and then to clone it either via the
/// Clone method on WritingSystemDefinition or via the MakeDuplicate method on the WritingSystemRepository. This allows
/// changes made to a WritingSystemDefinition to be registered back with the WritingSystemRepository via the Set method,
/// or to be discarded by simply discarding the object.
/// Internally the WritingSystemRepository uses the WritingSystemDefinition's StoreId property to establish the identity of
/// a WritingSystemDefinition. This allows the user to change the Rfc646Tag components and thereby the Id of a
/// WritingSystemDefinition and the WritingSystemRepository to update itself and the underlying store correctly.
/// </summary>
abstract public class WritingSystemRepositoryBase : IWritingSystemRepository
{
private readonly Dictionary<string, IWritingSystemDefinition> _writingSystems;
private readonly Dictionary<string, DateTime> _writingSystemsToIgnore;
protected Dictionary<string, string> _idChangeMap;
public event WritingSystemIdChangedEventHandler WritingSystemIdChanged;
public event WritingSystemDeleted WritingSystemDeleted;
public event WritingSystemConflatedEventHandler WritingSystemConflated;
protected bool Conflating{ get; private set; }
/// <summary>
/// Constructor, set the CompatibilityMode
/// </summary>
protected WritingSystemRepositoryBase(WritingSystemCompatibility compatibilityMode)
{
CompatibilityMode = compatibilityMode;
_writingSystems = new Dictionary<string, IWritingSystemDefinition>(StringComparer.OrdinalIgnoreCase);
_writingSystemsToIgnore = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
_idChangeMap = new Dictionary<string, string>();
//_sharedStore = LdmlSharedWritingSystemRepository.Singleton;
}
protected IDictionary<string, DateTime> WritingSystemsToIgnore
{
get
{
return _writingSystemsToIgnore;
}
}
virtual public IWritingSystemDefinition CreateNew()
{
return new WritingSystemDefinition();
}
virtual protected LdmlDataMapper CreateLdmlAdaptor()
{
return new LdmlDataMapper();
}
virtual public void Conflate(string wsToConflate, string wsToConflateWith)
{
Conflating = true;
if(WritingSystemConflated != null)
{
WritingSystemConflated(this, new WritingSystemConflatedEventArgs(wsToConflate, wsToConflateWith));
}
Remove(wsToConflate);
Conflating = false;
}
/// <summary>
/// Remove the specified WritingSystemDefinition.
/// </summary>
/// <param name="identifier">the StoreID of the WritingSystemDefinition</param>
/// <remarks>
/// Note that ws.StoreID may differ from ws.Id. The former is the key into the
/// dictionary, but the latter is what gets persisted to disk (and shown to the
/// user).
/// </remarks>
virtual public void Remove(string identifier)
{
if (identifier == null)
{
throw new ArgumentNullException("identifier");
}
if (!_writingSystems.ContainsKey(identifier))
{
throw new ArgumentOutOfRangeException("identifier");
}
// Remove() uses the StoreID field, but file storage and UI use the Id field.
string realId = _writingSystems[identifier].Id;
// Delete from us
//??? Do we really delete or just mark for deletion?
_writingSystems.Remove(identifier);
if (_writingSystemsToIgnore.ContainsKey(identifier))
_writingSystemsToIgnore.Remove(identifier);
if (_writingSystemsToIgnore.ContainsKey(realId))
_writingSystemsToIgnore.Remove(realId);
if (!Conflating && WritingSystemDeleted != null)
{
WritingSystemDeleted(this, new WritingSystemDeletedEventArgs(realId));
}
//TODO: Could call the shared store to advise that one has been removed.
//TODO: This may be useful if writing systems were reference counted.
}
abstract public string WritingSystemIdHasChangedTo(string id);
virtual public void LastChecked(string identifier, DateTime dateModified)
{
if (_writingSystemsToIgnore.ContainsKey(identifier))
{
_writingSystemsToIgnore[identifier] = dateModified;
}
else
{
_writingSystemsToIgnore.Add(identifier, dateModified);
}
}
protected void Clear()
{
_writingSystems.Clear();
}
public IWritingSystemDefinition MakeDuplicate(IWritingSystemDefinition definition)
{
if (definition == null)
{
throw new ArgumentNullException("definition");
}
return definition.Clone();
}
public abstract bool WritingSystemIdHasChanged(string id);
[Obsolete("Deprecated: use Contains instead")]
public bool Exists(string identifier)
{
return Contains(identifier);
}
public bool Contains(string identifier)
{
// identifier should not be null, but some unit tests never define StoreID
// on their temporary WritingSystemDefinition objects.
return identifier != null && _writingSystems.ContainsKey(identifier);
}
public bool CanSet(IWritingSystemDefinition ws)
{
if (ws == null)
{
return false;
}
return !(_writingSystems.Keys.Any(id => id.Equals(ws.Id, StringComparison.OrdinalIgnoreCase)) &&
ws.StoreID != _writingSystems[ws.Id].StoreID);
}
public virtual void Set(IWritingSystemDefinition ws)
{
if (ws == null)
{
throw new ArgumentNullException("ws");
}
//Check if this is a new writing system with a conflicting id
if (!CanSet(ws))
{
throw new ArgumentException(String.Format("Unable to set writing system '{0}' because this id already exists. Please change this writing system id before setting it.", ws.Id));
}
string oldId = _writingSystems.Where(kvp => kvp.Value.StoreID == ws.StoreID).Select(kvp => kvp.Key).FirstOrDefault();
//??? How do we update
//??? Is it sufficient to just set it, or can we not change the reference in case someone else has it too
//??? i.e. Do we need a ws.Copy(WritingSystemDefinition)?
if (!String.IsNullOrEmpty(oldId) && _writingSystems.ContainsKey(oldId))
{
_writingSystems.Remove(oldId);
}
_writingSystems[ws.Id] = ws;
// If the writing system already has a local keyboard, probably it has just been created in some dialog,
// and we should respect the one the user set...though this is a very unlikely scenario, as we probably
// don't have a local setting for a WS that is just being created.
IKeyboardDefinition keyboard;
if (_localKeyboardSettings != null && ((WritingSystemDefinition) ws).RawLocalKeyboard == null
&& _localKeyboardSettings.TryGetValue(ws.Id, out keyboard))
{
ws.LocalKeyboard = keyboard;
}
if (!String.IsNullOrEmpty(oldId) && (oldId != ws.Id))
{
UpdateIdChangeMap(oldId, ws.Id);
if (WritingSystemIdChanged != null)
{
WritingSystemIdChanged(this, new WritingSystemIdChangedEventArgs(oldId, ws.Id));
}
}
if (ws.StoreID != ws.Id)
{
ws.StoreID = ws.Id;
}
}
protected void UpdateIdChangeMap(string oldId, string newId)
{
if (_idChangeMap.ContainsValue(oldId))
{
// if the oldid is in the value of key/value, then we can update the cooresponding key with the newId
string keyToChange = _idChangeMap.Where(pair => pair.Value == oldId).First().Key;
_idChangeMap[keyToChange] = newId;
}
else if (_idChangeMap.ContainsKey(oldId))
{
// if oldId is already in the dictionary, set the result to be newId
_idChangeMap[oldId] = newId;
}
}
protected void LoadIdChangeMapFromExistingWritingSystems()
{
_idChangeMap.Clear();
foreach (var pair in _writingSystems)
{
_idChangeMap[pair.Key] = pair.Key;
}
}
public string GetNewStoreIDWhenSet(IWritingSystemDefinition ws)
{
if (ws == null)
{
throw new ArgumentNullException("ws");
}
return String.IsNullOrEmpty(ws.StoreID) ? ws.Id : ws.StoreID;
}
public IWritingSystemDefinition Get(string identifier)
{
if (identifier == null)
{
throw new ArgumentNullException("identifier");
}
if (!_writingSystems.ContainsKey(identifier))
{
throw new ArgumentOutOfRangeException("identifier", String.Format("Writing system id '{0}' does not exist.", identifier));
}
return _writingSystems[identifier];
}
public int Count
{
get
{
return _writingSystems.Count;
}
}
virtual public void Save()
{
}
virtual protected void OnChangeNotifySharedStore(IWritingSystemDefinition ws)
{
DateTime lastDateModified;
if (_writingSystemsToIgnore.TryGetValue(ws.Id, out lastDateModified) && ws.DateModified > lastDateModified)
_writingSystemsToIgnore.Remove(ws.Id);
}
virtual protected void OnRemoveNotifySharedStore()
{
}
virtual public IEnumerable<IWritingSystemDefinition> WritingSystemsNewerIn(IEnumerable<IWritingSystemDefinition> rhs)
{
if (rhs == null)
{
throw new ArgumentNullException("rhs");
}
var newerWritingSystems = new List<WritingSystemDefinition>();
foreach (var ws in rhs)
{
Guard.AgainstNull(ws, "ws in rhs");
if (_writingSystems.ContainsKey(ws.Bcp47Tag))
{
DateTime lastDateModified;
if ((!_writingSystemsToIgnore.TryGetValue(ws.Bcp47Tag, out lastDateModified) || ws.DateModified > lastDateModified)
&& (ws.DateModified > _writingSystems[ws.Bcp47Tag].DateModified))
{
newerWritingSystems.Add(ws.Clone());
}
}
}
return newerWritingSystems;
}
public IEnumerable<IWritingSystemDefinition> AllWritingSystems
{
get
{
return _writingSystems.Values;
}
}
public IEnumerable<IWritingSystemDefinition> TextWritingSystems
{
get { return _writingSystems.Values.Where(ws => !ws.IsVoice); }
}
public IEnumerable<IWritingSystemDefinition> VoiceWritingSystems
{
get { return _writingSystems.Values.Where(ws => ws.IsVoice); }
}
public virtual void OnWritingSystemIDChange(IWritingSystemDefinition ws, string oldId)
{
_writingSystems[ws.Id] = ws;
_writingSystems.Remove(oldId);
}
/// <summary>
/// filters the list down to those that are texts (not audio), while preserving their order
/// </summary>
/// <param name="idsToFilter"></param>
/// <returns></returns>
public IEnumerable<string> FilterForTextIds(IEnumerable<string> idsToFilter)
{
var textIds = TextWritingSystems.Select(ws => ws.Id);
return idsToFilter.Where(id => textIds.Contains(id));
}
public WritingSystemCompatibility CompatibilityMode { get; private set; }
private Dictionary<string, IKeyboardDefinition> _localKeyboardSettings;
/// <summary>
/// Getter gets the XML string that represents the user preferred keyboard for each writing
/// system.
/// Setter sets the user preferred keyboards on the writing systems based on the passed in
/// XML string.
/// </summary>
public string LocalKeyboardSettings
{
get
{
var root = new XElement("keyboards");
foreach (var ws in AllWritingSystems)
{
// We don't want to call LocalKeyboard here, because that will come up with some default.
// If RawLocalKeyboard is null, we have never typed in this WS.
// By the time we do, the user may have installed one of the keyboards in KnownKeyboards,
// or done a Send/Receive and obtained a better list of KnownKeyboards, and we can then
// make a better first guess than we can now. Calling LocalKeyboard and persisting the
// result would have the effect of making our current guess permanent.
var kbd = ((WritingSystemDefinition) ws).RawLocalKeyboard;
if (kbd == null)
continue;
root.Add(new XElement("keyboard",
new XAttribute("ws", ws.Id),
new XAttribute("layout", kbd.Layout),
new XAttribute("locale", kbd.Locale)));
}
return root.ToString();
}
set
{
_localKeyboardSettings = null;
if (string.IsNullOrWhiteSpace(value))
return;
var root = XElement.Parse(value);
_localKeyboardSettings = new Dictionary<string, IKeyboardDefinition>();
foreach (var kbd in root.Elements("keyboard"))
{
var keyboard = Keyboard.Controller.CreateKeyboardDefinition(
GetAttributeValue(kbd, "layout"), GetAttributeValue(kbd, "locale"));
_localKeyboardSettings[kbd.Attribute("ws").Value] = keyboard;
}
// We do it like this rather than looking up the writing system by the ws attribute so as not to force the
// creation of any writing systems which may be in the local keyboard settings but not in the current repo.
foreach (var ws in AllWritingSystems)
{
IKeyboardDefinition localKeyboard;
if (_localKeyboardSettings.TryGetValue(ws.Id, out localKeyboard))
ws.LocalKeyboard = localKeyboard;
}
}
}
/// <summary>
/// Get the writing system that is most probably intended by the user, when input language changes to the specified layout and cultureInfo,
/// given the indicated candidates, and that wsCurrent is the preferred result if it is a possible WS for the specified culture.
/// wsCurrent is also returned if none of the candidates is found to match the specified inputs.
/// See interface comment for intended usage information.
/// Enhance JohnT: it may be helpful, if no WS has an exact match, to look for one where the culture prefix (before hyphen) matches,
/// thus finding a WS that has a keyboard for the same language as the one the user selected.
/// Could similarly match against WS ID's language ID, for WS's with no RawLocalKeyboard.
/// Could use LocalKeyboard instead of RawLocalKeyboard, thus allowing us to find keyboards for writing systems where the
/// local keyboard has not yet been determined. However, this would potentially establish a particular local keyboard for
/// a user who has never typed in that writing system or configured a keyboard for it, nor even selected any text in it.
/// In the expected usage of this library, there will be a RawLocalKeyboard for every writing system in which the user has
/// ever typed or selected text. That should have a high probability of catching anything actually useful.
/// </summary>
/// <param name="layoutName"></param>
/// <param name="cultureInfo"></param>
/// <param name="wsCurrent"></param>
/// <param name="options"></param>
/// <returns></returns>
public IWritingSystemDefinition GetWsForInputLanguage(string layoutName, CultureInfo cultureInfo, IWritingSystemDefinition wsCurrent,
IWritingSystemDefinition[] options)
{
// See if the default is suitable.
if (WsMatchesLayout(layoutName, wsCurrent) && WsMatchesCulture(cultureInfo, wsCurrent))
return wsCurrent;
IWritingSystemDefinition layoutMatch = null;
IWritingSystemDefinition cultureMatch = null;
foreach (var ws in options)
{
bool matchesCulture = WsMatchesCulture(cultureInfo, ws);
if (WsMatchesLayout(layoutName, ws))
{
if (matchesCulture)
return ws;
if (layoutMatch == null || ws.Equals(wsCurrent))
layoutMatch = ws;
}
if (matchesCulture && (cultureMatch == null || ws.Equals(wsCurrent)))
cultureMatch = ws;
}
return layoutMatch ?? cultureMatch ?? wsCurrent;
}
bool WsMatchesLayout(string layoutName, IWritingSystemDefinition ws)
{
var wsd = ws as WritingSystemDefinition;
return wsd != null && wsd.RawLocalKeyboard != null && wsd.RawLocalKeyboard.Layout == layoutName;
}
private bool WsMatchesCulture(CultureInfo cultureInfo, IWritingSystemDefinition ws)
{
var wsd = ws as WritingSystemDefinition;
return wsd != null && wsd.RawLocalKeyboard != null && wsd.RawLocalKeyboard.Locale == cultureInfo.Name;
}
private string GetAttributeValue(XElement node, string attrName)
{
var attr = node.Attribute(attrName);
if (attr == null)
return "";
return attr.Value;
}
}
public class WritingSystemIdChangedEventArgs : EventArgs
{
public WritingSystemIdChangedEventArgs(string oldId, string newId)
{
OldId = oldId;
NewId = newId;
}
public string OldId { get; private set; }
public string NewId { get; private set; }
}
public class WritingSystemConflatedEventArgs:WritingSystemIdChangedEventArgs
{
public WritingSystemConflatedEventArgs(string oldId, string newId) : base(oldId, newId)
{
}
}
public class WritingSystemDeletedEventArgs : EventArgs
{
public WritingSystemDeletedEventArgs(string id)
{
Id = id;
}
public string Id { get; private set; }
}
}
| |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Collections;
using Lucene.Net.Util;
namespace Lucene.Net.Support
{
/// <summary>
/// This class provides supporting methods of java.util.BitSet
/// that are not present in System.Collections.BitArray.
/// </summary>
internal static class BitArrayExtensions
{
/// <summary>
/// Returns the next set bit at or after index, or -1 if no such bit exists.
/// </summary>
/// <param name="bitArray"></param>
/// <param name="index">the index of bit array at which to start checking</param>
/// <returns>the next set bit or -1</returns>
public static int NextSetBit(this BitArray bitArray, int index)
{
while (index < bitArray.Length)
{
// if index bit is set, return it
// otherwise check next index bit
if (bitArray.Get(index))
return index;
else
index++;
}
// if no bits are set at or after index, return -1
return -1;
}
public static int PrevSetBit(this BitArray bitArray, int index)
{
while (index >= 0 && index < bitArray.Length)
{
// if index bit is set, return it
// otherwise check previous index bit
if (bitArray.SafeGet(index))
return index;
index--;
}
// if no bits are set at or before index, return -1
return -1;
}
// Produces a bitwise-and of the two BitArrays without requiring they be the same length
public static BitArray And_UnequalLengths(this BitArray bitsA, BitArray bitsB)
{
//Cycle only through fewest bits neccessary without requiring size equality
var maxIdx = Math.Min(bitsA.Length, bitsB.Length);//exclusive
var bits = new BitArray(maxIdx);
for (int i = 0; i < maxIdx; i++)
{
bits[i] = bitsA[i] & bitsB[i];
}
return bits;
}
// Produces a bitwise-or of the two BitArrays without requiring they be the same length
public static BitArray Or_UnequalLengths(this BitArray bitsA, BitArray bitsB)
{
var shorter = bitsA.Length < bitsB.Length ? bitsA : bitsB;
var longer = bitsA.Length >= bitsB.Length ? bitsA : bitsB;
var bits = new BitArray(longer.Length);
for (int i = 0; i < longer.Length; i++)
{
if (i >= shorter.Length)
{
bits[i] = longer[i];
}
else
{
bits[i] = shorter[i] | longer[i];
}
}
return bits;
}
// Produces a bitwise-xor of the two BitArrays without requiring they be the same length
public static BitArray Xor_UnequalLengths(this BitArray bitsA, BitArray bitsB)
{
var shorter = bitsA.Length < bitsB.Length ? bitsA : bitsB;
var longer = bitsA.Length >= bitsB.Length ? bitsA : bitsB;
var bits = new BitArray(longer.Length);
for (int i = 0; i < longer.Length; i++)
{
if (i >= shorter.Length)
{
bits[i] = longer[i];
}
else
{
bits[i] = shorter[i] ^ longer[i];
}
}
return bits;
}
/// <summary>
/// Returns the next un-set bit at or after index, or -1 if no such bit exists.
/// </summary>
/// <param name="bitArray"></param>
/// <param name="index">the index of bit array at which to start checking</param>
/// <returns>the next set bit or -1</returns>
public static int NextClearBit(this BitArray bitArray, int index)
{
while (index < bitArray.Length)
{
// if index bit is not set, return it
// otherwise check next index bit
if (!bitArray.Get(index))
return index;
else
index++;
}
// if no bits are set at or after index, return -1
return -1;
}
/// <summary>
/// Returns the number of bits set to <c>true</c> in this <see cref="BitArray"/>.
/// </summary>
/// <param name="bits">This <see cref="BitArray"/>.</param>
/// <returns>The number of bits set to true in this <see cref="BitArray"/>.</returns>
public static int Cardinality(this BitArray bits)
{
if (bits == null)
throw new ArgumentNullException(nameof(bits));
int count = 0;
#if FEATURE_BITARRAY_COPYTO
int bitsLength = bits.Length;
int[] ints = new int[(bitsLength >> 5) + 1];
int intsLength = ints.Length;
int c;
bits.CopyTo(ints, 0);
// fix for not truncated bits in last integer that may have been set to true with SetAll()
ints[intsLength - 1] &= ~(-1 << (bitsLength % 32));
for (int i = 0; i < intsLength; i++)
{
c = ints[i];
// magic (http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel)
unchecked
{
c -= (c >> 1) & 0x55555555;
c = (c & 0x33333333) + ((c >> 2) & 0x33333333);
c = ((c + (c >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
}
count += c;
}
#else
for (int i = 0; i < bits.Length; i++)
{
if (bits[i])
count++;
}
#endif
return count;
}
/// <summary>
/// Sets the bit at the given <paramref name="index"/> to true.
/// </summary>
/// <param name="bits">The BitArray object.</param>
/// <param name="index">The position to set to true.</param>
public static void Set(this BitArray bits, int index)
{
bits.SafeSet(index, true);
}
/// <summary>
/// Sets the bit at the given index range to true.
/// </summary>
/// <param name="bits">The BitArray object.</param>
/// <param name="fromIndex">The start of the range to set(inclusive)</param>
/// <param name="toIndex">The end of the range to set(exclusive)</param>
/// <param name="value">the value to set to the range</param>
public static void Set(this BitArray bits, int fromIndex, int toIndex, bool value)
{
for (int i = fromIndex; i < toIndex; ++i)
{
bits.SafeSet(i, value);
}
}
/// <summary>
/// Sets the bit at the given <paramref name="index"/> to false.
/// </summary>
/// <param name="bits">The BitArray object.</param>
/// <param name="index">The position to set to false.</param>
public static void Clear(this BitArray bits, int index)
{
bits.SafeSet(index, false);
}
/// <summary>
/// Sets all bits to false
/// </summary>
/// <param name="bits">The BitArray object.</param>
public static void Clear(this BitArray bits)
{
bits.SetAll(false);
}
//Flip all bits in the desired range, startIdx inclusive to endIdx exclusive
public static void Flip(this BitArray bits, int startIdx, int endIdx)
{
for (int i = startIdx; i < endIdx; i++)
{
bits[i] = !bits[i];
}
}
// Sets all bits in the range to false [startIdx, endIdx)
public static void Clear(this BitArray bits, int startIdx, int endIdx)
{
for (int i = startIdx; i < endIdx; i++)
{
bits[i] = false;
}
}
// Sets all bits in the range to true [startIdx, endIdx)
public static void Set(this BitArray bits, int startIdx, int endIdx)
{
for (int i = startIdx; i < endIdx; i++)
{
bits[i] = true;
}
}
// Emulates the Java BitSet.Get() method.
// Prevents exceptions from being thrown when the index is too high.
public static bool SafeGet(this BitArray a, int loc)
{
return loc < a.Length && a.Get(loc);
}
//Emulates the Java BitSet.Set() method. Required to reconcile differences between Java BitSet and C# BitArray
public static void SafeSet(this BitArray a, int loc, bool value)
{
if (loc >= a.Length)
a.Length = loc + 1;
a.Set(loc, value);
}
// Clears all bits in this BitArray that correspond to a set bit in the parameter BitArray
public static void AndNot(this BitArray bitsA, BitArray bitsB)
{
//if (Debugging.AssertsEnabled) Debugging.Assert(bitsA.Length == bitsB.Length, "BitArray lengths are not the same");
for (int i = 0; i < bitsA.Length; i++)
{
//bitsA was longer than bitsB
if (i >= bitsB.Length)
{
return;
}
if (bitsA[i] && bitsB[i])
{
bitsA[i] = false;
}
}
}
//Does a deep comparison of two BitArrays
public static bool BitWiseEquals(this BitArray bitsA, BitArray bitsB)
{
if (bitsA == bitsB)
return true;
if (bitsA.Length != bitsB.Length)
return false;
for (int i = 0; i < bitsA.Length; i++)
{
if (bitsA[i] != bitsB[i])
return false;
}
return true;
}
//Compares a BitArray with an OpenBitSet
public static bool Equal(this BitArray a, OpenBitSet b)
{
var bitArrayCardinality = a.Cardinality();
if (bitArrayCardinality != b.Cardinality())
return false;
for (int i = 0; i < bitArrayCardinality; i++)
{
if (a.SafeGet(i) != b.Get(i))
return false;
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Crypto;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
namespace WalletWasabi.Io
{
/// <summary>
/// Safely manager file operations.
/// </summary>
public class DigestableSafeIoManager : SafeIoManager
{
private const string DigestExtension = ".dig";
/// <param name="digestRandomIndex">Use the random index of the line to create digest faster. -1 is special value, it means the last character. If null then hash whole file.</param>
public DigestableSafeIoManager(string filePath, int? digestRandomIndex = null) : base(filePath)
{
DigestRandomIndex = digestRandomIndex;
DigestFilePath = $"{FilePath}{DigestExtension}";
}
public string DigestFilePath { get; }
/// <summary>
/// Gets a random index of the line to create digest faster. -1 is special value, it means the last character. If null then hash whole file.
/// </summary>
private int? DigestRandomIndex { get; }
#region IoOperations
public new void DeleteMe()
{
base.DeleteMe();
if (File.Exists(DigestFilePath))
{
File.Delete(DigestFilePath);
}
}
public new async Task WriteAllLinesAsync(IEnumerable<string> lines, CancellationToken cancellationToken = default)
{
if (lines is null || !lines.Any())
{
return;
}
var byteArrayBuilder = new ByteArrayBuilder();
foreach (var line in lines)
{
ContinueBuildHash(byteArrayBuilder, line);
}
var (same, hash) = await WorkWithHashAsync(byteArrayBuilder, cancellationToken).ConfigureAwait(false);
if (same)
{
return;
}
await base.WriteAllLinesAsync(lines, cancellationToken).ConfigureAwait(false);
await WriteOutHashAsync(hash).ConfigureAwait(false);
}
public new async Task AppendAllLinesAsync(IEnumerable<string> lines, CancellationToken cancellationToken = default)
{
if (lines is null || !lines.Any())
{
return;
}
IoHelpers.EnsureContainingDirectoryExists(NewFilePath);
if (File.Exists(NewFilePath))
{
File.Delete(NewFilePath);
}
var byteArrayBuilder = new ByteArrayBuilder();
var linesArray = lines.ToArray();
var linesIndex = 0;
using (var sr = OpenText())
using (var fs = File.OpenWrite(NewFilePath))
using (var sw = new StreamWriter(fs, Encoding.ASCII, Constants.BigFileReadWriteBufferSize))
{
// 1. First copy.
if (!sr.EndOfStream)
{
var lineTask = sr.ReadLineAsync();
Task wTask = Task.CompletedTask;
string line = null;
while (lineTask is { })
{
line ??= await lineTask.ConfigureAwait(false);
lineTask = sr.EndOfStream ? null : sr.ReadLineAsync();
if (linesArray[linesIndex] == line) // If the line is a line we want to write, then we know that someone else have worked into the file.
{
linesIndex++;
continue;
}
await wTask.ConfigureAwait(false);
wTask = sw.WriteLineAsync(line);
ContinueBuildHash(byteArrayBuilder, line);
cancellationToken.ThrowIfCancellationRequested();
line = null;
}
await wTask.ConfigureAwait(false);
}
await sw.FlushAsync().ConfigureAwait(false);
// 2. Then append.
foreach (var line in linesArray)
{
await sw.WriteLineAsync(line).ConfigureAwait(false);
ContinueBuildHash(byteArrayBuilder, line);
cancellationToken.ThrowIfCancellationRequested();
}
await sw.FlushAsync().ConfigureAwait(false);
}
var (same, hash) = await WorkWithHashAsync(byteArrayBuilder, cancellationToken).ConfigureAwait(false);
if (same)
{
return;
}
SafeMoveNewToOriginal();
await WriteOutHashAsync(hash).ConfigureAwait(false);
}
#endregion IoOperations
#region Hashing
private async Task WriteOutHashAsync(byte[] hash)
{
try
{
IoHelpers.EnsureContainingDirectoryExists(DigestFilePath);
await File.WriteAllBytesAsync(DigestFilePath, hash).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogWarning("Failed to create digest.");
Logger.LogInfo(ex);
}
}
private async Task<(bool same, byte[] hash)> WorkWithHashAsync(ByteArrayBuilder byteArrayBuilder, CancellationToken cancellationToken)
{
byte[] hash = null;
try
{
var bytes = byteArrayBuilder.ToArray();
hash = HashHelpers.GenerateSha256Hash(bytes);
if (File.Exists(DigestFilePath))
{
var digest = await File.ReadAllBytesAsync(DigestFilePath, cancellationToken).ConfigureAwait(false);
if (ByteHelpers.CompareFastUnsafe(hash, digest))
{
if (File.Exists(NewFilePath))
{
File.Delete(NewFilePath);
}
return (true, hash);
}
}
}
catch (Exception ex)
{
Logger.LogWarning("Failed to read digest.");
Logger.LogInfo(ex);
}
return (false, hash);
}
private void ContinueBuildHash(ByteArrayBuilder byteArrayBuilder, string line)
{
if (string.IsNullOrWhiteSpace(line))
{
byteArrayBuilder.Append(0);
}
else
{
if (DigestRandomIndex.HasValue)
{
int index = DigestRandomIndex == -1 || DigestRandomIndex >= line.Length // Last char.
? line.Length - 1
: DigestRandomIndex.Value;
var c = line[index];
var b = (byte)c;
byteArrayBuilder.Append(b);
}
else
{
var b = Encoding.ASCII.GetBytes(line);
byteArrayBuilder.Append(b);
}
}
}
#endregion Hashing
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace Invoices.Business
{
/// <summary>
/// ProductTypeColl (editable root list).<br/>
/// This is a generated <see cref="ProductTypeColl"/> business object.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="ProductTypeItem"/> objects.
/// </remarks>
[Serializable]
#if WINFORMS
public partial class ProductTypeColl : BusinessBindingListBase<ProductTypeColl, ProductTypeItem>
#else
public partial class ProductTypeColl : BusinessListBase<ProductTypeColl, ProductTypeItem>
#endif
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="ProductTypeItem"/> item from the collection.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to be removed.</param>
public void Remove(int productTypeId)
{
foreach (var productTypeItem in this)
{
if (productTypeItem.ProductTypeId == productTypeId)
{
Remove(productTypeItem);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="ProductTypeItem"/> item is in the collection.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to search for.</param>
/// <returns><c>true</c> if the ProductTypeItem is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int productTypeId)
{
foreach (var productTypeItem in this)
{
if (productTypeItem.ProductTypeId == productTypeId)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="ProductTypeItem"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to search for.</param>
/// <returns><c>true</c> if the ProductTypeItem is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int productTypeId)
{
foreach (var productTypeItem in DeletedList)
{
if (productTypeItem.ProductTypeId == productTypeId)
{
return true;
}
}
return false;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="ProductTypeColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="ProductTypeColl"/> collection.</returns>
public static ProductTypeColl NewProductTypeColl()
{
return DataPortal.Create<ProductTypeColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="ProductTypeColl"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="ProductTypeColl"/> collection.</returns>
public static ProductTypeColl GetProductTypeColl()
{
return DataPortal.Fetch<ProductTypeColl>();
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="ProductTypeColl"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewProductTypeColl(EventHandler<DataPortalResult<ProductTypeColl>> callback)
{
DataPortal.BeginCreate<ProductTypeColl>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="ProductTypeColl"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetProductTypeColl(EventHandler<DataPortalResult<ProductTypeColl>> callback)
{
DataPortal.BeginFetch<ProductTypeColl>(callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductTypeColl()
{
// Use factory methods and do not use direct creation.
Saved += OnProductTypeCollSaved;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Cache Invalidation
// TODO: edit "ProductTypeColl.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: Saved += OnProductTypeCollSaved;
private void OnProductTypeCollSaved(object sender, Csla.Core.SavedEventArgs e)
{
// this runs on the client
ProductTypeCachedList.InvalidateCache();
ProductTypeCachedNVL.InvalidateCache();
}
/// <summary>
/// Called by the server-side DataPortal after calling the requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
protected override void DataPortal_OnDataPortalInvokeComplete(Csla.DataPortalEventArgs e)
{
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Server &&
e.Operation == DataPortalOperations.Update)
{
// this runs on the server
ProductTypeCachedNVL.InvalidateCache();
}
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="ProductTypeColl"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.InvoicesConnection, false))
{
using (var cmd = new SqlCommand("dbo.GetProductTypeColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
var args = new DataPortalHookArgs(cmd);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="ProductTypeColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(DataPortal.FetchChild<ProductTypeItem>(dr));
}
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Updates in the database all changes made to the <see cref="ProductTypeColl"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.InvoicesConnection, false))
{
base.Child_Update();
}
}
#endregion
#region DataPortal Hooks
/// <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);
#endregion
}
}
| |
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using Skybound.ComponentModel;
using Skybound.VisualTips;
namespace Skybound.VisualTips.Rendering
{
[Skybound.ComponentModel.DisplayName("Office")]
public class VisualTipOfficeRenderer : Skybound.VisualTips.Rendering.VisualTipRenderer
{
private Skybound.VisualTips.Rendering.VisualTipOfficePreset _Preset;
[System.ComponentModel.Description("The background color of a tip.")]
[Skybound.ComponentModel.PropertyListValue]
public System.Drawing.Color BackColor
{
get
{
return (System.Drawing.Color)Properties.GetValue("BackColor", Preset.BackColor);
}
set
{
Properties.SetValue("BackColor", MakeSolidColor(value), System.Drawing.Color.Empty);
}
}
[System.ComponentModel.Description("The color into which the background gradient blends on a tip.")]
[Skybound.ComponentModel.PropertyListValue]
public System.Drawing.Color BackColorGradient
{
get
{
return (System.Drawing.Color)Properties.GetValue("BackColorGradient", Preset.BackColorGradient);
}
set
{
Properties.SetValue("BackColorGradient", MakeSolidColor(value), System.Drawing.Color.Empty);
}
}
[System.ComponentModel.Description("The effect used to draw a tip background.")]
[Skybound.ComponentModel.PropertyListValue]
public Skybound.VisualTips.Rendering.VisualTipOfficeBackgroundEffect BackgroundEffect
{
get
{
return (Skybound.VisualTips.Rendering.VisualTipOfficeBackgroundEffect)Properties.GetValue("BackgroundEffect", 0);
}
set
{
Properties.SetValue("BackgroundEffect", value, 0);
}
}
[System.ComponentModel.Description("The color of the tip border.")]
[Skybound.ComponentModel.PropertyListValue]
public System.Drawing.Color BorderColor
{
get
{
return (System.Drawing.Color)Properties.GetValue("BorderColor", Preset.BorderColor);
}
set
{
Properties.SetValue("BorderColor", MakeSolidColor(value), System.Drawing.Color.Empty);
}
}
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.Description("The angle of the background gradient, in degrees clockwise from the x-axis (0-360).")]
public int GradientAngle
{
get
{
return (int)Properties.GetValue("GradientAngle", 90);
}
set
{
Properties.SetValue("GradientAngle", value, 90);
}
}
[System.ComponentModel.Description("The preset which determines the default colors used by the renderer.")]
[System.ComponentModel.DefaultValue(typeof(Skybound.VisualTips.Rendering.VisualTipOfficePreset), "AutoSelect")]
[System.ComponentModel.ParenthesizePropertyName(true)]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
private Skybound.VisualTips.Rendering.VisualTipOfficePreset Preset
{
get
{
if (_Preset != null)
return _Preset;
return Skybound.VisualTips.Rendering.VisualTipOfficePreset.AutoSelect;
}
set
{
_Preset = value;
OnPropertyChanged("Preset");
}
}
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.Description("Whether a tip is displayed with round corners.")]
public bool RoundCorners
{
get
{
return (bool)Properties.GetValue("RoundCorners", 1);
}
set
{
Properties.SetValue("RoundCorners", value, 1);
}
}
[System.ComponentModel.Description("The color of the text on a tip.")]
[Skybound.ComponentModel.PropertyListValue]
public System.Drawing.Color TextColor
{
get
{
return (System.Drawing.Color)Properties.GetValue("TextColor", Preset.TextColor);
}
set
{
Properties.SetValue("TextColor", MakeSolidColor(value), System.Drawing.Color.Empty);
}
}
public VisualTipOfficeRenderer()
{
}
private System.Drawing.Drawing2D.GraphicsPath CreateGlarePath(System.Drawing.Rectangle bounds, int radius)
{
System.Drawing.Drawing2D.GraphicsPath graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
if (radius == 0)
{
graphicsPath.AddLine(bounds.X, bounds.Y, bounds.Right - 1, bounds.Y);
graphicsPath.AddLine(bounds.Right - 1, bounds.Y, bounds.Right - 1, bounds.Bottom - 1);
}
else
{
graphicsPath.AddLine(bounds.X + radius, bounds.Y, bounds.Right - radius - 1, bounds.Y);
graphicsPath.AddArc(bounds.Right - radius - 1, bounds.Y, radius, radius, 270.0F, 90.0F);
graphicsPath.AddLine(bounds.Right - 1, bounds.Y + radius, bounds.Right - 1, bounds.Bottom - radius);
}
graphicsPath.AddBezier(bounds.Right - 1, bounds.Bottom - 1, bounds.Right, bounds.Y + (bounds.Height / 2), bounds.X + (bounds.Width / 2), bounds.Y, bounds.X, bounds.Y);
graphicsPath.CloseAllFigures();
return graphicsPath;
}
protected override System.Drawing.Color GetElementTextColor(Skybound.VisualTips.VisualTip tip, Skybound.VisualTips.Rendering.VisualTipRenderElement element)
{
return TextColor;
}
protected override System.Drawing.Region OnCreateMaskRegion(Skybound.VisualTips.VisualTip tip, Skybound.VisualTips.Rendering.VisualTipLayout layout)
{
if (RoundCorners)
{
System.Drawing.Rectangle rectangle = layout.WindowBounds;
rectangle.Width++;
rectangle.Height++;
System.Drawing.Drawing2D.GraphicsPath graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
System.Drawing.Point[] pointArr = new System.Drawing.Point[8];
pointArr[0] = new System.Drawing.Point(rectangle.X + 2, rectangle.Y);
pointArr[1] = new System.Drawing.Point(rectangle.Right - 3, rectangle.Y);
pointArr[2] = new System.Drawing.Point(rectangle.Right - 1, rectangle.Y + 2);
pointArr[3] = new System.Drawing.Point(rectangle.Right - 1, rectangle.Bottom - 4);
pointArr[4] = new System.Drawing.Point(rectangle.Right - 4, rectangle.Bottom - 1);
pointArr[5] = new System.Drawing.Point(rectangle.X + 2, rectangle.Bottom - 1);
pointArr[6] = new System.Drawing.Point(rectangle.X, rectangle.Bottom - 4);
pointArr[7] = new System.Drawing.Point(rectangle.X, rectangle.Y + 2);
graphicsPath.AddPolygon(pointArr);
return new System.Drawing.Region(graphicsPath);
}
return base.OnCreateMaskRegion(tip, layout);
}
protected override void OnDrawWindow(System.Windows.Forms.PaintEventArgs e, Skybound.VisualTips.VisualTip tip, Skybound.VisualTips.Rendering.VisualTipLayout layout)
{
System.Drawing.Drawing2D.GraphicsPath graphicsPath1;
System.Drawing.Rectangle rectangle1 = layout.WindowBounds;
bool flag = BackgroundEffect == Skybound.VisualTips.Rendering.VisualTipOfficeBackgroundEffect.Glass;
if (RoundCorners)
{
graphicsPath1 = Skybound.VisualTips.Rendering.VisualTipRenderer.CreateRoundRectPath(rectangle1, Skybound.VisualTips.Rendering.VisualTipRenderer.LayeredWindowsSupported ? 5 : 7, Skybound.VisualTips.Rendering.VisualTipRenderer.BorderCorners.All);
}
else
{
graphicsPath1 = new System.Drawing.Drawing2D.GraphicsPath();
graphicsPath1.AddRectangle(new System.Drawing.Rectangle(rectangle1.Location, rectangle1.Size - (new System.Drawing.Size(1, 1))));
}
using (System.Drawing.Brush brush = new System.Drawing.Drawing2D.LinearGradientBrush(rectangle1, BackColor, BackColorGradient, (float)(GradientAngle + (flag ? 180 : 0)), false))
{
e.Graphics.FillPath(brush, graphicsPath1);
}
if (flag)
{
System.Drawing.Color color3 = BackColor;
int i1 = (int)((1.0F - ((1.0F - color3.GetBrightness()) * 0.75F)) * 255.0F);
System.Drawing.Color color1 = System.Drawing.Color.FromArgb(i1, i1, i1);
using (System.Drawing.Drawing2D.LinearGradientBrush linearGradientBrush = new System.Drawing.Drawing2D.LinearGradientBrush(rectangle1, System.Drawing.Color.FromArgb(128, color1), System.Drawing.Color.FromArgb(0, color1), System.Drawing.Drawing2D.LinearGradientMode.Vertical))
using (System.Drawing.Drawing2D.GraphicsPath graphicsPath2 = CreateGlarePath(rectangle1, Skybound.VisualTips.Rendering.VisualTipRenderer.LayeredWindowsSupported ? 5 : 7))
{
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
e.Graphics.FillPath(linearGradientBrush, graphicsPath2);
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
}
}
using (System.Drawing.Pen pen1 = new System.Drawing.Pen(BorderColor))
{
if (Skybound.VisualTips.Rendering.VisualTipRenderer.LayeredWindowsSupported)
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
else
pen1.Alignment = System.Drawing.Drawing2D.PenAlignment.Center;
e.Graphics.DrawPath(pen1, graphicsPath1);
if (Skybound.VisualTips.Rendering.VisualTipRenderer.LayeredWindowsSupported)
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
}
if (HasFooter(tip))
{
System.Drawing.Rectangle rectangle2 = layout.GetElementBounds(Skybound.VisualTips.Rendering.VisualTipRenderElement.FooterImage);
int i2 = rectangle2.Top - 6;
System.Drawing.Color color4 = BackColorGradient;
System.Drawing.Color color5 = BackColorGradient;
System.Drawing.Color color6 = BackColorGradient;
System.Drawing.Color color2 = System.Drawing.Color.FromArgb((int)((float)color4.R * 0.9F), (int)((float)color5.G * 0.9F), (int)((float)color6.B * 0.9F));
using (System.Drawing.Pen pen2 = new System.Drawing.Pen(color2))
{
e.Graphics.DrawLine(pen2, rectangle1.X + 5, i2, rectangle1.Right - 6, i2);
pen2.Color = System.Windows.Forms.ControlPaint.Light(BackColor);
e.Graphics.DrawLine(pen2, rectangle1.X + 5, i2 + 1, rectangle1.Right - 6, i2 + 1);
}
}
}
} // class VisualTipOfficeRenderer
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.Core.Common.Models;
using Orchard.Core.Containers.Models;
using Orchard.Core.Contents;
using Orchard.Core.Contents.Settings;
using Orchard.DisplayManagement;
using Orchard.Lists.ViewModels;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Mvc;
using Orchard.Mvc.Extensions;
using Orchard.Settings;
using Orchard.UI.Navigation;
using Orchard.UI.Notify;
namespace Orchard.Lists.Controllers {
public class AdminController : Controller {
private readonly IContentManager _contentManager;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly ISiteService _siteService;
public IOrchardServices Services { get; set; }
public AdminController(
IOrchardServices orchardServices,
IContentManager contentManager,
IContentDefinitionManager contentDefinitionManager,
ISiteService siteService,
IShapeFactory shapeFactory) {
Services = orchardServices;
_contentManager = contentManager;
_contentDefinitionManager = contentDefinitionManager;
_siteService = siteService;
T = NullLocalizer.Instance;
Logger = NullLogger.Instance;
Shape = shapeFactory;
}
public Localizer T { get; set; }
public ILogger Logger { get; set; }
dynamic Shape { get; set; }
private IEnumerable<ContentTypeDefinition> GetContainableTypes() {
return _contentDefinitionManager.ListTypeDefinitions().Where(ctd => ctd.Parts.Any(c => c.PartDefinition.Name == "ContainablePart") && ctd.Settings.GetModel<ContentTypeSettings>().Creatable);
}
public ActionResult List(ListContentsViewModel model, PagerParameters pagerParameters) {
var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);
var container = model.ContainerId.HasValue ? _contentManager.GetLatest((int)model.ContainerId) : null;
if (container == null || !container.Has<ContainerPart>()) {
return HttpNotFound();
}
var restrictedContentType = container.As<ContainerPart>().Record.ItemContentType;
var hasRestriction = !string.IsNullOrEmpty(restrictedContentType);
if (hasRestriction) {
model.FilterByContentType = restrictedContentType;
}
model.Options.SelectedFilter = model.FilterByContentType;
model.ContainerDisplayName = container.ContentManager.GetItemMetadata(container).DisplayText;
if (string.IsNullOrEmpty(model.ContainerDisplayName)) {
model.ContainerDisplayName = container.ContentType;
}
var query = GetListContentItemQuery(model.ContainerId.Value, model.FilterByContentType, model.Options.OrderBy);
if (query == null) {
return HttpNotFound();
}
model.Options.FilterOptions = GetContainableTypes()
.Select(ctd => new KeyValuePair<string, string>(ctd.Name, ctd.DisplayName))
.ToList().OrderBy(kvp => kvp.Key);
var pagerShape = Shape.Pager(pager).TotalItemCount(query.Count());
var pageOfContentItems = query.Slice(pager.GetStartIndex(), pager.PageSize).ToList();
var list = Shape.List();
list.AddRange(pageOfContentItems.Select(ci => _contentManager.BuildDisplay(ci, "SummaryAdmin")));
var containerItemContentDisplayName = String.Empty;
if (hasRestriction)
containerItemContentDisplayName = _contentDefinitionManager.GetTypeDefinition(restrictedContentType).DisplayName;
else if (!string.IsNullOrEmpty(model.FilterByContentType))
containerItemContentDisplayName = _contentDefinitionManager.GetTypeDefinition(model.FilterByContentType).DisplayName;
dynamic viewModel = Shape.ViewModel()
.ContentItems(list)
.Pager(pagerShape)
.ContainerId(model.ContainerId)
.Options(model.Options)
.ContainerDisplayName(model.ContainerDisplayName)
.HasRestriction(hasRestriction)
.ContainerContentType(container.ContentType)
.ContainerItemContentDisplayName(containerItemContentDisplayName)
.ContainerItemContentType(hasRestriction ? restrictedContentType : (model.FilterByContentType ?? ""))
.OtherLists(_contentManager.Query<ContainerPart>(VersionOptions.Latest).List()
.Select(part => part.ContentItem)
.Where(item => item != container)
.OrderBy(item => item.As<CommonPart>().VersionPublishedUtc));
// Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
return View((object)viewModel);
}
private IContentQuery<ContentItem> GetListContentItemQuery(int containerId, string contentType, ContentsOrder orderBy) {
List<string> containableTypes = GetContainableTypes().Select(ctd => ctd.Name).ToList();
if (containableTypes.Count == 0) {
// Force the name to be matched against empty and return no items in the query
containableTypes.Add(string.Empty);
}
var query = _contentManager.Query(VersionOptions.Latest, containableTypes.ToArray());
if (!string.IsNullOrEmpty(contentType)) {
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(contentType);
if (contentTypeDefinition == null) {
return null;
}
query = query.ForType(contentType);
}
query = containerId == 0
? query.Join<CommonPartRecord>().Where(cr => cr.Container == null)
: query.Join<CommonPartRecord>().Where(cr => cr.Container.Id == containerId);
switch (orderBy) {
case ContentsOrder.Modified:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.ModifiedUtc);
break;
case ContentsOrder.Published:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.PublishedUtc);
break;
case ContentsOrder.Created:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.CreatedUtc);
break;
}
return query;
}
[HttpPost, ActionName("List")]
[FormValueRequired("submit.BulkEdit")]
public ActionResult ListPOST(ContentOptions options, IEnumerable<int> itemIds, int? targetContainerId, string returnUrl) {
if (itemIds != null) {
switch (options.BulkAction) {
case ContentsBulkAction.None:
break;
case ContentsBulkAction.PublishNow:
if (!BulkPublishNow(itemIds)) {
return new HttpUnauthorizedResult();
}
break;
case ContentsBulkAction.Unpublish:
if (!BulkUnpublish(itemIds)) {
return new HttpUnauthorizedResult();
}
break;
case ContentsBulkAction.Remove:
if (!BulkRemove(itemIds)) {
return new HttpUnauthorizedResult();
}
break;
case ContentsBulkAction.RemoveFromList:
if (!BulkRemoveFromList(itemIds)) {
return new HttpUnauthorizedResult();
}
break;
case ContentsBulkAction.MoveToList:
if (!BulkMoveToList(itemIds, targetContainerId)) {
return new HttpUnauthorizedResult();
}
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return this.RedirectLocal(returnUrl, () => RedirectToAction("List"));
}
[HttpPost, ActionName("List")]
[FormValueRequired("submit.Filter")]
public ActionResult ListFilterPOST(ContentOptions options) {
var routeValues = ControllerContext.RouteData.Values;
if (options != null) {
routeValues["Options.OrderBy"] = options.OrderBy;
if (GetContainableTypes().Any(ctd => string.Equals(ctd.Name, options.SelectedFilter, StringComparison.OrdinalIgnoreCase))) {
routeValues["filterByContentType"] = options.SelectedFilter;
}
else {
routeValues.Remove("filterByContentType");
}
}
return RedirectToAction("List", routeValues);
}
public ActionResult Choose(ChooseContentsViewModel model, PagerParameters pagerParameters) {
var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);
var container = model.SourceContainerId == 0 ? null : _contentManager.GetLatest(model.SourceContainerId);
if (container == null && model.SourceContainerId != 0) {
return HttpNotFound();
}
if (string.IsNullOrEmpty(model.FilterByContentType)) {
var targetContainer = _contentManager.Get<ContainerPart>(model.TargetContainerId);
if (targetContainer != null) {
model.FilterByContentType = targetContainer.Record.ItemContentType;
}
}
var query = GetListContentItemQuery(model.SourceContainerId, model.FilterByContentType, model.OrderBy);
if (query == null) {
return HttpNotFound();
}
model.SelectedFilter = model.FilterByContentType;
model.FilterOptions = GetContainableTypes()
.Select(ctd => new KeyValuePair<string, string>(ctd.Name, ctd.DisplayName))
.ToList().OrderBy(kvp => kvp.Key);
var pagerShape = Shape.Pager(pager).TotalItemCount(query.Count());
var pageOfContentItems = query.Slice(pager.GetStartIndex(), pager.PageSize).ToList();
var list = Shape.List();
list.AddRange(pageOfContentItems.Select(ci => _contentManager.BuildDisplay(ci, "SummaryAdmin")));
dynamic viewModel = Shape.ViewModel()
.ContentItems(list)
.Pager(pagerShape)
.SourceContainerId(model.SourceContainerId)
.TargetContainerId(model.TargetContainerId)
.SelectedFilter(model.SelectedFilter)
.FilterOptions(model.FilterOptions)
.OrderBy(model.OrderBy)
.Containers(_contentManager.Query<ContainerPart>(VersionOptions.Latest).List()
.Select(part => part.ContentItem)
.OrderBy(item => item.As<CommonPart>().VersionPublishedUtc));
// Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
return View((object)viewModel);
}
[HttpPost, ActionName("Choose")]
[FormValueRequired("submit.MoveTo")]
public ActionResult ChoosePOST(IEnumerable<int> itemIds, int targetContainerId, string returnUrl) {
if (itemIds != null && !BulkMoveToList(itemIds, targetContainerId)) {
return new HttpUnauthorizedResult();
}
return this.RedirectLocal(returnUrl, () => RedirectToAction("List", new { ContainerId = targetContainerId }));
}
[HttpPost, ActionName("Choose")]
[FormValueRequired("submit.Filter")]
public ActionResult ChooseFilterPOST(ChooseContentsViewModel model) {
var routeValues = ControllerContext.RouteData.Values;
if (GetContainableTypes().Any(ctd => string.Equals(ctd.Name, model.SelectedFilter, StringComparison.OrdinalIgnoreCase))) {
routeValues["filterByContentType"] = model.SelectedFilter;
}
else {
routeValues.Remove("filterByContentType");
}
if (model.SourceContainerId == 0) {
routeValues.Remove("SourceContainerId");
}
else {
routeValues["SourceContainerId"] = model.SourceContainerId;
}
routeValues["OrderBy"] = model.OrderBy;
routeValues["TargetContainerId"] = model.TargetContainerId;
return RedirectToAction("Choose", routeValues);
}
private void FixItemPath(ContentItem item) {
// Fixes an Item's path when its container changes.
// force a publish/unpublish event so RoutePart fixes the content items path
// and the paths of any child objects if it is also a container.
if (item.VersionRecord.Published) {
item.VersionRecord.Published = false;
_contentManager.Publish(item);
}
else {
item.VersionRecord.Published = true;
_contentManager.Unpublish(item);
}
}
private bool BulkMoveToList(IEnumerable<int> itemIds, int? targetContainerId) {
if (!targetContainerId.HasValue) {
Services.Notifier.Information(T("Please select the list to move the items to."));
return true;
}
var id = targetContainerId.Value;
var targetContainer = _contentManager.Get<ContainerPart>(id);
if (targetContainer == null) {
Services.Notifier.Information(T("Please select the list to move the items to."));
return true;
}
var itemContentType = targetContainer.Record.ItemContentType;
foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) {
if (!Services.Authorizer.Authorize(Permissions.EditContent, item, T("Couldn't move selected content."))) {
return false;
}
// ensure the item can be in that container.
if (!string.IsNullOrEmpty(itemContentType) && item.ContentType != itemContentType) {
Services.TransactionManager.Cancel();
Services.Notifier.Information(T("One or more items could not be moved to '{0}' because it is restricted to containing items of type '{1}'.", _contentManager.GetItemMetadata(targetContainer).DisplayText ?? targetContainer.ContentItem.ContentType, itemContentType));
return true; // todo: transactions
}
item.As<CommonPart>().Record.Container = targetContainer.ContentItem.Record;
FixItemPath(item);
}
Services.Notifier.Information(T("Content successfully moved to <a href=\"{0}\">{1}</a>.",
Url.Action("List", new { containerId = targetContainerId }), _contentManager.GetItemMetadata(targetContainer).DisplayText ?? targetContainer.ContentItem.ContentType));
return true;
}
private bool BulkRemoveFromList(IEnumerable<int> itemIds) {
foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) {
if (!Services.Authorizer.Authorize(Permissions.EditContent, item, T("Couldn't remove selected content from the list."))) {
Services.TransactionManager.Cancel();
return false;
}
item.As<CommonPart>().Record.Container = null;
FixItemPath(item);
}
Services.Notifier.Information(T("Content successfully removed from the list."));
return true;
}
private bool BulkRemove(IEnumerable<int> itemIds) {
foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) {
if (!Services.Authorizer.Authorize(Permissions.DeleteContent, item, T("Couldn't remove selected content."))) {
Services.TransactionManager.Cancel();
return false;
}
_contentManager.Remove(item);
}
Services.Notifier.Information(T("Content successfully removed."));
return true;
}
private bool BulkUnpublish(IEnumerable<int> itemIds) {
foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) {
if (!Services.Authorizer.Authorize(Permissions.PublishContent, item, T("Couldn't unpublish selected content."))) {
Services.TransactionManager.Cancel();
return false;
}
_contentManager.Unpublish(item);
}
Services.Notifier.Information(T("Content successfully unpublished."));
return true;
}
private bool BulkPublishNow(IEnumerable<int> itemIds) {
foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) {
if (!Services.Authorizer.Authorize(Permissions.PublishContent, item, T("Couldn't publish selected content."))) {
Services.TransactionManager.Cancel();
return false;
}
_contentManager.Publish(item);
}
Services.Notifier.Information(T("Content successfully published."));
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using AssociationOneToMany.Areas.HelpPage.ModelDescriptions;
using AssociationOneToMany.Areas.HelpPage.Models;
namespace AssociationOneToMany.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
if (complexTypeDescription != null)
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
public class UnitySequencerIO
{
#region Constants
const string Machinima = "machinima";
public delegate void OnCreatedCutscene(Cutscene cutscene);
#endregion
#region Variables
CutsceneEditor m_Timeline;
BMLParser m_BMLParser;
CutsceneEvent m_UtteranceAudioEvent;
OnCreatedCutscene m_OnCreatedCutscene;
#endregion
#region Properties
CutsceneEditor Timeline
{
get { return m_Timeline; }
}
public bool UseMecanimEvents
{
set
{
m_BMLParser.EventCategoryName = value ? GenericEventNames.Mecanim : GenericEventNames.SmartBody;
}
}
public string BmlSubDir
{
get { return m_BMLParser.LoadPathSubFolder; }
set { m_BMLParser.LoadPathSubFolder = value; }
}
#endregion
#region Functions
public UnitySequencerIO(CutsceneEditor sequencer)
{
m_Timeline = sequencer;
m_BMLParser = new BMLParser(OnAddBmlTiming, OnAddVisemeTiming, ParsedBMLEvent, OnFinishedReading, OnParsedCustomEvent);
UseMecanimEvents = true;
}
public void AddOnCreatedCutsceneCallback(OnCreatedCutscene cb)
{
m_OnCreatedCutscene += cb;
}
public void RemoveOnCreatedCutsceneCallback(OnCreatedCutscene cb)
{
m_OnCreatedCutscene -= cb;
}
public void OnAddBmlTiming(BMLParser.BMLTiming bmlTiming)
{
bool prevVal = Timeline.CreateBMLEvents;
Timeline.CreateBMLEvents = true;
Timeline.AddBmlTiming(bmlTiming.id, bmlTiming.time, bmlTiming.text);
// reset
Timeline.CreateBMLEvents = prevVal;
}
public void OnAddVisemeTiming(BMLParser.LipData lipData)
{
bool prevVal = Timeline.CreateBMLEvents;
Timeline.CreateBMLEvents = true;
Timeline.AddVisemeTiming(lipData.viseme, lipData.startTime, lipData.endTime);
// reset
Timeline.CreateBMLEvents = prevVal;
}
public bool LoadXMLString(string character, string xmlStr)
{
return m_BMLParser.LoadXMLString(character, xmlStr);
}
public bool LoadFile(string filePathAndName)
{
return m_BMLParser.LoadFile(filePathAndName);
}
void OnFinishedReading(bool succeeded, List<CutsceneEvent> createdEvents)
{
// get the name of the character that these events are associated with
foreach (CutsceneEvent ce in createdEvents)
{
CutsceneEventParam characterParam = ce.FindParameter("character");
if (characterParam != null && !string.IsNullOrEmpty(characterParam.stringData))
{
m_UtteranceAudioEvent.FindParameter("character").stringData = characterParam.stringData;
break;
}
}
foreach (CutsceneEvent ce in createdEvents)
{
// we do this for events that are based off of the timing of other events
CutsceneEvent timeLineEvent = Timeline.FindEventByID(ce.UniqueId);
timeLineEvent.StartTime = ce.StartTime;
timeLineEvent.Length = ce.Length;
}
if (m_OnCreatedCutscene != null)
{
m_OnCreatedCutscene(Timeline.GetSelectedCutscene());
}
}
void OnParsedCustomEvent(XmlTextReader reader)
{
if (reader.Name == Machinima)
{
float zoom = 0;
if (float.TryParse(reader["zoom"], out zoom))
{
Timeline.Zoom = zoom;
}
int numTrackGroups = 0;
if (int.TryParse(reader["numGroups"], out numTrackGroups))
{
for (int i = Timeline.GroupManager.NumGroups; i < numTrackGroups; i++)
{
Timeline.AddTrackGroup();
}
}
}
}
public void ParsedBMLEvent(XmlTextReader reader, string type, CutsceneEvent ce)
{
if (ce != null && ce.FunctionName.Contains("SendVHMsg"))
{
string message = ce.FindParameter("message").stringData;
if (message.Contains("vrAgentSpeech partial") || message.Contains("vrSpoke"))
{
// we don't want these messages
return;
}
}
else if (ce != null && ce.FunctionName.Contains("PlayViseme"))
{
if (reader["messageType"] == "visemeStop")
{
// we don't want these messages
return;
}
}
const float minPosition = TimelineWindow.TrackStartingY + TimelineWindow.TrackHeight * 2; // the first 2 tracks are reserved
float eventYPos = minPosition; // the first 2 tracks are reserved
if (!string.IsNullOrEmpty(reader["ypos"]))
{
eventYPos = float.Parse(reader["ypos"]);
}
if (eventYPos < minPosition)
{
eventYPos = minPosition;
}
CutsceneEvent newEvent = AddEvent(ce, eventYPos);
newEvent.SetParameters(reader);
// try to setup the reference to the character on the event using xml data
if (newEvent.EventType == GenericEventNames.SmartBody || newEvent.EventType == GenericEventNames.Mecanim)
{
CutsceneEventParam characterParam = newEvent.FindParameter("character");
characterParam.SetObjData(ce.FindParameter("character").objData);
characterParam.stringData = ce.FindParameter("character").stringData;
}
if (type == "speech")
{
m_UtteranceAudioEvent = newEvent;
}
}
public CutsceneEvent AddEvent(CutsceneEvent ce)
{
const float minPosition = TimelineWindow.TrackStartingY + TimelineWindow.TrackHeight * 2; // the first 2 tracks are reserved
return AddEvent(ce, minPosition);
}
public CutsceneEvent AddEvent(CutsceneEvent ce, float positionY)
{
Vector2 eventPos = new Vector2(Timeline.GetPositionFromTime(Timeline.StartTime, Timeline.EndTime, ce.StartTime, Timeline.m_TrackScrollArea), positionY);
CutsceneEvent newEvent = Timeline.CreateEventAtPosition(eventPos) as CutsceneEvent;
ce.CloneData(newEvent);
newEvent.m_UniqueId = ce.UniqueId;
newEvent.StartTime = ce.StartTime;
Timeline.ChangedCutsceneEventType(ce.EventType, newEvent);
Timeline.ChangedEventFunction(newEvent, ce.FunctionName, ce.FunctionOverloadIndex);
Timeline.CalculateTimelineLength();
newEvent.GuiPosition.width = Timeline.GetWidthFromTime(newEvent.EndTime, newEvent.GuiPosition.x);
// setup the length
float length = ce.Length;
CutsceneEventParam lengthParam = newEvent.GetLengthParameter();
if (lengthParam != null)
{
lengthParam.SetLength(length);
newEvent.SetEventLengthFromParameter(lengthParam.Name);
}
return newEvent;
}
public void CreateXml(string filePathAndName, Cutscene cutscene)
{
StreamWriter outfile = null;
for (int i = 0; i < cutscene.CutsceneEvents.Count; i++)
{
if (cutscene.CutsceneEvents[i].FunctionName == "Marker")
{
continue;
}
for (int j = i + 1; j < cutscene.CutsceneEvents.Count; j++)
{
if (cutscene.CutsceneEvents[i].Name == cutscene.CutsceneEvents[j].Name)
{
EditorUtility.DisplayDialog("Error", string.Format("You can't have 2 events with the same name \'{0}\'. XML Not Saved!", cutscene.CutsceneEvents[i].Name), "Ok");
return;
}
}
}
try
{
outfile = new StreamWriter(string.Format("{0}", filePathAndName));
outfile.WriteLine(@"<?xml version=""1.0""?>");
outfile.WriteLine(@"<act>");
outfile.WriteLine(@" <bml xmlns:sbm=""http://sourceforge.net/apps/mediawiki/smartbody/index.php?title=SmartBody_BML"" xmlns:mm=""https://confluence.ict.usc.edu/display/VHTK/Home"">");
//outfile.WriteLine(@" <bml xmlns:mm=""https://vhtoolkit.ict.usc.edu/"">");
outfile.WriteLine(string.Format(@" <speech id=""visSeq_3"" ref=""{0}"" type=""application/ssml+xml"" />", Path.GetFileNameWithoutExtension(filePathAndName)));
// write out mm cutscene meta data
outfile.WriteLine(string.Format(@" <{0} numGroups=""{1}"" numEvents=""{2}"" zoom=""{3}"" />", Machinima, cutscene.GroupManager.NumGroups, cutscene.NumEvents, Timeline.Zoom));
//for (int i = 0; i < cutscene.GroupManager.NumGroups
// sort the events by chronological order
List<CutsceneEvent> timeSortedEvents = new List<CutsceneEvent>();
timeSortedEvents.AddRange(cutscene.CutsceneEvents);
timeSortedEvents.Sort(delegate(CutsceneEvent a, CutsceneEvent b)
{
return a.StartTime > b.StartTime ? 1 : -1;
});
// save out the events
foreach (CutsceneEvent ce in timeSortedEvents)
{
string xmlString = ce.GetXMLString();
if (!string.IsNullOrEmpty(xmlString))
{
outfile.WriteLine(string.Format(" {0}", xmlString));
}
}
outfile.WriteLine(@" </bml>");
outfile.WriteLine(@"</act>");
}
catch (Exception e)
{
Debug.LogError(string.Format("CreateXml failed: {0}", e.Message));
EditorUtility.DisplayDialog("Error", string.Format("An error occured when saving \'{0}\'. XML was not properly saved!", Path.GetFileNameWithoutExtension(filePathAndName)), "Ok");
outfile.WriteLine(@" </bml>");
outfile.WriteLine(@"</act>");
}
finally
{
if (outfile != null)
{
outfile.Close();
}
}
}
public void ListenToNVBG(bool listen)
{
VHMsgBase vhmsg = VHMsgBase.Get();
if (vhmsg == null)
{
Debug.LogError(string.Format("Machinima Maker can't listen to NVBG because there is no VHMsgManager in the scene"));
return;
}
if (listen)
{
vhmsg.SubscribeMessage("vrSpeak");
vhmsg.RemoveMessageEventHandler(VHMsg_MessageEventHandler);
vhmsg.AddMessageEventHandler(VHMsg_MessageEventHandler);
}
else
{
vhmsg.RemoveMessageEventHandler(VHMsg_MessageEventHandler);
}
}
void VHMsg_MessageEventHandler(object sender, VHMsgBase.Message message)
{
Debug.Log("msg received: " + message.s);
string[] splitargs = message.s.Split(" ".ToCharArray());
if (splitargs[0] == "vrSpeak")
{
if (splitargs.Length > 4)
{
if (splitargs[3].Contains("idle"))
{
// we don't want random idle fidgets
// i.e. vrSpeak Brad all idle-1193041418-823
return;
}
Cutscene selectedCutscene = Timeline.GetSelectedCutscene();
if (selectedCutscene == null)
{
EditorUtility.DisplayDialog("Error", "You need to create a cutscene so that NVBG can be listened to", "Ok");
return;
}
if (EditorUtility.DisplayDialog("Warning", string.Format("Do you want to overwrite cutscene {0} with the message from NVBG. You will lose all the current events?", selectedCutscene.CutsceneName), "Yes", "No"))
{
//Timeline.AddCutscene();
Timeline.RemoveEvents(selectedCutscene.CutsceneEvents);
string character = splitargs[1];
string xml = String.Join(" ", splitargs, 4, splitargs.Length - 4);
m_BMLParser.LoadXMLString(character, xml);
}
}
}
}
#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;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.NodejsTools.Npm;
using Microsoft.NodejsTools.Telemetry;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.NodejsTools.NpmUI
{
internal sealed class NpmWorker : IDisposable
{
// todo: get this from a user specified location?
private static readonly Uri defaultRegistryUri = new Uri("https://registry.npmjs.org/");
private readonly INpmController npmController;
private readonly BlockingCollection<QueuedNpmCommandInfo> commandQueue = new BlockingCollection<QueuedNpmCommandInfo>();
private readonly Thread worker;
private QueuedNpmCommandInfo currentCommand;
public NpmWorker(INpmController controller)
{
this.npmController = controller;
this.worker = new Thread(this.Run)
{
Name = "NPM worker Execution",
IsBackground = true
};
this.worker.Start();
}
private void QueueCommand(QueuedNpmCommandInfo info)
{
if (this.commandQueue.IsAddingCompleted
|| this.commandQueue.Contains(info)
|| info.Equals(this.currentCommand))
{
return;
}
this.commandQueue.Add(info);
}
public void QueueCommand(string arguments)
{
// this is safe since the we use a blocking collection to
// store the commands
this.QueueCommand(new QueuedNpmCommandInfo(arguments));
}
private void Execute(QueuedNpmCommandInfo info)
{
// Wait on the command to complete.
// this way we're sure there's only one command being executed,
// since the only thread starting this commands is the worker thread
Debug.Assert(Thread.CurrentThread == this.worker, "The worked thread should be executing the NPM commands.");
var cmdr = this.npmController.CreateNpmCommander();
try
{
cmdr.ExecuteNpmCommandAsync(info.Arguments).Wait();
}
catch (AggregateException e) when (e.InnerException is TaskCanceledException)
{
// TaskCanceledException is not un-expected,
// and should not tear down this thread.
// Other exceptions are handled higher up the stack.
}
}
private void Run()
{
// We want the thread to continue running queued commands before
// exiting so the user can close the install window without having to wait
// for commands to complete.
while (!this.commandQueue.IsCompleted)
{
// The Take method will block the worker thread when there are no items left in the queue
// and the thread will be signalled when new items are items to the queue, or the queue is
// marked completed.
if (this.commandQueue.TryTake(out var command, Timeout.Infinite) && command != null)
{
this.currentCommand = command;
Execute(this.currentCommand);
}
}
}
public async Task<IEnumerable<IPackage>> GetCatalogPackagesAsync(string filterText)
{
if (string.IsNullOrWhiteSpace(filterText))
{
return Enumerable.Empty<IPackage>();
}
TelemetryHelper.LogSearchNpm();
var relativeUri = string.Format("/-/v1/search?text=\"{0}\"", WebUtility.UrlEncode(filterText));
var searchUri = new Uri(defaultRegistryUri, relativeUri);
var request = WebRequest.Create(searchUri);
using (var response = await request.GetResponseAsync())
{
/* We expect the following response:
{
"objects": [
{
"package": {
"name": "express",
"scope": "unscoped",
"version": "4.15.2",
"description": "Fast, unopinionated, minimalist web framework",
"keywords": [ "express", "framework", "sinatra", "web", "rest", "restful", "router", "app", "api" ],
"date": "2017-03-06T13:42:44.853Z",
"links": {
"npm": "https://www.npmjs.com/package/express",
"homepage": "http://expressjs.com/",
"repository": "https://github.com/expressjs/express",
"bugs": "https://github.com/expressjs/express/issues"
},
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"publisher": {
"username": "dougwilson",
"email": "doug@somethingdoug.com"
},
"maintainers": [
{
"username": "dougwilson",
"email": "doug@somethingdoug.com"
}
]
},
"score": {
"final": 0.9549640105248649,
"detail": {
"quality": 0.9427473299991661,
"popularity": 0.9496544159654299,
"maintenance": 0.9707450455348992
}
},
"searchScore": 100000.95
}
],
"total": 10991,
"time": "Tue May 09 2017 22:41:07 GMT+0000 (UTC)"
}
*/
var reader = new StreamReader(response.GetResponseStream());
using (var jsonReader = new JsonTextReader(reader))
{
while (jsonReader.Read())
{
switch (jsonReader.TokenType)
{
case JsonToken.StartObject:
case JsonToken.PropertyName:
continue;
case JsonToken.StartArray:
return ReadPackagesFromArray(jsonReader);
default:
throw new InvalidOperationException("Unexpected json token.");
}
}
}
}
// should never get here
throw new InvalidOperationException("Unexpected json token.");
}
private IEnumerable<IPackage> ReadPackagesFromArray(JsonTextReader jsonReader)
{
var pkgList = new List<IPackage>();
// Inside the array, each object is an NPM package
var builder = new NodeModuleBuilder();
while (jsonReader.Read())
{
switch (jsonReader.TokenType)
{
case JsonToken.PropertyName:
if (StringComparer.Ordinal.Equals(jsonReader.Value, "package"))
{
var token = (JProperty)JToken.ReadFrom(jsonReader);
var package = ReadPackage(token.Value, builder);
if (package != null)
{
pkgList.Add(package);
}
}
continue;
case JsonToken.EndArray:
// This is the spot the function should always exit on valid data
return pkgList;
default:
continue;
}
}
throw new JsonException("Unexpected end of stream reading the NPM catalog data array");
}
private IPackage ReadPackage(JToken package, NodeModuleBuilder builder)
{
builder.Reset();
try
{
builder.Name = (string)package["name"];
if (string.IsNullOrEmpty(builder.Name))
{
// I don't believe this should ever happen if the data returned is
// well formed. Could throw an exception, but just skip instead for
// resiliency on the NTVS side.
return null;
}
builder.AppendToDescription((string)package["description"] ?? string.Empty);
var date = package["date"];
if (date != null)
{
builder.SetDate((string)date);
}
var version = package["version"];
if (version != null)
{
var semver = SemverVersion.Parse((string)version);
builder.AddVersion(semver);
}
AddKeywords(builder, package["keywords"]);
AddAuthor(builder, package["author"]);
AddHomepage(builder, package["links"]);
return builder.Build();
}
catch (InvalidOperationException)
{
// Occurs if a JValue appears where we expect JProperty
return null;
}
catch (ArgumentException)
{
return null;
}
}
private static void AddKeywords(NodeModuleBuilder builder, JToken keywords)
{
if (keywords != null)
{
foreach (var keyword in keywords.Select(v => (string)v))
{
builder.AddKeyword(keyword);
}
}
}
private static void AddHomepage(NodeModuleBuilder builder, JToken links)
{
var homepage = links?["homepage"];
if (homepage != null)
{
builder.AddHomepage((string)homepage);
}
}
private static void AddAuthor(NodeModuleBuilder builder, JToken author)
{
var name = author?["name"];
if (author != null)
{
builder.AddAuthor((string)name);
}
}
public void Dispose()
{
this.commandQueue.CompleteAdding();
}
private sealed class QueuedNpmCommandInfo
{
public QueuedNpmCommandInfo(string arguments)
{
this.Arguments = arguments;
}
public string Arguments { get; }
public bool Equals(QueuedNpmCommandInfo other)
{
return StringComparer.CurrentCulture.Equals(this.ToString(), other?.ToString());
}
public override bool Equals(object obj)
{
return Equals(obj as QueuedNpmCommandInfo);
}
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
public override string ToString()
{
var buff = new StringBuilder("npm ");
buff.Append(this.Arguments);
return buff.ToString();
}
}
}
}
| |
namespace Fixtures.SwaggerBatBodyComplex
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
internal partial class Dictionary : IServiceOperations<AutoRestComplexTestService>, IDictionary
{
/// <summary>
/// Initializes a new instance of the Dictionary class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal Dictionary(AutoRestComplexTestService client)
{
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestComplexTestService
/// </summary>
public AutoRestComplexTestService Client { get; private set; }
/// <summary>
/// Get complex types with dictionary property
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<DictionaryWrapper>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//complex/dictionary/typed/valid";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DictionaryWrapper>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DictionaryWrapper>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put complex types with dictionary property
/// </summary>
/// <param name='complexBody'>
/// Please put a dictionary with 5 key-value pairs: "txt":"notepad",
/// "bmp":"mspaint", "xls":"excel", "exe":"", "":null
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(DictionaryWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//complex/dictionary/typed/valid";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get complex types with dictionary property which is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<DictionaryWrapper>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//complex/dictionary/typed/empty";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DictionaryWrapper>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DictionaryWrapper>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put complex types with dictionary property which is empty
/// </summary>
/// <param name='complexBody'>
/// Please put an empty dictionary
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(DictionaryWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutEmpty", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//complex/dictionary/typed/empty";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get complex types with dictionary property which is null
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<DictionaryWrapper>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//complex/dictionary/typed/null";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DictionaryWrapper>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DictionaryWrapper>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get complex types with dictionary property while server doesn't provide a
/// response payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<DictionaryWrapper>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetNotProvided", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//complex/dictionary/typed/notprovided";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DictionaryWrapper>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DictionaryWrapper>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Notes about TaiwanLunisolarCalendar
//
////////////////////////////////////////////////////////////////////////////
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 1912/02/18 2051/02/10
** TaiwanLunisolar 1912/01/01 2050/13/29
*/
public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar
{
// Since
// Gregorian Year = Era Year + yearOffset
// When Gregorian Year 1912 is year 1, so that
// 1912 = 1 + yearOffset
// So yearOffset = 1911
//m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911);
// Initialize our era info.
static internal EraInfo[] taiwanLunisolarEraInfo = new EraInfo[] {
new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear
};
internal GregorianCalendarHelper helper;
internal const int MIN_LUNISOLAR_YEAR = 1912;
internal const int MAX_LUNISOLAR_YEAR = 2050;
internal const int MIN_GREGORIAN_YEAR = 1912;
internal const int MIN_GREGORIAN_MONTH = 2;
internal const int MIN_GREGORIAN_DAY = 18;
internal const int MAX_GREGORIAN_YEAR = 2051;
internal const int MAX_GREGORIAN_MONTH = 2;
internal const int MAX_GREGORIAN_DAY = 10;
internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY);
internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999);
public override DateTime MinSupportedDateTime
{
get
{
return (minDate);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (maxDate);
}
}
protected override int DaysInYearBeforeMinSupportedYear
{
get
{
// 1911 from ChineseLunisolarCalendar
return 384;
}
}
static readonly int[,] yinfo =
{
/*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days
1912 */
{ 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
1914 */{ 5 , 1 , 26 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
1915 */{ 0 , 2 , 14 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
1916 */{ 0 , 2 , 3 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355
1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
1918 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
1919 */{ 7 , 2 , 1 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
1920 */{ 0 , 2 , 20 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
1923 */{ 0 , 2 , 16 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
1924 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
1925 */{ 4 , 1 , 24 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385
1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
1927 */{ 0 , 2 , 2 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
1928 */{ 2 , 1 , 23 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383
1931 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384
1934 */{ 0 , 2 , 14 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355
1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
1936 */{ 3 , 1 , 24 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384
1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384
1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354
1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384
1942 */{ 0 , 2 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
1943 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
1944 */{ 4 , 1 , 25 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
1949 */{ 7 , 1 , 29 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
1950 */{ 0 , 2 , 17 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354
1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
1952 */{ 5 , 1 , 27 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
1953 */{ 0 , 2 , 14 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354
1954 */{ 0 , 2 , 3 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
1955 */{ 3 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
1957 */{ 8 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383
1958 */{ 0 , 2 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355
1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
1965 */{ 0 , 2 , 2 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353
1966 */{ 3 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
1968 */{ 7 , 1 , 30 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
1970 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
1972 */{ 0 , 2 , 15 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
1973 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
1976 */{ 8 , 1 , 31 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
1978 */{ 0 , 2 , 7 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355
1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
1982 */{ 4 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
1987 */{ 6 , 1 , 29 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 29 384
1988 */{ 0 , 2 , 17 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
1989 */{ 0 , 2 , 6 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
1990 */{ 5 , 1 , 27 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
1995 */{ 8 , 1 , 31 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384
1996 */{ 0 , 2 , 19 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354
1997 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
1998 */{ 5 , 1 , 28 , 37736 },/* 30 29 29 30 29 29 30 30 29 30 30 29 30 384
1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
2001 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
2005 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
2012 */{ 4 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
2013 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354
2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
2017 */{ 6 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
2019 */{ 0 , 2 , 5 , 43312 },/* 30 29 30 29 30 29 29 30 29 29 30 30 0 354
2020 */{ 4 , 1 , 25 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384
2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
2023 */{ 2 , 1 , 22 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384
2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
2026 */{ 0 , 2 , 17 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354
2027 */{ 0 , 2 , 6 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
2028 */{ 5 , 1 , 26 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
2029 */{ 0 , 2 , 13 , 54576 },/* 30 30 29 30 29 30 29 30 29 29 30 30 0 355
2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
2031 */{ 3 , 1 , 23 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384
2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
2034 */{ 0 , 2 , 19 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
2036 */{ 6 , 1 , 28 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384
2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384
2040 */{ 0 , 2 , 12 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355
2041 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384
2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
2046 */{ 0 , 2 , 6 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
2048 */{ 0 , 2 , 14 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354
2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
2050 */{ 3 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
*/};
internal override int MinCalendarYear
{
get
{
return (MIN_LUNISOLAR_YEAR);
}
}
internal override int MaxCalendarYear
{
get
{
return (MAX_LUNISOLAR_YEAR);
}
}
internal override DateTime MinDate
{
get
{
return (minDate);
}
}
internal override DateTime MaxDate
{
get
{
return (maxDate);
}
}
internal override EraInfo[] CalEraInfo
{
get
{
return (taiwanLunisolarEraInfo);
}
}
internal override int GetYearInfo(int LunarYear, int Index)
{
if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR))
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
MIN_LUNISOLAR_YEAR,
MAX_LUNISOLAR_YEAR));
}
Contract.EndContractBlock();
return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
}
internal override int GetYear(int year, DateTime time)
{
return helper.GetYear(year, time);
}
internal override int GetGregorianYear(int year, int era)
{
return helper.GetGregorianYear(year, era);
}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of TaiwanLunisolarCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance()
{
if (m_defaultInstance == null) {
m_defaultInstance = new TaiwanLunisolarCalendar();
}
return (m_defaultInstance);
}
*/
// Construct an instance of TaiwanLunisolar calendar.
public TaiwanLunisolarCalendar()
{
helper = new GregorianCalendarHelper(this, taiwanLunisolarEraInfo);
}
public override int GetEra(DateTime time)
{
return (helper.GetEra(time));
}
internal override CalendarId BaseCalendarID
{
get
{
return (CalendarId.TAIWAN);
}
}
internal override CalendarId ID
{
get
{
return (CalendarId.TAIWANLUNISOLAR);
}
}
public override int[] Eras
{
get
{
return (helper.Eras);
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System;
namespace RootMotion {
/// <summary>
/// Class for identifying biped bones based on most common naming conventions.
/// </summary>
public static class BipedNaming {
/// <summary>
/// Type of the bone.
/// </summary>
[System.Serializable]
public enum BoneType {
Unassigned,
Spine,
Head,
Arm,
Leg,
Tail,
Eye
}
/// <summary>
/// Bone side: Left and Right for limbs and Center for spine, head and tail.
/// </summary>
[System.Serializable]
public enum BoneSide {
Center,
Left,
Right
}
// Bone identifications
public static string[]
typeLeft = {" L ", "_L_", "-L-", " l ", "_l_", "-l-", "Left", "left", "CATRigL"},
typeRight = {" R ", "_R_", "-R-", " r ", "_r_", "-r-", "Right", "right", "CATRigR"},
typeSpine = {"Spine", "spine", "Pelvis", "pelvis", "Root", "root", "Torso", "torso", "Body", "body", "Hips", "hips", "Neck", "neck", "Chest", "chest"},
typeHead = {"Head", "head"},
typeArm = {"Arm", "arm", "Hand", "hand", "Wrist", "Wrist", "Elbow", "elbow", "Palm", "palm"},
typeLeg = {"Leg", "leg", "Thigh", "thigh", "Calf", "calf", "Femur", "femur", "Knee", "knee", "Foot", "foot", "Ankle", "ankle", "Hip", "hip"},
typeTail = {"Tail", "tail"},
typeEye = {"Eye", "eye"},
typeExclude = {"Nub", "Dummy", "dummy", "Tip", "IK", "Mesh"},
typeExcludeSpine = {"Head", "head"},
typeExcludeHead = {"Top", "End" },
typeExcludeArm = {"Collar", "collar", "Clavicle", "clavicle", "Finger", "finger", "Index", "index", "Mid", "mid", "Pinky", "pinky", "Ring", "Thumb", "thumb", "Adjust", "adjust", "Twist", "twist"},
typeExcludeLeg = {"Toe", "toe", "Platform", "Adjust", "adjust", "Twist", "twist"},
typeExcludeTail = {},
typeExcludeEye = {"Lid", "lid", "Brow", "brow", "Lash", "lash"},
pelvis = {"Pelvis", "pelvis", "Hip", "hip"},
hand = {"Hand", "hand", "Wrist", "wrist", "Palm", "palm"},
foot = {"Foot", "foot", "Ankle", "ankle"};
#region Public methods
/// <summary>
/// Returns only the bones with the specified BoneType.
/// </summary>
public static Transform[] GetBonesOfType(BoneType boneType, Transform[] bones) {
Transform[] r = new Transform[0];
foreach (Transform bone in bones) {
if (bone != null && GetBoneType(bone.name) == boneType) {
Array.Resize(ref r, r.Length + 1);
r[r.Length - 1] = bone;
}
}
return r;
}
/// <summary>
/// Returns only the bones with the specified BoneSide.
/// </summary>
public static Transform[] GetBonesOfSide(BoneSide boneSide, Transform[] bones) {
Transform[] r = new Transform[0];
foreach (Transform bone in bones) {
if (bone != null && GetBoneSide(bone.name) == boneSide) {
Array.Resize(ref r, r.Length + 1);
r[r.Length - 1] = bone;
}
}
return r;
}
/// <summary>
/// Gets the bones of type and side.
/// </summary>
public static Transform[] GetBonesOfTypeAndSide(BoneType boneType, BoneSide boneSide, Transform[] bones) {
Transform[] bonesOfType = GetBonesOfType(boneType, bones);
return GetBonesOfSide(boneSide, bonesOfType);
}
/// <summary>
/// Gets the bone of type and side. If more than one is found, will return the first in the array.
/// </summary>
public static Transform GetFirstBoneOfTypeAndSide(BoneType boneType, BoneSide boneSide, Transform[] bones) {
Transform[] b = GetBonesOfTypeAndSide(boneType, boneSide, bones);
if (b.Length == 0) return null;
return b[0];
}
/// <summary>
/// Returns only the bones that match all the namings in params string[][] namings
/// </summary>
/// <returns>
/// The matching Transforms
/// </returns>
/// <param name='transforms'>
/// Transforms.
/// </param>
/// <param name='namings'>
/// Namings.
/// </param>
public static Transform GetNamingMatch(Transform[] transforms, params string[][] namings) {
foreach (Transform t in transforms) {
bool match = true;
foreach (string[] naming in namings) {
if (!matchesNaming(t.name, naming)) {
match = false;
break;
}
}
if (match) return t;
}
return null;
}
/// <summary>
/// Gets the type of the bone.
/// </summary>
public static BoneType GetBoneType(string boneName) {
if (isSpine(boneName)) return BoneType.Spine;
if (isHead(boneName)) return BoneType.Head;
if (isArm (boneName)) return BoneType.Arm;
if (isLeg(boneName)) return BoneType.Leg;
if (isTail(boneName)) return BoneType.Tail;
if (isEye(boneName)) return BoneType.Eye;
return BoneType.Unassigned;
}
/// <summary>
/// Gets the bone side.
/// </summary>
public static BoneSide GetBoneSide(string boneName) {
if (isLeft(boneName)) return BoneSide.Left;
if (isRight(boneName)) return BoneSide.Right;
return BoneSide.Center;
}
/// <summary>
/// Returns the bone of type and side with additional naming parameters.
/// </summary>
public static Transform GetBone(Transform[] transforms, BoneType boneType, BoneSide boneSide = BoneSide.Center, params string[][] namings) {
Transform[] bones = GetBonesOfTypeAndSide(boneType, boneSide, transforms);
return GetNamingMatch(bones, namings);
}
#endregion Public methods
private static bool isLeft(string boneName) {
return matchesNaming(boneName, typeLeft) || lastLetter(boneName) == "L" || firstLetter(boneName) == "L";
}
private static bool isRight(string boneName) {
return matchesNaming(boneName, typeRight) || lastLetter(boneName) == "R" || firstLetter(boneName) == "R";
}
private static bool isSpine(string boneName) {
return matchesNaming(boneName, typeSpine) && !excludesNaming(boneName, typeExcludeSpine);
}
private static bool isHead(string boneName) {
return matchesNaming(boneName, typeHead) && !excludesNaming(boneName, typeExcludeHead);
}
private static bool isArm(string boneName) {
return matchesNaming(boneName, typeArm) && !excludesNaming(boneName, typeExcludeArm);
}
private static bool isLeg(string boneName) {
return matchesNaming(boneName, typeLeg) && !excludesNaming(boneName, typeExcludeLeg);
}
private static bool isTail(string boneName) {
return matchesNaming(boneName, typeTail) && !excludesNaming(boneName, typeExcludeTail);
}
private static bool isEye(string boneName) {
return matchesNaming(boneName, typeEye) && !excludesNaming(boneName, typeExcludeEye);
}
private static bool isTypeExclude(string boneName) {
return matchesNaming(boneName, typeExclude);
}
private static bool matchesNaming(string boneName, string[] namingConvention) {
if (excludesNaming(boneName, typeExclude)) return false;
foreach(string n in namingConvention) {
if (boneName.Contains(n)) return true;
}
return false;
}
private static bool excludesNaming(string boneName, string[] namingConvention) {
foreach(string n in namingConvention) {
if (boneName.Contains(n)) return true;
}
return false;
}
private static bool matchesLastLetter(string boneName, string[] namingConvention) {
foreach(string n in namingConvention) {
if (LastLetterIs(boneName, n)) return true;
}
return false;
}
private static bool LastLetterIs(string boneName, string letter) {
string lastLetter = boneName.Substring(boneName.Length - 1, 1);
return lastLetter == letter;
}
private static string firstLetter(string boneName) {
if (boneName.Length > 0) return boneName.Substring(0, 1);
return "";
}
private static string lastLetter(string boneName) {
if (boneName.Length > 0) return boneName.Substring(boneName.Length - 1, 1);
return "";
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using mshtml;
using OpenLiveWriter.CoreServices;
namespace OpenLiveWriter.Mshtml
{
/// <summary>
/// Delegate used to filter element scanning operations. If this operation returns true, then the
/// scanning operation will consider the element as relevant to the scan.
/// </summary>
public delegate bool IHTMLElementFilter(IHTMLElement e);
/// <summary>
/// Delegate used to walk through a MarkupRange. Return true to continue walking and false to stop.
/// </summary>
public delegate bool MarkupRangeWalker(MarkupRange currentRange, MarkupContext context, string text);
/// <summary>
/// Range of markup within a document
/// </summary>
public class MarkupRange
{
/// <summary>
/// Initialize with begin and end pointers
/// </summary>
/// <param name="start">start</param>
/// <param name="end">end</param>
/// <param name="markupServices"></param>
internal MarkupRange(MarkupPointer start, MarkupPointer end, MshtmlMarkupServices markupServices)
{
Start = start;
End = end;
MarkupServices = markupServices;
}
/// <summary>
/// Returns the Html contained in this MarkupRange.
/// </summary>
public string HtmlText
{
get
{
try
{
if (!Positioned)
return null;
return MarkupHelpers.UseStagingTextRange(ref stagingTxtRange, this,
rng => rng.htmlText);
}
catch (Exception)
{
//this can occur when the pointers are not positioned
return null;
}
}
}
/// <summary>
/// Returns the text (stripped of HTML elements) contained in this MarkupRange.
/// </summary>
public string Text
{
get
{
try
{
if (!Positioned || Start.IsRightOf(End))
return null;
return MarkupHelpers.GetRangeTextFast(this);
}
catch (Exception)
{
//this can occur when the pointers are not positioned
return null;
}
}
set
{
MarkupHelpers.UseStagingTextRange(ref stagingTxtRange, this,
rng =>
{
rng.text = value;
return 0;
});
}
}
/// <summary>
/// Collapses the range to make the start/end equal.
/// </summary>
/// <param name="start">true if start pointer should be the anchor, else its the end pointer.</param>
public void Collapse(bool start)
{
if (start)
End.MoveToPointer(Start);
else
Start.MoveToPointer(End);
}
/// <summary>
/// Safely removes the content within this range without leaving the document badly formed.
/// </summary>
public void RemoveContent()
{
//delete the selection by moving a delete range right (from the start).
//Each time that a tag that does not entirely exist within this selection
//is encountered, the range content will be deleted, the deleteRange will
//skip over the element.
MarkupRange deleteRange = this.Clone();
Trace.Assert(deleteRange.Start.Positioned, "Trying to remove content from selection that contains pointers that are not positioned.");
deleteRange.End.MoveToPointer(deleteRange.Start);
MarkupPointer p = MarkupServices.CreateMarkupPointer();
MarkupPointer previousPosition = MarkupServices.CreateMarkupPointer(deleteRange.End);
MarkupContext context = new MarkupContext();
deleteRange.End.Right(true, context);
while (deleteRange.End.IsLeftOf(End))
{
if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope)
{
p.MoveAdjacentToElement(context.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
if (p.IsRightOf(End))
{
//this element does not exist entirely in this selection, so we need to
//ignore it in the delete.
//save this position so that the delete range can be repositioned here
p.MoveToPointer(deleteRange.End);
//move the end left since we overstepped the valid delete range
deleteRange.End.MoveToPointer(previousPosition);
//delete the content in the deleteRange, and move it back to this position
deleteRangeContentAndMoveToPosition(deleteRange, p);
}
else
{
//this element exists entirely in this selection, so skip to its end (since
//we know it can be deleted)
deleteRange.End.MoveToPointer(p);
}
}
else if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope)
{
p.MoveAdjacentToElement(context.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
if (p.IsLeftOf(Start))
{
//this element does not exist entirely in this selection, so we need to
//ignore it in the delete.
//save this position so that the delete range can be repositioned here
p.MoveToPointer(deleteRange.End);
//move the end left since we overstepped the valid delete range
deleteRange.End.MoveToPointer(previousPosition);
//delete the content in the deleteRange, and move it back to this position
deleteRangeContentAndMoveToPosition(deleteRange, p);
}
else
{
//this element exists entirely in this selection, so skip to its end (since
//we know it can be deleted)
deleteRange.End.MoveToPointer(p);
}
}
previousPosition.MoveToPointer(deleteRange.End);
deleteRange.End.Right(true, context);
}
//delete the last part of the range
deleteRange.End.MoveToPointer(End);
if (!deleteRange.Start.Equals(deleteRange.End))
MarkupServices.Remove(deleteRange.Start, deleteRange.End);
}
/// <summary>
/// Creates a clone that spans the same range as this MarkupRange.
/// Note: The clone can be manipulated without changing the position of this range.
/// </summary>
/// <returns></returns>
public MarkupRange Clone()
{
MarkupRange clone = MarkupServices.CreateMarkupRange();
clone.Start.MoveToPointer(Start);
clone.Start.Cling = Start.Cling;
clone.Start.Gravity = Start.Gravity;
clone.End.MoveToPointer(End);
clone.End.Cling = End.Cling;
clone.End.Gravity = End.Gravity;
return clone;
}
public void Normalize()
{
if (Start.IsRightOf(End))
{
MarkupPointer tmp = Start;
Start = End;
End = tmp;
}
}
/// <summary>
/// Returns the HTML Elements that a direct children of this range.
/// Note: Only children that are completely contained in this range will be returned.
/// </summary>
/// <returns></returns>
public IHTMLElement[] GetTopLevelElements(IHTMLElementFilter filter)
{
return GetTopLevelBlocksAndCells(filter, false);
}
//this is similar to the GetTopLevelElements except will also return table cells if correct filter
// is set and recurse is equal to true
public IHTMLElement[] GetTopLevelBlocksAndCells(IHTMLElementFilter filter, bool recurse)
{
ArrayList list = new ArrayList();
Hashtable usedElements = new Hashtable();
MarkupPointer p = MarkupServices.CreateMarkupPointer(Start);
MarkupContext context = p.Right(false);
//move p through the range to locate each of the top level elements
while (p.IsLeftOf(End))
{
if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope || context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_NoScope)
{
p.MoveAdjacentToElement(context.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
if (usedElements[context.Element] == null)
{
if (p.IsLeftOfOrEqualTo(End) && (filter == null || filter(context.Element)))
{
list.Add(context.Element);
}
//special case--inside of a table element, want to get out the cells inside
else if (recurse && ElementFilters.TABLE_ELEMENTS(context.Element))
{
MarkupRange newRange = MarkupServices.CreateMarkupRange(context.Element);
newRange.Start.MoveAdjacentToElement(context.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
if (newRange.Start.IsLeftOf(Start))
{
newRange.Start.MoveToPointer(Start);
}
if (newRange.End.IsRightOf(End))
{
newRange.End.MoveToPointer(End);
}
//recursively check inside table element for table cells
list.AddRange(newRange.GetTopLevelBlocksAndCells(filter, true));
}
//cache the fact that we've already tested this element.
usedElements[context.Element] = context.Element;
}
}
p.Right(true, context);
}
return HTMLElementHelper.ToElementArray(list);
}
public static bool FilterNone(IHTMLElement e)
{
return true;
}
/// <summary>
/// Gets the elements in the range that match the filter.
/// </summary>
/// <param name="filter">the delegate testing each element to determine if it should be added to the list of elements to return</param>
/// <param name="inScopeElementsOnly">if true, the only</param>
/// <returns></returns>
public IHTMLElement[] GetElements(IHTMLElementFilter filter, bool inScopeElementsOnly)
{
ArrayList list = new ArrayList();
if (!IsEmpty())
{
Hashtable usedElements = new Hashtable();
MarkupPointer p = MarkupServices.CreateMarkupPointer(Start);
MarkupPointer end = MarkupServices.CreateMarkupPointer(End);
MarkupContext context = p.Right(false);
//move p through the range to locate each the elements adding elements that pass the filter
while (p.IsLeftOfOrEqualTo(end))
{
if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope
|| context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope
|| context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_NoScope)
{
if (usedElements[context.Element] == null)
{
if ((inScopeElementsOnly && isInScope(context.Element)) || !inScopeElementsOnly)
if (filter(context.Element))
{
list.Add(context.Element);
}
//cache the fact that we've already tested this element.
usedElements[context.Element] = context.Element;
}
}
p.Right(true, context);
}
}
return HTMLElementHelper.ToElementArray(list);
}
/// <summary>
/// Returns true if the the range contains an element that matches the filter
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public bool ContainsElements(IHTMLElementFilter filter)
{
if (!IsEmpty())
{
Hashtable usedElements = new Hashtable();
MarkupPointer p = MarkupServices.CreateMarkupPointer(Start);
MarkupContext context = p.Right(false);
//move p through the range to locate each the elements adding elements that pass the filter
while (p.IsLeftOfOrEqualTo(End))
{
if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope
|| context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope
|| context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_NoScope)
{
if (usedElements[context.Element] == null)
{
if (filter(context.Element))
{
return true;
}
}
//cache the fact that we've already tested this element.
usedElements[context.Element] = context.Element;
}
p.Right(true, context);
}
}
return false;
}
/// <summary>
/// Returns true if the specified pointer is in a position between, or equal to this range's Start/End points.
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public bool InRange(MarkupPointer p)
{
return Start.IsLeftOfOrEqualTo(p) && End.IsRightOfOrEqualTo(p);
}
public bool InRange(IHTMLElement e)
{
Debug.Assert(e != null, "Unexpected null element.");
return InRange(MarkupServices.CreateMarkupRange(e, true));
}
/// <summary>
/// Returns true if the specified pointer is in a position between, or equal to this range's Start/End points.
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public bool InRange(MarkupPointer p, bool allowEquals)
{
if (allowEquals)
return Start.IsLeftOfOrEqualTo(p) && End.IsRightOfOrEqualTo(p);
else
return Start.IsLeftOf(p) && End.IsRightOf(p);
}
/// <summary>
/// Returns true if the specified range is in a position between, or equal to this range's Start/End points.
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public bool InRange(MarkupRange range)
{
return InRange(range, true);
}
/// <summary>
/// Returns true if the specified range is in a position between, or (if allowed) equal to this range's Start/End points.
/// </summary>
/// <returns></returns>
public bool InRange(MarkupRange range, bool allowEquals)
{
return InRange(range.Start, allowEquals) && InRange(range.End, allowEquals);
}
public bool Intersects(MarkupRange range)
{
return !(Start.IsRightOf(range.End) || End.IsLeftOf(range.Start));
}
/// <summary>
/// Move this markup range to the specified element.
/// </summary>
/// <param name="e">The element to move to</param>
/// <param name="outside">if true, then the range will be position around the outside of the element. If false,
/// then the range will be position inside the begin and end tags of this element.</param>
public void MoveToElement(IHTMLElement e, bool outside)
{
if (outside)
{
Start.MoveAdjacentToElement(e, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
End.MoveAdjacentToElement(e, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
}
else
{
Start.MoveAdjacentToElement(e, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
End.MoveAdjacentToElement(e, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd);
}
}
/// <summary>
/// Move this markup range to the specified location.
/// Note: this replaces the start/end pointer of this range, so the range will permanently follow the new pointers.
/// </summary>
/// <param name="textRange"></param>
public void MoveToPointers(MarkupPointer start, MarkupPointer end)
{
Start = start;
End = end;
}
/// <summary>
/// Move this markup range to the specified location.
/// </summary>
/// <param name="textRange"></param>
public void MoveToRange(MarkupRange range)
{
Start.MoveToPointer(range.Start);
End.MoveToPointer(range.End);
}
/// <summary>
/// Move to range.
/// </summary>
/// <param name="textRange"></param>
public void MoveToTextRange(IHTMLTxtRange textRange)
{
MarkupServices.MovePointersToRange(textRange, Start, End);
}
/// <summary>
/// Returns true if this range is currently positioned.
/// </summary>
public bool Positioned
{
get
{
return Start.Positioned && End.Positioned;
}
}
/// <summary>
/// Returns the parent element that the is shared by the start and end pointers.
/// </summary>
/// <returns></returns>
public IHTMLElement ParentElement()
{
return GetSharedParent(Start, End);
}
/// <summary>
/// Returns the parent element that the is shared by the start and end pointers.
/// </summary>
/// <returns></returns>
public IHTMLElement ParentBlockElement()
{
return ParentElement(ElementFilters.IsBlockElement);
}
public IHTMLElement ParentElement(IHTMLElementFilter filter)
{
IHTMLElement parent = ParentElement();
while (parent != null && !filter(parent))
{
parent = parent.parentElement;
}
return parent;
}
/// <summary>
/// Condenses this range into the smallest well-formed state that still contains the same
/// text markup.
/// </summary>
/// <returns></returns>
public bool Trim()
{
MarkupPointer newStart = MarkupServices.CreateMarkupPointer(Start);
MarkupPointer newEnd = MarkupServices.CreateMarkupPointer(End);
MarkupContext context = new MarkupContext();
//set newStart adjacent to the first text element to its right
newStart.Right(true, context);
while (!HasContentBetween(Start, newStart) && newStart.IsLeftOf(End))
newStart.Right(true, context);
if (HasContentBetween(Start, newStart))
newStart.Left(true); //we overstepped the text, so back up one step
//set newEnd adjacent to the first text element to its left
newEnd.Left(true, context);
while (!HasContentBetween(newEnd, End) && newEnd.IsRightOf(Start))
newEnd.Left(true, context);
if (HasContentBetween(newEnd, End))
newEnd.Right(true); //we overstepped the text, so back up one step
IHTMLElement sharedParent = GetSharedParent(newStart, newEnd);
//span the start and end pointers as siblings by finding the parents of start and end
//pointers that are direct children of the sharedParent
IHTMLElement child = GetOuterMostChildOfParent(newStart, true, sharedParent);
if (child != null)
newStart.MoveAdjacentToElement(child, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
child = GetOuterMostChildOfParent(newEnd, false, sharedParent);
if (child != null)
newEnd.MoveAdjacentToElement(child, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
if (!HasContentBetween(newStart, Start) && !HasContentBetween(End, newEnd)
&& !(Start.IsEqualTo(newStart) && End.IsEqualTo(newEnd)))
{
Start.MoveToPointer(newStart);
End.MoveToPointer(newEnd);
return true;
}
else
{
//the range didn't change, so return false.
return false;
}
}
public delegate bool RangeFilter(MarkupPointer start, MarkupPointer end);
public bool MoveOutwardIfNoText()
{
return MoveOutwardIfNo(HasTextBetween);
}
// <summary>
/// Expands this range out to the next parent shared by the start and end points
/// if there there are no non-empty text elements between them.
/// </summary>
/// <returns></returns>
public bool MoveOutwardIfNoContent()
{
return MoveOutwardIfNo(HasContentBetween);
}
/// <summary>
/// Expands this range out to the next parent shared by the start and end points
/// if there there are no non-empty text elements between them.
/// </summary>
/// <returns></returns>
public bool MoveOutwardIfNo(RangeFilter rangeFilter)
{
MarkupRange newRange = MarkupServices.CreateMarkupRange();
IHTMLElement sharedParent = GetSharedParent(Start, End);
// If share a common parent, we will take the shared parent's parent so we can see if we want to grab
// all the html inside of it, unless the shared parent is the body element, in which case we don't want to
// epxand outward anymore
if (Start.CurrentScope == sharedParent && End.CurrentScope == sharedParent && !(sharedParent is IHTMLBodyElement))
{
sharedParent = sharedParent.parentElement;
}
//expand to the inside of the shared parent first. If this matches the current placement
//of the pointers, then expand to the outside of the parent. This allows the outter selection
//to grow incrementally in such a way as to allow the shared parent to be tested between
//each iteration of this operation.
newRange.Start.MoveAdjacentToElement(sharedParent, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
newRange.End.MoveAdjacentToElement(sharedParent, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd);
if (newRange.IsEmpty() || newRange.Start.IsRightOf(Start) || newRange.End.IsLeftOf(End))
{
newRange.Start.MoveAdjacentToElement(sharedParent, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
newRange.End.MoveAdjacentToElement(sharedParent, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
}
if (!rangeFilter(newRange.Start, Start) && !rangeFilter(End, newRange.End)
&& !(Start.IsEqualTo(newRange.Start) && End.IsEqualTo(newRange.End)))
{
Start.MoveToPointer(newRange.Start);
End.MoveToPointer(newRange.End);
return true;
}
else
{
//span the start and end pointers as siblings by finding the parents of start and end
//pointers that are direct children of the sharedParent
IHTMLElement child = GetOuterMostChildOfParent(Start, true, sharedParent);
if (child != null)
newRange.Start.MoveAdjacentToElement(child, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
else
newRange.Start = Start;
child = GetOuterMostChildOfParent(End, false, sharedParent);
if (child != null)
newRange.End.MoveAdjacentToElement(child, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
else
newRange.End = End;
if (!rangeFilter(newRange.Start, Start) && !rangeFilter(End, newRange.End)
&& !(Start.IsEqualTo(newRange.Start) && End.IsEqualTo(newRange.End)))
{
Start.MoveToPointer(newRange.Start);
End.MoveToPointer(newRange.End);
return true;
}
else
{
//the range didn't change, so return false.
return false;
}
}
}
/// <summary>
/// Returns a text range located at the same position as this MarkupRange.
/// </summary>
/// <returns></returns>
public IHTMLTxtRange ToTextRange()
{
return MarkupServices.CreateTextRange(Start, End);
}
/// <summary>
/// Walk through the markup range letting the walker visit each position.
/// </summary>
/// <param name="walker">the delegate walking navigating the the markup range</param>
/// <returns></returns>
public void WalkRange(MarkupRangeWalker walker)
{
WalkRange(walker, false);
}
/// <summary>
/// Walk through the markup range letting the walker visit each position.
/// </summary>
/// <param name="walker">the delegate walking navigating the the markup range</param>
/// <param name="inScopeElementsOnly">if true, enter/exit notifications about out-of-scope elements will be suppressed.</param>
/// <returns></returns>
public void WalkRange(MarkupRangeWalker walker, bool inScopeContextsOnly)
{
MarkupPointer p1 = MarkupServices.CreateMarkupPointer(Start);
MarkupPointer p2 = MarkupServices.CreateMarkupPointer(Start);
p1.Cling = false;
p2.Cling = false;
MarkupContext context = new MarkupContext();
bool continueWalking = true;
MarkupRange currentRange = null;
while (continueWalking && p2.IsLeftOf(End))
{
string text = null;
bool isInScope = true;
p2.Right(true, context);
currentRange = new MarkupRange(p1.Clone(), p2.Clone(), MarkupServices);
if (inScopeContextsOnly)
{
if (context.Element != null)
{
if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope)
{
p1.MoveAdjacentToElement(context.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
isInScope = InRange(p1);
}
else if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope)
{
p1.MoveAdjacentToElement(context.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
isInScope = InRange(p1);
}
}
else if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_Text)
{
// It's possible part of the text is out of scope, so only return the in-scope text.
if (currentRange.End.IsRightOf(End))
{
currentRange.End.MoveToPointer(End);
}
}
}
if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_Text)
{
text = currentRange.Text;
}
if (!inScopeContextsOnly || isInScope)
{
continueWalking = walker(currentRange, context, text);
}
p1.MoveToPointer(p2);
}
}
/// <summary>
/// Walk through the markup range in reverse, letting the walker visit each position.
/// </summary>
/// <param name="walker">the delegate walking navigating the the markup range</param>
/// <param name="inScopeElementsOnly">if true, enter/exit notifications about out-of-scope elements will be suppressed.</param>
/// <returns></returns>
public void WalkRangeReverse(MarkupRangeWalker walker, bool inScopeContextsOnly)
{
MarkupPointer p1 = MarkupServices.CreateMarkupPointer(End);
MarkupPointer p2 = MarkupServices.CreateMarkupPointer(End);
p1.Cling = false;
p2.Cling = false;
MarkupContext context = new MarkupContext();
bool continueWalking = true;
MarkupRange currentRange = null;
while (continueWalking && p2.IsRightOf(Start))
{
string text = null;
bool isInScope = true;
p2.Left(true, context);
currentRange = new MarkupRange(p2.Clone(), p1.Clone(), MarkupServices);
if (inScopeContextsOnly)
{
if (context.Element != null)
{
if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope)
{
p1.MoveAdjacentToElement(context.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
isInScope = InRange(p1);
}
else if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope)
{
p1.MoveAdjacentToElement(context.Element, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
isInScope = InRange(p1);
}
}
else if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_Text)
{
// It's possible part of the text is out of scope, so only return the in-scope text.
if (currentRange.Start.IsLeftOf(Start))
{
currentRange.Start.MoveToPointer(Start);
}
}
}
if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_Text)
{
text = currentRange.Text;
}
if (!inScopeContextsOnly || isInScope)
{
continueWalking = walker(currentRange, context, text);
}
p1.MoveToPointer(p2);
}
}
/// <summary>
/// Returns true if the start and end points of the range are equal.
/// </summary>
/// <returns></returns>
public bool IsEmpty()
{
return Start.IsEqualTo(End);
}
/// <summary>
/// Returns true if this range is composes entirely of non-visible elements.
/// </summary>
/// <returns></returns>
public bool IsEmptyOfContent()
{
return IsEmptyOfContent(true);
}
/// <summary>
/// Returns true if this range is composes entirely of non-visible elements.
/// </summary>
/// <param name="inScopeContextsOnly">flag to ignore out of scope element
/// (use false unless you absolutely want to ignore visible content in cases like
/// [start]<p>[end]</p>)</param>
/// <returns></returns>
public bool IsEmptyOfContent(bool inScopeContextsOnly)
{
try
{
bool isEmptyOfContent = true;
WalkRange(
delegate (MarkupRange currentRange, MarkupContext context, string text)
{
text = text ?? string.Empty;
if (!String.IsNullOrEmpty(text.Trim()))
{
isEmptyOfContent = false;
return false;
}
if (context.Element != null && ElementFilters.IsVisibleEmptyElement(context.Element))
{
isEmptyOfContent = false;
return false;
}
// Continue walking the range.
return true;
},
inScopeContextsOnly);
return isEmptyOfContent;
}
catch (Exception)
{
return false;
}
}
public bool IsEmptyOfText(bool inScopeContextsOnly)
{
try
{
bool isEmptyOfText = true;
WalkRange(
delegate (MarkupRange currentRange, MarkupContext context, string text)
{
text = text ?? string.Empty;
if (!String.IsNullOrEmpty(text.Trim()))
{
isEmptyOfText = false;
return false;
}
// Continue walking the range.
return true;
},
inScopeContextsOnly);
return isEmptyOfText;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Beginning of range
/// </summary>
public MarkupPointer Start;
/// <summary>
/// End of range
/// </summary>
public MarkupPointer End;
internal MshtmlMarkupServices MarkupServices;
private IHTMLTxtRange stagingTxtRange;
#region PRIVATE UTILITIES
/// <summary>
/// Return the parent element that 2 pointers share in common
/// </summary>
/// <returns></returns>
private IHTMLElement GetSharedParent(MarkupPointer start, MarkupPointer end)
{
IHTMLElement startCurrentScope = start.CurrentScope;
IHTMLElement endCurrentScope = end.CurrentScope;
if (startCurrentScope == endCurrentScope)
{
//the start/end points share the same current scope, so return that element as the parent.
return startCurrentScope;
}
else
{
//find the parent element that these 2 pointers share in common
//by locating the first parent endtag that the rangeEnd pointer
//is contained within.
MarkupPointer parentStart = MarkupServices.CreateMarkupPointer();
MarkupPointer parentEnd = MarkupServices.CreateMarkupPointer();
IHTMLElement sharedParent = startCurrentScope;
if (sharedParent != null)
{
parentEnd.MoveAdjacentToElement(sharedParent, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
while (sharedParent != null && parentEnd.IsLeftOf(end))
{
sharedParent = sharedParent.parentElement;
parentEnd.MoveAdjacentToElement(sharedParent, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
}
}
return sharedParent;
}
}
/// <summary>
/// Returns true if there is non-empty content between 2 pointers.
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns>true if there is visible content between the pointers</returns>
private bool HasContentBetween(MarkupPointer start, MarkupPointer end)
{
MarkupRange range = MarkupServices.CreateMarkupRange(start, end);
return !range.IsEmptyOfContent(false);
}
private bool HasTextBetween(MarkupPointer start, MarkupPointer end)
{
MarkupRange range = MarkupServices.CreateMarkupRange(start, end);
return !range.IsEmptyOfText(false);
}
/// <summary>
/// Retrieve the parent of a child element that is closest to an outer parent element.
/// </summary>
/// <param name="from">the position to move move out from</param>
/// <param name="lookRight">if true, look right for the inner child to start from, otherwise look left</param>
/// <param name="outerParent">parent element to move out to</param>
/// <returns>the direct child of the outerparent that contains the innerChild</returns>
IHTMLElement GetOuterMostChildOfParent(MarkupPointer from, bool lookRight, IHTMLElement outerParent)
{
MarkupContext lookContext = new MarkupContext();
if (lookRight)
from.Right(false, lookContext);
else
from.Left(false, lookContext);
//if there is a new element coming into scope, start the search from there,
//otherwise, start from the currentScope.
IHTMLElement innerChild;
if (lookContext.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope)
innerChild = lookContext.Element;
else
innerChild = from.CurrentScope;
IHTMLElement parent = innerChild;
IHTMLElement innerParent = innerChild;
while (parent != outerParent && parent != null)
{
innerParent = parent;
parent = parent.parentElement;
}
Debug.Assert(innerParent != null, "Parent not found");
if (innerParent == outerParent) //occurs when the from pointer is position directly in the parent.
{
return null;
}
return innerParent;
}
/// <summary>
/// Returns true if the specified pointer is in a position between, or equal to the start/end points.
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
private static bool isInRange(MarkupPointer start, MarkupPointer end, MarkupPointer p)
{
return start.IsLeftOfOrEqualTo(p) && end.IsRightOfOrEqualTo(p);
}
/// <summary>
/// Returns true if the specified element begins and ends within the range.
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
private bool isInScope(IHTMLElement e)
{
MarkupPointer p = MarkupServices.CreateMarkupPointer(e, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
if (p.IsRightOfOrEqualTo(Start))
{
p = MarkupServices.CreateMarkupPointer(e, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
if (p.IsLeftOfOrEqualTo(End))
{
return true;
}
}
return false;
}
/// <summary>
/// Deletes (unsafely!) content within a range and repositions the range at a new position.
/// </summary>
/// <param name="range"></param>
/// <param name="newPosition"></param>
private void deleteRangeContentAndMoveToPosition(MarkupRange range, MarkupPointer newPosition)
{
MarkupServices.Remove(range.Start, range.End);
range.Start.MoveToPointer(newPosition);
range.End.MoveToPointer(newPosition);
}
#endregion
/// <summary>
/// Returns null if ranges do not intersect
/// </summary>
/// <param name="range"></param>
/// <returns></returns>
public MarkupRange Intersect(MarkupRange range)
{
MarkupPointer maxStart = Start.IsRightOf(range.Start) ? Start : range.Start;
MarkupPointer minEnd = End.IsLeftOf(range.End) ? End : range.End;
if (minEnd.IsLeftOf(maxStart))
return null;
MarkupRange intersection = MarkupServices.CreateMarkupRange();
intersection.Start.MoveToPointer(maxStart);
intersection.End.MoveToPointer(minEnd);
return intersection;
}
public void ExpandToInclude(MarkupRange range)
{
if (range == null)
return;
if (Positioned)
{
if (range.Start.IsLeftOf(Start))
Start.MoveToPointer(range.Start);
if (range.End.IsRightOf(End))
End.MoveToPointer(range.End);
}
else
MoveToRange(range);
}
/// <summary>
/// Determines if a range has a particular _ELEMENT_TAG_ID applied.
/// </summary>
/// <param name="tagId"></param>
/// <param name="partially">If true, then IsTagId will return true if any part of it is contained within a tagId element.
/// If false, then IsTagId will return true only if the range is entirely contained within a tagId element.</param>
/// <returns></returns>
public bool IsTagId(_ELEMENT_TAG_ID tagId, bool partially)
{
// This first block of code will return true if the range is entirely contained within an element with the given tagId.
IHTMLElement currentElement = ParentElement();
while (currentElement != null)
{
if (MarkupServices.GetElementTagId(currentElement) == tagId)
return true;
currentElement = currentElement.parentElement;
}
// This second block of code will return true if the range is partially contained within an element with the given tagId.
if (partially)
{
IHTMLElement[] elements = GetElements(ElementFilters.CreateTagIdFilter(MarkupServices.GetNameForTagId(tagId)), false);
return elements.Length > 0;
}
return false;
}
public void RemoveElementsByTagId(_ELEMENT_TAG_ID tagId, bool onlyIfNoAttributes)
{
if (tagId == _ELEMENT_TAG_ID.TAGID_NULL)
return;
// Remove the tagId up the parent chain
IHTMLElement currentElement = ParentElement();
while (currentElement != null)
{
if (MarkupServices.GetElementTagId(currentElement) == tagId &&
(!onlyIfNoAttributes || !HTMLElementHelper.HasMeaningfulAttributes(currentElement)))
{
try
{
MarkupServices.RemoveElement(currentElement);
}
catch (COMException e)
{
Trace.Fail(String.Format("Failed to remove element ({0}) with error: {1}",
currentElement.outerHTML, // {0}
e // {1}
));
}
}
currentElement = currentElement.parentElement;
}
// Remove any other instances
IHTMLElement[] elements =
GetElements(ElementFilters.CreateTagIdFilter(MarkupServices.GetNameForTagId(tagId)), false);
foreach (IHTMLElement e in elements)
{
if (MarkupServices.GetElementTagId(e) == tagId &&
(!onlyIfNoAttributes || !HTMLElementHelper.HasMeaningfulAttributes(e)))
{
try
{
MarkupServices.RemoveElement(e);
}
catch (COMException ex)
{
Trace.Fail(String.Format("Failed to remove element ({0}) with error: {1}",
e.outerHTML, // {0}
ex // {1}
));
}
}
}
}
public void EnsureStartIsBeforeEnd()
{
if (Start.IsRightOf(End))
{
MarkupPointer temp = End.Clone();
End = Start.Clone();
Start = temp;
}
}
private MarkupPointer GetFirstTextPoint(MarkupPointer from, bool forward)
{
MarkupPointer firstTextPoint = from.Clone();
MarkupContext context = new MarkupContext();
bool keepLooking = true;
do
{
if (forward)
firstTextPoint.Right(false, context);
else
firstTextPoint.Left(false, context);
if (context.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_Text)
break;
if (forward)
{
firstTextPoint.Right(true, context);
keepLooking = context.Element != null && firstTextPoint.IsLeftOf(End);
}
else
{
firstTextPoint.Left(true, context);
keepLooking = context.Element != null && firstTextPoint.IsRightOf(Start);
}
} while (keepLooking);
return firstTextPoint;
}
/// <summary>
/// Shrinks the range until further shrinking would exclude text that is currently in the range.
/// </summary>
public void SelectInner()
{
// Without this check, the start pointer can move outside
// of the current container tag (e.g. ...text...|</p> => </p>|)
if (IsEmpty())
return;
EnsureStartIsBeforeEnd();
// Move the start until you hit text
MarkupPointer innerStart = GetFirstTextPoint(Start, true);
MarkupPointer innerEnd = GetFirstTextPoint(End, false);
Start = innerStart;
End = innerEnd;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Linq;
using System.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
[KnownFailure]
public class ReadBufferSize_Property : PortsTest
{
private const int MAX_RANDOM_BUFFER_SIZE = 1024 * 16;
private const int LARGE_BUFFER_SIZE = 1024 * 128;
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadBufferSize_Default()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default ReadBufferSize before Open");
serPortProp.SetAllPropertiesToDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
serPortProp.VerifyPropertiesAndPrint(com1);
Debug.WriteLine("Verifying default ReadBufferSize after Open");
com1.Open();
serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
serPortProp.VerifyPropertiesAndPrint(com1);
Debug.WriteLine("Verifying default ReadBufferSize after Close");
com1.Close();
serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void ReadBufferSize_AfterOpen()
{
VerifyException(1024, null, typeof(InvalidOperationException));
}
[ConditionalFact(nameof(HasNullModem))]
public void ReadBufferSize_NEG1()
{
VerifyException(-1, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasNullModem))]
public void ReadBufferSize_Int32MinValue()
{
VerifyException(int.MinValue, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasNullModem))]
public void ReadBufferSize_0()
{
VerifyException(0, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasNullModem))]
public void ReadBufferSize_1()
{
Debug.WriteLine("Verifying setting ReadBufferSize=1");
VerifyException(1, typeof(IOException), typeof(InvalidOperationException), true);
}
[ConditionalFact(nameof(HasNullModem))]
public void ReadBufferSize_2()
{
Debug.WriteLine("Verifying setting ReadBufferSize=");
VerifyReadBufferSize(2);
}
[ConditionalFact(nameof(HasNullModem))]
public void ReadBufferSize_Smaller()
{
using (var com = new SerialPort())
{
uint newReadBufferSize = (uint)com.ReadBufferSize;
newReadBufferSize /= 2; //Make the new buffer size half the original size
newReadBufferSize &= 0xFFFFFFFE; //Make sure the new buffer size is even by clearing the lowest order bit
VerifyReadBufferSize((int)newReadBufferSize);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void ReadBufferSize_Larger()
{
VerifyReadBufferSize(((new SerialPort()).ReadBufferSize) * 2);
}
[ConditionalFact(nameof(HasNullModem))]
public void ReadBufferSize_Odd()
{
Debug.WriteLine("Verifying setting ReadBufferSize=Odd");
VerifyException(((new SerialPort()).ReadBufferSize) * 2 + 1, typeof(IOException), typeof(InvalidOperationException), true);
}
[ConditionalFact(nameof(HasNullModem))]
public void ReadBufferSize_Even()
{
Debug.WriteLine("Verifying setting ReadBufferSize=Even");
VerifyReadBufferSize(((new SerialPort()).ReadBufferSize) * 2);
}
[ConditionalFact(nameof(HasNullModem))]
public void ReadBufferSize_Rnd()
{
Random rndGen = new Random(-55);
uint newReadBufferSize = (uint)rndGen.Next(MAX_RANDOM_BUFFER_SIZE);
newReadBufferSize &= 0xFFFFFFFE; //Make sure the new buffer size is even by clearing the lowest order bit
// if(!VerifyReadBufferSize((int)newReadBufferSize)){
VerifyReadBufferSize(11620);
}
[ConditionalFact(nameof(HasNullModem))]
public void ReadBufferSize_Large()
{
VerifyReadBufferSize(LARGE_BUFFER_SIZE);
}
#endregion
#region Verification for Test Cases
private void VerifyException(int newReadBufferSize, Type expectedExceptionBeforeOpen, Type expectedExceptionAfterOpen)
{
VerifyException(newReadBufferSize, expectedExceptionBeforeOpen, expectedExceptionAfterOpen, false);
}
private void VerifyException(int newReadBufferSize, Type expectedExceptionBeforeOpen, Type expectedExceptionAfterOpen, bool throwAtOpen)
{
VerifyExceptionBeforeOpen(newReadBufferSize, expectedExceptionBeforeOpen, throwAtOpen);
VerifyExceptionAfterOpen(newReadBufferSize, expectedExceptionAfterOpen);
}
private void VerifyExceptionBeforeOpen(int newReadBufferSize, Type expectedException, bool throwAtOpen)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
try
{
com.ReadBufferSize = newReadBufferSize;
if (throwAtOpen)
com.Open();
if (null != expectedException)
{
Fail("Err_707278ahpa!!! expected exception {0} and nothing was thrown", expectedException);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("Err_201890ioyun Expected no exception to be thrown and following was thrown \n{0}", e);
}
else if (e.GetType() != expectedException)
{
Fail("Err_545498ahpba!!! expected exception {0} and {1} was thrown", expectedException, e.GetType());
}
}
}
}
private void VerifyExceptionAfterOpen(int newReadBufferSize, Type expectedException)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
int originalReadBufferSize = com.ReadBufferSize;
com.Open();
try
{
com.ReadBufferSize = newReadBufferSize;
Fail("Err_561567anhbp!!! expected exception {0} and nothing was thrown", expectedException);
}
catch (Exception e)
{
if (e.GetType() != expectedException)
{
Fail("Err_21288ajpbam!!! expected exception {0} and {1} was thrown", expectedException, e.GetType());
}
else if (originalReadBufferSize != com.ReadBufferSize)
{
Fail("Err_454987ahbopa!!! expected ReadBufferSize={0} and actual={1}", originalReadBufferSize, com.ReadBufferSize);
}
VerifyReadBufferSize(com);
}
}
}
private void VerifyReadBufferSize(int newReadBufferSize)
{
Debug.WriteLine("Verifying setting ReadBufferSize={0} BEFORE a call to Open() has been made", newReadBufferSize);
VerifyReadBufferSizeBeforeOpen(newReadBufferSize);
}
private void VerifyReadBufferSizeBeforeOpen(int newReadBufferSize)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
byte[] xmitBytes = new byte[newReadBufferSize];
byte[] rcvBytes;
SerialPortProperties serPortProp = new SerialPortProperties();
Random rndGen = new Random(-55);
int newBytesToRead;
for (int i = 0; i < xmitBytes.Length; i++)
{
xmitBytes[i] = (byte)rndGen.Next(0, 256);
}
if (newReadBufferSize < 4096)
newBytesToRead = Math.Min(4096, xmitBytes.Length + (xmitBytes.Length / 2));
else
newBytesToRead = Math.Min(newReadBufferSize, xmitBytes.Length);
rcvBytes = new byte[newBytesToRead];
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.ReadBufferSize = newReadBufferSize;
serPortProp.SetProperty("ReadBufferSize", newReadBufferSize);
com1.Open();
com2.Open();
int origBaudRate = com1.BaudRate;
com2.BaudRate = 115200;
com1.BaudRate = 115200;
for (int j = 0; j < 1; j++)
{
com2.Write(xmitBytes, 0, xmitBytes.Length);
com2.Write(xmitBytes, xmitBytes.Length / 2, xmitBytes.Length / 2);
TCSupport.WaitForReadBufferToLoad(com1, newBytesToRead);
Thread.Sleep(250);
//This is to wait for the bytes to be received after the buffer is full
serPortProp.SetProperty("BytesToRead", newBytesToRead);
serPortProp.SetProperty("BaudRate", 115200);
Debug.WriteLine("Verifying properties after bytes have been written");
serPortProp.VerifyPropertiesAndPrint(com1);
com1.Read(rcvBytes, 0, newBytesToRead);
Assert.Equal(xmitBytes.Take(newReadBufferSize), rcvBytes.Take(newReadBufferSize));
Debug.WriteLine("Verifying properties after bytes have been read");
serPortProp.SetProperty("BytesToRead", 0);
serPortProp.VerifyPropertiesAndPrint(com1);
}
com2.Write(xmitBytes, 0, xmitBytes.Length);
com2.Write(xmitBytes, xmitBytes.Length / 2, xmitBytes.Length / 2);
TCSupport.WaitForReadBufferToLoad(com1, newBytesToRead);
serPortProp.SetProperty("BytesToRead", newBytesToRead);
Debug.WriteLine("Verifying properties after writing bytes");
serPortProp.VerifyPropertiesAndPrint(com1);
com2.BaudRate = origBaudRate;
com1.BaudRate = origBaudRate;
}
}
private void VerifyReadBufferSize(SerialPort com1)
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
int readBufferSize = com1.ReadBufferSize;
byte[] xmitBytes = new byte[1024];
SerialPortProperties serPortProp = new SerialPortProperties();
Random rndGen = new Random(-55);
int bytesToRead = readBufferSize < 4096 ? 4096 : readBufferSize;
int origBaudRate = com1.BaudRate;
int origReadTimeout = com1.ReadTimeout;
int bytesRead;
for (int i = 0; i < xmitBytes.Length; i++)
{
xmitBytes[i] = (byte)rndGen.Next(0, 256);
}
//bytesToRead = Math.Min(4096, xmitBytes.Length + (xmitBytes.Length / 2));
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
serPortProp.SetProperty("ReadBufferSize", readBufferSize);
serPortProp.SetProperty("BaudRate", 115200);
com2.Open();
com2.BaudRate = 115200;
com1.BaudRate = 115200;
for (int i = 0; i < bytesToRead / xmitBytes.Length; i++)
{
com2.Write(xmitBytes, 0, xmitBytes.Length);
}
com2.Write(xmitBytes, 0, xmitBytes.Length / 2);
TCSupport.WaitForReadBufferToLoad(com1, bytesToRead);
Thread.Sleep(250); //This is to wait for the bytes to be received after the buffer is full
var rcvBytes = new byte[(int)(bytesToRead * 1.5)];
if (bytesToRead != (bytesRead = com1.Read(rcvBytes, 0, rcvBytes.Length)))
{
Fail("Err_2971ahius Did not read all expected bytes({0}) bytesRead={1} ReadBufferSize={2}", bytesToRead, bytesRead, com1.ReadBufferSize);
}
for (int i = 0; i < bytesToRead; i++)
{
if (rcvBytes[i] != xmitBytes[i % xmitBytes.Length])
{
Fail("Err_70929apba!!!: Expected to read byte {0} actual={1} at {2}", xmitBytes[i % xmitBytes.Length], rcvBytes[i], i);
}
}
serPortProp.SetProperty("BytesToRead", 0);
serPortProp.VerifyPropertiesAndPrint(com1);
com1.ReadTimeout = 250;
// "Err_1707ahspb!!!: After reading all bytes from buffer ReadByte() did not timeout");
Assert.Throws<TimeoutException>(() => com1.ReadByte());
com1.ReadTimeout = origReadTimeout;
}
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public enum ActorStates
{
Grounded = 0,
Jumping,
Rolling
}
public class ActorPhysics : ActorComponent
{
ActorStates currentState = ActorStates.Jumping;
delegate void ActorStateMethod();
ActorStateMethod CurrentStateMethod;
Dictionary<ActorStates, ActorStateMethod> stateMethodMap = new Dictionary<ActorStates, ActorStateMethod>();
// Movement
[SerializeField] float maxSpeed = 40f;
[SerializeField] float groundedMoveSpeed = 8.5f;
[SerializeField] float jumpMoveSpeed = 8.5f;
[SerializeField] float rollMoveSpeed = 6f;
public float moveSpeedMod = 1f;
Vector3 lastVelocity = Vector3.zero;
Vector3 inputVec = Vector3.zero;
Vector3 moveVec = Vector3.zero;
[Range (0.001f, 1000f)][SerializeField] float stoppingSpeed = 0.001f;
float currStoppingPower = 0.0f;
// Jumping
[SerializeField] float jumpForce = 8.5f;
[SerializeField] float jumpCheckDistance = 1.3f;
[SerializeField] float jumpCheckRadius = 0.7f;
[SerializeField] LayerMask jumpLayer;
[SerializeField] float jumpColCheckTime = 0.5f;
float jumpColCheckTimer = 0.0f;
[SerializeField] float lateJumpTime = 0.2f;
float lateJumpTimer = 0.0f;
[SerializeField] float stopMoveTime = 0.3f;
float stopMoveTimer = 0f;
// Rolling
[SerializeField] float rollTime = 1f;
[SerializeField] float rollCooldownTime = 1f;
float rollCooldownTimer = 0f;
[SerializeField] float rotCorrectionTime = 7f;
[SerializeField] float slideTurnSpeed = 7f;
public Transform model;
Vector3 modelOffset;
void Awake()
{
SetupStateMethodMap();
ChangeState(ActorStates.Grounded);
modelOffset = transform.position - model.position;
currStoppingPower = stoppingSpeed;
}
void SetupStateMethodMap()
{;
stateMethodMap.Add(ActorStates.Jumping, Jumping);
stateMethodMap.Add(ActorStates.Grounded, Grounded);
stateMethodMap.Add(ActorStates.Rolling, Rolling);
}
void Update ()
{
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
CurrentStateMethod();
ModelControl();
}
void Grounded()
{
JumpCheck();
RollCheck();
GroundMovement();
}
void Jumping()
{
JumpCheck();
RollCheck();
JumpMovement();
}
void Rolling()
{
RollCheck();
MoveAtSpeed(inputVec.normalized, rollMoveSpeed);
}
void ChangeState(ActorStates toState)
{
StartCoroutine(ChangeStateRoutine(toState));
}
public bool CanAttack()
{
return !IsInState(ActorStates.Rolling);
}
bool IsInState(ActorStates checkState)
{
return currentState == checkState;
}
IEnumerator ChangeStateRoutine(ActorStates toState)
{
switch(currentState)
{
case ActorStates.Grounded:
break;
default:
break;
}
currentState = toState;
CurrentStateMethod = stateMethodMap[currentState];
yield return 0;
}
// Do temporary state and then return to previous state
void EnterTemporaryState(float waitTime, ActorStates tempState)
{
StartCoroutine(EnterTemporaryStateRoutine(waitTime, tempState, currentState));
}
// Do temporary state and then move on to new state
void EnterTemporaryState(float waitTime, ActorStates tempState, ActorStates endState)
{
StartCoroutine(EnterTemporaryStateRoutine(waitTime, tempState, endState));
}
IEnumerator EnterTemporaryStateRoutine(float waitTime, ActorStates tempState, ActorStates endState)
{
ChangeState(tempState);
yield return new WaitForSeconds(waitTime);
ChangeState(endState);
}
void ComeToStop()
{
currStoppingPower -= Time.deltaTime;
currStoppingPower = Mathf.Clamp(currStoppingPower, 0.0f, stoppingSpeed);
moveVec = lastVelocity * currStoppingPower/stoppingSpeed;
moveVec.y = rigidbody.velocity.y;
rigidbody.velocity = moveVec;
actor.GetAnimator().SetBool("isMoving", false);
if(jumpColCheckTimer > jumpColCheckTime)
{
if(IsInState(ActorStates.Grounded))
{
if(stopMoveTimer >= stopMoveTime)
{
rigidbody.useGravity = false;
SetFallSpeed(0f);
}
stopMoveTimer += Time.deltaTime;
}
else
{
rigidbody.useGravity = true;
}
}
}
void MoveAtSpeed(Vector3 inputVec, float appliedMoveSpeed)
{
rigidbody.useGravity = true;
currStoppingPower = stoppingSpeed;
moveVec = inputVec * appliedMoveSpeed * moveSpeedMod;
moveVec.y = rigidbody.velocity.y;
lastVelocity = moveVec;
rigidbody.velocity = moveVec;
actor.GetAnimator().SetBool("isMoving", true);
}
Vector3 GetInputDirection()
{
Vector3 inputVec = new Vector3(Input.GetAxis("Horizontal" + WadeUtils.platformName), 0.0f, Input.GetAxis("Vertical" + WadeUtils.platformName));
if(actor.GetCamera())
{
inputVec = actor.GetCamera().transform.TransformDirection(inputVec);
inputVec.y = 0f;
}
return inputVec;
}
void SetFallSpeed(float fallSpeed)
{
Vector3 moveVec = rigidbody.velocity;
moveVec.y = fallSpeed;
rigidbody.velocity = moveVec;
}
void GroundMovement()
{
inputVec = GetInputDirection();
if( Mathf.Abs(inputVec.magnitude) < WadeUtils.SMALLNUMBER)
{
ComeToStop();
}
else
{
MoveAtSpeed(inputVec, groundedMoveSpeed);
}
}
void JumpMovement()
{
inputVec = GetInputDirection();
if( Mathf.Abs(inputVec.magnitude) < WadeUtils.SMALLNUMBER)
{
ComeToStop();
}
else
{
currStoppingPower = stoppingSpeed;
moveVec = inputVec * jumpMoveSpeed;
moveVec.y = rigidbody.velocity.y;
lastVelocity = moveVec;
rigidbody.velocity = moveVec;
actor.GetAnimator().SetBool("isMoving", true);
}
}
void RollCheck()
{
if(IsInState(ActorStates.Rolling))
{
if(rollCooldownTimer >= rollTime)
{
ChangeState(ActorStates.Jumping);
actor.GetAnimator().SetBool("isRolling", false);
}
}
else if(Input.GetButtonDown("Roll" + WadeUtils.platformName) &&
rollCooldownTimer >= rollCooldownTime && inputVec.magnitude > WadeUtils.SMALLNUMBER)
{
ChangeState(ActorStates.Rolling);
actor.GetAnimator().SetBool("isRolling", true);
rollCooldownTimer = 0f;
}
rollCooldownTimer += Time.deltaTime;
}
void AttackCheck()
{
}
void JumpCheck()
{
RaycastHit hit;
bool isOnGround = Physics.SphereCast(new Ray(transform.position, -Vector3.up), jumpCheckRadius, out hit, jumpCheckDistance, jumpLayer);
if((isOnGround || lateJumpTimer < lateJumpTime))
{
if(Input.GetButtonDown("Jump" + WadeUtils.platformName))
{
Vector3 curVelocity = rigidbody.velocity;
curVelocity.y = jumpForce;
rigidbody.velocity = curVelocity;
rigidbody.useGravity = true;
jumpColCheckTimer = 0.0f;
//actor.GetAnimator().SetBool("isSliding", false);
}
else if(jumpColCheckTimer > jumpColCheckTime && isOnGround && !IsInState(ActorStates.Rolling))
{
if(!IsInState(ActorStates.Grounded))
{
// if !launching
ChangeState(ActorStates.Grounded);
stopMoveTimer = 0f;
//GainControl();
}
actor.GetAnimator().SetBool("isJumping", false);
//actor.GetAnimator().SetBool("isSliding", false);
lateJumpTimer = 0.0f;
}
}
else if(!IsInState(ActorStates.Jumping) && !IsInState(ActorStates.Rolling)) // if not currently being launched
{
actor.GetAnimator().SetBool("isJumping", true);
//actor.GetAnimator().SetBool("isSliding", false);
ChangeState(ActorStates.Jumping);
}
if(!IsInState(ActorStates.Grounded))
{
jumpColCheckTimer += Time.deltaTime;
}
lateJumpTimer += Time.deltaTime;
rigidbody.velocity = Vector3.ClampMagnitude(rigidbody.velocity, maxSpeed);
}
public bool IsGrabbing()
{
return ((WadeUtils.platformName == "_OSX" && Input.GetAxis("Grab" + WadeUtils.platformName) > WadeUtils.SMALLNUMBER) ||
(WadeUtils.platformName != "_OSX" && Input.GetAxis("Grab" + WadeUtils.platformName) > WadeUtils.SMALLNUMBER));
}
void ModelControl()
{
model.position = transform.position - modelOffset; // this might be important so don't delete it
//transform.position = model.position + modelOffset;
if(Mathf.Abs(Input.GetAxisRaw("Horizontal" + WadeUtils.platformName)) > WadeUtils.SMALLNUMBER || Mathf.Abs(Input.GetAxisRaw("Vertical" + WadeUtils.platformName)) > WadeUtils.SMALLNUMBER)
{
Vector3 lookVec = moveVec;
lookVec.y = 0.0f;
if(lookVec != Vector3.zero)
{
model.rotation = Quaternion.LookRotation(lookVec * 10.0f, transform.up);
}
}
}
void SlideModelControl()
{
model.position = transform.position - modelOffset; // this might be important so don't delete it
Vector3 lookVec = rigidbody.velocity.normalized;
lookVec.y = 0.0f;
if(lookVec != Vector3.zero)
{
model.rotation = Quaternion.Lerp(model.rotation,
Quaternion.LookRotation(lookVec * 10.0f, transform.up),
Time.deltaTime * slideTurnSpeed);
}
}
public void Stop()
{
rigidbody.velocity = Vector3.zero;
}
void OnLandFromLaunch()
{
ChangeState(ActorStates.Grounded);
}
void OnDrawGizmos()
{
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(transform.position + Vector3.up * 0.5f, 0.5f);
Gizmos.DrawWireSphere(transform.position - Vector3.up * 0.5f, 0.5f);
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position - Vector3.up, jumpCheckRadius);
}
}
| |
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using System;
using System.Collections.Generic;
namespace OpenSim.Region.Framework.Scenes
{
#region Delegates
public delegate bool AbandonParcelHandler(UUID user, ILandObject parcel, Scene scene);
public delegate bool BuyLandHandler(UUID user, ILandObject parcel, Scene scene);
public delegate bool BypassPermissionsHandler();
public delegate bool CompileScriptHandler(UUID ownerUUID, int scriptType, Scene scene);
public delegate bool ControlPrimMediaHandler(UUID userID, UUID primID, int face);
public delegate bool CopyObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID);
public delegate bool CopyUserInventoryHandler(UUID itemID, UUID userID);
public delegate bool CreateObjectInventoryHandler(int invType, UUID objectID, UUID userID);
public delegate bool CreateUserInventoryHandler(int invType, UUID userID);
public delegate bool DeedObjectHandler(UUID user, UUID group, Scene scene);
public delegate bool DeedParcelHandler(UUID user, ILandObject parcel, Scene scene);
public delegate bool DeleteObjectHandler(UUID objectID, UUID deleter, Scene scene);
public delegate bool DeleteObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID);
public delegate bool DeleteUserInventoryHandler(UUID itemID, UUID userID);
public delegate bool DelinkObjectHandler(UUID user, UUID objectID);
public delegate bool DuplicateObjectHandler(int objectCount, UUID objectID, UUID owner, Scene scene, Vector3 objectPosition);
public delegate bool EditNotecardHandler(UUID notecard, UUID objectID, UUID user, Scene scene);
public delegate bool EditObjectHandler(UUID objectID, UUID editorID, Scene scene);
public delegate bool EditObjectInventoryHandler(UUID objectID, UUID editorID, Scene scene);
public delegate bool EditParcelHandler(UUID user, ILandObject parcel, Scene scene);
public delegate bool EditParcelPropertiesHandler(UUID user, ILandObject parcel, GroupPowers p, Scene scene);
public delegate bool EditScriptHandler(UUID script, UUID objectID, UUID user, Scene scene);
public delegate bool EditUserInventoryHandler(UUID itemID, UUID userID);
public delegate uint GenerateClientFlagsHandler(UUID userID, UUID objectID);
public delegate bool InstantMessageHandler(UUID user, UUID target, Scene startScene);
public delegate bool InteractWithPrimMediaHandler(UUID userID, UUID primID, int face);
public delegate bool InventoryTransferHandler(UUID user, UUID target, Scene startScene);
public delegate bool IsAdministratorHandler(UUID user);
public delegate bool IsGodHandler(UUID user, Scene requestFromScene);
public delegate bool IsGridGodHandler(UUID user, Scene requestFromScene);
public delegate bool IssueEstateCommandHandler(UUID user, Scene requestFromScene, bool ownerCommand);
public delegate bool LinkObjectHandler(UUID user, UUID objectID);
public delegate bool MoveObjectHandler(UUID objectID, UUID moverID, Scene scene);
public delegate bool ObjectEntryHandler(UUID objectID, bool enteringRegion, Vector3 newPoint, Scene scene);
public delegate bool PropagatePermissionsHandler();
public delegate bool ReclaimParcelHandler(UUID user, ILandObject parcel, Scene scene);
public delegate bool ResetScriptHandler(UUID prim, UUID script, UUID user, Scene scene);
public delegate bool ReturnObjectsHandler(ILandObject land, UUID user, List<SceneObjectGroup> objects, Scene scene);
public delegate bool RezObjectHandler(int objectCount, UUID owner, Vector3 objectPosition, Scene scene);
public delegate bool RunConsoleCommandHandler(UUID user, Scene requestFromScene);
public delegate bool RunScriptHandler(UUID script, UUID objectID, UUID user, Scene scene);
public delegate bool SellParcelHandler(UUID user, ILandObject parcel, Scene scene);
public delegate void SetBypassPermissionsHandler(bool value);
public delegate bool StartScriptHandler(UUID script, UUID user, Scene scene);
public delegate bool StopScriptHandler(UUID script, UUID user, Scene scene);
public delegate bool TakeCopyObjectHandler(UUID objectID, UUID userID, Scene inScene);
public delegate bool TakeObjectHandler(UUID objectID, UUID stealer, Scene scene);
public delegate bool TeleportHandler(UUID userID, Scene scene);
public delegate bool TerraformLandHandler(UUID user, Vector3 position, Scene requestFromScene);
public delegate bool TransferObjectHandler(UUID objectID, UUID recipient, Scene scene);
public delegate bool TransferObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID);
public delegate bool TransferUserInventoryHandler(UUID itemID, UUID userID, UUID recipientID);
public delegate bool ViewNotecardHandler(UUID script, UUID objectID, UUID user, Scene scene);
public delegate bool ViewScriptHandler(UUID script, UUID objectID, UUID user, Scene scene);
#endregion Delegates
public class ScenePermissions
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
public ScenePermissions(Scene scene)
{
m_scene = scene;
}
#region Events
public event AbandonParcelHandler OnAbandonParcel;
public event BuyLandHandler OnBuyLand;
public event BypassPermissionsHandler OnBypassPermissions;
public event CompileScriptHandler OnCompileScript;
public event ControlPrimMediaHandler OnControlPrimMedia;
public event CopyObjectInventoryHandler OnCopyObjectInventory;
public event CopyUserInventoryHandler OnCopyUserInventory;
public event CreateObjectInventoryHandler OnCreateObjectInventory;
public event CreateUserInventoryHandler OnCreateUserInventory;
public event DeedObjectHandler OnDeedObject;
public event DeedParcelHandler OnDeedParcel;
public event DeleteObjectHandler OnDeleteObject;
public event DeleteObjectInventoryHandler OnDeleteObjectInventory;
public event DeleteUserInventoryHandler OnDeleteUserInventory;
public event DelinkObjectHandler OnDelinkObject;
public event DuplicateObjectHandler OnDuplicateObject;
public event EditNotecardHandler OnEditNotecard;
public event EditObjectHandler OnEditObject;
public event EditObjectInventoryHandler OnEditObjectInventory;
// public event EditParcelHandler OnEditParcel;
public event EditParcelPropertiesHandler OnEditParcelProperties;
public event EditScriptHandler OnEditScript;
public event EditUserInventoryHandler OnEditUserInventory;
public event GenerateClientFlagsHandler OnGenerateClientFlags;
public event InstantMessageHandler OnInstantMessage;
public event InteractWithPrimMediaHandler OnInteractWithPrimMedia;
public event InventoryTransferHandler OnInventoryTransfer;
public event IsAdministratorHandler OnIsAdministrator;
public event IsGodHandler OnIsGod;
public event IsGridGodHandler OnIsGridGod;
public event IssueEstateCommandHandler OnIssueEstateCommand;
public event LinkObjectHandler OnLinkObject;
public event MoveObjectHandler OnMoveObject;
public event ObjectEntryHandler OnObjectEntry;
public event PropagatePermissionsHandler OnPropagatePermissions;
public event ReclaimParcelHandler OnReclaimParcel;
public event ResetScriptHandler OnResetScript;
public event ReturnObjectsHandler OnReturnObjects;
public event RezObjectHandler OnRezObject;
public event RunConsoleCommandHandler OnRunConsoleCommand;
public event RunScriptHandler OnRunScript;
public event SellParcelHandler OnSellParcel;
public event SetBypassPermissionsHandler OnSetBypassPermissions;
public event StartScriptHandler OnStartScript;
public event StopScriptHandler OnStopScript;
public event TakeCopyObjectHandler OnTakeCopyObject;
public event TakeObjectHandler OnTakeObject;
public event TeleportHandler OnTeleport;
public event TerraformLandHandler OnTerraformLand;
public event TransferObjectHandler OnTransferObject;
public event TransferObjectInventoryHandler OnTransferObjectInventory;
public event TransferUserInventoryHandler OnTransferUserInventory;
public event ViewNotecardHandler OnViewNotecard;
public event ViewScriptHandler OnViewScript;
#endregion Events
#region Object Permission Checks
public bool BypassPermissions()
{
BypassPermissionsHandler handler = OnBypassPermissions;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (BypassPermissionsHandler h in list)
{
if (h() == false)
return false;
}
}
return true;
}
public bool CanBuyLand(UUID user, ILandObject parcel)
{
BuyLandHandler handler = OnBuyLand;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (BuyLandHandler h in list)
{
if (h(user, parcel, m_scene) == false)
return false;
}
}
return true;
}
public bool CanDeedObject(UUID user, UUID group)
{
DeedObjectHandler handler = OnDeedObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeedObjectHandler h in list)
{
if (h(user, group, m_scene) == false)
return false;
}
}
return true;
}
public bool CanDeedParcel(UUID user, ILandObject parcel)
{
DeedParcelHandler handler = OnDeedParcel;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeedParcelHandler h in list)
{
if (h(user, parcel, m_scene) == false)
return false;
}
}
return true;
}
public bool CanDelinkObject(UUID user, UUID objectID)
{
DelinkObjectHandler handler = OnDelinkObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DelinkObjectHandler h in list)
{
if (h(user, objectID) == false)
return false;
}
}
return true;
}
public bool CanLinkObject(UUID user, UUID objectID)
{
LinkObjectHandler handler = OnLinkObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (LinkObjectHandler h in list)
{
if (h(user, objectID) == false)
return false;
}
}
return true;
}
public bool CanReclaimParcel(UUID user, ILandObject parcel)
{
ReclaimParcelHandler handler = OnReclaimParcel;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ReclaimParcelHandler h in list)
{
if (h(user, parcel, m_scene) == false)
return false;
}
}
return true;
}
public uint GenerateClientFlags(UUID userID, UUID objectID)
{
// libomv will moan about PrimFlags.ObjectYouOfficer being
// obsolete...
#pragma warning disable 0612
const PrimFlags DEFAULT_FLAGS =
PrimFlags.ObjectModify |
PrimFlags.ObjectCopy |
PrimFlags.ObjectMove |
PrimFlags.ObjectTransfer |
PrimFlags.ObjectYouOwner |
PrimFlags.ObjectAnyOwner |
PrimFlags.ObjectOwnerModify |
PrimFlags.ObjectYouOfficer;
#pragma warning restore 0612
SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
if (part == null)
return 0;
uint perms = part.GetEffectiveObjectFlags() | (uint)DEFAULT_FLAGS;
GenerateClientFlagsHandler handlerGenerateClientFlags = OnGenerateClientFlags;
if (handlerGenerateClientFlags != null)
{
Delegate[] list = handlerGenerateClientFlags.GetInvocationList();
foreach (GenerateClientFlagsHandler check in list)
{
perms &= check(userID, objectID);
}
}
return perms;
}
public bool PropagatePermissions()
{
PropagatePermissionsHandler handler = OnPropagatePermissions;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (PropagatePermissionsHandler h in list)
{
if (h() == false)
return false;
}
}
return true;
}
public void SetBypassPermissions(bool value)
{
SetBypassPermissionsHandler handler = OnSetBypassPermissions;
if (handler != null)
handler(value);
}
#region REZ OBJECT
public bool CanRezObject(int objectCount, UUID owner, Vector3 objectPosition)
{
RezObjectHandler handler = OnRezObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (RezObjectHandler h in list)
{
if (h(objectCount, owner, objectPosition, m_scene) == false)
return false;
}
}
return true;
}
#endregion REZ OBJECT
#region DELETE OBJECT
public bool CanDeleteObject(UUID objectID, UUID deleter)
{
bool result = true;
DeleteObjectHandler handler = OnDeleteObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeleteObjectHandler h in list)
{
if (h(objectID, deleter, m_scene) == false)
{
result = false;
break;
}
}
}
return result;
}
public bool CanTransferObject(UUID objectID, UUID recipient)
{
bool result = true;
TransferObjectHandler handler = OnTransferObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TransferObjectHandler h in list)
{
if (h(objectID, recipient, m_scene) == false)
{
result = false;
break;
}
}
}
return result;
}
#endregion DELETE OBJECT
#region TAKE OBJECT
public bool CanTakeObject(UUID objectID, UUID AvatarTakingUUID)
{
bool result = true;
TakeObjectHandler handler = OnTakeObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TakeObjectHandler h in list)
{
if (h(objectID, AvatarTakingUUID, m_scene) == false)
{
result = false;
break;
}
}
}
// m_log.DebugFormat(
// "[SCENE PERMISSIONS]: CanTakeObject() fired for object {0}, taker {1}, result {2}",
// objectID, AvatarTakingUUID, result);
return result;
}
#endregion TAKE OBJECT
#region TAKE COPY OBJECT
public bool CanTakeCopyObject(UUID objectID, UUID userID)
{
bool result = true;
TakeCopyObjectHandler handler = OnTakeCopyObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TakeCopyObjectHandler h in list)
{
if (h(objectID, userID, m_scene) == false)
{
result = false;
break;
}
}
}
// m_log.DebugFormat(
// "[SCENE PERMISSIONS]: CanTakeCopyObject() fired for object {0}, user {1}, result {2}",
// objectID, userID, result);
return result;
}
#endregion TAKE COPY OBJECT
#region DUPLICATE OBJECT
public bool CanDuplicateObject(int objectCount, UUID objectID, UUID owner, Vector3 objectPosition)
{
DuplicateObjectHandler handler = OnDuplicateObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DuplicateObjectHandler h in list)
{
if (h(objectCount, objectID, owner, m_scene, objectPosition) == false)
return false;
}
}
return true;
}
#endregion DUPLICATE OBJECT
#region EDIT OBJECT
public bool CanEditObject(UUID objectID, UUID editorID)
{
EditObjectHandler handler = OnEditObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditObjectHandler h in list)
{
if (h(objectID, editorID, m_scene) == false)
return false;
}
}
return true;
}
public bool CanEditObjectInventory(UUID objectID, UUID editorID)
{
EditObjectInventoryHandler handler = OnEditObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditObjectInventoryHandler h in list)
{
if (h(objectID, editorID, m_scene) == false)
return false;
}
}
return true;
}
#endregion EDIT OBJECT
#region MOVE OBJECT
public bool CanMoveObject(UUID objectID, UUID moverID)
{
MoveObjectHandler handler = OnMoveObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (MoveObjectHandler h in list)
{
if (h(objectID, moverID, m_scene) == false)
return false;
}
}
return true;
}
#endregion MOVE OBJECT
#region OBJECT ENTRY
public bool CanObjectEntry(UUID objectID, bool enteringRegion, Vector3 newPoint)
{
ObjectEntryHandler handler = OnObjectEntry;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ObjectEntryHandler h in list)
{
if (h(objectID, enteringRegion, newPoint, m_scene) == false)
return false;
}
}
return true;
}
#endregion OBJECT ENTRY
#region RETURN OBJECT
public bool CanReturnObjects(ILandObject land, UUID user, List<SceneObjectGroup> objects)
{
bool result = true;
ReturnObjectsHandler handler = OnReturnObjects;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ReturnObjectsHandler h in list)
{
if (h(land, user, objects, m_scene) == false)
{
result = false;
break;
}
}
}
// m_log.DebugFormat(
// "[SCENE PERMISSIONS]: CanReturnObjects() fired for user {0} for {1} objects on {2}, result {3}",
// user, objects.Count, land.LandData.Name, result);
return result;
}
#endregion RETURN OBJECT
#region INSTANT MESSAGE
public bool CanInstantMessage(UUID user, UUID target)
{
InstantMessageHandler handler = OnInstantMessage;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (InstantMessageHandler h in list)
{
if (h(user, target, m_scene) == false)
return false;
}
}
return true;
}
#endregion INSTANT MESSAGE
#region INVENTORY TRANSFER
public bool CanInventoryTransfer(UUID user, UUID target)
{
InventoryTransferHandler handler = OnInventoryTransfer;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (InventoryTransferHandler h in list)
{
if (h(user, target, m_scene) == false)
return false;
}
}
return true;
}
#endregion INVENTORY TRANSFER
#region VIEW SCRIPT
public bool CanViewNotecard(UUID script, UUID objectID, UUID user)
{
ViewNotecardHandler handler = OnViewNotecard;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ViewNotecardHandler h in list)
{
if (h(script, objectID, user, m_scene) == false)
return false;
}
}
return true;
}
public bool CanViewScript(UUID script, UUID objectID, UUID user)
{
ViewScriptHandler handler = OnViewScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ViewScriptHandler h in list)
{
if (h(script, objectID, user, m_scene) == false)
return false;
}
}
return true;
}
#endregion VIEW SCRIPT
#region EDIT SCRIPT
public bool CanEditNotecard(UUID script, UUID objectID, UUID user)
{
EditNotecardHandler handler = OnEditNotecard;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditNotecardHandler h in list)
{
if (h(script, objectID, user, m_scene) == false)
return false;
}
}
return true;
}
public bool CanEditScript(UUID script, UUID objectID, UUID user)
{
EditScriptHandler handler = OnEditScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditScriptHandler h in list)
{
if (h(script, objectID, user, m_scene) == false)
return false;
}
}
return true;
}
#endregion EDIT SCRIPT
#region RUN SCRIPT (When Script Placed in Object)
public bool CanRunScript(UUID script, UUID objectID, UUID user)
{
RunScriptHandler handler = OnRunScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (RunScriptHandler h in list)
{
if (h(script, objectID, user, m_scene) == false)
return false;
}
}
return true;
}
#endregion RUN SCRIPT (When Script Placed in Object)
#region COMPILE SCRIPT (When Script needs to get (re)compiled)
public bool CanCompileScript(UUID ownerUUID, int scriptType)
{
CompileScriptHandler handler = OnCompileScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CompileScriptHandler h in list)
{
if (h(ownerUUID, scriptType, m_scene) == false)
return false;
}
}
return true;
}
#endregion COMPILE SCRIPT (When Script needs to get (re)compiled)
#region START SCRIPT (When Script run box is Checked after placed in object)
public bool CanStartScript(UUID script, UUID user)
{
StartScriptHandler handler = OnStartScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (StartScriptHandler h in list)
{
if (h(script, user, m_scene) == false)
return false;
}
}
return true;
}
#endregion START SCRIPT (When Script run box is Checked after placed in object)
#region STOP SCRIPT (When Script run box is unchecked after placed in object)
public bool CanStopScript(UUID script, UUID user)
{
StopScriptHandler handler = OnStopScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (StopScriptHandler h in list)
{
if (h(script, user, m_scene) == false)
return false;
}
}
return true;
}
#endregion STOP SCRIPT (When Script run box is unchecked after placed in object)
#region RESET SCRIPT
public bool CanResetScript(UUID prim, UUID script, UUID user)
{
ResetScriptHandler handler = OnResetScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ResetScriptHandler h in list)
{
if (h(prim, script, user, m_scene) == false)
return false;
}
}
return true;
}
#endregion RESET SCRIPT
#region TERRAFORM LAND
public bool CanTerraformLand(UUID user, Vector3 pos)
{
TerraformLandHandler handler = OnTerraformLand;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TerraformLandHandler h in list)
{
if (h(user, pos, m_scene) == false)
return false;
}
}
return true;
}
#endregion TERRAFORM LAND
#region RUN CONSOLE COMMAND
public bool CanRunConsoleCommand(UUID user)
{
RunConsoleCommandHandler handler = OnRunConsoleCommand;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (RunConsoleCommandHandler h in list)
{
if (h(user, m_scene) == false)
return false;
}
}
return true;
}
#endregion RUN CONSOLE COMMAND
#region CAN ISSUE ESTATE COMMAND
public bool CanIssueEstateCommand(UUID user, bool ownerCommand)
{
IssueEstateCommandHandler handler = OnIssueEstateCommand;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (IssueEstateCommandHandler h in list)
{
if (h(user, m_scene, ownerCommand) == false)
return false;
}
}
return true;
}
#endregion CAN ISSUE ESTATE COMMAND
#region CAN BE GODLIKE
public bool IsAdministrator(UUID user)
{
IsAdministratorHandler handler = OnIsAdministrator;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (IsAdministratorHandler h in list)
{
if (h(user) == false)
return false;
}
}
return true;
}
public bool IsGod(UUID user)
{
IsGodHandler handler = OnIsGod;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (IsGodHandler h in list)
{
if (h(user, m_scene) == false)
return false;
}
}
return true;
}
public bool IsGridGod(UUID user)
{
IsGridGodHandler handler = OnIsGridGod;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (IsGridGodHandler h in list)
{
if (h(user, m_scene) == false)
return false;
}
}
return true;
}
#endregion CAN BE GODLIKE
#region EDIT PARCEL
public bool CanEditParcelProperties(UUID user, ILandObject parcel, GroupPowers p)
{
EditParcelPropertiesHandler handler = OnEditParcelProperties;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditParcelPropertiesHandler h in list)
{
if (h(user, parcel, p, m_scene) == false)
return false;
}
}
return true;
}
#endregion EDIT PARCEL
#region SELL PARCEL
public bool CanSellParcel(UUID user, ILandObject parcel)
{
SellParcelHandler handler = OnSellParcel;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (SellParcelHandler h in list)
{
if (h(user, parcel, m_scene) == false)
return false;
}
}
return true;
}
#endregion SELL PARCEL
#region ABANDON PARCEL
public bool CanAbandonParcel(UUID user, ILandObject parcel)
{
AbandonParcelHandler handler = OnAbandonParcel;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (AbandonParcelHandler h in list)
{
if (h(user, parcel, m_scene) == false)
return false;
}
}
return true;
}
#endregion ABANDON PARCEL
#endregion Object Permission Checks
public bool CanControlPrimMedia(UUID userID, UUID primID, int face)
{
ControlPrimMediaHandler handler = OnControlPrimMedia;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ControlPrimMediaHandler h in list)
{
if (h(userID, primID, face) == false)
return false;
}
}
return true;
}
public bool CanCopyObjectInventory(UUID itemID, UUID objectID, UUID userID)
{
CopyObjectInventoryHandler handler = OnCopyObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CopyObjectInventoryHandler h in list)
{
if (h(itemID, objectID, userID) == false)
return false;
}
}
return true;
}
/// <summary>
/// Check whether the specified user is allowed to copy the given inventory item from their own inventory.
/// </summary>
/// <param name="itemID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanCopyUserInventory(UUID itemID, UUID userID)
{
CopyUserInventoryHandler handler = OnCopyUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CopyUserInventoryHandler h in list)
{
if (h(itemID, userID) == false)
return false;
}
}
return true;
}
/// Check whether the specified user is allowed to directly create the given inventory type in a prim's
/// inventory (e.g. the New Script button in the 1.21 Linden Lab client).
/// </summary>
/// <param name="invType"></param>
/// <param name="objectID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanCreateObjectInventory(int invType, UUID objectID, UUID userID)
{
CreateObjectInventoryHandler handler = OnCreateObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CreateObjectInventoryHandler h in list)
{
if (h(invType, objectID, userID) == false)
return false;
}
}
return true;
}
/// <summary>
/// Check whether the specified user is allowed to create the given inventory type in their inventory.
/// </summary>
/// <param name="invType"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanCreateUserInventory(int invType, UUID userID)
{
CreateUserInventoryHandler handler = OnCreateUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CreateUserInventoryHandler h in list)
{
if (h(invType, userID) == false)
return false;
}
}
return true;
}
public bool CanDeleteObjectInventory(UUID itemID, UUID objectID, UUID userID)
{
DeleteObjectInventoryHandler handler = OnDeleteObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeleteObjectInventoryHandler h in list)
{
if (h(itemID, objectID, userID) == false)
return false;
}
}
return true;
}
/// <summary>
/// Check whether the specified user is allowed to edit the given inventory item within their own inventory.
/// </summary>
/// <param name="itemID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanDeleteUserInventory(UUID itemID, UUID userID)
{
DeleteUserInventoryHandler handler = OnDeleteUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeleteUserInventoryHandler h in list)
{
if (h(itemID, userID) == false)
return false;
}
}
return true;
}
/// <summary>
/// Check whether the specified user is allowed to edit the given inventory item within their own inventory.
/// </summary>
/// <param name="itemID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanEditUserInventory(UUID itemID, UUID userID)
{
EditUserInventoryHandler handler = OnEditUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditUserInventoryHandler h in list)
{
if (h(itemID, userID) == false)
return false;
}
}
return true;
}
public bool CanInteractWithPrimMedia(UUID userID, UUID primID, int face)
{
InteractWithPrimMediaHandler handler = OnInteractWithPrimMedia;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (InteractWithPrimMediaHandler h in list)
{
if (h(userID, primID, face) == false)
return false;
}
}
return true;
}
public bool CanTeleport(UUID userID)
{
TeleportHandler handler = OnTeleport;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TeleportHandler h in list)
{
if (h(userID, m_scene) == false)
return false;
}
}
return true;
}
public bool CanTransferObjectInventory(UUID itemID, UUID objectID, UUID userID)
{
TransferObjectInventoryHandler handler = OnTransferObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TransferObjectInventoryHandler h in list)
{
if (h(itemID, objectID, userID) == false)
return false;
}
}
return true;
}
public bool CanTransferUserInventory(UUID itemID, UUID userID, UUID recipientID)
{
TransferUserInventoryHandler handler = OnTransferUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TransferUserInventoryHandler h in list)
{
if (h(itemID, userID, recipientID) == false)
return false;
}
}
return true;
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
namespace Boggle2
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private IContainer components;
private FormHelp FormHelp1;
private FormAbout FormAbout1;
private MainMenu MainMenu;
private MenuItem Menu10Item;
private MenuItem Menu11Item;
private MenuItem MenuBar1;
private MenuItem Menu12Item;
private MenuItem Menu20Item;
private MenuItem Menu21Item;
private MenuItem MenuBar2;
private MenuItem Menu22Item;
private TextBox AnswerBox;
private Label BogLbl;
private TextBox Loc00Box;
private TextBox Loc01Box;
private TextBox Loc02Box;
private TextBox Loc03Box;
private TextBox Loc10Box;
private TextBox Loc11Box;
private TextBox Loc12Box;
private TextBox Loc13Box;
private TextBox Loc20Box;
private TextBox Loc21Box;
private TextBox Loc22Box;
private TextBox Loc23Box;
private TextBox Loc30Box;
private TextBox Loc31Box;
private TextBox Loc32Box;
private TextBox Loc33Box;
private Button RandBtn;
private Button DispAllBtn;
private GroupBox LengthGrp;
private TextBox MinBox;
private TextBox MaxBox;
private Label MinLbl;
private Label MaxLbl;
private string[] Dictionary;
private char[,] Block;
private TextBox[,] BoggleSquare;
private int Min;
private int Max;
private ArrayList Answers;
private char[,] Dice;
private Random rdm;
private bool MaxMinAllowEntry;
private Point TextBoxCornerPoint;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
FormHelp1 = new FormHelp();
FormAbout1 = new FormAbout();
BoggleSquare = new TextBox[,]
{
{Loc00Box, Loc10Box, Loc20Box, Loc30Box},
{Loc01Box, Loc11Box, Loc21Box, Loc31Box},
{Loc02Box, Loc12Box, Loc22Box, Loc32Box},
{Loc03Box, Loc13Box, Loc23Box, Loc33Box}
};
Dice = new char[16,6]
{
{'R', 'L', 'T', 'Y', 'E', 'T'},
{'D', 'E', 'R', 'X', 'L', 'I'},
{'F', 'A', 'K', 'P', 'S', 'F'},
{'Q', 'I', 'M', 'N', 'H', 'U'},
{'T', 'T', 'A', 'O', 'O', 'W'},
{'D', 'I', 'Y', 'S', 'T', 'T'},
{'B', 'O', 'B', 'A', 'J', 'O'},
{'N', 'E', 'I', 'S', 'E', 'U'},
{'L', 'V', 'E', 'R', 'D', 'Y'},
{'P', 'C', 'H', 'O', 'A', 'S'},
{'W', 'H', 'E', 'V', 'T', 'R'},
{'E', 'A', 'G', 'A', 'N', 'E'},
{'E', 'S', 'T', 'I', 'S', 'O'},
{'T', 'C', 'I', 'U', 'O', 'M'},
{'R', 'N', 'Z', 'N', 'L', 'H'},
{'N', 'E', 'E', 'H', 'W', 'G'}
};
rdm = new Random();
LoadDictionary();
Answers = new ArrayList();
TextBoxCornerPoint = new Point(AnswerBox.Width - 5, AnswerBox.Height - 20);
foreach(TextBox s in BoggleSquare)
{
s.KeyPress += new KeyPressEventHandler(s_KeyPress);
s.Enter +=new EventHandler(s_Enter);
s.Click +=new EventHandler(s_Click);
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.AnswerBox = new System.Windows.Forms.TextBox();
this.BogLbl = new System.Windows.Forms.Label();
this.RandBtn = new System.Windows.Forms.Button();
this.Loc13Box = new System.Windows.Forms.TextBox();
this.Loc12Box = new System.Windows.Forms.TextBox();
this.Loc11Box = new System.Windows.Forms.TextBox();
this.Loc10Box = new System.Windows.Forms.TextBox();
this.Loc23Box = new System.Windows.Forms.TextBox();
this.Loc22Box = new System.Windows.Forms.TextBox();
this.Loc21Box = new System.Windows.Forms.TextBox();
this.Loc20Box = new System.Windows.Forms.TextBox();
this.Loc33Box = new System.Windows.Forms.TextBox();
this.Loc32Box = new System.Windows.Forms.TextBox();
this.Loc31Box = new System.Windows.Forms.TextBox();
this.Loc30Box = new System.Windows.Forms.TextBox();
this.Loc03Box = new System.Windows.Forms.TextBox();
this.Loc02Box = new System.Windows.Forms.TextBox();
this.Loc01Box = new System.Windows.Forms.TextBox();
this.Loc00Box = new System.Windows.Forms.TextBox();
this.DispAllBtn = new System.Windows.Forms.Button();
this.MinBox = new System.Windows.Forms.TextBox();
this.MaxBox = new System.Windows.Forms.TextBox();
this.MinLbl = new System.Windows.Forms.Label();
this.MaxLbl = new System.Windows.Forms.Label();
this.LengthGrp = new System.Windows.Forms.GroupBox();
this.MainMenu = new System.Windows.Forms.MainMenu(this.components);
this.Menu10Item = new System.Windows.Forms.MenuItem();
this.Menu11Item = new System.Windows.Forms.MenuItem();
this.MenuBar1 = new System.Windows.Forms.MenuItem();
this.Menu12Item = new System.Windows.Forms.MenuItem();
this.Menu20Item = new System.Windows.Forms.MenuItem();
this.Menu21Item = new System.Windows.Forms.MenuItem();
this.MenuBar2 = new System.Windows.Forms.MenuItem();
this.Menu22Item = new System.Windows.Forms.MenuItem();
this.LengthGrp.SuspendLayout();
this.SuspendLayout();
//
// AnswerBox
//
this.AnswerBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.AnswerBox.Location = new System.Drawing.Point(240, 8);
this.AnswerBox.Multiline = true;
this.AnswerBox.Name = "AnswerBox";
this.AnswerBox.Size = new System.Drawing.Size(280, 400);
this.AnswerBox.TabIndex = 21;
//
// BogLbl
//
this.BogLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.BogLbl.Location = new System.Drawing.Point(44, 25);
this.BogLbl.Name = "BogLbl";
this.BogLbl.Size = new System.Drawing.Size(113, 21);
this.BogLbl.TabIndex = 57;
this.BogLbl.Text = "Boggle Square";
this.BogLbl.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// RandBtn
//
this.RandBtn.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.RandBtn.Location = new System.Drawing.Point(60, 160);
this.RandBtn.Name = "RandBtn";
this.RandBtn.Size = new System.Drawing.Size(87, 24);
this.RandBtn.TabIndex = 17;
this.RandBtn.Text = "Randomize";
this.RandBtn.Click += new System.EventHandler(this.RandBtn_Click);
//
// Loc13Box
//
this.Loc13Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc13Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc13Box.Location = new System.Drawing.Point(140, 76);
this.Loc13Box.MaxLength = 1;
this.Loc13Box.Name = "Loc13Box";
this.Loc13Box.Size = new System.Drawing.Size(27, 20);
this.Loc13Box.TabIndex = 8;
this.Loc13Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc12Box
//
this.Loc12Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc12Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc12Box.Location = new System.Drawing.Point(107, 76);
this.Loc12Box.MaxLength = 1;
this.Loc12Box.Name = "Loc12Box";
this.Loc12Box.Size = new System.Drawing.Size(26, 20);
this.Loc12Box.TabIndex = 7;
this.Loc12Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc11Box
//
this.Loc11Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc11Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc11Box.Location = new System.Drawing.Point(73, 76);
this.Loc11Box.MaxLength = 1;
this.Loc11Box.Name = "Loc11Box";
this.Loc11Box.Size = new System.Drawing.Size(27, 20);
this.Loc11Box.TabIndex = 6;
this.Loc11Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc10Box
//
this.Loc10Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc10Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc10Box.Location = new System.Drawing.Point(40, 76);
this.Loc10Box.MaxLength = 1;
this.Loc10Box.Name = "Loc10Box";
this.Loc10Box.Size = new System.Drawing.Size(27, 20);
this.Loc10Box.TabIndex = 5;
this.Loc10Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc23Box
//
this.Loc23Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc23Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc23Box.Location = new System.Drawing.Point(140, 104);
this.Loc23Box.MaxLength = 1;
this.Loc23Box.Name = "Loc23Box";
this.Loc23Box.Size = new System.Drawing.Size(27, 20);
this.Loc23Box.TabIndex = 12;
this.Loc23Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc22Box
//
this.Loc22Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc22Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc22Box.Location = new System.Drawing.Point(107, 104);
this.Loc22Box.MaxLength = 1;
this.Loc22Box.Name = "Loc22Box";
this.Loc22Box.Size = new System.Drawing.Size(26, 20);
this.Loc22Box.TabIndex = 11;
this.Loc22Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc21Box
//
this.Loc21Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc21Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc21Box.Location = new System.Drawing.Point(73, 104);
this.Loc21Box.MaxLength = 1;
this.Loc21Box.Name = "Loc21Box";
this.Loc21Box.Size = new System.Drawing.Size(27, 20);
this.Loc21Box.TabIndex = 10;
this.Loc21Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc20Box
//
this.Loc20Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc20Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc20Box.Location = new System.Drawing.Point(40, 104);
this.Loc20Box.MaxLength = 1;
this.Loc20Box.Name = "Loc20Box";
this.Loc20Box.Size = new System.Drawing.Size(27, 20);
this.Loc20Box.TabIndex = 9;
this.Loc20Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc33Box
//
this.Loc33Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc33Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc33Box.Location = new System.Drawing.Point(140, 132);
this.Loc33Box.MaxLength = 1;
this.Loc33Box.Name = "Loc33Box";
this.Loc33Box.Size = new System.Drawing.Size(27, 20);
this.Loc33Box.TabIndex = 16;
this.Loc33Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc32Box
//
this.Loc32Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc32Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc32Box.Location = new System.Drawing.Point(107, 132);
this.Loc32Box.MaxLength = 1;
this.Loc32Box.Name = "Loc32Box";
this.Loc32Box.Size = new System.Drawing.Size(26, 20);
this.Loc32Box.TabIndex = 15;
this.Loc32Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc31Box
//
this.Loc31Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc31Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc31Box.Location = new System.Drawing.Point(73, 132);
this.Loc31Box.MaxLength = 1;
this.Loc31Box.Name = "Loc31Box";
this.Loc31Box.Size = new System.Drawing.Size(27, 20);
this.Loc31Box.TabIndex = 14;
this.Loc31Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc30Box
//
this.Loc30Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc30Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc30Box.Location = new System.Drawing.Point(40, 132);
this.Loc30Box.MaxLength = 1;
this.Loc30Box.Name = "Loc30Box";
this.Loc30Box.Size = new System.Drawing.Size(27, 20);
this.Loc30Box.TabIndex = 13;
this.Loc30Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc03Box
//
this.Loc03Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc03Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc03Box.Location = new System.Drawing.Point(140, 49);
this.Loc03Box.MaxLength = 1;
this.Loc03Box.Name = "Loc03Box";
this.Loc03Box.Size = new System.Drawing.Size(27, 20);
this.Loc03Box.TabIndex = 4;
this.Loc03Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc02Box
//
this.Loc02Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc02Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc02Box.Location = new System.Drawing.Point(107, 49);
this.Loc02Box.MaxLength = 1;
this.Loc02Box.Name = "Loc02Box";
this.Loc02Box.Size = new System.Drawing.Size(26, 20);
this.Loc02Box.TabIndex = 3;
this.Loc02Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc01Box
//
this.Loc01Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc01Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc01Box.Location = new System.Drawing.Point(73, 49);
this.Loc01Box.MaxLength = 1;
this.Loc01Box.Name = "Loc01Box";
this.Loc01Box.Size = new System.Drawing.Size(27, 20);
this.Loc01Box.TabIndex = 2;
this.Loc01Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// Loc00Box
//
this.Loc00Box.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.Loc00Box.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.Loc00Box.Location = new System.Drawing.Point(40, 49);
this.Loc00Box.MaxLength = 1;
this.Loc00Box.Name = "Loc00Box";
this.Loc00Box.Size = new System.Drawing.Size(27, 20);
this.Loc00Box.TabIndex = 1;
this.Loc00Box.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// DispAllBtn
//
this.DispAllBtn.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.DispAllBtn.ForeColor = System.Drawing.Color.Red;
this.DispAllBtn.Location = new System.Drawing.Point(120, 296);
this.DispAllBtn.Name = "DispAllBtn";
this.DispAllBtn.Size = new System.Drawing.Size(93, 26);
this.DispAllBtn.TabIndex = 20;
this.DispAllBtn.Text = "Display All";
this.DispAllBtn.Click += new System.EventHandler(this.DispAllBtn_Click);
//
// MinBox
//
this.MinBox.Location = new System.Drawing.Point(33, 21);
this.MinBox.MaxLength = 2;
this.MinBox.Name = "MinBox";
this.MinBox.Size = new System.Drawing.Size(27, 20);
this.MinBox.TabIndex = 2;
this.MinBox.Text = "4";
this.MinBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.MinBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.MinBox_KeyPress);
this.MinBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MinBox_KeyDown);
//
// MaxBox
//
this.MaxBox.Location = new System.Drawing.Point(100, 21);
this.MaxBox.MaxLength = 2;
this.MaxBox.Name = "MaxBox";
this.MaxBox.Size = new System.Drawing.Size(27, 20);
this.MaxBox.TabIndex = 4;
this.MaxBox.Text = "16";
this.MaxBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.MaxBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.MaxBox_KeyPress);
this.MaxBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MaxBox_KeyDown);
//
// MinLbl
//
this.MinLbl.Location = new System.Drawing.Point(7, 21);
this.MinLbl.Name = "MinLbl";
this.MinLbl.Size = new System.Drawing.Size(26, 21);
this.MinLbl.TabIndex = 1;
this.MinLbl.Text = "Min";
this.MinLbl.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// MaxLbl
//
this.MaxLbl.Location = new System.Drawing.Point(73, 21);
this.MaxLbl.Name = "MaxLbl";
this.MaxLbl.Size = new System.Drawing.Size(27, 21);
this.MaxLbl.TabIndex = 3;
this.MaxLbl.Text = "Max";
this.MaxLbl.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// LengthGrp
//
this.LengthGrp.Controls.Add(this.MaxLbl);
this.LengthGrp.Controls.Add(this.MinLbl);
this.LengthGrp.Controls.Add(this.MaxBox);
this.LengthGrp.Controls.Add(this.MinBox);
this.LengthGrp.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.LengthGrp.Location = new System.Drawing.Point(47, 222);
this.LengthGrp.Name = "LengthGrp";
this.LengthGrp.Size = new System.Drawing.Size(133, 48);
this.LengthGrp.TabIndex = 18;
this.LengthGrp.TabStop = false;
this.LengthGrp.Text = "Length of Words";
//
// MainMenu
//
this.MainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.Menu10Item,
this.Menu20Item});
//
// Menu10Item
//
this.Menu10Item.Index = 0;
this.Menu10Item.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.Menu11Item,
this.MenuBar1,
this.Menu12Item});
this.Menu10Item.Text = "Control";
//
// Menu11Item
//
this.Menu11Item.Index = 0;
this.Menu11Item.Shortcut = System.Windows.Forms.Shortcut.F2;
this.Menu11Item.Text = "Reset";
this.Menu11Item.Click += new System.EventHandler(this.Menu11Item_Click);
//
// MenuBar1
//
this.MenuBar1.Index = 1;
this.MenuBar1.Text = "-";
//
// Menu12Item
//
this.Menu12Item.Index = 2;
this.Menu12Item.Text = "Exit";
this.Menu12Item.Click += new System.EventHandler(this.Menu12Item_Click);
//
// Menu20Item
//
this.Menu20Item.Index = 1;
this.Menu20Item.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.Menu21Item,
this.MenuBar2,
this.Menu22Item});
this.Menu20Item.Text = "Help";
//
// Menu21Item
//
this.Menu21Item.Index = 0;
this.Menu21Item.Shortcut = System.Windows.Forms.Shortcut.F1;
this.Menu21Item.Text = "Help";
this.Menu21Item.Click += new System.EventHandler(this.Menu21Item_Click);
//
// MenuBar2
//
this.MenuBar2.Index = 1;
this.MenuBar2.Text = "-";
//
// Menu22Item
//
this.Menu22Item.Index = 2;
this.Menu22Item.Text = "About...";
this.Menu22Item.Click += new System.EventHandler(this.Menu22Item_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(531, 419);
this.Controls.Add(this.LengthGrp);
this.Controls.Add(this.DispAllBtn);
this.Controls.Add(this.BogLbl);
this.Controls.Add(this.RandBtn);
this.Controls.Add(this.Loc13Box);
this.Controls.Add(this.Loc12Box);
this.Controls.Add(this.Loc11Box);
this.Controls.Add(this.Loc10Box);
this.Controls.Add(this.Loc23Box);
this.Controls.Add(this.Loc22Box);
this.Controls.Add(this.Loc21Box);
this.Controls.Add(this.Loc20Box);
this.Controls.Add(this.Loc33Box);
this.Controls.Add(this.Loc32Box);
this.Controls.Add(this.Loc31Box);
this.Controls.Add(this.Loc30Box);
this.Controls.Add(this.Loc03Box);
this.Controls.Add(this.Loc02Box);
this.Controls.Add(this.Loc01Box);
this.Controls.Add(this.Loc00Box);
this.Controls.Add(this.AnswerBox);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(537, 464);
this.Menu = this.MainMenu;
this.MinimumSize = new System.Drawing.Size(537, 464);
this.Name = "Form1";
this.Text = "Boggle Word Finder";
this.LengthGrp.ResumeLayout(false);
this.LengthGrp.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void LoadDictionary()
//Loads the dictionary
{
string dir = Directory.GetCurrentDirectory();
ArrayList data = new ArrayList();
StreamReader rdr = new StreamReader(dir + "\\" + "dictionary.txt");
string word;
while((word = rdr.ReadLine()) != null)
{
data.Add(word);
}
rdr.Close();
Dictionary = data.ToArray(typeof(string)) as string[];
}
private void RandBtn_Click(object sender, System.EventArgs e)
//Rolls the dice and puts in the letters
{
ArrayList ilist = new ArrayList(16);
int temp;
while(true)
{
temp = rdm.Next(0, 16);
if(!ilist.Contains(temp))
{
ilist.Add(temp);
}
if(ilist.Count == 16) break;
}
for(int i = 0; i < 16; i++)
{
BoggleSquare[i % 4, i / 4].Text = Dice[int.Parse(ilist[i].ToString()), rdm.Next(0, 5)].ToString();
}
}
private void DispAllBtn_Click(object sender, System.EventArgs e)
{
bool go = true;
foreach(TextBox s in BoggleSquare)
{
if(s.Text == "")
{
go = false;
string msg = "All sixteen fields must be filled before the square can be solved.";
MessageBox.Show(this, msg, "Blank field error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
}
if(go)
{
Answers.Clear();
Block = new char[4,4]
{
{char.Parse(Loc00Box.Text), char.Parse(Loc10Box.Text), char.Parse(Loc20Box.Text), char.Parse(Loc30Box.Text)},
{char.Parse(Loc01Box.Text), char.Parse(Loc11Box.Text), char.Parse(Loc21Box.Text), char.Parse(Loc31Box.Text)},
{char.Parse(Loc02Box.Text), char.Parse(Loc12Box.Text), char.Parse(Loc22Box.Text), char.Parse(Loc32Box.Text)},
{char.Parse(Loc03Box.Text), char.Parse(Loc13Box.Text), char.Parse(Loc23Box.Text), char.Parse(Loc33Box.Text)}
};
if(MinBox.Text != "") Min = int.Parse(MinBox.Text);
else Min = 4;
if(MaxBox.Text != "") Max = int.Parse(MaxBox.Text);
else Max = 99;
for(int i = 0; i < Dictionary.Length; i++)
{
string word = Dictionary[i];
if(word.Length >= Min && word.Length <= Max)
{
if(WordFinder(0, word.ToUpper(), new int[word.Length]))
{
Answers.Add(word);
}
}
}
string display = "";
for(int i = 0; i < Answers.Count; i++)
{
display += Answers[i].ToString() + " ";
}
AnswerBox.Text = display;
AnswerBox.ScrollBars = ScrollBars.None;
if (AnswerBox.GetCharIndexFromPosition(TextBoxCornerPoint) < AnswerBox.Lines[0].Length - 1)
{
AnswerBox.ScrollBars = ScrollBars.Vertical;
}
}
}
public bool WordFinder(int q, string word, int[] poslist)
//Primary search function
{
/*
* Give WordFinder a word and it will return whether or not the word exists
* in the Boggle block.
*
* Activater: WordFinder(0, string 'word', new char['word'.Length], new int['word'.Length})
*
* Static Passed Items:
* 1. string word: gets passed this from the Dictionary
*
* Variable Passed Items:
* 1. int q: how many loops have been created
* 2. char[] aword: gets built along the way
* 3. int[] poslist: list of all positions listed in aword
*
* Returned Item:
* 1. bool answer: whether or not it was found
*/
bool answer = false;
if(q == 0)
//For the first loop
{
for(int loc = 0; loc < 16; loc++)
{
poslist[0] = loc;
if(word[0] == Block[loc % 4, loc / 4] && WordFinder(1, word, poslist))
{
answer = true;
break;
}
}
return answer;
}
else if(q != word.Length && q != 0)
//For the loops inbetween
{
for(int i = 0; i < 8; i++)
{
int loc = ModPos(poslist[q - 1], i);
bool goodloc = true;
if(loc == -1) goodloc = false;
else if(word[q] != Block[loc % 4, loc / 4]) goodloc = false;
for(int j = 0; j < q; j++)
//Looks to see if this position has already been used
{
if(loc == poslist[j])
{
goodloc = false;
}
}
if(goodloc)
{
poslist[q] = loc;
if(WordFinder(q + 1, word, poslist))
{
answer = true;
break;
}
}
}
return answer;
}
else if(q == word.Length)
//No loops left, it passes
{
return true;
}
else return false;
}
private int ModPos(int loc, int dir)
//With a given position and direction, it returns the new position
{
int[] pos = new int[2]{loc % 4, loc / 4};
if(dir == 0)
{
pos[1] = pos[1] - 1;
}
else if(dir == 1)
{
pos[0] = pos[0] + 1;
pos[1] = pos[1] - 1;
}
else if(dir == 2)
{
pos[0] = pos[0] + 1;
}
else if(dir == 3)
{
pos[0] = pos[0] + 1;
pos[1] = pos[1] + 1;
}
else if(dir == 4)
{
pos[1] = pos[1] + 1;
}
else if(dir == 5)
{
pos[0] = pos[0] - 1;
pos[1] = pos[1] + 1;
}
else if(dir == 6)
{
pos[0] = pos[0] - 1;
}
else if(dir == 7)
{
pos[0] = pos[0] - 1;
pos[1] = pos[1] - 1;
}
if(pos[0] < 0 || pos[0] > 3 || pos[1] < 0 || pos[1] > 3)
{
return -1;
}
else
{
return pos[0] + pos[1] * 4;
}
}
//***Menu functions***//
private void Menu11Item_Click(object sender, System.EventArgs e)
//Reset button
{
foreach(TextBox s in BoggleSquare)
{
s.Text = "";
}
AnswerBox.Text = "";
MinBox.Text = "4";
MaxBox.Text = "16";
}
private void Menu12Item_Click(object sender, System.EventArgs e)
//Exit button
{
this.Close();
}
private void Menu21Item_Click(object sender, System.EventArgs e)
//Help button
{
FormHelp1.CenterToForm1(this.Location);
FormHelp1.Show();
FormHelp1.BringToFront();
}
private void Menu22Item_Click(object sender, System.EventArgs e)
//About button
{
FormAbout1.CenterToForm1(this.Location);
FormAbout1.Show();
FormAbout1.BringToFront();
}
//***Letterbox functions***//
private void s_KeyPress(object sender, KeyPressEventArgs e)
//Replaces a letter in the letterbox and ignores all non-letter characters
{
if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' && e.KeyChar <= 'z'))
{
(sender as TextBox).Text = e.KeyChar.ToString();
}
e.Handled = true;
}
private void s_Enter(object sender, EventArgs e)
//Highlights the letterbox when it is tabbed
{
(sender as TextBox).SelectAll();
}
private void s_Click(object sender, EventArgs e)
//Highlights the letterbox when it is clicked
{
(sender as TextBox).SelectAll();
}
//***Disallow non-numerical inputs in Minbox/Maxbox***//
private void MinBox_KeyDown(object sender, KeyEventArgs e)
{
MaxMinAllowEntry = false;
if ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) || (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) || e.KeyCode == Keys.Back)
{
MaxMinAllowEntry = true;
}
}
private void MaxBox_KeyDown(object sender, KeyEventArgs e)
{
MaxMinAllowEntry = false;
if ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) || (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) || e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete)
{
MaxMinAllowEntry = true;
}
}
private void MinBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!MaxMinAllowEntry)
{
e.Handled = true;
}
}
private void MaxBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!MaxMinAllowEntry)
{
e.Handled = true;
}
}
}
}
| |
/*
* 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 NVelocity.App.Event
{
using System;
using Context;
using Runtime;
using Util;
/// <summary> Stores the event handlers. Event handlers can be assigned on a per
/// VelocityEngine instance basis by specifying the class names in the
/// velocity.properties file. Event handlers may also be assigned on a per-page
/// basis by creating a new instance of EventCartridge, adding the event
/// handlers, and then calling AttachToContext. For clarity, it's recommended
/// that one approach or the other be followed, as the second method is primarily
/// presented for backwards compatibility.
///
/// <P>
/// Note that Event Handlers follow a filter pattern, with multiple event
/// handlers allowed for each event. When the appropriate event occurs, all the
/// appropriate event handlers are called in the sequence they were added to the
/// Event Cartridge. See the javadocs of the specific event handler interfaces
/// for more details.
///
/// </summary>
/// <author> <a href="mailto:wglass@wglass@forio.com">Will Glass-Husain </a>
/// </author>
/// <author> <a href="mailto:geirm@optonline.net">Geir Magnusson Jr. </a>
/// </author>
/// <author> <a href="mailto:j_a_fernandez@yahoo.com">Jose Alberto Fernandez </a>
/// </author>
/// <version> $Id: EventCartridge.java 685685 2008-08-13 21:43:27Z nbubna $
/// </version>
public class EventCartridge
{
/// <summary> Iterate through all the stored IReferenceInsertionEventHandler objects
///
/// </summary>
/// <returns> iterator of handler objects, null if there are not handlers
/// </returns>
/// <since> 1.5
/// </since>
virtual public System.Collections.IEnumerator ReferenceInsertionEventHandlers
{
get
{
return referenceHandlers.Count == 0 ? null : referenceHandlers.GetEnumerator();
}
}
/// <summary> Iterate through all the stored NullSetEventHandler objects
///
/// </summary>
/// <returns> iterator of handler objects
/// </returns>
/// <since> 1.5
/// </since>
virtual public System.Collections.IEnumerator NullSetEventHandlers
{
get
{
return nullSetHandlers.GetEnumerator();
}
}
/// <summary> Iterate through all the stored IMethodExceptionEventHandler objects
///
/// </summary>
/// <returns> iterator of handler objects
/// </returns>
/// <since> 1.5
/// </since>
virtual public System.Collections.IEnumerator MethodExceptionEventHandlers
{
get
{
return methodExceptionHandlers.GetEnumerator();
}
}
/// <summary> Iterate through all the stored IncludeEventHandlers objects
///
/// </summary>
/// <returns> iterator of handler objects
/// </returns>
virtual public System.Collections.IEnumerator IncludeEventHandlers
{
get
{
return includeHandlers.GetEnumerator();
}
}
/// <summary> Iterate through all the stored InvalidReferenceEventHandlers objects
///
/// </summary>
/// <returns> iterator of handler objects
/// </returns>
/// <since> 1.5
/// </since>
virtual public System.Collections.IEnumerator InvalidReferenceEventHandlers
{
get
{
return invalidReferenceHandlers.GetEnumerator();
}
}
private System.Collections.IList referenceHandlers = new System.Collections.ArrayList();
private System.Collections.IList nullSetHandlers = new System.Collections.ArrayList();
private System.Collections.IList methodExceptionHandlers = new System.Collections.ArrayList();
private System.Collections.IList includeHandlers = new System.Collections.ArrayList();
private System.Collections.IList invalidReferenceHandlers = new System.Collections.ArrayList();
/// <summary> Ensure that handlers are not initialized more than once.</summary>
internal System.Collections.Generic.HashSet<object> initializedHandlers = new System.Collections.Generic.HashSet<object>();
/// <summary> Adds an event handler(s) to the Cartridge. This method
/// will find all possible event handler interfaces supported
/// by the passed in object.
///
/// </summary>
/// <param name="ev">object impementing a valid EventHandler-derived interface
/// </param>
/// <returns> true if a supported interface, false otherwise or if null
/// </returns>
public virtual bool AddEventHandler(IEventHandler ev)
{
if (ev == null)
{
return false;
}
bool found = false;
if (ev is IReferenceInsertionEventHandler)
{
AddReferenceInsertionEventHandler((IReferenceInsertionEventHandler)ev);
found = true;
}
if (ev is INullSetEventHandler)
{
AddNullSetEventHandler((INullSetEventHandler)ev);
found = true;
}
if (ev is IMethodExceptionEventHandler)
{
AddMethodExceptionHandler((IMethodExceptionEventHandler)ev);
found = true;
}
if (ev is IIncludeEventHandler)
{
AddIncludeEventHandler((IIncludeEventHandler)ev);
found = true;
}
if (ev is IInvalidReferenceEventHandler)
{
AddInvalidReferenceEventHandler((IInvalidReferenceEventHandler)ev);
found = true;
}
return found;
}
/// <summary> Add a reference insertion event handler to the Cartridge.
///
/// </summary>
/// <param name="ev">IReferenceInsertionEventHandler
/// </param>
/// <since> 1.5
/// </since>
public virtual void AddReferenceInsertionEventHandler(IReferenceInsertionEventHandler ev)
{
referenceHandlers.Add(ev);
}
/// <summary> Add a null set event handler to the Cartridge.
///
/// </summary>
/// <param name="ev">NullSetEventHandler
/// </param>
/// <since> 1.5
/// </since>
public virtual void AddNullSetEventHandler(INullSetEventHandler ev)
{
nullSetHandlers.Add(ev);
}
/// <summary> Add a method exception event handler to the Cartridge.
///
/// </summary>
/// <param name="ev">IMethodExceptionEventHandler
/// </param>
/// <since> 1.5
/// </since>
public virtual void AddMethodExceptionHandler(IMethodExceptionEventHandler ev)
{
methodExceptionHandlers.Add(ev);
}
/// <summary> Add an include event handler to the Cartridge.
///
/// </summary>
/// <param name="ev">IIncludeEventHandler
/// </param>
/// <since> 1.5
/// </since>
public virtual void AddIncludeEventHandler(IIncludeEventHandler ev)
{
includeHandlers.Add(ev);
}
/// <summary> Add an invalid reference event handler to the Cartridge.
///
/// </summary>
/// <param name="ev">IInvalidReferenceEventHandler
/// </param>
/// <since> 1.5
/// </since>
public virtual void AddInvalidReferenceEventHandler(IInvalidReferenceEventHandler ev)
{
invalidReferenceHandlers.Add(ev);
}
/// <summary> Removes an event handler(s) from the Cartridge. This method will find all
/// possible event handler interfaces supported by the passed in object and
/// remove them.
///
/// </summary>
/// <param name="ev"> object impementing a valid EventHandler-derived interface
/// </param>
/// <returns> true if event handler was previously registered, false if not
/// found
/// </returns>
public virtual bool RemoveEventHandler(EventHandler ev)
{
if (ev == null)
{
return false;
}
bool found = false;
if (ev.GetType() is IReferenceInsertionEventHandler)
{
System.Boolean tempBoolean;
tempBoolean = referenceHandlers.Contains(ev);
referenceHandlers.Remove(ev);
return tempBoolean;
}
if (ev.GetType() is INullSetEventHandler)
{
System.Boolean tempBoolean2;
tempBoolean2 = nullSetHandlers.Contains(ev);
nullSetHandlers.Remove(ev);
return tempBoolean2;
}
if (ev.GetType() is IMethodExceptionEventHandler)
{
System.Boolean tempBoolean3;
tempBoolean3 = methodExceptionHandlers.Contains(ev);
methodExceptionHandlers.Remove(ev);
return tempBoolean3;
}
if (ev.GetType() is IIncludeEventHandler)
{
System.Boolean tempBoolean4;
tempBoolean4 = includeHandlers.Contains(ev);
includeHandlers.Remove(ev);
return tempBoolean4;
}
if (ev.GetType() is IInvalidReferenceEventHandler)
{
System.Boolean tempBoolean5;
tempBoolean5 = invalidReferenceHandlers.Contains(ev);
invalidReferenceHandlers.Remove(ev);
return tempBoolean5;
}
return found;
}
/// <summary> Attached the EventCartridge to the context
///
/// Final because not something one should mess with lightly :)
///
/// </summary>
/// <param name="context">context to attach to
/// </param>
/// <returns> true if successful, false otherwise
/// </returns>
public bool AttachToContext(IContext context)
{
if (context is IInternalEventContext)
{
IInternalEventContext iec = (IInternalEventContext)context;
iec.AttachEventCartridge(this);
/**
* while it's tempting to call setContext on each handler from here,
* this needs to be done before each method call. This is
* because the specific context will change as inner contexts
* are linked in through macros, foreach, or directly by the user.
*/
return true;
}
else
{
return false;
}
}
/// <summary> Initialize the handlers. For global handlers this is called when Velocity
/// is initialized. For local handlers this is called when the first handler
/// is executed. Handlers will not be initialized more than once.
///
/// </summary>
/// <param name="rs">
/// </param>
/// <throws> Exception </throws>
/// <since> 1.5
/// </since>
public virtual void Initialize(IRuntimeServices rs)
{
for (System.Collections.IEnumerator i = referenceHandlers.GetEnumerator(); i.MoveNext(); )
{
IEventHandler eh = (IEventHandler)i.Current;
if ((eh is IRuntimeServicesAware) && !initializedHandlers.Contains(eh))
{
((IRuntimeServicesAware)eh).SetRuntimeServices(rs);
initializedHandlers.Add(eh);
}
}
for (System.Collections.IEnumerator i = nullSetHandlers.GetEnumerator(); i.MoveNext(); )
{
IEventHandler eh = (IEventHandler)i.Current;
if ((eh is IRuntimeServicesAware) && !initializedHandlers.Contains(eh))
{
((IRuntimeServicesAware)eh).SetRuntimeServices(rs);
initializedHandlers.Add(eh);
}
}
for (System.Collections.IEnumerator i = methodExceptionHandlers.GetEnumerator(); i.MoveNext(); )
{
IEventHandler eh = (IEventHandler)i.Current;
if ((eh is IRuntimeServicesAware) && !initializedHandlers.Contains(eh))
{
((IRuntimeServicesAware)eh).SetRuntimeServices(rs);
initializedHandlers.Add(eh);
}
}
for (System.Collections.IEnumerator i = includeHandlers.GetEnumerator(); i.MoveNext(); )
{
IEventHandler eh = (IEventHandler)i.Current;
if ((eh is IRuntimeServicesAware) && !initializedHandlers.Contains(eh))
{
((IRuntimeServicesAware)eh).SetRuntimeServices(rs);
initializedHandlers.Add(eh);
}
}
for (System.Collections.IEnumerator i = invalidReferenceHandlers.GetEnumerator(); i.MoveNext(); )
{
IEventHandler eh = (IEventHandler)i.Current;
if ((eh is IRuntimeServicesAware) && !initializedHandlers.Contains(eh))
{
((IRuntimeServicesAware)eh).SetRuntimeServices(rs);
initializedHandlers.Add(eh);
}
}
}
}
}
| |
using System;
using System.Threading.Tasks;
using Abp.Events.Bus.Factories;
using Abp.Events.Bus.Handlers;
namespace Abp.Events.Bus
{
/// <summary>
/// Defines interface of the event bus.
/// </summary>
public interface IEventBus
{
#region Register
/// <summary>
/// Registers to an event.
/// Given action is called for all event occurrences.
/// </summary>
/// <param name="action">Action to handle events</param>
/// <typeparam name="TEventData">Event type</typeparam>
IDisposable Register<TEventData>(Action<TEventData> action) where TEventData : IEventData;
/// <summary>
/// Registers to an event.
/// Given action is called for all event occurrences.
/// </summary>
/// <param name="action">Action to handle events</param>
/// <typeparam name="TEventData">Event type</typeparam>
IDisposable AsyncRegister<TEventData>(Func<TEventData, Task> action) where TEventData : IEventData;
/// <summary>
/// Registers to an event.
/// Same (given) instance of the handler is used for all event occurrences.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <param name="handler">Object to handle the event</param>
IDisposable Register<TEventData>(IEventHandler<TEventData> handler) where TEventData : IEventData;
/// <summary>
/// Registers to an event.
/// Same (given) instance of the async handler is used for all event occurrences.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <param name="handler">Object to handle the event</param>
IDisposable AsyncRegister<TEventData>(IAsyncEventHandler<TEventData> handler) where TEventData : IEventData;
/// <summary>
/// Registers to an event.
/// A new instance of <typeparamref name="THandler"/> object is created for every event occurrence.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <typeparam name="THandler">Type of the event handler</typeparam>
IDisposable Register<TEventData, THandler>() where TEventData : IEventData where THandler : IEventHandler, new();
/// <summary>
/// Registers to an event.
/// Same (given) instance of the handler is used for all event occurrences.
/// </summary>
/// <param name="eventType">Event type</param>
/// <param name="handler">Object to handle the event</param>
IDisposable Register(Type eventType, IEventHandler handler);
/// <summary>
/// Registers to an event.
/// Given factory is used to create/release handlers
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <param name="factory">A factory to create/release handlers</param>
IDisposable Register<TEventData>(IEventHandlerFactory factory) where TEventData : IEventData;
/// <summary>
/// Registers to an event.
/// </summary>
/// <param name="eventType">Event type</param>
/// <param name="factory">A factory to create/release handlers</param>
IDisposable Register(Type eventType, IEventHandlerFactory factory);
#endregion
#region Unregister
/// <summary>
/// Unregisters from an event.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <param name="action"></param>
void Unregister<TEventData>(Action<TEventData> action) where TEventData : IEventData;
/// <summary>
/// Unregisters from an event.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <param name="action"></param>
void AsyncUnregister<TEventData>(Func<TEventData, Task> action) where TEventData : IEventData;
/// <summary>
/// Unregisters from an event.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <param name="handler">Handler object that is registered before</param>
void Unregister<TEventData>(IEventHandler<TEventData> handler) where TEventData : IEventData;
/// <summary>
/// Unregisters from an event.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <param name="handler">Handler object that is registered before</param>
void AsyncUnregister<TEventData>(IAsyncEventHandler<TEventData> handler) where TEventData : IEventData;
/// <summary>
/// Unregisters from an event.
/// </summary>
/// <param name="eventType">Event type</param>
/// <param name="handler">Handler object that is registered before</param>
void Unregister(Type eventType, IEventHandler handler);
/// <summary>
/// Unregisters from an event.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <param name="factory">Factory object that is registered before</param>
void Unregister<TEventData>(IEventHandlerFactory factory) where TEventData : IEventData;
/// <summary>
/// Unregisters from an event.
/// </summary>
/// <param name="eventType">Event type</param>
/// <param name="factory">Factory object that is registered before</param>
void Unregister(Type eventType, IEventHandlerFactory factory);
/// <summary>
/// Unregisters all event handlers of given event type.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
void UnregisterAll<TEventData>() where TEventData : IEventData;
/// <summary>
/// Unregisters all event handlers of given event type.
/// </summary>
/// <param name="eventType">Event type</param>
void UnregisterAll(Type eventType);
#endregion
#region Trigger
/// <summary>
/// Triggers an event.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <param name="eventData">Related data for the event</param>
void Trigger<TEventData>(TEventData eventData) where TEventData : IEventData;
/// <summary>
/// Triggers an event.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <param name="eventSource">The object which triggers the event</param>
/// <param name="eventData">Related data for the event</param>
void Trigger<TEventData>(object eventSource, TEventData eventData) where TEventData : IEventData;
/// <summary>
/// Triggers an event.
/// </summary>
/// <param name="eventType">Event type</param>
/// <param name="eventData">Related data for the event</param>
void Trigger(Type eventType, IEventData eventData);
/// <summary>
/// Triggers an event.
/// </summary>
/// <param name="eventType">Event type</param>
/// <param name="eventSource">The object which triggers the event</param>
/// <param name="eventData">Related data for the event</param>
void Trigger(Type eventType, object eventSource, IEventData eventData);
/// <summary>
/// Triggers an event asynchronously.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <param name="eventData">Related data for the event</param>
/// <returns>The task to handle async operation</returns>
Task TriggerAsync<TEventData>(TEventData eventData) where TEventData : IEventData;
/// <summary>
/// Triggers an event asynchronously.
/// </summary>
/// <typeparam name="TEventData">Event type</typeparam>
/// <param name="eventSource">The object which triggers the event</param>
/// <param name="eventData">Related data for the event</param>
/// <returns>The task to handle async operation</returns>
Task TriggerAsync<TEventData>(object eventSource, TEventData eventData) where TEventData : IEventData;
/// <summary>
/// Triggers an event asynchronously.
/// </summary>
/// <param name="eventType">Event type</param>
/// <param name="eventData">Related data for the event</param>
/// <returns>The task to handle async operation</returns>
Task TriggerAsync(Type eventType, IEventData eventData);
/// <summary>
/// Triggers an event asynchronously.
/// </summary>
/// <param name="eventType">Event type</param>
/// <param name="eventSource">The object which triggers the event</param>
/// <param name="eventData">Related data for the event</param>
/// <returns>The task to handle async operation</returns>
Task TriggerAsync(Type eventType, object eventSource, IEventData eventData);
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse;
using Ode.NET;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
using log4net;
namespace OpenSim.Region.Physics.OdePlugin
{
/// <summary>
/// Various properties that ODE uses for AMotors but isn't exposed in ODE.NET so we must define them ourselves.
/// </summary>
public enum dParam : int
{
LowStop = 0,
HiStop = 1,
Vel = 2,
FMax = 3,
FudgeFactor = 4,
Bounce = 5,
CFM = 6,
StopERP = 7,
StopCFM = 8,
LoStop2 = 256,
HiStop2 = 257,
Vel2 = 258,
FMax2 = 259,
StopERP2 = 7 + 256,
StopCFM2 = 8 + 256,
LoStop3 = 512,
HiStop3 = 513,
Vel3 = 514,
FMax3 = 515,
StopERP3 = 7 + 512,
StopCFM3 = 8 + 512
}
public class OdeCharacter : PhysicsActor
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Vector3 _position;
private d.Vector3 _zeroPosition;
// private d.Matrix3 m_StandUpRotation;
private bool _zeroFlag = false;
private bool m_lastUpdateSent = false;
private Vector3 _velocity;
private Vector3 _target_velocity;
private Vector3 _acceleration;
private Vector3 m_rotationalVelocity;
private float m_mass = 80f;
public float m_density = 60f;
private bool m_pidControllerActive = true;
public float PID_D = 800.0f;
public float PID_P = 900.0f;
//private static float POSTURE_SERVO = 10000.0f;
public float CAPSULE_RADIUS = 0.37f;
public float CAPSULE_LENGTH = 2.140599f;
public float m_tensor = 3800000f;
public float heightFudgeFactor = 0.52f;
public float walkDivisor = 1.3f;
public float runDivisor = 0.8f;
private bool flying = false;
private bool m_iscolliding = false;
private bool m_iscollidingGround = false;
private bool m_wascolliding = false;
private bool m_wascollidingGround = false;
private bool m_iscollidingObj = false;
private bool m_alwaysRun = false;
private bool m_hackSentFall = false;
private bool m_hackSentFly = false;
private int m_requestedUpdateFrequency = 0;
private Vector3 m_taintPosition = Vector3.Zero;
public uint m_localID = 0;
public bool m_returnCollisions = false;
// taints and their non-tainted counterparts
public bool m_isPhysical = false; // the current physical status
public bool m_tainted_isPhysical = false; // set when the physical status is tainted (false=not existing in physics engine, true=existing)
public float MinimumGroundFlightOffset = 3f;
private float m_tainted_CAPSULE_LENGTH; // set when the capsule length changes.
private float m_tiltMagnitudeWhenProjectedOnXYPlane = 0.1131371f; // used to introduce a fixed tilt because a straight-up capsule falls through terrain, probably a bug in terrain collider
private float m_buoyancy = 0f;
// private CollisionLocker ode;
private string m_name = String.Empty;
private bool[] m_colliderarr = new bool[11];
private bool[] m_colliderGroundarr = new bool[11];
// Default we're a Character
private CollisionCategories m_collisionCategories = (CollisionCategories.Character);
// Default, Collide with Other Geometries, spaces, bodies and characters.
private CollisionCategories m_collisionFlags = (CollisionCategories.Geom
| CollisionCategories.Space
| CollisionCategories.Body
| CollisionCategories.Character
| CollisionCategories.Land);
public IntPtr Body = IntPtr.Zero;
private OdeScene _parent_scene;
public IntPtr Shell = IntPtr.Zero;
public IntPtr Amotor = IntPtr.Zero;
public d.Mass ShellMass;
public bool collidelock = false;
public int m_eventsubscription = 0;
private CollisionEventUpdate CollisionEventsThisFrame = new CollisionEventUpdate();
// unique UUID of this character object
public UUID m_uuid;
public bool bad = false;
public OdeCharacter(String avName, OdeScene parent_scene, Vector3 pos, CollisionLocker dode, Vector3 size, float pid_d, float pid_p, float capsule_radius, float tensor, float density, float height_fudge_factor, float walk_divisor, float rundivisor)
{
m_uuid = UUID.Random();
if (pos.IsFinite())
{
if (pos.Z > 9999999f)
{
pos.Z = parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
}
if (pos.Z < -90000f)
{
pos.Z = parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
}
_position = pos;
m_taintPosition.X = pos.X;
m_taintPosition.Y = pos.Y;
m_taintPosition.Z = pos.Z;
}
else
{
_position = new Vector3(((float)_parent_scene.WorldExtents.X * 0.5f), ((float)_parent_scene.WorldExtents.Y * 0.5f), parent_scene.GetTerrainHeightAtXY(128f, 128f) + 10f);
m_taintPosition.X = _position.X;
m_taintPosition.Y = _position.Y;
m_taintPosition.Z = _position.Z;
m_log.Warn("[PHYSICS]: Got NaN Position on Character Create");
}
_parent_scene = parent_scene;
PID_D = pid_d;
PID_P = pid_p;
CAPSULE_RADIUS = capsule_radius;
m_tensor = tensor;
m_density = density;
heightFudgeFactor = height_fudge_factor;
walkDivisor = walk_divisor;
runDivisor = rundivisor;
// m_StandUpRotation =
// new d.Matrix3(0.5f, 0.7071068f, 0.5f, -0.7071068f, 0f, 0.7071068f, 0.5f, -0.7071068f,
// 0.5f);
for (int i = 0; i < 11; i++)
{
m_colliderarr[i] = false;
}
CAPSULE_LENGTH = (size.Z * 1.15f) - CAPSULE_RADIUS * 2.0f;
//m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
m_tainted_CAPSULE_LENGTH = CAPSULE_LENGTH;
m_isPhysical = false; // current status: no ODE information exists
m_tainted_isPhysical = true; // new tainted status: need to create ODE information
_parent_scene.AddPhysicsActorTaint(this);
m_name = avName;
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Agent; }
set { return; }
}
/// <summary>
/// If this is set, the avatar will move faster
/// </summary>
public override bool SetAlwaysRun
{
get { return m_alwaysRun; }
set { m_alwaysRun = value; }
}
public override uint LocalID
{
set { m_localID = value; }
}
public override bool Grabbed
{
set { return; }
}
public override bool Selected
{
set { return; }
}
public override float Buoyancy
{
get { return m_buoyancy; }
set { m_buoyancy = value; }
}
public override bool FloatOnWater
{
set { return; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool Flying
{
get { return flying; }
set { flying = value; }
}
/// <summary>
/// Returns if the avatar is colliding in general.
/// This includes the ground and objects and avatar.
/// </summary>
public override bool IsColliding
{
get { return m_iscolliding; }
set
{
int i;
int truecount = 0;
int falsecount = 0;
if (m_colliderarr.Length >= 10)
{
for (i = 0; i < 10; i++)
{
m_colliderarr[i] = m_colliderarr[i + 1];
}
}
m_colliderarr[10] = value;
for (i = 0; i < 11; i++)
{
if (m_colliderarr[i])
{
truecount++;
}
else
{
falsecount++;
}
}
// Equal truecounts and false counts means we're colliding with something.
if (falsecount > 1.2*truecount)
{
m_iscolliding = false;
}
else
{
m_iscolliding = true;
}
if (m_wascolliding != m_iscolliding)
{
//base.SendCollisionUpdate(new CollisionEventUpdate());
}
m_wascolliding = m_iscolliding;
}
}
/// <summary>
/// Returns if an avatar is colliding with the ground
/// </summary>
public override bool CollidingGround
{
get { return m_iscollidingGround; }
set
{
// Collisions against the ground are not really reliable
// So, to get a consistant value we have to average the current result over time
// Currently we use 1 second = 10 calls to this.
int i;
int truecount = 0;
int falsecount = 0;
if (m_colliderGroundarr.Length >= 10)
{
for (i = 0; i < 10; i++)
{
m_colliderGroundarr[i] = m_colliderGroundarr[i + 1];
}
}
m_colliderGroundarr[10] = value;
for (i = 0; i < 11; i++)
{
if (m_colliderGroundarr[i])
{
truecount++;
}
else
{
falsecount++;
}
}
// Equal truecounts and false counts means we're colliding with something.
if (falsecount > 1.2*truecount)
{
m_iscollidingGround = false;
}
else
{
m_iscollidingGround = true;
}
if (m_wascollidingGround != m_iscollidingGround)
{
//base.SendCollisionUpdate(new CollisionEventUpdate());
}
m_wascollidingGround = m_iscollidingGround;
}
}
/// <summary>
/// Returns if the avatar is colliding with an object
/// </summary>
public override bool CollidingObj
{
get { return m_iscollidingObj; }
set
{
m_iscollidingObj = value;
if (value)
m_pidControllerActive = false;
else
m_pidControllerActive = true;
}
}
/// <summary>
/// turn the PID controller on or off.
/// The PID Controller will turn on all by itself in many situations
/// </summary>
/// <param name="status"></param>
public void SetPidStatus(bool status)
{
m_pidControllerActive = status;
}
public override bool Stopped
{
get { return _zeroFlag; }
}
/// <summary>
/// This 'puts' an avatar somewhere in the physics space.
/// Not really a good choice unless you 'know' it's a good
/// spot otherwise you're likely to orbit the avatar.
/// </summary>
public override Vector3 Position
{
get { return _position; }
set
{
if (Body == IntPtr.Zero || Shell == IntPtr.Zero)
{
if (value.IsFinite())
{
if (value.Z > 9999999f)
{
value.Z = _parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
}
if (value.Z < -90000f)
{
value.Z = _parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
}
_position.X = value.X;
_position.Y = value.Y;
_position.Z = value.Z;
m_taintPosition.X = value.X;
m_taintPosition.Y = value.Y;
m_taintPosition.Z = value.Z;
_parent_scene.AddPhysicsActorTaint(this);
}
else
{
m_log.Warn("[PHYSICS]: Got a NaN Position from Scene on a Character");
}
}
}
}
public override Vector3 RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
/// <summary>
/// This property sets the height of the avatar only. We use the height to make sure the avatar stands up straight
/// and use it to offset landings properly
/// </summary>
public override Vector3 Size
{
get { return new Vector3(CAPSULE_RADIUS * 2, CAPSULE_RADIUS * 2, CAPSULE_LENGTH); }
set
{
if (value.IsFinite())
{
m_pidControllerActive = true;
Vector3 SetSize = value;
m_tainted_CAPSULE_LENGTH = (SetSize.Z*1.15f) - CAPSULE_RADIUS*2.0f;
//m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
Velocity = Vector3.Zero;
_parent_scene.AddPhysicsActorTaint(this);
}
else
{
m_log.Warn("[PHYSICS]: Got a NaN Size from Scene on a Character");
}
}
}
private void AlignAvatarTiltWithCurrentDirectionOfMovement(Vector3 movementVector)
{
movementVector.Z = 0f;
float magnitude = (float)Math.Sqrt((double)(movementVector.X * movementVector.X + movementVector.Y * movementVector.Y));
if (magnitude < 0.1f) return;
// normalize the velocity vector
float invMagnitude = 1.0f / magnitude;
movementVector.X *= invMagnitude;
movementVector.Y *= invMagnitude;
// if we change the capsule heading too often, the capsule can fall down
// therefore we snap movement vector to just 1 of 4 predefined directions (ne, nw, se, sw),
// meaning only 4 possible capsule tilt orientations
if (movementVector.X > 0)
{
// east
if (movementVector.Y > 0)
{
// northeast
movementVector.X = (float)Math.Sqrt(2.0);
movementVector.Y = (float)Math.Sqrt(2.0);
}
else
{
// southeast
movementVector.X = (float)Math.Sqrt(2.0);
movementVector.Y = -(float)Math.Sqrt(2.0);
}
}
else
{
// west
if (movementVector.Y > 0)
{
// northwest
movementVector.X = -(float)Math.Sqrt(2.0);
movementVector.Y = (float)Math.Sqrt(2.0);
}
else
{
// southwest
movementVector.X = -(float)Math.Sqrt(2.0);
movementVector.Y = -(float)Math.Sqrt(2.0);
}
}
// movementVector.Z is zero
// calculate tilt components based on desired amount of tilt and current (snapped) heading.
// the "-" sign is to force the tilt to be OPPOSITE the direction of movement.
float xTiltComponent = -movementVector.X * m_tiltMagnitudeWhenProjectedOnXYPlane;
float yTiltComponent = -movementVector.Y * m_tiltMagnitudeWhenProjectedOnXYPlane;
//m_log.Debug("[PHYSICS] changing avatar tilt");
d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, xTiltComponent);
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, xTiltComponent); // must be same as lowstop, else a different, spurious tilt is introduced
d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, yTiltComponent);
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, yTiltComponent); // same as lowstop
d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, 0f);
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0f); // same as lowstop
}
/// <summary>
/// This creates the Avatar's physical Surrogate at the position supplied
/// </summary>
/// <param name="npositionX"></param>
/// <param name="npositionY"></param>
/// <param name="npositionZ"></param>
// WARNING: This MUST NOT be called outside of ProcessTaints, else we can have unsynchronized access
// to ODE internals. ProcessTaints is called from within thread-locked Simulate(), so it is the only
// place that is safe to call this routine AvatarGeomAndBodyCreation.
private void AvatarGeomAndBodyCreation(float npositionX, float npositionY, float npositionZ, float tensor)
{
//CAPSULE_LENGTH = -5;
//CAPSULE_RADIUS = -5;
int dAMotorEuler = 1;
_parent_scene.waitForSpaceUnlock(_parent_scene.space);
if (CAPSULE_LENGTH <= 0)
{
m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!");
CAPSULE_LENGTH = 0.01f;
}
if (CAPSULE_RADIUS <= 0)
{
m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!");
CAPSULE_RADIUS = 0.01f;
}
Shell = d.CreateCapsule(_parent_scene.space, CAPSULE_RADIUS, CAPSULE_LENGTH);
d.GeomSetCategoryBits(Shell, (int)m_collisionCategories);
d.GeomSetCollideBits(Shell, (int)m_collisionFlags);
d.MassSetCapsuleTotal(out ShellMass, m_mass, 2, CAPSULE_RADIUS, CAPSULE_LENGTH);
Body = d.BodyCreate(_parent_scene.world);
d.BodySetPosition(Body, npositionX, npositionY, npositionZ);
_position.X = npositionX;
_position.Y = npositionY;
_position.Z = npositionZ;
m_taintPosition.X = npositionX;
m_taintPosition.Y = npositionY;
m_taintPosition.Z = npositionZ;
d.BodySetMass(Body, ref ShellMass);
d.Matrix3 m_caprot;
// 90 Stand up on the cap of the capped cyllinder
if (_parent_scene.IsAvCapsuleTilted)
{
d.RFromAxisAndAngle(out m_caprot, 1, 0, 1, (float)(Math.PI / 2));
}
else
{
d.RFromAxisAndAngle(out m_caprot, 0, 0, 1, (float)(Math.PI / 2));
}
d.GeomSetRotation(Shell, ref m_caprot);
d.BodySetRotation(Body, ref m_caprot);
d.GeomSetBody(Shell, Body);
// The purpose of the AMotor here is to keep the avatar's physical
// surrogate from rotating while moving
Amotor = d.JointCreateAMotor(_parent_scene.world, IntPtr.Zero);
d.JointAttach(Amotor, Body, IntPtr.Zero);
d.JointSetAMotorMode(Amotor, dAMotorEuler);
d.JointSetAMotorNumAxes(Amotor, 3);
d.JointSetAMotorAxis(Amotor, 0, 0, 1, 0, 0);
d.JointSetAMotorAxis(Amotor, 1, 0, 0, 1, 0);
d.JointSetAMotorAxis(Amotor, 2, 0, 0, 0, 1);
d.JointSetAMotorAngle(Amotor, 0, 0);
d.JointSetAMotorAngle(Amotor, 1, 0);
d.JointSetAMotorAngle(Amotor, 2, 0);
// These lowstops and high stops are effectively (no wiggle room)
if (_parent_scene.IsAvCapsuleTilted)
{
d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, -0.000000000001f);
d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, -0.000000000001f);
d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, -0.000000000001f);
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, 0.000000000001f);
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0.000000000001f);
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, 0.000000000001f);
}
else
{
#region Documentation of capsule motor LowStop and HighStop parameters
// Intentionally introduce some tilt into the capsule by setting
// the motor stops to small epsilon values. This small tilt prevents
// the capsule from falling into the terrain; a straight-up capsule
// (with -0..0 motor stops) falls into the terrain for reasons yet
// to be comprehended in their entirety.
#endregion
AlignAvatarTiltWithCurrentDirectionOfMovement(Vector3.Zero);
d.JointSetAMotorParam(Amotor, (int)dParam.LowStop, 0.08f);
d.JointSetAMotorParam(Amotor, (int)dParam.LoStop3, -0f);
d.JointSetAMotorParam(Amotor, (int)dParam.LoStop2, 0.08f);
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop, 0.08f); // must be same as lowstop, else a different, spurious tilt is introduced
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop3, 0f); // same as lowstop
d.JointSetAMotorParam(Amotor, (int)dParam.HiStop2, 0.08f); // same as lowstop
}
// Fudge factor is 1f by default, we're setting it to 0. We don't want it to Fudge or the
// capped cyllinder will fall over
d.JointSetAMotorParam(Amotor, (int)dParam.FudgeFactor, 0f);
d.JointSetAMotorParam(Amotor, (int)dParam.FMax, tensor);
//d.Matrix3 bodyrotation = d.BodyGetRotation(Body);
//d.QfromR(
//d.Matrix3 checkrotation = new d.Matrix3(0.7071068,0.5, -0.7071068,
//
//m_log.Info("[PHYSICSAV]: Rotation: " + bodyrotation.M00 + " : " + bodyrotation.M01 + " : " + bodyrotation.M02 + " : " + bodyrotation.M10 + " : " + bodyrotation.M11 + " : " + bodyrotation.M12 + " : " + bodyrotation.M20 + " : " + bodyrotation.M21 + " : " + bodyrotation.M22);
//standupStraight();
}
//
/// <summary>
/// Uses the capped cyllinder volume formula to calculate the avatar's mass.
/// This may be used in calculations in the scene/scenepresence
/// </summary>
public override float Mass
{
get
{
float AVvolume = (float) (Math.PI*Math.Pow(CAPSULE_RADIUS, 2)*CAPSULE_LENGTH);
return m_density*AVvolume;
}
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(Vector3 axis)
{
}
// This code is very useful. Written by DanX0r. We're just not using it right now.
// Commented out to prevent a warning.
//
// private void standupStraight()
// {
// // The purpose of this routine here is to quickly stabilize the Body while it's popped up in the air.
// // The amotor needs a few seconds to stabilize so without it, the avatar shoots up sky high when you
// // change appearance and when you enter the simulator
// // After this routine is done, the amotor stabilizes much quicker
// d.Vector3 feet;
// d.Vector3 head;
// d.BodyGetRelPointPos(Body, 0.0f, 0.0f, -1.0f, out feet);
// d.BodyGetRelPointPos(Body, 0.0f, 0.0f, 1.0f, out head);
// float posture = head.Z - feet.Z;
// // restoring force proportional to lack of posture:
// float servo = (2.5f - posture) * POSTURE_SERVO;
// d.BodyAddForceAtRelPos(Body, 0.0f, 0.0f, servo, 0.0f, 0.0f, 1.0f);
// d.BodyAddForceAtRelPos(Body, 0.0f, 0.0f, -servo, 0.0f, 0.0f, -1.0f);
// //d.Matrix3 bodyrotation = d.BodyGetRotation(Body);
// //m_log.Info("[PHYSICSAV]: Rotation: " + bodyrotation.M00 + " : " + bodyrotation.M01 + " : " + bodyrotation.M02 + " : " + bodyrotation.M10 + " : " + bodyrotation.M11 + " : " + bodyrotation.M12 + " : " + bodyrotation.M20 + " : " + bodyrotation.M21 + " : " + bodyrotation.M22);
// }
public override Vector3 Force
{
get { return _target_velocity; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, Vector3 value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void SetVolumeDetect(int param)
{
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 GeometricCenter
{
get { return Vector3.Zero; }
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override Vector3 Velocity
{
get {
// There's a problem with Vector3.Zero! Don't Use it Here!
if (_zeroFlag)
return Vector3.Zero;
m_lastUpdateSent = false;
return _velocity;
}
set
{
if (value.IsFinite())
{
m_pidControllerActive = true;
_target_velocity = value;
}
else
{
m_log.Warn("[PHYSICS]: Got a NaN velocity from Scene in a Character");
}
}
}
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override bool Kinematic
{
get { return false; }
set { }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set {
//Matrix3 or = Orientation.ToRotationMatrix();
//d.Matrix3 ord = new d.Matrix3(or.m00, or.m10, or.m20, or.m01, or.m11, or.m21, or.m02, or.m12, or.m22);
//d.BodySetRotation(Body, ref ord);
}
}
public override Vector3 Acceleration
{
get { return _acceleration; }
}
public void SetAcceleration(Vector3 accel)
{
m_pidControllerActive = true;
_acceleration = accel;
}
/// <summary>
/// Adds the force supplied to the Target Velocity
/// The PID controller takes this target velocity and tries to make it a reality
/// </summary>
/// <param name="force"></param>
public override void AddForce(Vector3 force, bool pushforce)
{
if (force.IsFinite())
{
if (pushforce)
{
m_pidControllerActive = false;
force *= 100f;
doForce(force);
// If uncommented, things get pushed off world
//
// m_log.Debug("Push!");
// _target_velocity.X += force.X;
// _target_velocity.Y += force.Y;
// _target_velocity.Z += force.Z;
}
else
{
m_pidControllerActive = true;
_target_velocity.X += force.X;
_target_velocity.Y += force.Y;
_target_velocity.Z += force.Z;
}
}
else
{
m_log.Warn("[PHYSICS]: Got a NaN force applied to a Character");
}
//m_lastUpdateSent = false;
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
/// <summary>
/// After all of the forces add up with 'add force' we apply them with doForce
/// </summary>
/// <param name="force"></param>
public void doForce(Vector3 force)
{
if (!collidelock)
{
d.BodyAddForce(Body, force.X, force.Y, force.Z);
//d.BodySetRotation(Body, ref m_StandUpRotation);
//standupStraight();
}
}
public override void SetMomentum(Vector3 momentum)
{
}
/// <summary>
/// Called from Simulate
/// This is the avatar's movement control + PID Controller
/// </summary>
/// <param name="timeStep"></param>
public void Move(float timeStep, List<OdeCharacter> defects)
{
// no lock; for now it's only called from within Simulate()
// If the PID Controller isn't active then we set our force
// calculating base velocity to the current position
if (Body == IntPtr.Zero)
return;
if (m_pidControllerActive == false)
{
_zeroPosition = d.BodyGetPosition(Body);
}
//PidStatus = true;
d.Vector3 localpos = d.BodyGetPosition(Body);
Vector3 localPos = new Vector3(localpos.X, localpos.Y, localpos.Z);
if (!localPos.IsFinite())
{
m_log.Warn("[PHYSICS]: Avatar Position is non-finite!");
defects.Add(this);
// _parent_scene.RemoveCharacter(this);
// destroy avatar capsule and related ODE data
if (Amotor != IntPtr.Zero)
{
// Kill the Amotor
d.JointDestroy(Amotor);
Amotor = IntPtr.Zero;
}
//kill the Geometry
_parent_scene.waitForSpaceUnlock(_parent_scene.space);
if (Body != IntPtr.Zero)
{
//kill the body
d.BodyDestroy(Body);
Body = IntPtr.Zero;
}
if (Shell != IntPtr.Zero)
{
d.GeomDestroy(Shell);
_parent_scene.geom_name_map.Remove(Shell);
Shell = IntPtr.Zero;
}
return;
}
Vector3 vec = Vector3.Zero;
d.Vector3 vel = d.BodyGetLinearVel(Body);
float movementdivisor = 1f;
if (!m_alwaysRun)
{
movementdivisor = walkDivisor;
}
else
{
movementdivisor = runDivisor;
}
// if velocity is zero, use position control; otherwise, velocity control
if (_target_velocity.X == 0.0f && _target_velocity.Y == 0.0f && _target_velocity.Z == 0.0f && m_iscolliding)
{
// keep track of where we stopped. No more slippin' & slidin'
if (!_zeroFlag)
{
_zeroFlag = true;
_zeroPosition = d.BodyGetPosition(Body);
}
if (m_pidControllerActive)
{
// We only want to deactivate the PID Controller if we think we want to have our surrogate
// react to the physics scene by moving it's position.
// Avatar to Avatar collisions
// Prim to avatar collisions
d.Vector3 pos = d.BodyGetPosition(Body);
vec.X = (_target_velocity.X - vel.X) * (PID_D) + (_zeroPosition.X - pos.X) * (PID_P * 2);
vec.Y = (_target_velocity.Y - vel.Y)*(PID_D) + (_zeroPosition.Y - pos.Y)* (PID_P * 2);
if (flying)
{
vec.Z = (_target_velocity.Z - vel.Z) * (PID_D) + (_zeroPosition.Z - pos.Z) * PID_P;
}
}
//PidStatus = true;
}
else
{
m_pidControllerActive = true;
_zeroFlag = false;
if (m_iscolliding && !flying)
{
// We're standing on something
vec.X = ((_target_velocity.X / movementdivisor) - vel.X) * (PID_D);
vec.Y = ((_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D);
}
else if (m_iscolliding && flying)
{
// We're flying and colliding with something
vec.X = ((_target_velocity.X/movementdivisor) - vel.X)*(PID_D / 16);
vec.Y = ((_target_velocity.Y/movementdivisor) - vel.Y)*(PID_D / 16);
}
else if (!m_iscolliding && flying)
{
// we're in mid air suspended
vec.X = ((_target_velocity.X / movementdivisor) - vel.X) * (PID_D/6);
vec.Y = ((_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D/6);
}
if (m_iscolliding && !flying && _target_velocity.Z > 0.0f)
{
// We're colliding with something and we're not flying but we're moving
// This means we're walking or running.
d.Vector3 pos = d.BodyGetPosition(Body);
vec.Z = (_target_velocity.Z - vel.Z)*PID_D + (_zeroPosition.Z - pos.Z)*PID_P;
if (_target_velocity.X > 0)
{
vec.X = ((_target_velocity.X - vel.X)/1.2f)*PID_D;
}
if (_target_velocity.Y > 0)
{
vec.Y = ((_target_velocity.Y - vel.Y)/1.2f)*PID_D;
}
}
else if (!m_iscolliding && !flying)
{
// we're not colliding and we're not flying so that means we're falling!
// m_iscolliding includes collisions with the ground.
// d.Vector3 pos = d.BodyGetPosition(Body);
if (_target_velocity.X > 0)
{
vec.X = ((_target_velocity.X - vel.X)/1.2f)*PID_D;
}
if (_target_velocity.Y > 0)
{
vec.Y = ((_target_velocity.Y - vel.Y)/1.2f)*PID_D;
}
}
if (flying)
{
vec.Z = (_target_velocity.Z - vel.Z) * (PID_D);
}
}
if (flying)
{
vec.Z += ((-1 * _parent_scene.gravityz)*m_mass);
//Added for auto fly height. Kitto Flora
//d.Vector3 pos = d.BodyGetPosition(Body);
float target_altitude = _parent_scene.GetTerrainHeightAtXY(_position.X, _position.Y) + MinimumGroundFlightOffset;
if (_position.Z < target_altitude)
{
vec.Z += (target_altitude - _position.Z) * PID_P * 5.0f;
}
// end add Kitto Flora
}
if (vec.IsFinite())
{
doForce(vec);
if (!_zeroFlag)
{
AlignAvatarTiltWithCurrentDirectionOfMovement(vec);
}
}
else
{
m_log.Warn("[PHYSICS]: Got a NaN force vector in Move()");
m_log.Warn("[PHYSICS]: Avatar Position is non-finite!");
defects.Add(this);
// _parent_scene.RemoveCharacter(this);
// destroy avatar capsule and related ODE data
if (Amotor != IntPtr.Zero)
{
// Kill the Amotor
d.JointDestroy(Amotor);
Amotor = IntPtr.Zero;
}
//kill the Geometry
_parent_scene.waitForSpaceUnlock(_parent_scene.space);
if (Body != IntPtr.Zero)
{
//kill the body
d.BodyDestroy(Body);
Body = IntPtr.Zero;
}
if (Shell != IntPtr.Zero)
{
d.GeomDestroy(Shell);
_parent_scene.geom_name_map.Remove(Shell);
Shell = IntPtr.Zero;
}
}
}
/// <summary>
/// Updates the reported position and velocity. This essentially sends the data up to ScenePresence.
/// </summary>
public void UpdatePositionAndVelocity()
{
// no lock; called from Simulate() -- if you call this from elsewhere, gotta lock or do Monitor.Enter/Exit!
d.Vector3 vec;
try
{
vec = d.BodyGetPosition(Body);
}
catch (NullReferenceException)
{
bad = true;
_parent_scene.BadCharacter(this);
vec = new d.Vector3(_position.X, _position.Y, _position.Z);
base.RaiseOutOfBounds(_position); // Tells ScenePresence that there's a problem!
m_log.WarnFormat("[ODEPLUGIN]: Avatar Null reference for Avatar {0}, physical actor {1}", m_name, m_uuid);
}
// kluge to keep things in bounds. ODE lets dead avatars drift away (they should be removed!)
if (vec.X < 0.0f) vec.X = 0.0f;
if (vec.Y < 0.0f) vec.Y = 0.0f;
if (vec.X > (int)_parent_scene.WorldExtents.X - 0.05f) vec.X = (int)_parent_scene.WorldExtents.X - 0.05f;
if (vec.Y > (int)_parent_scene.WorldExtents.Y - 0.05f) vec.Y = (int)_parent_scene.WorldExtents.Y - 0.05f;
_position.X = vec.X;
_position.Y = vec.Y;
_position.Z = vec.Z;
// Did we move last? = zeroflag
// This helps keep us from sliding all over
if (_zeroFlag)
{
_velocity.X = 0.0f;
_velocity.Y = 0.0f;
_velocity.Z = 0.0f;
// Did we send out the 'stopped' message?
if (!m_lastUpdateSent)
{
m_lastUpdateSent = true;
//base.RequestPhysicsterseUpdate();
}
}
else
{
m_lastUpdateSent = false;
try
{
vec = d.BodyGetLinearVel(Body);
}
catch (NullReferenceException)
{
vec.X = _velocity.X;
vec.Y = _velocity.Y;
vec.Z = _velocity.Z;
}
_velocity.X = (vec.X);
_velocity.Y = (vec.Y);
_velocity.Z = (vec.Z);
if (_velocity.Z < -6 && !m_hackSentFall)
{
m_hackSentFall = true;
m_pidControllerActive = false;
}
else if (flying && !m_hackSentFly)
{
//m_hackSentFly = true;
//base.SendCollisionUpdate(new CollisionEventUpdate());
}
else
{
m_hackSentFly = false;
m_hackSentFall = false;
}
}
}
/// <summary>
/// Cleanup the things we use in the scene.
/// </summary>
public void Destroy()
{
m_tainted_isPhysical = false;
_parent_scene.AddPhysicsActorTaint(this);
}
public override void CrossingFailure()
{
}
public override Vector3 PIDTarget { set { return; } }
public override bool PIDActive { set { return; } }
public override float PIDTau { set { return; } }
public override float PIDHoverHeight { set { return; } }
public override bool PIDHoverActive { set { return; } }
public override PIDHoverType PIDHoverType { set { return; } }
public override float PIDHoverTau { set { return; } }
public override void SubscribeEvents(int ms)
{
m_requestedUpdateFrequency = ms;
m_eventsubscription = ms;
_parent_scene.addCollisionEventReporting(this);
}
public override void UnSubscribeEvents()
{
_parent_scene.remCollisionEventReporting(this);
m_requestedUpdateFrequency = 0;
m_eventsubscription = 0;
}
public void AddCollisionEvent(uint CollidedWith, ContactPoint contact)
{
if (m_eventsubscription > 0)
{
CollisionEventsThisFrame.addCollider(CollidedWith, contact);
}
}
public void SendCollisions()
{
if (m_eventsubscription > m_requestedUpdateFrequency)
{
base.SendCollisionUpdate(CollisionEventsThisFrame);
CollisionEventsThisFrame = new CollisionEventUpdate();
m_eventsubscription = 0;
}
}
public override bool SubscribedEvents()
{
if (m_eventsubscription > 0)
return true;
return false;
}
public void ProcessTaints(float timestep)
{
if (m_tainted_isPhysical != m_isPhysical)
{
if (m_tainted_isPhysical)
{
// Create avatar capsule and related ODE data
if (!(Shell == IntPtr.Zero && Body == IntPtr.Zero && Amotor == IntPtr.Zero))
{
m_log.Warn("[PHYSICS]: re-creating the following avatar ODE data, even though it already exists - "
+ (Shell!=IntPtr.Zero ? "Shell ":"")
+ (Body!=IntPtr.Zero ? "Body ":"")
+ (Amotor!=IntPtr.Zero ? "Amotor ":""));
}
AvatarGeomAndBodyCreation(_position.X, _position.Y, _position.Z, m_tensor);
_parent_scene.geom_name_map[Shell] = m_name;
_parent_scene.actor_name_map[Shell] = (PhysicsActor)this;
_parent_scene.AddCharacter(this);
}
else
{
_parent_scene.RemoveCharacter(this);
// destroy avatar capsule and related ODE data
if (Amotor != IntPtr.Zero)
{
// Kill the Amotor
d.JointDestroy(Amotor);
Amotor = IntPtr.Zero;
}
//kill the Geometry
_parent_scene.waitForSpaceUnlock(_parent_scene.space);
if (Body != IntPtr.Zero)
{
//kill the body
d.BodyDestroy(Body);
Body = IntPtr.Zero;
}
if (Shell != IntPtr.Zero)
{
d.GeomDestroy(Shell);
_parent_scene.geom_name_map.Remove(Shell);
Shell = IntPtr.Zero;
}
}
m_isPhysical = m_tainted_isPhysical;
}
if (m_tainted_CAPSULE_LENGTH != CAPSULE_LENGTH)
{
if (Shell != IntPtr.Zero && Body != IntPtr.Zero && Amotor != IntPtr.Zero)
{
m_pidControllerActive = true;
// no lock needed on _parent_scene.OdeLock because we are called from within the thread lock in OdePlugin's simulate()
d.JointDestroy(Amotor);
float prevCapsule = CAPSULE_LENGTH;
CAPSULE_LENGTH = m_tainted_CAPSULE_LENGTH;
//m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
d.BodyDestroy(Body);
d.GeomDestroy(Shell);
AvatarGeomAndBodyCreation(_position.X, _position.Y,
_position.Z + (Math.Abs(CAPSULE_LENGTH - prevCapsule) * 2), m_tensor);
Velocity = Vector3.Zero;
_parent_scene.geom_name_map[Shell] = m_name;
_parent_scene.actor_name_map[Shell] = (PhysicsActor)this;
}
else
{
m_log.Warn("[PHYSICS]: trying to change capsule size, but the following ODE data is missing - "
+ (Shell==IntPtr.Zero ? "Shell ":"")
+ (Body==IntPtr.Zero ? "Body ":"")
+ (Amotor==IntPtr.Zero ? "Amotor ":""));
}
}
if (!m_taintPosition.ApproxEquals(_position, 0.05f))
{
if (Body != IntPtr.Zero)
{
d.BodySetPosition(Body, m_taintPosition.X, m_taintPosition.Y, m_taintPosition.Z);
_position.X = m_taintPosition.X;
_position.Y = m_taintPosition.Y;
_position.Z = m_taintPosition.Z;
}
}
}
internal void AddCollisionFrameTime(int p)
{
// protect it from overflow crashing
if (m_eventsubscription + p >= int.MaxValue)
m_eventsubscription = 0;
m_eventsubscription += p;
}
}
}
| |
using System;
using System.Collections.Generic;
using Avalonia.Platform;
namespace Avalonia.Media
{
/// <summary>
/// Represents a piece of text with formatting.
/// </summary>
public class FormattedText
{
private readonly IPlatformRenderInterface _platform;
private Size _constraint = Size.Infinity;
private IFormattedTextImpl? _platformImpl;
private IReadOnlyList<FormattedTextStyleSpan>? _spans;
private Typeface _typeface;
private double _fontSize;
private string? _text;
private TextAlignment _textAlignment;
private TextWrapping _textWrapping;
/// <summary>
/// Initializes a new instance of the <see cref="FormattedText"/> class.
/// </summary>
public FormattedText()
{
_platform = AvaloniaLocator.Current.GetRequiredService<IPlatformRenderInterface>();
}
/// <summary>
/// Initializes a new instance of the <see cref="FormattedText"/> class.
/// </summary>
/// <param name="platform">The platform render interface.</param>
public FormattedText(IPlatformRenderInterface platform)
{
_platform = platform;
}
/// <summary>
/// Initializes a new instance of the <see cref="FormattedText"/> class.
/// </summary>
/// <param name="text"></param>
/// <param name="typeface"></param>
/// <param name="fontSize"></param>
/// <param name="textAlignment"></param>
/// <param name="textWrapping"></param>
/// <param name="constraint"></param>
public FormattedText(string text, Typeface typeface, double fontSize, TextAlignment textAlignment,
TextWrapping textWrapping, Size constraint) : this()
{
_text = text;
_typeface = typeface;
_fontSize = fontSize;
_textAlignment = textAlignment;
_textWrapping = textWrapping;
_constraint = constraint;
}
/// <summary>
/// Gets the bounds of the text within the <see cref="Constraint"/>.
/// </summary>
/// <returns>The bounds of the text.</returns>
public Rect Bounds => PlatformImpl.Bounds;
/// <summary>
/// Gets or sets the constraint of the text.
/// </summary>
public Size Constraint
{
get => _constraint;
set => Set(ref _constraint, value);
}
/// <summary>
/// Gets or sets the base typeface.
/// </summary>
public Typeface Typeface
{
get => _typeface;
set => Set(ref _typeface, value);
}
/// <summary>
/// Gets or sets the font size.
/// </summary>
public double FontSize
{
get => _fontSize;
set => Set(ref _fontSize, value);
}
/// <summary>
/// Gets or sets a collection of spans that describe the formatting of subsections of the
/// text.
/// </summary>
public IReadOnlyList<FormattedTextStyleSpan>? Spans
{
get => _spans;
set => Set(ref _spans, value);
}
/// <summary>
/// Gets or sets the text.
/// </summary>
public string? Text
{
get => _text;
set => Set(ref _text, value);
}
/// <summary>
/// Gets or sets the alignment of the text.
/// </summary>
public TextAlignment TextAlignment
{
get => _textAlignment;
set => Set(ref _textAlignment, value);
}
/// <summary>
/// Gets or sets the text wrapping.
/// </summary>
public TextWrapping TextWrapping
{
get => _textWrapping;
set => Set(ref _textWrapping, value);
}
/// <summary>
/// Gets platform-specific platform implementation.
/// </summary>
public IFormattedTextImpl PlatformImpl
{
get
{
if (_platformImpl == null)
{
_platformImpl = _platform.CreateFormattedText(
_text ?? string.Empty,
_typeface,
_fontSize,
_textAlignment,
_textWrapping,
_constraint,
_spans);
}
return _platformImpl;
}
}
/// <summary>
/// Gets the lines in the text.
/// </summary>
/// <returns>
/// A collection of <see cref="FormattedTextLine"/> objects.
/// </returns>
public IEnumerable<FormattedTextLine> GetLines()
{
return PlatformImpl.GetLines();
}
/// <summary>
/// Hit tests a point in the text.
/// </summary>
/// <param name="point">The point.</param>
/// <returns>
/// A <see cref="TextHitTestResult"/> describing the result of the hit test.
/// </returns>
public TextHitTestResult HitTestPoint(Point point)
{
return PlatformImpl.HitTestPoint(point);
}
/// <summary>
/// Gets the bounds rectangle that the specified character occupies.
/// </summary>
/// <param name="index">The index of the character.</param>
/// <returns>The character bounds.</returns>
public Rect HitTestTextPosition(int index)
{
return PlatformImpl.HitTestTextPosition(index);
}
/// <summary>
/// Gets the bounds rectangles that the specified text range occupies.
/// </summary>
/// <param name="index">The index of the first character.</param>
/// <param name="length">The number of characters in the text range.</param>
/// <returns>The character bounds.</returns>
public IEnumerable<Rect> HitTestTextRange(int index, int length)
{
return PlatformImpl.HitTestTextRange(index, length);
}
private void Set<T>(ref T field, T value)
{
if (EqualityComparer<T>.Default.Equals(field, value))
{
return;
}
field = value;
_platformImpl = null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Common.Logging;
using ReMi.Common.Utils;
using ReMi.Common.Utils.Repository;
using ReMi.DataAccess.Exceptions;
using ReMi.DataEntities;
using ReMi.DataEntities.Auth;
using ReMi.DataEntities.ReleaseCalendar;
namespace ReMi.DataAccess.BusinessEntityGateways.ReleasePlan
{
public class ReleaseParticipantGateway : BaseGateway, IReleaseParticipantGateway
{
public IRepository<Account> AccountRepository { get; set; }
public IRepository<ReleaseWindow> ReleaseWindowRepository { get; set; }
public IRepository<ReleaseParticipant> ReleaseParticipantRepository { get; set; }
public IMappingEngine Mapper { get; set; }
private static readonly ILog Log = LogManager.GetCurrentClassLogger();
public override void OnDisposing()
{
AccountRepository.Dispose();
ReleaseWindowRepository.Dispose();
ReleaseParticipantRepository.Dispose();
base.OnDisposing();
}
public void AddReleaseParticipants(List<BusinessEntities.ReleasePlan.ReleaseParticipant> releaseParticipants, Guid authorId)
{
var releaseWindowGuid = releaseParticipants[0].ReleaseWindowId;
var releaseWindow =
ReleaseWindowRepository.GetSatisfiedBy(x => x.ExternalId == releaseWindowGuid);
if (releaseWindow == null)
{
Log.ErrorFormat(
"ReleaseParticipantGateway: ReleaseWindow with ExternalId={0} was not found in accounts repository",
releaseParticipants[0].ReleaseWindowId);
throw new ReleaseWindowNotFoundException(releaseWindowGuid);
}
var releaseWindowId = releaseWindow.ReleaseWindowId;
var existingParticipants =
ReleaseParticipantRepository.GetAllSatisfiedBy(rp => rp.ReleaseWindowId == releaseWindowId).ToList();
foreach (var releaseParticipant in releaseParticipants)
{
var accountId =
AccountRepository.GetSatisfiedBy(acc => acc.Email == releaseParticipant.Account.Email).AccountId;
if (!existingParticipants.Any(p => p.AccountId == accountId && p.ReleaseWindowId == releaseWindowId))
{
var releaseParticipantEntity = new ReleaseParticipant
{
AccountId = accountId,
ReleaseWindowId = releaseWindowId,
ExternalId = releaseParticipant.ReleaseParticipantId == Guid.Empty ? Guid.NewGuid() : releaseParticipant.ReleaseParticipantId,
ApprovedOn =
releaseParticipant.Account.ExternalId == authorId
? SystemTime.Now
: (DateTime?) null
};
ReleaseParticipantRepository.Insert(releaseParticipantEntity);
}
}
}
public void AddReleaseParticipants(List<BusinessEntities.ReleasePlan.ReleaseParticipant> releaseParticipants)
{
AddReleaseParticipants(releaseParticipants, Guid.NewGuid());
}
public void RemoveReleaseParticipant(BusinessEntities.ReleasePlan.ReleaseParticipant releaseParticipant)
{
var account =
AccountRepository.GetSatisfiedBy(
x =>
x.Email == releaseParticipant.Account.Email);
if (account == null)
{
Log.ErrorFormat("ReleaseParticipantGateway: Account={0} was not found in accounts repository",
releaseParticipant.Account);
}
var accountId = account.AccountId;
var releaseWindow =
ReleaseWindowRepository.GetSatisfiedBy(x => x.ExternalId == releaseParticipant.ReleaseWindowId);
if (releaseWindow == null)
{
Log.ErrorFormat(
"ReleaseParticipantGateway: ReleaseWindow with ExternalId={0} was not found in accounts repository",
releaseParticipant.ReleaseWindowId);
}
var releaseWindowId = releaseWindow.ReleaseWindowId;
var participant =
ReleaseParticipantRepository.GetSatisfiedBy(
x => x.AccountId == accountId && x.ReleaseWindowId == releaseWindowId);
if (participant != null)
{
ReleaseParticipantRepository.Delete(participant);
}
else
{
Log.ErrorFormat("ReleaseParticipantGateway: Cannot find release participant={0} in repository",
releaseParticipant);
}
}
public IEnumerable<BusinessEntities.ReleasePlan.ReleaseParticipant> GetReleaseParticipants(Guid releaseWindowId)
{
var releaseWindow = ReleaseWindowRepository.GetSatisfiedBy(window => window.ExternalId == releaseWindowId);
if (releaseWindow == null)
Log.ErrorFormat("Releease window with id={0} was not found in repository", releaseWindowId);
var releaseParticipants =
ReleaseParticipantRepository.GetAllSatisfiedBy(
rp => rp.ReleaseWindowId == releaseWindow.ReleaseWindowId).ToList();
if (!releaseParticipants.Any())
{
Log.InfoFormat("There are no participants for release={0}", releaseWindowId);
return new List<BusinessEntities.ReleasePlan.ReleaseParticipant>();
}
var accountIdList = releaseParticipants.Select(account => account.AccountId).ToList();
var accounts =
AccountRepository.GetAllSatisfiedBy(account => accountIdList.Any(acc => acc == account.AccountId))
.ToList();
var releaseParticipantsList = releaseParticipants.Join(accounts, rp => rp.AccountId, a => a.AccountId,
(rp, a) =>
new BusinessEntities.ReleasePlan.ReleaseParticipant
{
ReleaseWindowId = releaseWindowId,
ReleaseParticipantId = rp.ExternalId,
Account = Mapper.Map<Account, BusinessEntities.Auth.Account>(a),
IsParticipationConfirmed = rp.ApprovedOn != null
}).ToList();
return releaseParticipantsList;
}
public List<BusinessEntities.Auth.Account> GetReleaseMembers(Guid releaseWindowId)
{
var window = ReleaseWindowRepository.GetSatisfiedBy(x => x.ExternalId == releaseWindowId);
var members = window.ReleaseParticipants.Select(x => x.Account).ToList();
members.AddRange(
window.SignOffs.Where(x => members.All(m => m.Email != x.Account.Email)).Select(s => s.Account));
members.AddRange(
window.ReleaseApprovers.Where(x => members.All(m => m.Email != x.Account.Email)).Select(s => s.Account));
return Mapper.Map<List<Account>, List<BusinessEntities.Auth.Account>>(members);
}
public BusinessEntities.ReleaseCalendar.ReleaseWindow GetReleaseWindow(Guid releaseParticipantId)
{
return
Mapper.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(
ReleaseParticipantRepository.GetSatisfiedBy(x => x.ExternalId == releaseParticipantId).ReleaseWindow);
}
public void ApproveReleaseParticipation(Guid releaseParticipantId)
{
var releaseParticipant =
ReleaseParticipantRepository.GetSatisfiedBy(rp => rp.ExternalId == releaseParticipantId);
if (releaseParticipant.ApprovedOn == null)
{
releaseParticipant.ApprovedOn = SystemTime.Now;
ReleaseParticipantRepository.Update(releaseParticipant);
}
}
public void ClearParticipationApprovements(Guid releaseWindowId, Guid authorId)
{
var participants =
ReleaseParticipantRepository.GetAllSatisfiedBy(rp => rp.ReleaseWindow.ExternalId == releaseWindowId);
foreach (var releaseParticipant in participants)
{
if (releaseParticipant.Account.ExternalId == authorId)
{
releaseParticipant.ApprovedOn = SystemTime.Now;
}
else
{
releaseParticipant.ApprovedOn = null;
}
ReleaseParticipantRepository.Update(releaseParticipant);
}
}
}
}
| |
/*
* Copyright 2006-2015 TIBIC SOLUTIONS
*
* 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;
using System.Web.UI;
using System.Xml;
using LWAS.Extensible.Interfaces.Storage;
using LWAS.Infrastructure.Storage;
using LWAS.Infrastructure.Security;
namespace LWAS.WebParts.Editors
{
public class RolesDataSource : DataSourceControl
{
public string ApplicationName { get; set; }
private string _rolesFile;
private IStorageAgent _agent;
public IStorageAgent Agent
{
get
{
return this._agent;
}
}
public RolesDataSource(string rolesFile, string application)
{
this._rolesFile = rolesFile;
this.ApplicationName = application;
this._agent = new FileAgent();
if (!this._agent.HasKey(rolesFile))
{
XmlDocument doc = new XmlDocument();
doc.AppendChild(doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""));
doc.AppendChild(doc.CreateNode(XmlNodeType.Element, "roles", ""));
this._agent.Write(this._rolesFile, string.Empty);
this.SaveRolesFile(doc);
}
}
protected XmlDocument LoadRolesFile()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(this._agent.Read(this._rolesFile));
return doc;
}
protected void SaveRolesFile(XmlDocument doc)
{
this._agent.Erase(this._rolesFile);
try
{
doc.Save(this._agent.OpenStream(this._rolesFile));
}
finally
{
this._agent.CloseStream(this._rolesFile);
}
}
public IEnumerable ListRoles()
{
ArrayList ret = new ArrayList();
XmlDocument doc = this.LoadRolesFile();
XmlNode root = doc.SelectSingleNode("roles");
if (null == root)
{
throw new InvalidOperationException("Roles file has no roles node");
}
foreach (XmlNode roleNode in root.ChildNodes)
{
if ("role" == roleNode.Name)
{
ret.Add(roleNode.Attributes["name"].Value);
}
}
return ret;
}
public void CreateRole(string name)
{
if (!String.IsNullOrEmpty(this.ApplicationName) && !DeveloperAccessVerifier.Instance.IsOwner(this.ApplicationName))
throw new InvalidOperationException(String.Format("Failed to setup roles for the application '{0}'. You don't have access to that application.", this.ApplicationName));
XmlDocument doc = this.LoadRolesFile();
XmlNode root = doc.SelectSingleNode("roles");
if (null == root)
{
throw new InvalidOperationException("Roles file has no roles node");
}
XmlNode node = doc.CreateNode(XmlNodeType.Element, "role", "");
XmlAttribute nameAttribute = doc.CreateAttribute("name");
nameAttribute.Value = name;
node.Attributes.Append(nameAttribute);
root.AppendChild(node);
this.SaveRolesFile(doc);
}
public void RenameRole(string oldname, string newname)
{
if (!String.IsNullOrEmpty(this.ApplicationName) && !DeveloperAccessVerifier.Instance.IsOwner(this.ApplicationName))
throw new InvalidOperationException(String.Format("Failed to setup roles for the application '{0}'. You don't have access to that application.", this.ApplicationName));
if (!(oldname == newname))
{
XmlDocument doc = this.LoadRolesFile();
XmlNode root = doc.SelectSingleNode("roles");
if (null == root)
{
throw new InvalidOperationException("Roles file has no roles node");
}
XmlNode roleNode = root.SelectSingleNode("child::role[attribute::name='" + oldname + "']");
if (null == roleNode)
{
throw new ArgumentException(string.Format("Can't find role '{0}'", oldname));
}
roleNode.Attributes["name"].Value = newname;
this.SaveRolesFile(doc);
}
}
public void DeleteRole(string name)
{
if (!String.IsNullOrEmpty(this.ApplicationName) && !DeveloperAccessVerifier.Instance.IsOwner(this.ApplicationName))
throw new InvalidOperationException(String.Format("Failed to setup roles for the application '{0}'. You don't have access to that application.", this.ApplicationName));
XmlDocument doc = this.LoadRolesFile();
XmlNode root = doc.SelectSingleNode("roles");
if (null == root)
{
throw new InvalidOperationException("Roles file has no roles node");
}
XmlNode roleNode = root.SelectSingleNode("child::role[attribute::name='" + name + "']");
if (null == roleNode)
{
throw new ArgumentException(string.Format("Can't find role '{0}'", name));
}
root.RemoveChild(roleNode);
this.SaveRolesFile(doc);
}
public IEnumerable ListUsers(string role)
{
ArrayList ret = new ArrayList();
XmlDocument doc = this.LoadRolesFile();
XmlNode root = doc.SelectSingleNode("roles");
if (null == root)
{
throw new InvalidOperationException("Roles file has no roles node");
}
XmlNode roleNode = root.SelectSingleNode("child::role[attribute::name='" + role + "']");
if (null != roleNode)
{
foreach (XmlNode userNode in roleNode.ChildNodes)
{
if ("user" == userNode.Name)
{
ret.Add(userNode.Attributes["name"].Value);
}
}
}
return ret;
}
public void CreateUser(string role, string name)
{
if (!String.IsNullOrEmpty(this.ApplicationName) && !DeveloperAccessVerifier.Instance.IsOwner(this.ApplicationName))
throw new InvalidOperationException(String.Format("Failed to setup roles for the application '{0}'. You don't have access to that application.", this.ApplicationName));
XmlDocument doc = this.LoadRolesFile();
XmlNode root = doc.SelectSingleNode("roles");
if (null == root)
{
throw new InvalidOperationException("Roles file has no roles node");
}
XmlNode roleNode = root.SelectSingleNode("child::role[attribute::name='" + role + "']");
if (null == roleNode)
{
throw new ArgumentException(string.Format("Can't find role '{0}'", role));
}
XmlNode node = doc.CreateNode(XmlNodeType.Element, "user", "");
XmlAttribute nameAttribute = doc.CreateAttribute("name");
nameAttribute.Value = name;
node.Attributes.Append(nameAttribute);
roleNode.AppendChild(node);
this.SaveRolesFile(doc);
}
public void RenameUser(string role, string oldname, string newname)
{
if (!String.IsNullOrEmpty(this.ApplicationName) && !DeveloperAccessVerifier.Instance.IsOwner(this.ApplicationName))
throw new InvalidOperationException(String.Format("Failed to setup roles for the application '{0}'. You don't have access to that application.", this.ApplicationName));
if (!(oldname == newname))
{
XmlDocument doc = this.LoadRolesFile();
XmlNode root = doc.SelectSingleNode("roles");
if (null == root)
{
throw new InvalidOperationException("Roles file has no roles node");
}
XmlNode roleNode = root.SelectSingleNode("child::role[attribute::name='" + role + "']");
if (null == roleNode)
{
throw new ArgumentException(string.Format("Can't find role '{0}'", role));
}
XmlNode userNode = roleNode.SelectSingleNode("child::user[attribute::name='" + oldname + "']");
if (null != userNode)
{
userNode.Attributes["name"].Value = newname;
}
this.SaveRolesFile(doc);
}
}
public void DeleteUser(string role, string name)
{
if (!String.IsNullOrEmpty(this.ApplicationName) && !DeveloperAccessVerifier.Instance.IsOwner(this.ApplicationName))
throw new InvalidOperationException(String.Format("Failed to setup roles for the application '{0}'. You don't have access to that application.", this.ApplicationName));
XmlDocument doc = this.LoadRolesFile();
XmlNode root = doc.SelectSingleNode("roles");
if (null == root)
{
throw new InvalidOperationException("Roles file has no roles node");
}
XmlNode roleNode = root.SelectSingleNode("child::role[attribute::name='" + role + "']");
if (null == roleNode)
{
throw new ArgumentException(string.Format("Can't find role '{0}'", role));
}
XmlNode userNode = roleNode.SelectSingleNode("child::user[attribute::name='" + name + "']");
if (null != userNode)
{
roleNode.RemoveChild(userNode);
}
this.SaveRolesFile(doc);
}
protected override DataSourceView GetView(string viewName)
{
DataSourceView result;
if ("/" == viewName)
{
result = new RolesView(this, viewName);
}
else
{
if (!string.IsNullOrEmpty(viewName))
{
result = new RoleUsersView(this, viewName);
}
else
{
result = new NoEditView(this, string.Empty);
}
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using BugsnagUnity.Payload;
using UnityEngine;
using System.Threading;
using System.Text;
namespace BugsnagUnity
{
class NativeInterface
{
private IntPtr BugsnagNativeInterface;
private IntPtr BugsnagUnityClass;
// Cache of classes used:
private IntPtr LastRunInfoClass;
private IntPtr BreadcrumbClass;
private IntPtr BreadcrumbTypeClass;
private IntPtr CollectionClass;
private IntPtr IteratorClass;
private IntPtr ListClass;
private IntPtr MapClass;
private IntPtr DateClass;
private IntPtr DateUtilsClass;
private IntPtr MapEntryClass;
private IntPtr SetClass;
private IntPtr StringClass;
private IntPtr SessionClass;
private IntPtr ClientClass;
// Cache of methods used:
private IntPtr BreadcrumbGetMessage;
private IntPtr BreadcrumbGetMetadata;
private IntPtr BreadcrumbGetTimestamp;
private IntPtr BreadcrumbGetType;
private IntPtr ClassIsArray;
private IntPtr CollectionIterator;
private IntPtr IteratorHasNext;
private IntPtr IteratorNext;
private IntPtr MapEntryGetKey;
private IntPtr MapEntryGetValue;
private IntPtr MapEntrySet;
private IntPtr ObjectGetClass;
private IntPtr ObjectToString;
private IntPtr ToIso8601;
private IntPtr AddFeatureFlagMethod;
private IntPtr ClearFeatureFlagMethod;
private IntPtr ClearFeatureFlagsMethod;
private bool CanRunOnBackgroundThread;
private static bool Unity2019OrNewer;
private Thread MainThread;
private class OnSessionCallback : AndroidJavaProxy
{
private Configuration _config;
public OnSessionCallback(Configuration config) : base("com.bugsnag.android.OnSessionCallback")
{
_config = config;
}
public bool onSession(AndroidJavaObject session)
{
var wrapper = new NativeSession(session);
foreach (var callback in _config.GetOnSessionCallbacks())
{
try
{
if (!callback.Invoke(wrapper))
{
return false;
}
}
catch {
// If the callback causes an exception, ignore it and execute the next one
}
}
return true;
}
}
private class OnSendErrorCallback : AndroidJavaProxy
{
private Configuration _config;
public OnSendErrorCallback(Configuration config) : base("com.bugsnag.android.OnSendCallback")
{
_config = config;
}
public bool onSend(AndroidJavaObject @event)
{
var wrapper = new NativeEvent(@event);
foreach (var callback in _config.GetOnSendErrorCallbacks())
{
try
{
if (!callback.Invoke(wrapper))
{
return false;
}
}
catch {
// If the callback causes an exception, ignore it and execute the next one
}
}
return true;
}
}
public NativeInterface(Configuration cfg)
{
AndroidJavaObject config = CreateNativeConfig(cfg);
Unity2019OrNewer = IsUnity2019OrNewer();
MainThread = Thread.CurrentThread;
using (AndroidJavaClass system = new AndroidJavaClass("java.lang.System"))
{
string arch = system.CallStatic<string>("getProperty", "os.arch");
CanRunOnBackgroundThread = (arch != "x86" && arch != "i686" && arch != "x86_64");
}
using (AndroidJavaClass unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
using (AndroidJavaObject activity = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity"))
using (AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext"))
using (AndroidJavaObject client = new AndroidJavaObject("com.bugsnag.android.Client", context, config))
{
// lookup the NativeInterface class and set the client to the local object.
// all subsequent communication should go through the NativeInterface.
IntPtr nativeInterfaceRef = AndroidJNI.FindClass("com/bugsnag/android/NativeInterface");
BugsnagNativeInterface = AndroidJNI.NewGlobalRef(nativeInterfaceRef);
AndroidJNI.DeleteLocalRef(nativeInterfaceRef);
IntPtr setClient = AndroidJNI.GetStaticMethodID(BugsnagNativeInterface, "setClient", "(Lcom/bugsnag/android/Client;)V");
object[] args = new object[] { client };
jvalue[] jargs = AndroidJNIHelper.CreateJNIArgArray(args);
AndroidJNI.CallStaticVoidMethod(BugsnagNativeInterface, setClient, jargs);
AndroidJNIHelper.DeleteJNIArgArray(args, jargs);
// Cache JNI refs which will be used to load report data later in the
// app lifecycle to avoid repeated lookups
IntPtr unityRef = AndroidJNI.FindClass("com/bugsnag/android/unity/BugsnagUnity");
BugsnagUnityClass = AndroidJNI.NewGlobalRef(unityRef);
AndroidJNI.DeleteLocalRef(unityRef);
IntPtr crumbRef = AndroidJNI.FindClass("com/bugsnag/android/Breadcrumb");
BreadcrumbClass = AndroidJNI.NewGlobalRef(crumbRef);
AndroidJNI.DeleteLocalRef(crumbRef);
IntPtr lastRunInfoRef = AndroidJNI.FindClass("com/bugsnag/android/LastRunInfo");
LastRunInfoClass = AndroidJNI.NewGlobalRef(lastRunInfoRef);
AndroidJNI.DeleteLocalRef(lastRunInfoRef);
IntPtr crumbTypeRef = AndroidJNI.FindClass("com/bugsnag/android/BreadcrumbType");
BreadcrumbTypeClass = AndroidJNI.NewGlobalRef(crumbTypeRef);
AndroidJNI.DeleteLocalRef(crumbTypeRef);
IntPtr collectionRef = AndroidJNI.FindClass("java/util/Collection");
CollectionClass = AndroidJNI.NewGlobalRef(collectionRef);
AndroidJNI.DeleteLocalRef(collectionRef);
IntPtr iterRef = AndroidJNI.FindClass("java/util/Iterator");
IteratorClass = AndroidJNI.NewGlobalRef(iterRef);
AndroidJNI.DeleteLocalRef(iterRef);
IntPtr listRef = AndroidJNI.FindClass("java/util/List");
ListClass = AndroidJNI.NewGlobalRef(listRef);
AndroidJNI.DeleteLocalRef(listRef);
IntPtr mapRef = AndroidJNI.FindClass("java/util/Map");
MapClass = AndroidJNI.NewGlobalRef(mapRef);
AndroidJNI.DeleteLocalRef(mapRef);
IntPtr dateRef = AndroidJNI.FindClass("java/util/Date");
DateClass = AndroidJNI.NewGlobalRef(dateRef);
AndroidJNI.DeleteLocalRef(dateRef);
IntPtr dateUtilsRef = AndroidJNI.FindClass("com/bugsnag/android/internal/DateUtils");
DateUtilsClass = AndroidJNI.NewGlobalRef(dateUtilsRef);
IntPtr entryRef = AndroidJNI.FindClass("java/util/Map$Entry");
MapEntryClass = AndroidJNI.NewGlobalRef(entryRef);
AndroidJNI.DeleteLocalRef(entryRef);
IntPtr setRef = AndroidJNI.FindClass("java/util/Set");
SetClass = AndroidJNI.NewGlobalRef(setRef);
AndroidJNI.DeleteLocalRef(setRef);
IntPtr stringRef = AndroidJNI.FindClass("java/lang/String");
StringClass = AndroidJNI.NewGlobalRef(stringRef);
AndroidJNI.DeleteLocalRef(stringRef);
IntPtr sessionRef = AndroidJNI.FindClass("com/bugsnag/android/Session");
SessionClass = AndroidJNI.NewGlobalRef(sessionRef);
AndroidJNI.DeleteLocalRef(sessionRef);
IntPtr clientRef = AndroidJNI.FindClass("com/bugsnag/android/Client");
ClientClass = AndroidJNI.NewGlobalRef(clientRef);
AndroidJNI.DeleteLocalRef(clientRef);
BreadcrumbGetMetadata = AndroidJNI.GetMethodID(BreadcrumbClass, "getMetadata", "()Ljava/util/Map;");
BreadcrumbGetType = AndroidJNI.GetMethodID(BreadcrumbClass, "getType", "()Lcom/bugsnag/android/BreadcrumbType;");
BreadcrumbGetTimestamp = AndroidJNI.GetMethodID(BreadcrumbClass, "getStringTimestamp", "()Ljava/lang/String;");
BreadcrumbGetMessage = AndroidJNI.GetMethodID(BreadcrumbClass, "getMessage", "()Ljava/lang/String;");
CollectionIterator = AndroidJNI.GetMethodID(CollectionClass, "iterator", "()Ljava/util/Iterator;");
IteratorHasNext = AndroidJNI.GetMethodID(IteratorClass, "hasNext", "()Z");
IteratorNext = AndroidJNI.GetMethodID(IteratorClass, "next", "()Ljava/lang/Object;");
MapEntryGetKey = AndroidJNI.GetMethodID(MapEntryClass, "getKey", "()Ljava/lang/Object;");
MapEntryGetValue = AndroidJNI.GetMethodID(MapEntryClass, "getValue", "()Ljava/lang/Object;");
MapEntrySet = AndroidJNI.GetMethodID(MapClass, "entrySet", "()Ljava/util/Set;");
AddFeatureFlagMethod = AndroidJNI.GetMethodID(ClientClass, "addFeatureFlag", "(Ljava/lang/String;Ljava/lang/String;)V");
ClearFeatureFlagMethod = AndroidJNI.GetMethodID(ClientClass, "clearFeatureFlag", "(Ljava/lang/String;)V");
ClearFeatureFlagsMethod = AndroidJNI.GetMethodID(ClientClass, "clearFeatureFlags", "()V");
IntPtr objectRef = AndroidJNI.FindClass("java/lang/Object");
ObjectToString = AndroidJNI.GetMethodID(objectRef, "toString", "()Ljava/lang/String;");
ObjectGetClass = AndroidJNI.GetMethodID(objectRef, "getClass", "()Ljava/lang/Class;");
AndroidJNI.DeleteLocalRef(objectRef);
IntPtr classRef = AndroidJNI.FindClass("java/lang/Class");
ClassIsArray = AndroidJNI.GetMethodID(classRef, "isArray", "()Z");
AndroidJNI.DeleteLocalRef(classRef);
ToIso8601 = AndroidJNI.GetStaticMethodID(DateUtilsClass, "toIso8601", "(Ljava/util/Date;)Ljava/lang/String;");
AndroidJNI.DeleteLocalRef(dateUtilsRef);
// the bugsnag-android notifier uses Activity lifecycle tracking to
// determine if the application is in the foreground. As the unity
// activity has already started at this point we need to tell the
// notifier about the activity and the fact that it has started.
using (AndroidJavaObject sessionTracker = client.Get<AndroidJavaObject>("sessionTracker"))
using (AndroidJavaObject activityClass = activity.Call<AndroidJavaObject>("getClass"))
{
string activityName = null;
using (AndroidJavaObject activityNameObject = activityClass.Call<AndroidJavaObject>("getSimpleName"))
{
if (activityNameObject != null)
{
activityName = AndroidJNI.GetStringUTFChars(activityNameObject.GetRawObject());
}
}
sessionTracker.Call("updateForegroundTracker", activityName, true, 0L);
}
ConfigureNotifierInfo(client);
}
}
/**
* Transforms an IConfiguration C# object into a Java Configuration object.
*/
AndroidJavaObject CreateNativeConfig(Configuration config)
{
var obj = new AndroidJavaObject("com.bugsnag.android.Configuration", config.ApiKey);
// configure automatic tracking of errors/sessions
using (AndroidJavaObject errorTypes = new AndroidJavaObject("com.bugsnag.android.ErrorTypes"))
{
errorTypes.Call("setAnrs", config.EnabledErrorTypes.ANRs);
errorTypes.Call("setNdkCrashes", config.EnabledErrorTypes.Crashes);
errorTypes.Call("setUnhandledExceptions", config.EnabledErrorTypes.Crashes);
obj.Call("setEnabledErrorTypes", errorTypes);
}
obj.Call("setAutoTrackSessions", config.AutoTrackSessions);
obj.Call("setAutoDetectErrors", config.AutoDetectErrors);
obj.Call("setAppVersion", config.AppVersion);
obj.Call("setContext", config.Context);
obj.Call("setMaxBreadcrumbs", config.MaximumBreadcrumbs);
obj.Call("setMaxPersistedEvents", config.MaxPersistedEvents);
obj.Call("setMaxPersistedSessions", config.MaxPersistedSessions);
obj.Call("setPersistUser", config.PersistUser);
obj.Call("setLaunchDurationMillis", config.LaunchDurationMillis);
obj.Call("setSendLaunchCrashesSynchronously", config.SendLaunchCrashesSynchronously);
if (config.GetUser() != null)
{
var user = config.GetUser();
obj.Call("setUser", user.Id, user.Email, user.Name);
}
//Register for callbacks
obj.Call("addOnSession", new OnSessionCallback(config));
obj.Call("addOnSend", new OnSendErrorCallback(config));
// set endpoints
var notify = config.Endpoints.Notify.ToString();
var sessions = config.Endpoints.Session.ToString();
using (AndroidJavaObject endpointConfig = new AndroidJavaObject("com.bugsnag.android.EndpointConfiguration", notify, sessions))
{
obj.Call("setEndpoints", endpointConfig);
}
//android layer expects a nonnull java Integer not just an int, so we check if it has actually been set to a valid value
if (config.VersionCode > -1)
{
var javaInteger = new AndroidJavaObject("java.lang.Integer", config.VersionCode);
obj.Call("setVersionCode", javaInteger);
}
//Null or empty check necessary because android will set the app.type to empty if that or null is passed as default
if (!string.IsNullOrEmpty(config.AppType))
{
obj.Call("setAppType", config.AppType);
}
// set EnabledBreadcrumbTypes
if (config.EnabledBreadcrumbTypes != null)
{
using (AndroidJavaObject enabledBreadcrumbs = new AndroidJavaObject("java.util.HashSet"))
{
AndroidJavaClass androidBreadcrumbEnumClass = new AndroidJavaClass("com.bugsnag.android.BreadcrumbType");
for (int i = 0; i < config.EnabledBreadcrumbTypes.Length; i++)
{
var stringValue = Enum.GetName(typeof(BreadcrumbType), config.EnabledBreadcrumbTypes[i]).ToUpper();
using (AndroidJavaObject crumbType = androidBreadcrumbEnumClass.CallStatic<AndroidJavaObject>("valueOf", stringValue))
{
enabledBreadcrumbs.Call<Boolean>("add", crumbType);
}
}
obj.Call("setEnabledBreadcrumbTypes", enabledBreadcrumbs);
}
}
// set feature flags
if (config.FeatureFlags != null && config.FeatureFlags.Count > 0)
{
foreach (var flag in config.FeatureFlags)
{
obj.Call("addFeatureFlag",flag.Name,flag.Variant);
}
}
// set sendThreads
AndroidJavaClass androidThreadSendPolicyClass = new AndroidJavaClass("com.bugsnag.android.ThreadSendPolicy");
using (AndroidJavaObject policy = androidThreadSendPolicyClass.CallStatic<AndroidJavaObject>("valueOf", GetAndroidFormatThreadSendName(config.SendThreads)))
{
obj.Call("setSendThreads", policy);
}
// set release stages
obj.Call("setReleaseStage", config.ReleaseStage);
if (config.EnabledReleaseStages != null && config.EnabledReleaseStages.Length > 0)
{
obj.Call("setEnabledReleaseStages", GetAndroidStringSetFromArray(config.EnabledReleaseStages));
}
// set DiscardedClasses
if (config.DiscardClasses != null && config.DiscardClasses.Length > 0)
{
obj.Call("setDiscardClasses", GetAndroidStringSetFromArray(config.DiscardClasses));
}
// set ProjectPackages
if (config.ProjectPackages != null && config.ProjectPackages.Length > 0)
{
obj.Call("setProjectPackages", GetAndroidStringSetFromArray(config.ProjectPackages));
}
// set redacted keys
if (config.RedactedKeys != null && config.RedactedKeys.Length > 0)
{
obj.Call("setRedactedKeys", GetAndroidStringSetFromArray(config.RedactedKeys));
}
// add unity event callback
var BugsnagUnity = new AndroidJavaClass("com.bugsnag.android.unity.BugsnagUnity");
obj.Call("addOnError", BugsnagUnity.CallStatic<AndroidJavaObject>("getNativeCallback", new object[] { }));
// set persistence directory
if (!string.IsNullOrEmpty(config.PersistenceDirectory))
{
AndroidJavaObject androidFile = new AndroidJavaObject("java.io.File", config.PersistenceDirectory);
obj.Call("setPersistenceDirectory", androidFile);
}
return obj;
}
private string GetAndroidFormatThreadSendName(ThreadSendPolicy threadSendPolicy)
{
switch (threadSendPolicy)
{
case ThreadSendPolicy.Always:
return "ALWAYS";
case ThreadSendPolicy.UnhandledOnly:
return "UNHANDLED_ONLY";
default:
return "NEVER";
}
}
private AndroidJavaObject GetAndroidStringSetFromArray(string[] array)
{
AndroidJavaObject set = new AndroidJavaObject("java.util.HashSet");
foreach (var item in array)
{
set.Call<Boolean>("add", item);
}
return set;
}
private void ConfigureNotifierInfo(AndroidJavaObject client)
{
using (AndroidJavaObject notifier = client.Get<AndroidJavaObject>("notifier"))
{
AndroidJavaObject androidNotifier = new AndroidJavaObject("com.bugsnag.android.Notifier");
androidNotifier.Call("setUrl", androidNotifier.Get<string>("url"));
androidNotifier.Call("setName", androidNotifier.Get<string>("name"));
androidNotifier.Call("setVersion", androidNotifier.Get<string>("version"));
AndroidJavaObject list = new AndroidJavaObject("java.util.ArrayList");
list.Call<Boolean>("add", androidNotifier);
notifier.Call("setDependencies", list);
notifier.Call("setUrl", NotifierInfo.NotifierUrl);
notifier.Call("setName", "Unity Bugsnag Notifier");
notifier.Call("setVersion", NotifierInfo.NotifierVersion);
}
}
/**
* Pushes a local JNI frame with 128 capacity. This avoids the reference table
* being exceeded, which can happen on some lower-end Android devices in extreme conditions
* (e.g. Nexus 7 running Android 6). This is likely due to AndroidJavaObject
* not deleting local references immediately.
*
* If this call is unsuccessful it indicates the device is low on memory so the caller should no-op.
* https://docs.unity3d.com/ScriptReference/AndroidJNI.PopLocalFrame.html
*/
private bool PushLocalFrame()
{
if (AndroidJNI.PushLocalFrame(128) != 0)
{
AndroidJNI.ExceptionClear(); // clear pending OutOfMemoryError.
return false;
}
return true;
}
/**
* Pops the local JNI frame, freeing any references in the table.
* https://docs.unity3d.com/ScriptReference/AndroidJNI.PopLocalFrame.html
*/
private void PopLocalFrame()
{
AndroidJNI.PopLocalFrame(System.IntPtr.Zero);
}
public void SetAutoDetectErrors(bool newValue)
{
CallNativeVoidMethod("setAutoNotify", "(Z)V", new object[] { newValue });
}
public void SetContext(string newValue)
{
CallNativeVoidMethod("setContext", "(Ljava/lang/String;)V", new object[] { newValue });
}
public void SetUser(User user)
{
var method = "setUser";
var description = "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V";
if (user == null)
{
CallNativeVoidMethod(method, description, new object[] { null, null, null });
}
else
{
CallNativeVoidMethod(method, description,
new object[] { user.Id, user.Email, user.Name });
}
}
public void StartSession()
{
CallNativeVoidMethod("startSession", "()V", new object[] { });
}
public bool ResumeSession()
{
return CallNativeBoolMethod("resumeSession", "()Z", new object[] { });
}
public void PauseSession()
{
CallNativeVoidMethod("pauseSession", "()V", new object[] { });
}
public void UpdateSession(Session session)
{
if (session != null)
{
// The ancient version of the runtime used doesn't have an equivalent to GetUnixTime()
var startedAt = (long)(session.StartedAt - new DateTime(1970, 1, 1, 0, 0, 0, 0))?.TotalMilliseconds;
CallNativeVoidMethod("registerSession", "(JLjava/lang/String;II)V", new object[]{
startedAt, session.Id.ToString(), session.UnhandledCount(),
session.HandledCount()
});
}
}
public Session GetCurrentSession()
{
var javaSession = CallNativeObjectMethodRef("getCurrentSession", "()Lcom/bugsnag/android/Session;", new object[] { });
var id = AndroidJNI.CallStringMethod(javaSession, AndroidJNIHelper.GetMethodID(SessionClass, "getId"), new jvalue[] { });
if (id == null)
{
return null;
}
var javaStartedAt = AndroidJNI.CallObjectMethod(javaSession, AndroidJNIHelper.GetMethodID(SessionClass, "getStartedAt"), new jvalue[] { });
var unhandledCount = AndroidJNI.CallIntMethod(javaSession, AndroidJNIHelper.GetMethodID(SessionClass, "getUnhandledCount"), new jvalue[] { });
var handledCount = AndroidJNI.CallIntMethod(javaSession, AndroidJNIHelper.GetMethodID(SessionClass, "getHandledCount"), new jvalue[] { });
var timeLong = AndroidJNI.CallLongMethod(javaStartedAt, AndroidJNIHelper.GetMethodID(DateClass, "getTime"), new jvalue[] { });
var unityDateTime = new DateTime(1970, 1, 1).AddMilliseconds(timeLong);
return new Session(id, unityDateTime, unhandledCount, handledCount);
}
public void MarkLaunchCompleted()
{
CallNativeVoidMethod("markLaunchCompleted", "()V", new object[] { });
}
public Dictionary<string, object> GetApp()
{
return GetJavaMapData("getApp");
}
public Dictionary<string, object> GetDevice()
{
return GetJavaMapData("getDevice");
}
public Dictionary<string, object> GetMetadata()
{
return GetJavaMapData("getMetadata");
}
public Dictionary<string, object> GetUser()
{
return GetJavaMapData("getUser");
}
public void ClearMetadata(string tab)
{
if (tab == null)
{
return;
}
CallNativeVoidMethod("clearMetadata", "(Ljava/lang/String;Ljava/lang/String;)V", new object[] { tab, null });
}
public void ClearMetadata(string tab, string key)
{
if (tab == null)
{
return;
}
CallNativeVoidMethod("clearMetadata", "(Ljava/lang/String;Ljava/lang/String;)V", new object[] { tab, key });
}
public void AddMetadata(string tab, string key, string value)
{
if (tab == null || key == null)
{
return;
}
CallNativeVoidMethod("addMetadata", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;)V",
new object[] { tab, key, value });
}
public void LeaveBreadcrumb(string name, string type, IDictionary<string, object> metadata)
{
if (!CanRunJNI())
{
return;
}
bool isAttached = bsg_unity_isJNIAttached();
if (!isAttached)
{
AndroidJNI.AttachCurrentThread();
}
if (PushLocalFrame())
{
using (AndroidJavaObject map = BuildJavaMapDisposable(metadata))
{
CallNativeVoidMethod("leaveBreadcrumb", "(Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)V",
new object[] { name, type, map });
}
PopLocalFrame();
}
if (!isAttached)
{
AndroidJNI.DetachCurrentThread();
}
}
public List<Breadcrumb> GetBreadcrumbs()
{
List<Breadcrumb> breadcrumbs = new List<Breadcrumb>();
if (!CanRunJNI())
{
return breadcrumbs;
}
bool isAttached = bsg_unity_isJNIAttached();
if (!isAttached)
{
AndroidJNI.AttachCurrentThread();
}
IntPtr javaBreadcrumbs = CallNativeObjectMethodRef("getBreadcrumbs", "()Ljava/util/List;", new object[] { });
IntPtr iterator = AndroidJNI.CallObjectMethod(javaBreadcrumbs, CollectionIterator, new jvalue[] { });
AndroidJNI.DeleteLocalRef(javaBreadcrumbs);
while (AndroidJNI.CallBooleanMethod(iterator, IteratorHasNext, new jvalue[] { }))
{
IntPtr crumb = AndroidJNI.CallObjectMethod(iterator, IteratorNext, new jvalue[] { });
breadcrumbs.Add(ConvertToBreadcrumb(crumb));
AndroidJNI.DeleteLocalRef(crumb);
}
AndroidJNI.DeleteLocalRef(iterator);
if (!isAttached)
{
AndroidJNI.DetachCurrentThread();
}
return breadcrumbs;
}
private Dictionary<string, object> GetJavaMapData(string methodName)
{
if (!CanRunJNI())
{
return new Dictionary<string, object>();
}
bool isAttached = bsg_unity_isJNIAttached();
if (!isAttached)
{
AndroidJNI.AttachCurrentThread();
}
IntPtr map = CallNativeObjectMethodRef(methodName, "()Ljava/util/Map;", new object[] { });
Dictionary<string, object> value = DictionaryFromJavaMap(map);
AndroidJNI.DeleteLocalRef(map);
if (!isAttached)
{
AndroidJNI.DetachCurrentThread();
}
return value;
}
// Manually converts any C# strings in the arguments, replacing invalid chars with the replacement char..
// If we don't do this, C# will coerce them using NewStringUTF, which crashes on invalid UTF-8.
// Arg lists processed this way must be released using ReleaseConvertedStringArgs.
private object[] ConvertStringArgsToNative(object[] args)
{
object[] itemsAsJavaObjects = new object[args.Length];
for (int i = 0; i < args.Length; i++)
{
var obj = args[i];
if (obj is string)
{
itemsAsJavaObjects[i] = BuildJavaStringDisposable(obj as string);
}
else
{
itemsAsJavaObjects[i] = obj;
}
}
return itemsAsJavaObjects;
}
// Release any strings in a processed argument list.
// @param originalArgs: The original C# args.
// @param convertedArgs: The args list returned by ConvertStringArgsToNative.
private void ReleaseConvertedStringArgs(object[] originalArgs, object[] convertedArgs)
{
for (int i = 0; i < originalArgs.Length; i++)
{
if (originalArgs[i] is string)
{
(convertedArgs[i] as AndroidJavaObject).Dispose();
}
}
}
private void CallNativeVoidMethod(string methodName, string methodSig, object[] args)
{
if (!CanRunJNI())
{
return;
}
bool isAttached = bsg_unity_isJNIAttached();
if (!isAttached)
{
AndroidJNI.AttachCurrentThread();
}
object[] convertedArgs = ConvertStringArgsToNative(args);
jvalue[] jargs = AndroidJNIHelper.CreateJNIArgArray(convertedArgs);
IntPtr methodID = AndroidJNI.GetStaticMethodID(BugsnagNativeInterface, methodName, methodSig);
AndroidJNI.CallStaticVoidMethod(BugsnagNativeInterface, methodID, jargs);
AndroidJNIHelper.DeleteJNIArgArray(convertedArgs, jargs);
ReleaseConvertedStringArgs(args, convertedArgs);
if (!isAttached)
{
AndroidJNI.DetachCurrentThread();
}
}
private IntPtr CallNativeObjectMethodRef(string methodName, string methodSig, object[] args)
{
if (!CanRunJNI())
{
return IntPtr.Zero;
}
bool isAttached = bsg_unity_isJNIAttached();
if (!isAttached)
{
AndroidJNI.AttachCurrentThread();
}
object[] convertedArgs = ConvertStringArgsToNative(args);
jvalue[] jargs = AndroidJNIHelper.CreateJNIArgArray(convertedArgs);
IntPtr methodID = AndroidJNI.GetStaticMethodID(BugsnagNativeInterface, methodName, methodSig);
IntPtr nativeValue = AndroidJNI.CallStaticObjectMethod(BugsnagNativeInterface, methodID, jargs);
AndroidJNIHelper.DeleteJNIArgArray(args, jargs);
ReleaseConvertedStringArgs(args, convertedArgs);
if (!isAttached)
{
AndroidJNI.DetachCurrentThread();
}
return nativeValue;
}
private IntPtr ConvertToStringJNIArrayRef(string[] items)
{
if (items == null || items.Length == 0)
{
return IntPtr.Zero;
}
AndroidJavaObject[] itemsAsJavaObjects = new AndroidJavaObject[items.Length];
for (int i = 0; i < items.Length; i++)
{
itemsAsJavaObjects[i] = BuildJavaStringDisposable(items[i]);
}
AndroidJavaObject first = itemsAsJavaObjects[0];
IntPtr rawArray = AndroidJNI.NewObjectArray(items.Length, StringClass, first.GetRawObject());
first.Dispose();
for (int i = 1; i < items.Length; i++)
{
AndroidJNI.SetObjectArrayElement(rawArray, i, itemsAsJavaObjects[i].GetRawObject());
itemsAsJavaObjects[i].Dispose();
}
return rawArray;
}
private string CallNativeStringMethod(string methodName, string methodSig, object[] args)
{
if (!CanRunJNI())
{
return "";
}
bool isAttached = bsg_unity_isJNIAttached();
if (!isAttached)
{
AndroidJNI.AttachCurrentThread();
}
object[] convertedArgs = ConvertStringArgsToNative(args);
jvalue[] jargs = AndroidJNIHelper.CreateJNIArgArray(convertedArgs);
IntPtr methodID = AndroidJNI.GetStaticMethodID(BugsnagNativeInterface, methodName, methodSig);
IntPtr nativeValue = AndroidJNI.CallStaticObjectMethod(BugsnagNativeInterface, methodID, jargs);
AndroidJNIHelper.DeleteJNIArgArray(args, jargs);
ReleaseConvertedStringArgs(args, convertedArgs);
string value = null;
if (nativeValue != null && nativeValue != IntPtr.Zero)
{
value = AndroidJNI.GetStringUTFChars(nativeValue);
}
AndroidJNI.DeleteLocalRef(nativeValue);
if (!isAttached)
{
AndroidJNI.DetachCurrentThread();
}
return value;
}
private bool CallNativeBoolMethod(string methodName, string methodSig, object[] args)
{
if (!CanRunJNI())
{
return false;
}
bool isAttached = bsg_unity_isJNIAttached();
if (!isAttached)
{
AndroidJNI.AttachCurrentThread();
}
object[] convertedArgs = ConvertStringArgsToNative(args);
jvalue[] jargs = AndroidJNIHelper.CreateJNIArgArray(convertedArgs);
IntPtr methodID = AndroidJNI.GetStaticMethodID(BugsnagNativeInterface, methodName, methodSig);
bool nativeValue = AndroidJNI.CallStaticBooleanMethod(BugsnagNativeInterface, methodID, jargs);
AndroidJNIHelper.DeleteJNIArgArray(args, jargs);
ReleaseConvertedStringArgs(args, convertedArgs);
if (!isAttached)
{
AndroidJNI.DetachCurrentThread();
}
return nativeValue;
}
[DllImport("bugsnag-unity")]
private static extern bool bsg_unity_isJNIAttached();
private Breadcrumb ConvertToBreadcrumb(IntPtr javaBreadcrumb)
{
var metadata = new Dictionary<string, object>();
IntPtr javaMetadata = AndroidJNI.CallObjectMethod(javaBreadcrumb, BreadcrumbGetMetadata, new jvalue[] { });
IntPtr entries = AndroidJNI.CallObjectMethod(javaMetadata, MapEntrySet, new jvalue[] { });
AndroidJNI.DeleteLocalRef(javaMetadata);
IntPtr iterator = AndroidJNI.CallObjectMethod(entries, CollectionIterator, new jvalue[] { });
AndroidJNI.DeleteLocalRef(entries);
while (AndroidJNI.CallBooleanMethod(iterator, IteratorHasNext, new jvalue[] { }))
{
IntPtr entry = AndroidJNI.CallObjectMethod(iterator, IteratorNext, new jvalue[] { });
IntPtr key = AndroidJNI.CallObjectMethod(entry, MapEntryGetKey, new jvalue[] { });
IntPtr value = AndroidJNI.CallObjectMethod(entry, MapEntryGetValue, new jvalue[] { });
AndroidJNI.DeleteLocalRef(entry);
if (key != IntPtr.Zero && value != IntPtr.Zero)
{
var obj = AndroidJNI.CallStringMethod(value, ObjectToString, new jvalue[] { });
metadata.Add(AndroidJNI.GetStringUTFChars(key), obj);
}
AndroidJNI.DeleteLocalRef(key);
AndroidJNI.DeleteLocalRef(value);
}
AndroidJNI.DeleteLocalRef(iterator);
IntPtr type = AndroidJNI.CallObjectMethod(javaBreadcrumb, BreadcrumbGetType, new jvalue[] { });
string typeName = AndroidJNI.CallStringMethod(type, ObjectToString, new jvalue[] { });
AndroidJNI.DeleteLocalRef(type);
string message = "<empty>";
IntPtr messageObj = AndroidJNI.CallObjectMethod(javaBreadcrumb, BreadcrumbGetMessage, new jvalue[] { });
if (messageObj != IntPtr.Zero)
{
message = AndroidJNI.GetStringUTFChars(messageObj);
}
AndroidJNI.DeleteLocalRef(messageObj);
string timestamp = AndroidJNI.CallStringMethod(javaBreadcrumb, BreadcrumbGetTimestamp, new jvalue[] { });
return new Breadcrumb(message, timestamp, typeName, metadata);
}
internal static AndroidJavaObject BuildJavaMapDisposable(IDictionary<string, object> src)
{
AndroidJavaObject map = new AndroidJavaObject("java.util.HashMap");
if (src != null)
{
foreach (var entry in src)
{
using (AndroidJavaObject key = BuildJavaStringDisposable(entry.Key))
using (AndroidJavaObject value = BuildJavaStringDisposable(entry.Value.ToString()))
{
map.Call<AndroidJavaObject>("put", key, value);
}
}
}
return map;
}
internal static AndroidJavaObject BuildJavaStringDisposable(string input)
{
if (input == null)
{
return null;
}
try
{
// The default encoding on Android is UTF-8
using (AndroidJavaClass CharsetClass = new AndroidJavaClass("java.nio.charset.Charset"))
using (AndroidJavaObject Charset = CharsetClass.CallStatic<AndroidJavaObject>("defaultCharset"))
{
byte[] Bytes = Encoding.UTF8.GetBytes(input);
if (Unity2019OrNewer)
{ // should succeed on Unity 2019.1 and above
sbyte[] SBytes = new sbyte[Bytes.Length];
Buffer.BlockCopy(Bytes, 0, SBytes, 0, Bytes.Length);
return new AndroidJavaObject("java.lang.String", SBytes, Charset);
}
else
{ // use legacy API on older versions
return new AndroidJavaObject("java.lang.String", Bytes, Charset);
}
}
}
catch (EncoderFallbackException _)
{
// The input string could not be encoded as UTF-8
return new AndroidJavaObject("java.lang.String");
}
}
internal static bool IsUnity2019OrNewer()
{
using (AndroidJavaClass CharsetClass = new AndroidJavaClass("java.nio.charset.Charset"))
using (AndroidJavaObject Charset = CharsetClass.CallStatic<AndroidJavaObject>("defaultCharset"))
{
try
{ // should succeed on Unity 2019.1 and above
using (AndroidJavaObject obj = new AndroidJavaObject("java.lang.String", new sbyte[0], Charset))
{
return true;
}
}
catch (System.Exception _)
{ // use legacy API on older versions
return false;
}
}
}
private bool CanRunJNI()
{
return CanRunOnBackgroundThread || object.ReferenceEquals(Thread.CurrentThread, MainThread);
}
private Dictionary<string, object> DictionaryFromJavaMap(IntPtr source)
{
var dict = new Dictionary<string, object>();
IntPtr entries = AndroidJNI.CallObjectMethod(source, MapEntrySet, new jvalue[] { });
IntPtr iterator = AndroidJNI.CallObjectMethod(entries, CollectionIterator, new jvalue[] { });
AndroidJNI.DeleteLocalRef(entries);
while (AndroidJNI.CallBooleanMethod(iterator, IteratorHasNext, new jvalue[] { }))
{
IntPtr entry = AndroidJNI.CallObjectMethod(iterator, IteratorNext, new jvalue[] { });
string key = AndroidJNI.CallStringMethod(entry, MapEntryGetKey, new jvalue[] { });
IntPtr value = AndroidJNI.CallObjectMethod(entry, MapEntryGetValue, new jvalue[] { });
AndroidJNI.DeleteLocalRef(entry);
if (value != null && value != IntPtr.Zero)
{
IntPtr valueClass = AndroidJNI.CallObjectMethod(value, ObjectGetClass, new jvalue[] { });
if (AndroidJNI.CallBooleanMethod(valueClass, ClassIsArray, new jvalue[] { }))
{
string[] values = AndroidJNIHelper.ConvertFromJNIArray<string[]>(value);
dict.AddToPayload(key, values);
}
else if (AndroidJNI.IsInstanceOf(value, MapClass))
{
dict.AddToPayload(key, DictionaryFromJavaMap(value));
}
else if (AndroidJNI.IsInstanceOf(value, DateClass))
{
jvalue[] args = new jvalue[1];
args[0].l = value;
var time = AndroidJNI.CallStaticStringMethod(DateUtilsClass, ToIso8601, args);
dict.AddToPayload(key, time);
}
else
{
// FUTURE(dm): check if Integer, Long, Double, or Float before calling toString
dict.AddToPayload(key, AndroidJNI.CallStringMethod(value, ObjectToString, new jvalue[] { }));
}
AndroidJNI.DeleteLocalRef(valueClass);
}
AndroidJNI.DeleteLocalRef(value);
}
AndroidJNI.DeleteLocalRef(iterator);
return dict;
}
public LastRunInfo GetlastRunInfo()
{
var javaLastRunInfo = CallNativeObjectMethodRef("getLastRunInfo", "()Lcom/bugsnag/android/LastRunInfo;", new object[] { });
var crashed = AndroidJNI.GetBooleanField(javaLastRunInfo, AndroidJNIHelper.GetFieldID(LastRunInfoClass, "crashed"));
var consecutiveLaunchCrashes = AndroidJNI.GetIntField(javaLastRunInfo, AndroidJNIHelper.GetFieldID(LastRunInfoClass, "consecutiveLaunchCrashes"));
var crashedDuringLaunch = AndroidJNI.GetBooleanField(javaLastRunInfo, AndroidJNIHelper.GetFieldID(LastRunInfoClass, "crashedDuringLaunch"));
var lastRunInfo = new LastRunInfo
{
ConsecutiveLaunchCrashes = consecutiveLaunchCrashes,
Crashed = crashed,
CrashedDuringLaunch = crashedDuringLaunch
};
return lastRunInfo;
}
private IntPtr GetClientRef()
{
return CallNativeObjectMethodRef("getClient", "()Lcom/bugsnag/android/Client;", new object[] { });
}
public void AddFeatureFlag(string name, string variant)
{
object[] args = new object[] { name, variant };
jvalue[] jargs = AndroidJNIHelper.CreateJNIArgArray(args);
AndroidJNI.CallVoidMethod(GetClientRef(), AddFeatureFlagMethod, jargs);
}
public void ClearFeatureFlag(string name)
{
object[] args = new object[] { name };
jvalue[] jargs = AndroidJNIHelper.CreateJNIArgArray(args);
AndroidJNI.CallVoidMethod(GetClientRef(), ClearFeatureFlagMethod, jargs);
}
public void ClearFeatureFlags()
{
AndroidJNI.CallVoidMethod(GetClientRef(), ClearFeatureFlagsMethod, null);
}
}
}
| |
using System.ComponentModel;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraReports.UserDesigner;
using bv.winclient.Core;
namespace EIDSS.Reports.Barcode.Designer
{
public partial class DesignForm : BvForm
{
private DevExpress.XtraReports.UserDesigner.XRDesignBarManager xrDesignBarManager1;
private Bar bar2;
private BarSubItem barSubItem1;
private DevExpress.XtraReports.UserDesigner.CommandBarItem biGetOriginal;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem39;
private DevExpress.XtraReports.UserDesigner.CommandBarItem biSave;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem40;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem41;
private BarSubItem barSubItem2;
private DevExpress.XtraReports.UserDesigner.CommandBarItem biUndo;
private DevExpress.XtraReports.UserDesigner.CommandBarItem biRedo;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem42;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem43;
private BarSubItem barSubItem3;
private DevExpress.XtraReports.UserDesigner.BarReportTabButtonsListItem barReportTabButtonsListItem1;
private BarSubItem barSubItem4;
private DevExpress.XtraReports.UserDesigner.XRBarToolbarsListItem xrBarToolbarsListItem1;
private BarSubItem barSubItem5;
private DevExpress.XtraReports.UserDesigner.BarDockPanelsListItem barDockPanelsListItem1;
private BarSubItem barSubItem6;
private BarSubItem barSubItem7;
private BarSubItem barSubItem8;
private DevExpress.XtraReports.UserDesigner.CommandBarItem biJustifyLeft;
private DevExpress.XtraReports.UserDesigner.CommandBarItem biJustifyCenter;
private DevExpress.XtraReports.UserDesigner.CommandBarItem biJustifyRight;
private DevExpress.XtraReports.UserDesigner.CommandBarItem biJustifyJustify;
private BarSubItem barSubItem9;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem9;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem10;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem11;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem12;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem13;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem14;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem8;
private BarSubItem barSubItem10;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem15;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem16;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem17;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem18;
private BarSubItem barSubItem11;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem19;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem20;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem21;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem22;
private BarSubItem barSubItem12;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem23;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem24;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem25;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem26;
private BarSubItem barSubItem13;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem27;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem28;
private BarSubItem barSubItem14;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem29;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem30;
private BarSubItem barSubItem15;
private DevExpress.XtraReports.UserDesigner.CommandBarCheckItem commandBarCheckItem1;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem44;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem45;
private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem46;
private BarMdiChildrenListItem barMdiChildrenListItem1;
private BarSubItem bsiLookAndFeel;
private DevExpress.XtraReports.UserDesigner.DesignBar designBar2;
private DevExpress.XtraReports.UserDesigner.DesignBar designBar3;
private BarEditItem biFontName;
private DevExpress.XtraReports.UserDesigner.RecentlyUsedItemsComboBox recentlyUsedItemsComboBox1;
private BarEditItem biFontSize;
private DevExpress.XtraReports.UserDesigner.DesignRepositoryItemComboBox designRepositoryItemComboBox1;
private DevExpress.XtraReports.UserDesigner.CommandBarItem biZoomOut;
private DevExpress.XtraReports.UserDesigner.XRZoomBarEditItem biZoom;
private DevExpress.XtraReports.UserDesigner.DesignRepositoryItemComboBox designRepositoryItemComboBox2;
private DevExpress.XtraReports.UserDesigner.CommandBarItem biZoomIn;
private DevExpress.XtraReports.UserDesigner.XRDesignDockManager xrDesignDockManager1;
private DevExpress.XtraReports.UserDesigner.XRDesignMdiController xrDesignMdiController1;
private XRTabbedMdiManager xtraTabbedMdiManager1;
private CommandBarItem commandBarItem49;
private DevExpress.XtraBars.Docking.DockPanel panelContainer3;
private GroupAndSortDockPanel groupAndSortDockPanel1;
private DesignControlContainer groupAndSortDockPanel1_Container;
private ErrorListDockPanel errorListDockPanel1;
private DesignControlContainer errorListDockPanel1_Container;
private DevExpress.XtraBars.Docking.DockPanel panelContainer1;
private DevExpress.XtraBars.Docking.DockPanel panelContainer2;
private ReportExplorerDockPanel reportExplorerDockPanel1;
private DesignControlContainer reportExplorerDockPanel1_Container;
private FieldListDockPanel fieldListDockPanel1;
private DesignControlContainer fieldListDockPanel1_Container;
private PropertyGridDockPanel propertyGridDockPanel1;
private DesignControlContainer propertyGridDockPanel1_Container;
private IContainer components;
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DesignForm));
DevExpress.XtraReports.UserDesigner.BarInfo barInfo1 = new DevExpress.XtraReports.UserDesigner.BarInfo();
DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener1 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener();
DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener2 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener();
DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener3 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener();
DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener4 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener();
DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener5 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener();
DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener6 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener();
DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener7 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener();
this.bar2 = new DevExpress.XtraBars.Bar();
this.xrDesignBarManager1 = new DevExpress.XtraReports.UserDesigner.XRDesignBarManager();
this.designBar2 = new DevExpress.XtraReports.UserDesigner.DesignBar();
this.biGetOriginal = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.biSave = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.biUndo = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.biRedo = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.biZoomOut = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.biZoom = new DevExpress.XtraReports.UserDesigner.XRZoomBarEditItem();
this.designRepositoryItemComboBox2 = new DevExpress.XtraReports.UserDesigner.DesignRepositoryItemComboBox();
this.biZoomIn = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.designBar3 = new DevExpress.XtraReports.UserDesigner.DesignBar();
this.biFontName = new DevExpress.XtraBars.BarEditItem();
this.recentlyUsedItemsComboBox1 = new DevExpress.XtraReports.UserDesigner.RecentlyUsedItemsComboBox();
this.biFontSize = new DevExpress.XtraBars.BarEditItem();
this.designRepositoryItemComboBox1 = new DevExpress.XtraReports.UserDesigner.DesignRepositoryItemComboBox();
this.biJustifyLeft = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.biJustifyCenter = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.biJustifyRight = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.biJustifyJustify = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.xrDesignDockManager1 = new DevExpress.XtraReports.UserDesigner.XRDesignDockManager();
this.panelContainer3 = new DevExpress.XtraBars.Docking.DockPanel();
this.groupAndSortDockPanel1 = new DevExpress.XtraReports.UserDesigner.GroupAndSortDockPanel();
this.groupAndSortDockPanel1_Container = new DevExpress.XtraReports.UserDesigner.DesignControlContainer();
this.errorListDockPanel1 = new DevExpress.XtraReports.UserDesigner.ErrorListDockPanel();
this.errorListDockPanel1_Container = new DevExpress.XtraReports.UserDesigner.DesignControlContainer();
this.panelContainer1 = new DevExpress.XtraBars.Docking.DockPanel();
this.panelContainer2 = new DevExpress.XtraBars.Docking.DockPanel();
this.reportExplorerDockPanel1 = new DevExpress.XtraReports.UserDesigner.ReportExplorerDockPanel();
this.reportExplorerDockPanel1_Container = new DevExpress.XtraReports.UserDesigner.DesignControlContainer();
this.fieldListDockPanel1 = new DevExpress.XtraReports.UserDesigner.FieldListDockPanel();
this.fieldListDockPanel1_Container = new DevExpress.XtraReports.UserDesigner.DesignControlContainer();
this.propertyGridDockPanel1 = new DevExpress.XtraReports.UserDesigner.PropertyGridDockPanel();
this.propertyGridDockPanel1_Container = new DevExpress.XtraReports.UserDesigner.DesignControlContainer();
this.commandBarItem8 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem9 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem10 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem11 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem12 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem13 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem14 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem15 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem16 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem17 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem18 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem19 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem20 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem21 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem22 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem23 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem24 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem25 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem26 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem27 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem28 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem29 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem30 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.barSubItem1 = new DevExpress.XtraBars.BarSubItem();
this.commandBarItem39 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem40 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem49 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem41 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.barSubItem2 = new DevExpress.XtraBars.BarSubItem();
this.commandBarItem42 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem43 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.barSubItem3 = new DevExpress.XtraBars.BarSubItem();
this.barReportTabButtonsListItem1 = new DevExpress.XtraReports.UserDesigner.BarReportTabButtonsListItem();
this.barSubItem4 = new DevExpress.XtraBars.BarSubItem();
this.xrBarToolbarsListItem1 = new DevExpress.XtraReports.UserDesigner.XRBarToolbarsListItem();
this.barSubItem5 = new DevExpress.XtraBars.BarSubItem();
this.barDockPanelsListItem1 = new DevExpress.XtraReports.UserDesigner.BarDockPanelsListItem();
this.barSubItem6 = new DevExpress.XtraBars.BarSubItem();
this.barSubItem7 = new DevExpress.XtraBars.BarSubItem();
this.barSubItem8 = new DevExpress.XtraBars.BarSubItem();
this.barSubItem9 = new DevExpress.XtraBars.BarSubItem();
this.barSubItem10 = new DevExpress.XtraBars.BarSubItem();
this.barSubItem11 = new DevExpress.XtraBars.BarSubItem();
this.barSubItem12 = new DevExpress.XtraBars.BarSubItem();
this.barSubItem13 = new DevExpress.XtraBars.BarSubItem();
this.barSubItem14 = new DevExpress.XtraBars.BarSubItem();
this.barSubItem15 = new DevExpress.XtraBars.BarSubItem();
this.commandBarCheckItem1 = new DevExpress.XtraReports.UserDesigner.CommandBarCheckItem();
this.commandBarItem44 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem45 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.commandBarItem46 = new DevExpress.XtraReports.UserDesigner.CommandBarItem();
this.barMdiChildrenListItem1 = new DevExpress.XtraBars.BarMdiChildrenListItem();
this.bsiLookAndFeel = new DevExpress.XtraBars.BarSubItem();
this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem();
this.xrDesignMdiController1 = new DevExpress.XtraReports.UserDesigner.XRDesignMdiController();
this.xtraTabbedMdiManager1 = new XRTabbedMdiManager(this.components);
this.HidePopupTimer = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.xrDesignBarManager1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.designRepositoryItemComboBox2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.recentlyUsedItemsComboBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.designRepositoryItemComboBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrDesignDockManager1)).BeginInit();
this.panelContainer3.SuspendLayout();
this.groupAndSortDockPanel1.SuspendLayout();
this.errorListDockPanel1.SuspendLayout();
this.panelContainer1.SuspendLayout();
this.panelContainer2.SuspendLayout();
this.reportExplorerDockPanel1.SuspendLayout();
this.fieldListDockPanel1.SuspendLayout();
this.propertyGridDockPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.xtraTabbedMdiManager1)).BeginInit();
this.SuspendLayout();
//
// bar2
//
this.bar2.BarName = "Toolbox";
this.bar2.DockCol = 1;
this.bar2.DockRow = 0;
this.bar2.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.bar2.FloatLocation = new System.Drawing.Point(202, 248);
this.bar2.OptionsBar.AllowQuickCustomization = false;
this.bar2.OptionsBar.DisableClose = true;
this.bar2.OptionsBar.DisableCustomization = true;
this.bar2.OptionsBar.DrawDragBorder = false;
resources.ApplyResources(this.bar2, "bar2");
//
// xrDesignBarManager1
//
this.xrDesignBarManager1.AllowCustomization = false;
this.xrDesignBarManager1.AllowMoveBarOnToolbar = false;
this.xrDesignBarManager1.AllowQuickCustomization = false;
barInfo1.Bar = this.bar2;
barInfo1.ToolboxType = DevExpress.XtraReports.UserDesigner.ToolboxType.Custom;
this.xrDesignBarManager1.BarInfos.AddRange(new DevExpress.XtraReports.UserDesigner.BarInfo[] {
barInfo1});
this.xrDesignBarManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.designBar2,
this.designBar3,
this.bar2});
this.xrDesignBarManager1.DockControls.Add(this.barDockControlTop);
this.xrDesignBarManager1.DockControls.Add(this.barDockControlBottom);
this.xrDesignBarManager1.DockControls.Add(this.barDockControlLeft);
this.xrDesignBarManager1.DockControls.Add(this.barDockControlRight);
this.xrDesignBarManager1.DockManager = this.xrDesignDockManager1;
this.xrDesignBarManager1.FontNameBox = this.recentlyUsedItemsComboBox1;
this.xrDesignBarManager1.FontNameEdit = this.biFontName;
this.xrDesignBarManager1.FontSizeBox = this.designRepositoryItemComboBox1;
this.xrDesignBarManager1.FontSizeEdit = this.biFontSize;
this.xrDesignBarManager1.Form = this;
this.xrDesignBarManager1.FormattingToolbar = this.designBar3;
this.xrDesignBarManager1.HintStaticItem = null;
this.xrDesignBarManager1.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("xrDesignBarManager1.ImageStream")));
this.xrDesignBarManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.biFontName,
this.biFontSize,
this.biJustifyLeft,
this.biJustifyCenter,
this.biJustifyRight,
this.biJustifyJustify,
this.commandBarItem8,
this.commandBarItem9,
this.commandBarItem10,
this.commandBarItem11,
this.commandBarItem12,
this.commandBarItem13,
this.commandBarItem14,
this.commandBarItem15,
this.commandBarItem16,
this.commandBarItem17,
this.commandBarItem18,
this.commandBarItem19,
this.commandBarItem20,
this.commandBarItem21,
this.commandBarItem22,
this.commandBarItem23,
this.commandBarItem24,
this.commandBarItem25,
this.commandBarItem26,
this.commandBarItem27,
this.commandBarItem28,
this.commandBarItem29,
this.commandBarItem30,
this.biGetOriginal,
this.biSave,
this.biUndo,
this.biRedo,
this.barSubItem1,
this.barSubItem2,
this.barSubItem3,
this.barReportTabButtonsListItem1,
this.barSubItem4,
this.xrBarToolbarsListItem1,
this.barSubItem5,
this.barDockPanelsListItem1,
this.barSubItem6,
this.barSubItem7,
this.barSubItem8,
this.barSubItem9,
this.barSubItem10,
this.barSubItem11,
this.barSubItem12,
this.barSubItem13,
this.barSubItem14,
this.commandBarItem39,
this.commandBarItem40,
this.commandBarItem41,
this.commandBarItem42,
this.commandBarItem43,
this.barSubItem15,
this.commandBarCheckItem1,
this.commandBarItem44,
this.commandBarItem45,
this.commandBarItem46,
this.barMdiChildrenListItem1,
this.biZoomOut,
this.biZoom,
this.biZoomIn,
this.bsiLookAndFeel,
this.commandBarItem49,
this.barButtonItem1});
this.xrDesignBarManager1.LayoutToolbar = null;
this.xrDesignBarManager1.MaxItemId = 80;
this.xrDesignBarManager1.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] {
this.recentlyUsedItemsComboBox1,
this.designRepositoryItemComboBox1,
this.designRepositoryItemComboBox2});
this.xrDesignBarManager1.Toolbar = this.designBar2;
this.xrDesignBarManager1.Updates.AddRange(new string[] {
"Toolbox"});
this.xrDesignBarManager1.ZoomItem = this.biZoom;
//
// designBar2
//
this.designBar2.BarName = "Toolbar";
this.designBar2.DockCol = 0;
this.designBar2.DockRow = 0;
this.designBar2.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.designBar2.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.biGetOriginal),
new DevExpress.XtraBars.LinkPersistInfo(this.biSave),
new DevExpress.XtraBars.LinkPersistInfo(this.biUndo, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biRedo),
new DevExpress.XtraBars.LinkPersistInfo(this.biZoomOut, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biZoom),
new DevExpress.XtraBars.LinkPersistInfo(this.biZoomIn)});
this.designBar2.OptionsBar.AllowQuickCustomization = false;
this.designBar2.OptionsBar.DisableClose = true;
this.designBar2.OptionsBar.DisableCustomization = true;
this.designBar2.OptionsBar.DrawDragBorder = false;
resources.ApplyResources(this.designBar2, "designBar2");
//
// biGetOriginal
//
resources.ApplyResources(this.biGetOriginal, "biGetOriginal");
this.biGetOriginal.Enabled = false;
this.biGetOriginal.Glyph = global::EIDSS.Reports.Properties.Resources.restore;
this.biGetOriginal.Id = 34;
this.biGetOriginal.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.R));
this.biGetOriginal.Name = "biGetOriginal";
this.biGetOriginal.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biRestoreDefault_ItemClick);
//
// biSave
//
resources.ApplyResources(this.biSave, "biSave");
this.biSave.Enabled = false;
this.biSave.Id = 36;
this.biSave.ImageIndex = 11;
this.biSave.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S));
this.biSave.Name = "biSave";
this.biSave.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biSave_ItemClick);
//
// biUndo
//
resources.ApplyResources(this.biUndo, "biUndo");
this.biUndo.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.Undo;
this.biUndo.Enabled = false;
this.biUndo.Id = 40;
this.biUndo.ImageIndex = 15;
this.biUndo.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z));
this.biUndo.Name = "biUndo";
//
// biRedo
//
resources.ApplyResources(this.biRedo, "biRedo");
this.biRedo.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.Redo;
this.biRedo.Enabled = false;
this.biRedo.Id = 41;
this.biRedo.ImageIndex = 16;
this.biRedo.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y));
this.biRedo.Name = "biRedo";
//
// biZoomOut
//
resources.ApplyResources(this.biZoomOut, "biZoomOut");
this.biZoomOut.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.ZoomOut;
this.biZoomOut.Enabled = false;
this.biZoomOut.Id = 71;
this.biZoomOut.ImageIndex = 43;
this.biZoomOut.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Subtract));
this.biZoomOut.Name = "biZoomOut";
//
// biZoom
//
resources.ApplyResources(this.biZoom, "biZoom");
this.biZoom.Edit = this.designRepositoryItemComboBox2;
this.biZoom.Enabled = false;
this.biZoom.Id = 72;
this.biZoom.Name = "biZoom";
//
// designRepositoryItemComboBox2
//
this.designRepositoryItemComboBox2.AutoComplete = false;
this.designRepositoryItemComboBox2.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("designRepositoryItemComboBox2.Buttons"))))});
this.designRepositoryItemComboBox2.Name = "designRepositoryItemComboBox2";
//
// biZoomIn
//
resources.ApplyResources(this.biZoomIn, "biZoomIn");
this.biZoomIn.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.ZoomIn;
this.biZoomIn.Enabled = false;
this.biZoomIn.Id = 73;
this.biZoomIn.ImageIndex = 44;
this.biZoomIn.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Add));
this.biZoomIn.Name = "biZoomIn";
//
// designBar3
//
this.designBar3.BarName = "Formatting Toolbar";
this.designBar3.DockCol = 2;
this.designBar3.DockRow = 0;
this.designBar3.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.designBar3.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(DevExpress.XtraBars.BarLinkUserDefines.None, false, this.biFontName, false),
new DevExpress.XtraBars.LinkPersistInfo(this.biFontSize),
new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyLeft, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyCenter),
new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyRight),
new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyJustify)});
this.designBar3.OptionsBar.DisableClose = true;
this.designBar3.OptionsBar.DisableCustomization = true;
this.designBar3.OptionsBar.DrawDragBorder = false;
resources.ApplyResources(this.designBar3, "designBar3");
//
// biFontName
//
resources.ApplyResources(this.biFontName, "biFontName");
this.biFontName.Edit = this.recentlyUsedItemsComboBox1;
this.biFontName.Id = 0;
this.biFontName.Name = "biFontName";
//
// recentlyUsedItemsComboBox1
//
resources.ApplyResources(this.recentlyUsedItemsComboBox1, "recentlyUsedItemsComboBox1");
this.recentlyUsedItemsComboBox1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("recentlyUsedItemsComboBox1.Buttons"))))});
this.recentlyUsedItemsComboBox1.DropDownRows = 12;
this.recentlyUsedItemsComboBox1.Name = "recentlyUsedItemsComboBox1";
//
// biFontSize
//
resources.ApplyResources(this.biFontSize, "biFontSize");
this.biFontSize.Edit = this.designRepositoryItemComboBox1;
this.biFontSize.Id = 1;
this.biFontSize.Name = "biFontSize";
//
// designRepositoryItemComboBox1
//
resources.ApplyResources(this.designRepositoryItemComboBox1, "designRepositoryItemComboBox1");
this.designRepositoryItemComboBox1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("designRepositoryItemComboBox1.Buttons"))))});
this.designRepositoryItemComboBox1.Name = "designRepositoryItemComboBox1";
//
// biJustifyLeft
//
resources.ApplyResources(this.biJustifyLeft, "biJustifyLeft");
this.biJustifyLeft.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.JustifyLeft;
this.biJustifyLeft.Enabled = false;
this.biJustifyLeft.Id = 7;
this.biJustifyLeft.ImageIndex = 5;
this.biJustifyLeft.Name = "biJustifyLeft";
//
// biJustifyCenter
//
resources.ApplyResources(this.biJustifyCenter, "biJustifyCenter");
this.biJustifyCenter.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.JustifyCenter;
this.biJustifyCenter.Enabled = false;
this.biJustifyCenter.Id = 8;
this.biJustifyCenter.ImageIndex = 6;
this.biJustifyCenter.Name = "biJustifyCenter";
//
// biJustifyRight
//
resources.ApplyResources(this.biJustifyRight, "biJustifyRight");
this.biJustifyRight.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.JustifyRight;
this.biJustifyRight.Enabled = false;
this.biJustifyRight.Id = 9;
this.biJustifyRight.ImageIndex = 7;
this.biJustifyRight.Name = "biJustifyRight";
//
// biJustifyJustify
//
resources.ApplyResources(this.biJustifyJustify, "biJustifyJustify");
this.biJustifyJustify.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.JustifyJustify;
this.biJustifyJustify.Enabled = false;
this.biJustifyJustify.Id = 10;
this.biJustifyJustify.ImageIndex = 8;
this.biJustifyJustify.Name = "biJustifyJustify";
//
// barDockControlTop
//
this.barDockControlTop.CausesValidation = false;
resources.ApplyResources(this.barDockControlTop, "barDockControlTop");
//
// barDockControlBottom
//
this.barDockControlBottom.CausesValidation = false;
resources.ApplyResources(this.barDockControlBottom, "barDockControlBottom");
//
// barDockControlLeft
//
this.barDockControlLeft.CausesValidation = false;
resources.ApplyResources(this.barDockControlLeft, "barDockControlLeft");
//
// barDockControlRight
//
this.barDockControlRight.CausesValidation = false;
resources.ApplyResources(this.barDockControlRight, "barDockControlRight");
//
// xrDesignDockManager1
//
this.xrDesignDockManager1.Form = this;
this.xrDesignDockManager1.HiddenPanels.AddRange(new DevExpress.XtraBars.Docking.DockPanel[] {
this.panelContainer3,
this.panelContainer1});
this.xrDesignDockManager1.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("xrDesignDockManager1.ImageStream")));
this.xrDesignDockManager1.TopZIndexControls.AddRange(new string[] {
"DevExpress.XtraBars.BarDockControl",
"DevExpress.XtraBars.StandaloneBarDockControl",
"System.Windows.Forms.StatusBar",
"DevExpress.XtraBars.Ribbon.RibbonStatusBar",
"DevExpress.XtraBars.Ribbon.RibbonControl"});
//
// panelContainer3
//
this.panelContainer3.ActiveChild = this.groupAndSortDockPanel1;
this.panelContainer3.Controls.Add(this.groupAndSortDockPanel1);
this.panelContainer3.Controls.Add(this.errorListDockPanel1);
this.panelContainer3.Dock = DevExpress.XtraBars.Docking.DockingStyle.Bottom;
this.panelContainer3.ID = new System.Guid("6027d502-d4b1-488d-b50b-ac2fbbd40bf8");
this.panelContainer3.ImageIndex = 1;
resources.ApplyResources(this.panelContainer3, "panelContainer3");
this.panelContainer3.Name = "panelContainer3";
this.panelContainer3.OriginalSize = new System.Drawing.Size(200, 160);
this.panelContainer3.SavedDock = DevExpress.XtraBars.Docking.DockingStyle.Bottom;
this.panelContainer3.SavedIndex = 1;
this.panelContainer3.Tabbed = true;
this.panelContainer3.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
//
// groupAndSortDockPanel1
//
this.groupAndSortDockPanel1.Controls.Add(this.groupAndSortDockPanel1_Container);
this.groupAndSortDockPanel1.Dock = DevExpress.XtraBars.Docking.DockingStyle.Fill;
this.groupAndSortDockPanel1.ID = new System.Guid("4bab159e-c495-4d67-87dc-f4e895da443e");
this.groupAndSortDockPanel1.ImageIndex = 1;
resources.ApplyResources(this.groupAndSortDockPanel1, "groupAndSortDockPanel1");
this.groupAndSortDockPanel1.Name = "groupAndSortDockPanel1";
this.groupAndSortDockPanel1.OriginalSize = new System.Drawing.Size(620, 106);
this.groupAndSortDockPanel1.XRDesignPanel = null;
//
// groupAndSortDockPanel1_Container
//
resources.ApplyResources(this.groupAndSortDockPanel1_Container, "groupAndSortDockPanel1_Container");
this.groupAndSortDockPanel1_Container.Name = "groupAndSortDockPanel1_Container";
//
// errorListDockPanel1
//
this.errorListDockPanel1.Controls.Add(this.errorListDockPanel1_Container);
this.errorListDockPanel1.Dock = DevExpress.XtraBars.Docking.DockingStyle.Fill;
this.errorListDockPanel1.ID = new System.Guid("5a9a01fd-6e95-4e81-a8c4-ac63153d7488");
this.errorListDockPanel1.ImageIndex = 5;
resources.ApplyResources(this.errorListDockPanel1, "errorListDockPanel1");
this.errorListDockPanel1.Name = "errorListDockPanel1";
this.errorListDockPanel1.OriginalSize = new System.Drawing.Size(620, 106);
this.errorListDockPanel1.XRDesignPanel = null;
//
// errorListDockPanel1_Container
//
resources.ApplyResources(this.errorListDockPanel1_Container, "errorListDockPanel1_Container");
this.errorListDockPanel1_Container.Name = "errorListDockPanel1_Container";
//
// panelContainer1
//
this.panelContainer1.Controls.Add(this.panelContainer2);
this.panelContainer1.Controls.Add(this.propertyGridDockPanel1);
this.panelContainer1.Dock = DevExpress.XtraBars.Docking.DockingStyle.Right;
this.panelContainer1.ID = new System.Guid("73163da5-9eeb-4b18-8992-c9a9a9f93986");
resources.ApplyResources(this.panelContainer1, "panelContainer1");
this.panelContainer1.Name = "panelContainer1";
this.panelContainer1.OriginalSize = new System.Drawing.Size(250, 200);
this.panelContainer1.SavedDock = DevExpress.XtraBars.Docking.DockingStyle.Right;
this.panelContainer1.SavedIndex = 0;
this.panelContainer1.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
//
// panelContainer2
//
this.panelContainer2.ActiveChild = this.reportExplorerDockPanel1;
this.panelContainer2.Controls.Add(this.reportExplorerDockPanel1);
this.panelContainer2.Controls.Add(this.fieldListDockPanel1);
this.panelContainer2.Dock = DevExpress.XtraBars.Docking.DockingStyle.Fill;
this.panelContainer2.ID = new System.Guid("ec598d35-f04f-46c8-8b97-6b28f6c4dc4f");
this.panelContainer2.ImageIndex = 3;
resources.ApplyResources(this.panelContainer2, "panelContainer2");
this.panelContainer2.Name = "panelContainer2";
this.panelContainer2.OriginalSize = new System.Drawing.Size(250, 187);
this.panelContainer2.Tabbed = true;
//
// reportExplorerDockPanel1
//
this.reportExplorerDockPanel1.Controls.Add(this.reportExplorerDockPanel1_Container);
this.reportExplorerDockPanel1.Dock = DevExpress.XtraBars.Docking.DockingStyle.Fill;
this.reportExplorerDockPanel1.ID = new System.Guid("fb3ec6cc-3b9b-4b9c-91cf-cff78c1edbf1");
this.reportExplorerDockPanel1.ImageIndex = 3;
resources.ApplyResources(this.reportExplorerDockPanel1, "reportExplorerDockPanel1");
this.reportExplorerDockPanel1.Name = "reportExplorerDockPanel1";
this.reportExplorerDockPanel1.OriginalSize = new System.Drawing.Size(244, 133);
this.reportExplorerDockPanel1.XRDesignPanel = null;
//
// reportExplorerDockPanel1_Container
//
resources.ApplyResources(this.reportExplorerDockPanel1_Container, "reportExplorerDockPanel1_Container");
this.reportExplorerDockPanel1_Container.Name = "reportExplorerDockPanel1_Container";
//
// fieldListDockPanel1
//
this.fieldListDockPanel1.Controls.Add(this.fieldListDockPanel1_Container);
this.fieldListDockPanel1.Dock = DevExpress.XtraBars.Docking.DockingStyle.Fill;
this.fieldListDockPanel1.ID = new System.Guid("faf69838-a93f-4114-83e8-d0d09cc5ce95");
this.fieldListDockPanel1.ImageIndex = 0;
resources.ApplyResources(this.fieldListDockPanel1, "fieldListDockPanel1");
this.fieldListDockPanel1.Name = "fieldListDockPanel1";
this.fieldListDockPanel1.OriginalSize = new System.Drawing.Size(244, 133);
this.fieldListDockPanel1.XRDesignPanel = null;
//
// fieldListDockPanel1_Container
//
resources.ApplyResources(this.fieldListDockPanel1_Container, "fieldListDockPanel1_Container");
this.fieldListDockPanel1_Container.Name = "fieldListDockPanel1_Container";
//
// propertyGridDockPanel1
//
this.propertyGridDockPanel1.Controls.Add(this.propertyGridDockPanel1_Container);
this.propertyGridDockPanel1.Dock = DevExpress.XtraBars.Docking.DockingStyle.Fill;
this.propertyGridDockPanel1.ID = new System.Guid("b38d12c3-cd06-4dec-b93d-63a0088e495a");
this.propertyGridDockPanel1.ImageIndex = 2;
resources.ApplyResources(this.propertyGridDockPanel1, "propertyGridDockPanel1");
this.propertyGridDockPanel1.Name = "propertyGridDockPanel1";
this.propertyGridDockPanel1.OriginalSize = new System.Drawing.Size(250, 187);
this.propertyGridDockPanel1.XRDesignPanel = null;
//
// propertyGridDockPanel1_Container
//
resources.ApplyResources(this.propertyGridDockPanel1_Container, "propertyGridDockPanel1_Container");
this.propertyGridDockPanel1_Container.Name = "propertyGridDockPanel1_Container";
//
// commandBarItem8
//
resources.ApplyResources(this.commandBarItem8, "commandBarItem8");
this.commandBarItem8.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignToGrid;
this.commandBarItem8.Enabled = false;
this.commandBarItem8.Id = 11;
this.commandBarItem8.ImageIndex = 17;
this.commandBarItem8.Name = "commandBarItem8";
//
// commandBarItem9
//
resources.ApplyResources(this.commandBarItem9, "commandBarItem9");
this.commandBarItem9.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignLeft;
this.commandBarItem9.Enabled = false;
this.commandBarItem9.Id = 12;
this.commandBarItem9.ImageIndex = 18;
this.commandBarItem9.Name = "commandBarItem9";
//
// commandBarItem10
//
resources.ApplyResources(this.commandBarItem10, "commandBarItem10");
this.commandBarItem10.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignVerticalCenters;
this.commandBarItem10.Enabled = false;
this.commandBarItem10.Id = 13;
this.commandBarItem10.ImageIndex = 19;
this.commandBarItem10.Name = "commandBarItem10";
//
// commandBarItem11
//
resources.ApplyResources(this.commandBarItem11, "commandBarItem11");
this.commandBarItem11.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignRight;
this.commandBarItem11.Enabled = false;
this.commandBarItem11.Id = 14;
this.commandBarItem11.ImageIndex = 20;
this.commandBarItem11.Name = "commandBarItem11";
//
// commandBarItem12
//
resources.ApplyResources(this.commandBarItem12, "commandBarItem12");
this.commandBarItem12.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignTop;
this.commandBarItem12.Enabled = false;
this.commandBarItem12.Id = 15;
this.commandBarItem12.ImageIndex = 21;
this.commandBarItem12.Name = "commandBarItem12";
//
// commandBarItem13
//
resources.ApplyResources(this.commandBarItem13, "commandBarItem13");
this.commandBarItem13.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignHorizontalCenters;
this.commandBarItem13.Enabled = false;
this.commandBarItem13.Id = 16;
this.commandBarItem13.ImageIndex = 22;
this.commandBarItem13.Name = "commandBarItem13";
//
// commandBarItem14
//
resources.ApplyResources(this.commandBarItem14, "commandBarItem14");
this.commandBarItem14.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignBottom;
this.commandBarItem14.Enabled = false;
this.commandBarItem14.Id = 17;
this.commandBarItem14.ImageIndex = 23;
this.commandBarItem14.Name = "commandBarItem14";
//
// commandBarItem15
//
resources.ApplyResources(this.commandBarItem15, "commandBarItem15");
this.commandBarItem15.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SizeToControlWidth;
this.commandBarItem15.Enabled = false;
this.commandBarItem15.Id = 18;
this.commandBarItem15.ImageIndex = 24;
this.commandBarItem15.Name = "commandBarItem15";
//
// commandBarItem16
//
resources.ApplyResources(this.commandBarItem16, "commandBarItem16");
this.commandBarItem16.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SizeToGrid;
this.commandBarItem16.Enabled = false;
this.commandBarItem16.Id = 19;
this.commandBarItem16.ImageIndex = 25;
this.commandBarItem16.Name = "commandBarItem16";
//
// commandBarItem17
//
resources.ApplyResources(this.commandBarItem17, "commandBarItem17");
this.commandBarItem17.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SizeToControlHeight;
this.commandBarItem17.Enabled = false;
this.commandBarItem17.Id = 20;
this.commandBarItem17.ImageIndex = 26;
this.commandBarItem17.Name = "commandBarItem17";
//
// commandBarItem18
//
resources.ApplyResources(this.commandBarItem18, "commandBarItem18");
this.commandBarItem18.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SizeToControl;
this.commandBarItem18.Enabled = false;
this.commandBarItem18.Id = 21;
this.commandBarItem18.ImageIndex = 27;
this.commandBarItem18.Name = "commandBarItem18";
//
// commandBarItem19
//
resources.ApplyResources(this.commandBarItem19, "commandBarItem19");
this.commandBarItem19.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.HorizSpaceMakeEqual;
this.commandBarItem19.Enabled = false;
this.commandBarItem19.Id = 22;
this.commandBarItem19.ImageIndex = 28;
this.commandBarItem19.Name = "commandBarItem19";
//
// commandBarItem20
//
resources.ApplyResources(this.commandBarItem20, "commandBarItem20");
this.commandBarItem20.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.HorizSpaceIncrease;
this.commandBarItem20.Enabled = false;
this.commandBarItem20.Id = 23;
this.commandBarItem20.ImageIndex = 29;
this.commandBarItem20.Name = "commandBarItem20";
//
// commandBarItem21
//
resources.ApplyResources(this.commandBarItem21, "commandBarItem21");
this.commandBarItem21.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.HorizSpaceDecrease;
this.commandBarItem21.Enabled = false;
this.commandBarItem21.Id = 24;
this.commandBarItem21.ImageIndex = 30;
this.commandBarItem21.Name = "commandBarItem21";
//
// commandBarItem22
//
resources.ApplyResources(this.commandBarItem22, "commandBarItem22");
this.commandBarItem22.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.HorizSpaceConcatenate;
this.commandBarItem22.Enabled = false;
this.commandBarItem22.Id = 25;
this.commandBarItem22.ImageIndex = 31;
this.commandBarItem22.Name = "commandBarItem22";
//
// commandBarItem23
//
resources.ApplyResources(this.commandBarItem23, "commandBarItem23");
this.commandBarItem23.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.VertSpaceMakeEqual;
this.commandBarItem23.Enabled = false;
this.commandBarItem23.Id = 26;
this.commandBarItem23.ImageIndex = 32;
this.commandBarItem23.Name = "commandBarItem23";
//
// commandBarItem24
//
resources.ApplyResources(this.commandBarItem24, "commandBarItem24");
this.commandBarItem24.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.VertSpaceIncrease;
this.commandBarItem24.Enabled = false;
this.commandBarItem24.Id = 27;
this.commandBarItem24.ImageIndex = 33;
this.commandBarItem24.Name = "commandBarItem24";
//
// commandBarItem25
//
resources.ApplyResources(this.commandBarItem25, "commandBarItem25");
this.commandBarItem25.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.VertSpaceDecrease;
this.commandBarItem25.Enabled = false;
this.commandBarItem25.Id = 28;
this.commandBarItem25.ImageIndex = 34;
this.commandBarItem25.Name = "commandBarItem25";
//
// commandBarItem26
//
resources.ApplyResources(this.commandBarItem26, "commandBarItem26");
this.commandBarItem26.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.VertSpaceConcatenate;
this.commandBarItem26.Enabled = false;
this.commandBarItem26.Id = 29;
this.commandBarItem26.ImageIndex = 35;
this.commandBarItem26.Name = "commandBarItem26";
//
// commandBarItem27
//
resources.ApplyResources(this.commandBarItem27, "commandBarItem27");
this.commandBarItem27.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.CenterHorizontally;
this.commandBarItem27.Enabled = false;
this.commandBarItem27.Id = 30;
this.commandBarItem27.ImageIndex = 36;
this.commandBarItem27.Name = "commandBarItem27";
//
// commandBarItem28
//
resources.ApplyResources(this.commandBarItem28, "commandBarItem28");
this.commandBarItem28.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.CenterVertically;
this.commandBarItem28.Enabled = false;
this.commandBarItem28.Id = 31;
this.commandBarItem28.ImageIndex = 37;
this.commandBarItem28.Name = "commandBarItem28";
//
// commandBarItem29
//
resources.ApplyResources(this.commandBarItem29, "commandBarItem29");
this.commandBarItem29.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.BringToFront;
this.commandBarItem29.Enabled = false;
this.commandBarItem29.Id = 32;
this.commandBarItem29.ImageIndex = 38;
this.commandBarItem29.Name = "commandBarItem29";
//
// commandBarItem30
//
resources.ApplyResources(this.commandBarItem30, "commandBarItem30");
this.commandBarItem30.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SendToBack;
this.commandBarItem30.Enabled = false;
this.commandBarItem30.Id = 33;
this.commandBarItem30.ImageIndex = 39;
this.commandBarItem30.Name = "commandBarItem30";
//
// barSubItem1
//
resources.ApplyResources(this.barSubItem1, "barSubItem1");
this.barSubItem1.Id = 43;
this.barSubItem1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.biGetOriginal),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem39),
new DevExpress.XtraBars.LinkPersistInfo(this.biSave, true),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem40),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem49),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem41, true)});
this.barSubItem1.Name = "barSubItem1";
//
// commandBarItem39
//
resources.ApplyResources(this.commandBarItem39, "commandBarItem39");
this.commandBarItem39.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.NewReportWizard;
this.commandBarItem39.Enabled = false;
this.commandBarItem39.Id = 60;
this.commandBarItem39.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.W));
this.commandBarItem39.Name = "commandBarItem39";
//
// commandBarItem40
//
resources.ApplyResources(this.commandBarItem40, "commandBarItem40");
this.commandBarItem40.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SaveFileAs;
this.commandBarItem40.Enabled = false;
this.commandBarItem40.Id = 61;
this.commandBarItem40.Name = "commandBarItem40";
//
// commandBarItem49
//
resources.ApplyResources(this.commandBarItem49, "commandBarItem49");
this.commandBarItem49.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.Close;
this.commandBarItem49.Enabled = false;
this.commandBarItem49.Id = 78;
this.commandBarItem49.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F4));
this.commandBarItem49.Name = "commandBarItem49";
//
// commandBarItem41
//
resources.ApplyResources(this.commandBarItem41, "commandBarItem41");
this.commandBarItem41.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.Exit;
this.commandBarItem41.Enabled = false;
this.commandBarItem41.Id = 62;
this.commandBarItem41.Name = "commandBarItem41";
//
// barSubItem2
//
resources.ApplyResources(this.barSubItem2, "barSubItem2");
this.barSubItem2.Id = 44;
this.barSubItem2.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.biUndo, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biRedo),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem42),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem43, true)});
this.barSubItem2.Name = "barSubItem2";
//
// commandBarItem42
//
resources.ApplyResources(this.commandBarItem42, "commandBarItem42");
this.commandBarItem42.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.Delete;
this.commandBarItem42.Enabled = false;
this.commandBarItem42.Id = 63;
this.commandBarItem42.Name = "commandBarItem42";
//
// commandBarItem43
//
resources.ApplyResources(this.commandBarItem43, "commandBarItem43");
this.commandBarItem43.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SelectAll;
this.commandBarItem43.Enabled = false;
this.commandBarItem43.Id = 64;
this.commandBarItem43.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A));
this.commandBarItem43.Name = "commandBarItem43";
//
// barSubItem3
//
resources.ApplyResources(this.barSubItem3, "barSubItem3");
this.barSubItem3.Id = 45;
this.barSubItem3.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.barReportTabButtonsListItem1),
new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem4, true),
new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem5, true)});
this.barSubItem3.Name = "barSubItem3";
//
// barReportTabButtonsListItem1
//
resources.ApplyResources(this.barReportTabButtonsListItem1, "barReportTabButtonsListItem1");
this.barReportTabButtonsListItem1.Id = 46;
this.barReportTabButtonsListItem1.Name = "barReportTabButtonsListItem1";
//
// barSubItem4
//
resources.ApplyResources(this.barSubItem4, "barSubItem4");
this.barSubItem4.Id = 47;
this.barSubItem4.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.xrBarToolbarsListItem1)});
this.barSubItem4.Name = "barSubItem4";
//
// xrBarToolbarsListItem1
//
resources.ApplyResources(this.xrBarToolbarsListItem1, "xrBarToolbarsListItem1");
this.xrBarToolbarsListItem1.Id = 48;
this.xrBarToolbarsListItem1.Name = "xrBarToolbarsListItem1";
//
// barSubItem5
//
resources.ApplyResources(this.barSubItem5, "barSubItem5");
this.barSubItem5.Id = 49;
this.barSubItem5.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.barDockPanelsListItem1)});
this.barSubItem5.Name = "barSubItem5";
//
// barDockPanelsListItem1
//
resources.ApplyResources(this.barDockPanelsListItem1, "barDockPanelsListItem1");
this.barDockPanelsListItem1.Id = 50;
this.barDockPanelsListItem1.Name = "barDockPanelsListItem1";
this.barDockPanelsListItem1.ShowCustomizationItem = false;
this.barDockPanelsListItem1.ShowDockPanels = true;
this.barDockPanelsListItem1.ShowToolbars = false;
//
// barSubItem6
//
resources.ApplyResources(this.barSubItem6, "barSubItem6");
this.barSubItem6.Id = 51;
this.barSubItem6.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem7, true),
new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem8),
new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem9, true),
new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem10),
new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem11, true),
new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem12),
new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem13, true),
new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem14, true)});
this.barSubItem6.Name = "barSubItem6";
//
// barSubItem7
//
resources.ApplyResources(this.barSubItem7, "barSubItem7");
this.barSubItem7.Id = 52;
this.barSubItem7.Name = "barSubItem7";
//
// barSubItem8
//
resources.ApplyResources(this.barSubItem8, "barSubItem8");
this.barSubItem8.Id = 53;
this.barSubItem8.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyLeft, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyCenter),
new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyRight),
new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyJustify)});
this.barSubItem8.Name = "barSubItem8";
//
// barSubItem9
//
resources.ApplyResources(this.barSubItem9, "barSubItem9");
this.barSubItem9.Id = 54;
this.barSubItem9.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem9, true),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem10),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem11),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem12, true),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem13),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem14),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem8, true)});
this.barSubItem9.Name = "barSubItem9";
//
// barSubItem10
//
resources.ApplyResources(this.barSubItem10, "barSubItem10");
this.barSubItem10.Id = 55;
this.barSubItem10.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem15, true),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem16),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem17),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem18)});
this.barSubItem10.Name = "barSubItem10";
//
// barSubItem11
//
resources.ApplyResources(this.barSubItem11, "barSubItem11");
this.barSubItem11.Id = 56;
this.barSubItem11.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem19, true),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem20),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem21),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem22)});
this.barSubItem11.Name = "barSubItem11";
//
// barSubItem12
//
resources.ApplyResources(this.barSubItem12, "barSubItem12");
this.barSubItem12.Id = 57;
this.barSubItem12.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem23, true),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem24),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem25),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem26)});
this.barSubItem12.Name = "barSubItem12";
//
// barSubItem13
//
resources.ApplyResources(this.barSubItem13, "barSubItem13");
this.barSubItem13.Id = 58;
this.barSubItem13.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem27, true),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem28)});
this.barSubItem13.Name = "barSubItem13";
//
// barSubItem14
//
resources.ApplyResources(this.barSubItem14, "barSubItem14");
this.barSubItem14.Id = 59;
this.barSubItem14.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem29, true),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem30)});
this.barSubItem14.Name = "barSubItem14";
//
// barSubItem15
//
resources.ApplyResources(this.barSubItem15, "barSubItem15");
this.barSubItem15.Id = 65;
this.barSubItem15.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarCheckItem1, true),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem44),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem45),
new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem46),
new DevExpress.XtraBars.LinkPersistInfo(this.barMdiChildrenListItem1, true)});
this.barSubItem15.Name = "barSubItem15";
//
// commandBarCheckItem1
//
resources.ApplyResources(this.commandBarCheckItem1, "commandBarCheckItem1");
this.commandBarCheckItem1.Checked = true;
this.commandBarCheckItem1.CheckedCommand = DevExpress.XtraReports.UserDesigner.ReportCommand.ShowTabbedInterface;
this.commandBarCheckItem1.Enabled = false;
this.commandBarCheckItem1.Id = 66;
this.commandBarCheckItem1.Name = "commandBarCheckItem1";
this.commandBarCheckItem1.UncheckedCommand = DevExpress.XtraReports.UserDesigner.ReportCommand.ShowWindowInterface;
//
// commandBarItem44
//
resources.ApplyResources(this.commandBarItem44, "commandBarItem44");
this.commandBarItem44.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.MdiCascade;
this.commandBarItem44.Enabled = false;
this.commandBarItem44.Id = 67;
this.commandBarItem44.ImageIndex = 40;
this.commandBarItem44.Name = "commandBarItem44";
//
// commandBarItem45
//
resources.ApplyResources(this.commandBarItem45, "commandBarItem45");
this.commandBarItem45.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.MdiTileHorizontal;
this.commandBarItem45.Enabled = false;
this.commandBarItem45.Id = 68;
this.commandBarItem45.ImageIndex = 41;
this.commandBarItem45.Name = "commandBarItem45";
//
// commandBarItem46
//
resources.ApplyResources(this.commandBarItem46, "commandBarItem46");
this.commandBarItem46.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.MdiTileVertical;
this.commandBarItem46.Enabled = false;
this.commandBarItem46.Id = 69;
this.commandBarItem46.ImageIndex = 42;
this.commandBarItem46.Name = "commandBarItem46";
//
// barMdiChildrenListItem1
//
resources.ApplyResources(this.barMdiChildrenListItem1, "barMdiChildrenListItem1");
this.barMdiChildrenListItem1.Id = 70;
this.barMdiChildrenListItem1.Name = "barMdiChildrenListItem1";
//
// bsiLookAndFeel
//
resources.ApplyResources(this.bsiLookAndFeel, "bsiLookAndFeel");
this.bsiLookAndFeel.Id = 74;
this.bsiLookAndFeel.Name = "bsiLookAndFeel";
//
// barButtonItem1
//
resources.ApplyResources(this.barButtonItem1, "barButtonItem1");
this.barButtonItem1.Id = 79;
this.barButtonItem1.Name = "barButtonItem1";
//
// xrDesignMdiController1
//
xrDesignPanelListener1.DesignControl = this.xrDesignBarManager1;
xrDesignPanelListener2.DesignControl = this.xrDesignDockManager1;
xrDesignPanelListener3.DesignControl = this.fieldListDockPanel1;
xrDesignPanelListener4.DesignControl = this.propertyGridDockPanel1;
xrDesignPanelListener5.DesignControl = this.reportExplorerDockPanel1;
xrDesignPanelListener6.DesignControl = this.groupAndSortDockPanel1;
xrDesignPanelListener7.DesignControl = this.errorListDockPanel1;
this.xrDesignMdiController1.DesignPanelListeners.AddRange(new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener[] {
xrDesignPanelListener1,
xrDesignPanelListener2,
xrDesignPanelListener3,
xrDesignPanelListener4,
xrDesignPanelListener5,
xrDesignPanelListener6,
xrDesignPanelListener7});
this.xrDesignMdiController1.Form = this;
this.xrDesignMdiController1.XtraTabbedMdiManager = this.xtraTabbedMdiManager1;
//
// xtraTabbedMdiManager1
//
this.xtraTabbedMdiManager1.MdiParent = this;
//
// HidePopupTimer
//
this.HidePopupTimer.Tick += new System.EventHandler(this.HidePopupTimer_Tick);
//
// DesignForm
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.barDockControlLeft);
this.Controls.Add(this.barDockControlRight);
this.Controls.Add(this.barDockControlBottom);
this.Controls.Add(this.barDockControlTop);
this.IsMdiContainer = true;
this.Name = "DesignForm";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
this.Load += new System.EventHandler(this.MainForm_Load);
((System.ComponentModel.ISupportInitialize)(this.xrDesignBarManager1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.designRepositoryItemComboBox2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.recentlyUsedItemsComboBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.designRepositoryItemComboBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrDesignDockManager1)).EndInit();
this.panelContainer3.ResumeLayout(false);
this.groupAndSortDockPanel1.ResumeLayout(false);
this.errorListDockPanel1.ResumeLayout(false);
this.panelContainer1.ResumeLayout(false);
this.panelContainer2.ResumeLayout(false);
this.reportExplorerDockPanel1.ResumeLayout(false);
this.fieldListDockPanel1.ResumeLayout(false);
this.propertyGridDockPanel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.xtraTabbedMdiManager1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private BarButtonItem barButtonItem1;
private BarDockControl barDockControlTop;
private BarDockControl barDockControlBottom;
private BarDockControl barDockControlLeft;
private BarDockControl barDockControlRight;
private System.Windows.Forms.Timer HidePopupTimer;
}
}
| |
/* ====================================================================
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.
==================================================================== */
/*
* FormulaRecord.java
*
* Created on October 28, 2001, 5:44 PM
*/
namespace NPOI.HSSF.Record
{
using System;
using System.Text;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.PTG;
using NPOI.Util;
/**
* Manages the cached formula result values of other types besides numeric.
* Excel encodes the same 8 bytes that would be field_4_value with various NaN
* values that are decoded/encoded by this class.
*/
internal class SpecialCachedValue
{
/** deliberately chosen by Excel in order to encode other values within Double NaNs */
private const long BIT_MARKER = unchecked((long)0xFFFF000000000000L);
private const int VARIABLE_DATA_LENGTH = 6;
private const int DATA_INDEX = 2;
public const int STRING = 0;
public const int BOOLEAN = 1;
public const int ERROR_CODE = 2;
public const int EMPTY = 3;
private byte[] _variableData;
private SpecialCachedValue(byte[] data)
{
_variableData = data;
}
public int GetTypeCode()
{
return _variableData[0];
}
/**
* @return <c>null</c> if the double value encoded by <c>valueLongBits</c>
* is a normal (non NaN) double value.
*/
public static SpecialCachedValue Create(long valueLongBits)
{
if ((BIT_MARKER & valueLongBits) != BIT_MARKER)
{
return null;
}
byte[] result = new byte[VARIABLE_DATA_LENGTH];
long x = valueLongBits;
for (int i = 0; i < VARIABLE_DATA_LENGTH; i++)
{
result[i] = (byte)x;
x >>= 8;
}
switch (result[0])
{
case STRING:
case BOOLEAN:
case ERROR_CODE:
case EMPTY:
break;
default:
throw new RecordFormatException("Bad special value code (" + result[0] + ")");
}
return new SpecialCachedValue(result);
}
//public void Serialize(byte[] data, int offset)
//{
// System.Array.Copy(_variableData, 0, data, offset, VARIABLE_DATA_LENGTH);
// LittleEndian.PutUShort(data, offset + VARIABLE_DATA_LENGTH, 0xFFFF);
//}
public void Serialize(ILittleEndianOutput out1) {
out1.Write(_variableData);
out1.WriteShort(0xFFFF);
}
public String FormatDebugString
{
get
{
return FormatValue + ' ' + HexDump.ToHex(_variableData);
}
}
private String FormatValue
{
get
{
int typeCode = GetTypeCode();
switch (typeCode)
{
case STRING: return "<string>";
case BOOLEAN: return DataValue == 0 ? "FALSE" : "TRUE";
case ERROR_CODE: return ErrorEval.GetText(DataValue);
case EMPTY: return "<empty>";
}
return "#error(type=" + typeCode + ")#";
}
}
private int DataValue
{
get
{
return _variableData[DATA_INDEX];
}
}
public static SpecialCachedValue CreateCachedEmptyValue()
{
return Create(EMPTY, 0);
}
public static SpecialCachedValue CreateForString()
{
return Create(STRING, 0);
}
public static SpecialCachedValue CreateCachedBoolean(bool b)
{
return Create(BOOLEAN, b ? 1 : 0);
}
public static SpecialCachedValue CreateCachedErrorCode(int errorCode)
{
return Create(ERROR_CODE, errorCode);
}
private static SpecialCachedValue Create(int code, int data)
{
byte[] vd = {
(byte) code,
0,
(byte) data,
0,
0,
0,
};
return new SpecialCachedValue(vd);
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(GetType().Name);
sb.Append('[').Append(FormatValue).Append(']');
return sb.ToString();
}
public NPOI.SS.UserModel.CellType GetValueType()
{
int typeCode = GetTypeCode();
switch (typeCode)
{
case STRING: return NPOI.SS.UserModel.CellType.String;
case BOOLEAN: return NPOI.SS.UserModel.CellType.Boolean;
case ERROR_CODE: return NPOI.SS.UserModel.CellType.Error;
case EMPTY: return NPOI.SS.UserModel.CellType.String; // is this correct?
}
throw new InvalidOperationException("Unexpected type id (" + typeCode + ")");
}
public bool GetBooleanValue()
{
if (GetTypeCode() != BOOLEAN)
{
throw new InvalidOperationException("Not a bool cached value - " + FormatValue);
}
return DataValue != 0;
}
public int GetErrorValue()
{
if (GetTypeCode() != ERROR_CODE)
{
throw new InvalidOperationException("Not an error cached value - " + FormatValue);
}
return DataValue;
}
}
/**
* Formula Record.
* REFERENCE: PG 317/444 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)
* @author Andrew C. Oliver (acoliver at apache dot org)
* @author Jason Height (jheight at chariot dot net dot au)
* @version 2.0-pre
*/
[Serializable]
public class FormulaRecord : CellRecord
{
public const short sid = 0x06; // docs say 406...because of a bug Microsoft support site article #Q184647)
private const int FIXED_SIZE = 14;
private double field_4_value;
private short field_5_options;
private BitField alwaysCalc = BitFieldFactory.GetInstance(0x0001);
private BitField calcOnLoad = BitFieldFactory.GetInstance(0x0002);
private BitField sharedFormula = BitFieldFactory.GetInstance(0x0008);
private int field_6_zero;
[NonSerialized]
private NPOI.SS.Formula.Formula field_8_parsed_expr;
/**
* Since the NaN support seems sketchy (different constants) we'll store and spit it out directly
*/
[NonSerialized]
private SpecialCachedValue specialCachedValue;
/*
* Since the NaN support seems sketchy (different constants) we'll store and spit it out directly
*/
// fix warning CS0169 "never used": private byte[] value_data;
// fix warning CS0169 "never used": private byte[] all_data; //if formula support is not enabled then
//we'll just store/reSerialize
/** Creates new FormulaRecord */
public FormulaRecord()
{
field_8_parsed_expr = NPOI.SS.Formula.Formula.Create(Ptg.EMPTY_PTG_ARRAY);
}
/**
* Constructs a Formula record and Sets its fields appropriately.
* Note - id must be 0x06 (NOT 0x406 see MSKB #Q184647 for an
* "explanation of this bug in the documentation) or an exception
* will be throw upon validation
*
* @param in the RecordInputstream to Read the record from
*/
public FormulaRecord(RecordInputStream in1):base(in1)
{
long valueLongBits = in1.ReadLong();
field_5_options = in1.ReadShort();
specialCachedValue = SpecialCachedValue.Create(valueLongBits);
if (specialCachedValue == null) {
field_4_value = BitConverter.Int64BitsToDouble(valueLongBits);
}
field_6_zero = in1.ReadInt();
int field_7_expression_len = in1.ReadShort();
field_8_parsed_expr = NPOI.SS.Formula.Formula.Read(field_7_expression_len, in1,in1.Available());
}
/**
* @return <c>true</c> if this {@link FormulaRecord} is followed by a
* {@link StringRecord} representing the cached text result of the formula
* evaluation.
*/
public bool HasCachedResultString
{
get
{
if (specialCachedValue == null)
{
return false;
}
return specialCachedValue.GetTypeCode() == SpecialCachedValue.STRING;
}
}
public void SetParsedExpression(Ptg[] ptgs)
{
field_8_parsed_expr = NPOI.SS.Formula.Formula.Create(ptgs);
}
public void SetSharedFormula(bool flag)
{
field_5_options =
sharedFormula.SetShortBoolean(field_5_options, flag);
}
/**
* Get the calculated value of the formula
*
* @return calculated value
*/
public double Value
{
get { return field_4_value; }
set {
field_4_value = value;
specialCachedValue = null;
}
}
/**
* Get the option flags
*
* @return bitmask
*/
public short Options
{
get { return field_5_options; }
set { field_5_options = value; }
}
public bool IsSharedFormula
{
get { return sharedFormula.IsSet(field_5_options); }
set
{
field_5_options =
sharedFormula.SetShortBoolean(field_5_options, value);
}
}
public bool IsAlwaysCalc
{
get { return alwaysCalc.IsSet(field_5_options); }
set
{
field_5_options =
alwaysCalc.SetShortBoolean(field_5_options, value);
}
}
public bool IsCalcOnLoad
{
get { return calcOnLoad.IsSet(field_5_options); }
set
{
field_5_options =
calcOnLoad.SetShortBoolean(field_5_options, value);
}
}
/**
* Get the stack as a list
*
* @return list of tokens (casts stack to a list and returns it!)
* this method can return null Is we are Unable to Create Ptgs from
* existing excel file
* callers should Check for null!
*/
public Ptg[] ParsedExpression
{
get { return (Ptg[])field_8_parsed_expr.Tokens; }
set { field_8_parsed_expr = NPOI.SS.Formula.Formula.Create(value); }
}
public NPOI.SS.Formula.Formula Formula
{
get
{
return field_8_parsed_expr;
}
}
protected override String RecordName
{
get
{
return "FORMULA";
}
}
protected override int ValueDataSize
{
get
{
return FIXED_SIZE + field_8_parsed_expr.EncodedSize;
}
}
public override short Sid
{
get { return sid; }
}
public void SetCachedResultTypeEmptyString()
{
specialCachedValue = SpecialCachedValue.CreateCachedEmptyValue();
}
public void SetCachedResultTypeString()
{
specialCachedValue = SpecialCachedValue.CreateForString();
}
public void SetCachedResultErrorCode(int errorCode)
{
specialCachedValue = SpecialCachedValue.CreateCachedErrorCode(errorCode);
}
public void SetCachedResultBoolean(bool value)
{
specialCachedValue = SpecialCachedValue.CreateCachedBoolean(value);
}
public bool CachedBooleanValue
{
get
{
return specialCachedValue.GetBooleanValue();
}
}
public int CachedErrorValue
{
get
{
return specialCachedValue.GetErrorValue();
}
}
public NPOI.SS.UserModel.CellType CachedResultType
{
get
{
if (specialCachedValue == null)
{
return NPOI.SS.UserModel.CellType.Numeric;
}
return (NPOI.SS.UserModel.CellType)specialCachedValue.GetValueType();
}
}
public override bool Equals(Object obj)
{
if (!(obj is CellValueRecordInterface))
{
return false;
}
CellValueRecordInterface loc = (CellValueRecordInterface)obj;
if ((this.Row == loc.Row)
&& (this.Column == loc.Column))
{
return true;
}
return false;
}
public override int GetHashCode ()
{
return Row ^ Column;
}
protected override void SerializeValue(ILittleEndianOutput out1)
{
if (specialCachedValue == null)
{
out1.WriteDouble(field_4_value);
}
else
{
specialCachedValue.Serialize(out1);
}
out1.WriteShort(Options);
out1.WriteInt(field_6_zero); // may as well write original data back so as to minimise differences from original
field_8_parsed_expr.Serialize(out1);
}
protected override void AppendValueText(StringBuilder buffer)
{
buffer.Append(" .value = ");
if (specialCachedValue == null)
{
buffer.Append(field_4_value).Append("\n");
}
else
{
buffer.Append(specialCachedValue.FormatDebugString).Append("\n");
}
buffer.Append(" .options = ").Append(Options).Append("\n");
buffer.Append(" .alwaysCalc = ").Append(alwaysCalc.IsSet(Options)).Append("\n");
buffer.Append(" .CalcOnLoad = ").Append(calcOnLoad.IsSet(Options)).Append("\n");
buffer.Append(" .sharedFormula = ").Append(sharedFormula.IsSet(Options)).Append("\n");
buffer.Append(" .zero = ").Append(field_6_zero).Append("\n");
Ptg[] ptgs = field_8_parsed_expr.Tokens;
for (int k = 0; k < ptgs.Length; k++)
{
buffer.Append(" Ptg[").Append(k).Append("]=");
Ptg ptg = ptgs[k];
buffer.Append(ptg.ToString()).Append(ptg.RVAType).Append("\n");
}
}
public override Object Clone()
{
FormulaRecord rec = new FormulaRecord();
CopyBaseFields(rec);
rec.field_4_value = field_4_value;
rec.field_5_options = field_5_options;
rec.field_6_zero = field_6_zero;
rec.field_8_parsed_expr = field_8_parsed_expr.Copy();
rec.specialCachedValue = specialCachedValue;
return rec;
}
}
}
| |
// Copyright 2011, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Ads.Common.Config;
using Google.Api.Ads.Common.Logging;
using Google.Apis.Auth.OAuth2;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
#if NET452
using System.Web.Configuration;
using System.Web.Hosting;
# endif
namespace Google.Api.Ads.Common.Lib
{
/// <summary>
/// This class reads the configuration keys from App.config.
/// </summary>
public class AppConfigBase : AppConfig, INotifyPropertyChanged
{
/// <summary>
/// The registry for saving feature usage information..
/// </summary>
private static readonly AdsFeatureUsageRegistry featureUsageRegistry =
AdsFeatureUsageRegistry.Instance;
/// <summary>
/// The short name to identify this assembly.
/// </summary>
private const string SHORT_NAME = "Common-Dotnet";
/// <summary>
/// Web proxy to be used with the services.
/// </summary>
private ConfigSetting<IWebProxy> proxy = new ConfigSetting<IWebProxy>("Proxy", null);
/// <summary>
/// True, if the credentials in the log file should be masked.
/// </summary>
private ConfigSetting<bool> maskCredentials =
new ConfigSetting<bool>("MaskCredentials", true);
/// <summary>
/// Timeout to be used for Ads services in milliseconds.
/// </summary>
private ConfigSetting<int> timeout = new ConfigSetting<int>("Timeout", DEFAULT_TIMEOUT);
/// <summary>
/// Number of times to retry a call if an API call fails and can be retried.
/// </summary>
private ConfigSetting<int> retryCount = new ConfigSetting<int>("RetryCount", 0);
/// <summary>
/// True, if gzip compression should be turned on for SOAP requests and
/// responses.
/// </summary>
private ConfigSetting<bool> enableGzipCompression =
new ConfigSetting<bool>("EnableGzipCompression", true);
/// <summary>
/// OAuth2 client ID.
/// </summary>
private ConfigSetting<string> oAuth2ClientId =
new ConfigSetting<string>("OAuth2ClientId", "");
/// <summary>
/// OAuth2 server URL.
/// </summary>
private ConfigSetting<string> oAuth2ServerUrl =
new ConfigSetting<string>("OAuth2ServerUrl", DEFAULT_OAUTH2_SERVER);
/// <summary>
/// OAuth2 client secret.
/// </summary>
private ConfigSetting<string> oAuth2ClientSecret =
new ConfigSetting<string>("OAuth2ClientSecret", "");
/// <summary>
/// OAuth2 access token.
/// </summary>
private ConfigSetting<string> oAuth2AccessToken =
new ConfigSetting<string>("OAuth2AccessToken", "");
/// <summary>
/// OAuth2 refresh token.
/// </summary>
private ConfigSetting<string> oAuth2RefreshToken =
new ConfigSetting<string>("OAuth2RefreshToken", "");
/// <summary>
/// OAuth2 prn email.
/// </summary>
private ConfigSetting<string> oAuth2PrnEmail =
new ConfigSetting<string>("OAuth2PrnEmail", "");
/// <summary>
/// OAuth2 service account email loaded from secrets JSON file.
/// </summary>
private ConfigSetting<string> oAuth2ServiceAccountEmail =
new ConfigSetting<string>("client_email", null);
/// <summary>
/// OAuth2 private key loaded from secrets JSON file.
/// </summary>
private ConfigSetting<string> oAuth2PrivateKey =
new ConfigSetting<string>("private_key", "");
/// <summary>
/// OAuth2 secrets JSON file path.
/// </summary>
private ConfigSetting<string> oAuth2SecretsJsonPath =
new ConfigSetting<string>("OAuth2SecretsJsonPath", "");
/// <summary>
/// OAuth2 scope.
/// </summary>
private ConfigSetting<string> oAuth2Scope = new ConfigSetting<string>("OAuth2Scope", "");
/// <summary>
/// Redirect uri.
/// </summary>
private ConfigSetting<string> oAuth2RedirectUri =
new ConfigSetting<string>("OAuth2RedirectUri",
GoogleAuthConsts.InstalledAppRedirectUri);
/// <summary>
/// OAuth2 mode.
/// </summary>
private ConfigSetting<OAuth2Flow> oAuth2Mode =
new ConfigSetting<OAuth2Flow>("OAuth2Mode", OAuth2Flow.APPLICATION);
/// <summary>
/// True, if the usage of a feature should be added to the user agent,
/// false otherwise.
/// </summary>
private ConfigSetting<bool> includeUtilitiesInUserAgent =
new ConfigSetting<bool>("IncludeUtilitiesInUserAgent", false);
/// <summary>
/// Default value for timeout for Ads services.
/// </summary>
private const int DEFAULT_TIMEOUT = 1000 * 60 * 10;
/// <summary>
/// The default value of OAuth2 server URL.
/// </summary>
private const string DEFAULT_OAUTH2_SERVER = "https://accounts.google.com";
/// <summary>
/// Gets or sets whether the credentials in the log file should be masked.
/// </summary>
public bool MaskCredentials
{
get => maskCredentials.Value;
set => SetPropertyAndNotify(maskCredentials, value);
}
/// <summary>
/// Gets or sets the web proxy to be used with the services.
/// </summary>
public IWebProxy Proxy
{
get => proxy.Value;
set => SetPropertyAndNotify(proxy, value);
}
/// <summary>
/// Gets or sets the timeout for Ads services in milliseconds.
/// </summary>
public int Timeout
{
get => timeout.Value;
set => SetPropertyAndNotify(timeout, value);
}
/// <summary>
/// Gets or sets the number of times to retry a call if an API call fails
/// and can be retried.
/// </summary>
public int RetryCount
{
get => retryCount.Value;
set => SetPropertyAndNotify(retryCount, value);
}
/// <summary>
/// Gets or sets whether gzip compression should be turned on for SOAP
/// requests and responses.
/// </summary>
public bool EnableGzipCompression
{
get => enableGzipCompression.Value;
set => SetPropertyAndNotify(enableGzipCompression, value);
}
/// <summary>
/// Gets or sets the OAuth2 server URL.
/// </summary>
/// <remarks>This property's setter is primarily used for testing purposes.
/// </remarks>
public string OAuth2ServerUrl
{
get => oAuth2ServerUrl.Value;
set => SetPropertyAndNotify(oAuth2ServerUrl, value);
}
/// <summary>
/// Gets or sets the OAuth2 client ID.
/// </summary>
public string OAuth2ClientId
{
get => oAuth2ClientId.Value;
set => SetPropertyAndNotify(oAuth2ClientId, value);
}
/// <summary>
/// Gets or sets the OAuth2 client secret.
/// </summary>
public string OAuth2ClientSecret
{
get => oAuth2ClientSecret.Value;
set => SetPropertyAndNotify(oAuth2ClientSecret, value);
}
/// <summary>
/// Gets or sets the OAuth2 access token.
/// </summary>
public string OAuth2AccessToken
{
get => oAuth2AccessToken.Value;
set => SetPropertyAndNotify(oAuth2AccessToken, value);
}
/// <summary>
/// Gets or sets the OAuth2 refresh token.
/// </summary>
/// <remarks>This setting is applicable only when using OAuth2 web / application
/// flow in offline mode.</remarks>
public string OAuth2RefreshToken
{
get => oAuth2RefreshToken.Value;
set => SetPropertyAndNotify(oAuth2RefreshToken, value);
}
/// <summary>
/// Gets or sets the OAuth2 scope.
/// </summary>
public string OAuth2Scope
{
get => oAuth2Scope.Value;
set => SetPropertyAndNotify(oAuth2Scope, value);
}
/// <summary>
/// Gets or sets the OAuth2 redirect URI.
/// </summary>
/// <remarks>This setting is applicable only when using OAuth2 web flow.
/// </remarks>
public string OAuth2RedirectUri
{
get => oAuth2RedirectUri.Value;
set => SetPropertyAndNotify(oAuth2RedirectUri, value);
}
/// <summary>
/// Gets or sets the OAuth2 mode.
/// </summary>
public OAuth2Flow OAuth2Mode
{
get => oAuth2Mode.Value;
set => SetPropertyAndNotify(oAuth2Mode, value);
}
/// <summary>
/// Gets or sets the OAuth2 prn email.
/// </summary>
/// <remarks>This setting is applicable only when using OAuth2 service accounts.
/// </remarks>
public string OAuth2PrnEmail
{
get => oAuth2PrnEmail.Value;
set => SetPropertyAndNotify(oAuth2PrnEmail, value);
}
/// <summary>
/// Gets the OAuth2 service account email.
/// </summary>
/// <remarks>
/// This setting is applicable only when using OAuth2 service accounts.
/// This setting is read directly from the file referred to in
/// <see cref="OAuth2SecretsJsonPath"/> setting.
/// </remarks>
public string OAuth2ServiceAccountEmail
{
get => oAuth2ServiceAccountEmail.Value;
private set => SetPropertyAndNotify(oAuth2ServiceAccountEmail, value);
}
/// <summary>
/// Gets the OAuth2 private key for service account flow.
/// </summary>
/// <remarks>
/// This setting is applicable only when using OAuth2 service accounts.
/// This setting is read directly from the file referred to in
/// <see cref="OAuth2SecretsJsonPath"/> setting.
/// </remarks>
public string OAuth2PrivateKey
{
get => oAuth2PrivateKey.Value;
private set => SetPropertyAndNotify(oAuth2PrivateKey, value);
}
/// <summary>
/// Gets or sets the OAuth2 secrets JSON file path.
/// </summary>
/// <remarks>
/// This setting is applicable only when using OAuth2 service accounts.
/// </remarks>
public string OAuth2SecretsJsonPath
{
get => oAuth2SecretsJsonPath.Value;
set
{
SetPropertyAndNotify(oAuth2SecretsJsonPath, value);
LoadOAuth2SecretsFromFile();
}
}
/// <summary>
/// Gets or sets whether usage of various client library features should be
/// tracked.
/// </summary>
/// <remarks>The name of the property is kept different to match the setting
/// name for other client libraries.</remarks>
public bool IncludeUtilitiesInUserAgent
{
get => includeUtilitiesInUserAgent.Value;
set => SetPropertyAndNotify(includeUtilitiesInUserAgent, value);
}
/// <summary>
/// Gets the default OAuth2 scope.
/// </summary>
public virtual string GetDefaultOAuth2Scope()
{
return "";
}
/// <summary>
/// Gets the user agent text.
/// </summary>
/// <returns>The user agent.</returns>
public virtual string GetUserAgent()
{
return "";
}
/// <summary>
/// Gets the signature for this assembly, given a type derived from
/// AppConfigBase.
/// </summary>
/// <param name="type">Type of the class derived from AppConfigBase.</param>
/// <returns>The assembly signature.</returns>
/// <exception cref="ArgumentException">Thrown if type is not derived from
/// AppConfigBase.</exception>
private string GetAssemblySignatureFromAppConfigType(Type type)
{
Type appConfigBaseType = typeof(AppConfigBase);
if (!(type.BaseType == appConfigBaseType || type == appConfigBaseType))
{
throw new ArgumentException(string.Format("{0} is not derived from {1}.",
type.FullName, appConfigBaseType.FullName));
}
Version version = type.Assembly.GetName().Version;
string shortName = (string) type
.GetField("SHORT_NAME", BindingFlags.NonPublic | BindingFlags.Static)
.GetValue(null);
return string.Format("{0}/{1}.{2}.{3}", shortName, version.Major, version.Minor,
version.Revision);
}
/// <summary>
/// Gets the signature for this library.
/// </summary>
public string Signature
{
get
{
string utilsAgent = (IncludeUtilitiesInUserAgent) ? featureUsageRegistry.Text : "";
return string.Format("{0}, {1}, .NET CLR/{2}, {3}",
GetAssemblySignatureFromAppConfigType(GetType()),
GetAssemblySignatureFromAppConfigType(GetType().BaseType), Environment.Version,
utilsAgent);
}
}
/// <summary>
/// Gets the number of seconds after Jan 1, 1970, 00:00:00
/// </summary>
public virtual long UnixTimestamp
{
get
{
TimeSpan unixTime = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
return (long) unixTime.TotalSeconds;
}
}
/// <summary>
/// The default constructor.
/// </summary>
public AppConfigBase()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AppConfigBase"/> class.
/// </summary>
/// <param name="configurationRoot">The configuration root.</param>
public AppConfigBase(IConfigurationRoot configurationRoot) : base()
{
LoadFromConfiguration(configurationRoot, "");
}
/// <summary>
/// Initializes a new instance of the <see cref="AppConfigBase"/> class.
/// </summary>
/// <param name="configurationSection">The configuration section.</param>
public AppConfigBase(IConfigurationSection configurationSection) : base()
{
LoadFromConfiguration(configurationSection, configurationSection.Key);
}
/// <summary>
/// Initializes a new instance of the <see cref="AppConfigBase"/> class.
/// </summary>
/// <param name="configuration">The configuration section.</param>
/// <param name="sectionName">The section name.</param>
protected void LoadFromConfiguration(IConfiguration configuration, string sectionName)
{
ReadSettings(ToDictionary(configuration, sectionName));
}
/// <summary>
/// Attempts to load the configuration section with the given name.
/// </summary>
/// <param name="sectionName">The name of the configuration section to load.</param>
/// <returns>
/// The request configuration section, or <code>null</code> if none was found.
/// </returns>
protected void LoadFromAppConfigSection(string sectionName)
{
ReadSettings(ReadAppConfigSection(sectionName));
}
/// <summary>
/// Reads the application configuration section.
/// </summary>
/// <param name="sectionName">Name of the section.</param>
/// <returns>A dictionary with key as configuration keyname and value as configuration
/// value.</returns>
private static Dictionary<string, string> ReadAppConfigSection(string sectionName)
{
Hashtable config = null;
#if NET452
if (HostingEnvironment.IsHosted)
{
config = (Hashtable) WebConfigurationManager.GetSection(sectionName);
}
else
{
config = (Hashtable) ConfigurationManager.GetSection(sectionName);
}
#else
config = (Hashtable) ConfigurationManager.GetSection(sectionName);
#endif
return config != null ?
config.Cast<DictionaryEntry>().ToDictionary(
d => d.Key.ToString(), d => d.Value?.ToString()) :
new Dictionary<string, string>();
;
}
/// <summary>
/// Converts a configuration section into a dictionary. Section name prefix is stripped
/// from the key names.
/// </summary>
/// <param name="configuration">The configuration section.</param>
/// <param name="sectionName">Name of the section.</param>
/// <returns>A dictionary with key as configuration keyname and value as configuration
/// value.</returns>
private static Dictionary<string, string> ToDictionary(IConfiguration configuration,
string sectionName)
{
string sectionPrefix = sectionName + ":";
return configuration.AsEnumerable().ToDictionary(
setting => setting.Key.ToString().Replace(sectionPrefix, ""),
setting => setting.Value?.ToString());
}
/// <summary>
/// Read all settings from App.config.
/// </summary>
/// <param name="settings">The parsed app.config settings.</param>
protected virtual void ReadSettings(Dictionary<string, string> settings)
{
ReadProxySettings(settings);
ReadSetting(settings, maskCredentials);
ReadSetting(settings, oAuth2Mode);
ReadSetting(settings, retryCount);
ReadSetting(settings, oAuth2ServerUrl);
ReadSetting(settings, oAuth2ClientId);
ReadSetting(settings, oAuth2ClientSecret);
ReadSetting(settings, oAuth2AccessToken);
ReadSetting(settings, oAuth2RefreshToken);
ReadSetting(settings, oAuth2Scope);
ReadSetting(settings, oAuth2RedirectUri);
// Read and parse the OAuth2 JSON secrets file if applicable.
ReadSetting(settings, oAuth2SecretsJsonPath);
if (!string.IsNullOrEmpty(oAuth2SecretsJsonPath.Value))
{
LoadOAuth2SecretsFromFile();
}
ReadSetting(settings, oAuth2PrnEmail);
ReadSetting(settings, timeout);
ReadSetting(settings, enableGzipCompression);
ReadSetting(settings, includeUtilitiesInUserAgent);
}
/// <summary>
/// Reads the proxy settings.
/// </summary>
/// <param name="settings">The parsed app.config settings.</param>
private void ReadProxySettings(Dictionary<string, string> settings)
{
ConfigSetting<string> proxyServer = new ConfigSetting<string>("ProxyServer", null);
ConfigSetting<string> proxyUser = new ConfigSetting<string>("ProxyUser", null);
ConfigSetting<string> proxyPassword = new ConfigSetting<string>("ProxyPassword", null);
ConfigSetting<string> proxyDomain = new ConfigSetting<string>("ProxyDomain", null);
ReadSetting(settings, proxyServer);
if (!string.IsNullOrEmpty(proxyServer.Value))
{
WebProxy proxy = new WebProxy()
{
Address = new Uri(proxyServer.Value)
};
ReadSetting(settings, proxyUser);
ReadSetting(settings, proxyPassword);
ReadSetting(settings, proxyDomain);
if (!string.IsNullOrEmpty(proxyUser.Value))
{
proxy.Credentials = new NetworkCredential(proxyUser.Value, proxyPassword.Value,
proxyDomain.Value);
}
this.proxy.Value = proxy;
}
else
{
// System.Net.WebRequest will find a proxy if needed.
this.proxy.Value = null;
}
}
/// <summary>
/// Loads the OAuth2 private key and service account email settings from the
/// secrets JSON file.
/// </summary>
private void LoadOAuth2SecretsFromFile()
{
try
{
using (StreamReader reader = new StreamReader(OAuth2SecretsJsonPath))
{
string contents = reader.ReadToEnd();
Dictionary<string, string> config =
JsonConvert.DeserializeObject<Dictionary<string, string>>(contents);
ReadSetting(config, oAuth2ServiceAccountEmail);
if (string.IsNullOrEmpty(this.OAuth2ServiceAccountEmail))
{
throw new AdsOAuthException(CommonErrorMessages
.ClientEmailIsMissingInJsonFile);
}
ReadSetting(config, oAuth2PrivateKey);
if (string.IsNullOrEmpty(this.OAuth2PrivateKey))
{
throw new AdsOAuthException(CommonErrorMessages
.PrivateKeyIsMissingInJsonFile);
}
}
}
catch (AdsOAuthException)
{
throw;
}
catch (Exception e)
{
throw new AdsOAuthException(CommonErrorMessages.FailedToLoadJsonSecretsFile, e);
}
}
/// <summary>
/// Reads a setting from a given dictionary.
/// </summary>
/// <param name="settings">The settings collection from which the keys
/// are to be read.</param>
/// <param name="settingField">The field that holds the setting value.</param>
protected void ReadSetting(Dictionary<string, string> settings, ConfigSetting settingField)
{
if (settings != null && settings.ContainsKey(settingField.Name))
{
settingField.TryParse(settings[settingField.Name]);
}
}
/// <summary>
/// Sets the specified property and notify any listeners.
/// </summary>
/// <typeparam name="T">Type of the property.</typeparam>
/// <param name="field">The field that store property value.</param>
/// <param name="newValue">The new value to be set.</param>
/// <param name="propertyName">Name of the property.</param>
protected void SetPropertyAndNotify<T>(ConfigSetting<T> field, T newValue,
[CallerMemberName] String propertyName = "")
{
if (!EqualityComparer<T>.Default.Equals(field.Value, newValue))
{
field.Value = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public virtual object Clone()
{
return MemberwiseClone();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using System.Text;
using Npgsql;
namespace OpenSim.Data.PGSQL
{
public class PGSQLGenericTableHandler<T> : PGSqlFramework where T : class, new()
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_ConnectionString;
protected PGSQLManager m_database; //used for parameter type translation
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
protected Dictionary<string, string> m_FieldTypes = new Dictionary<string, string>();
protected List<string> m_ColumnNames = null;
protected string m_Realm;
protected FieldInfo m_DataField = null;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public PGSQLGenericTableHandler(string connectionString,
string realm, string storeName)
: base(connectionString)
{
m_Realm = realm;
m_ConnectionString = connectionString;
if (storeName != String.Empty)
{
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
{
conn.Open();
Migration m = new Migration(conn, GetType().Assembly, storeName);
m.Update();
}
}
m_database = new PGSQLManager(m_ConnectionString);
Type t = typeof(T);
FieldInfo[] fields = t.GetFields(BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
LoadFieldTypes();
if (fields.Length == 0)
return;
foreach (FieldInfo f in fields)
{
if (f.Name != "Data")
m_Fields[f.Name] = f;
else
m_DataField = f;
}
}
private void LoadFieldTypes()
{
m_FieldTypes = new Dictionary<string, string>();
string query = string.Format(@"select column_name,data_type
from INFORMATION_SCHEMA.COLUMNS
where table_name = lower('{0}');
", m_Realm);
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn))
{
conn.Open();
using (NpgsqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// query produces 0 to many rows of single column, so always add the first item in each row
m_FieldTypes.Add((string)rdr[0], (string)rdr[1]);
}
}
}
}
private void CheckColumnNames(NpgsqlDataReader reader)
{
if (m_ColumnNames != null)
return;
m_ColumnNames = new List<string>();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
if (row["ColumnName"] != null &&
(!m_Fields.ContainsKey(row["ColumnName"].ToString())))
m_ColumnNames.Add(row["ColumnName"].ToString());
}
}
// TODO GET CONSTRAINTS FROM POSTGRESQL
private List<string> GetConstraints()
{
List<string> constraints = new List<string>();
string query = string.Format(@"SELECT kcu.column_name
FROM information_schema.table_constraints tc
LEFT JOIN information_schema.key_column_usage kcu
ON tc.constraint_catalog = kcu.constraint_catalog
AND tc.constraint_schema = kcu.constraint_schema
AND tc.constraint_name = kcu.constraint_name
LEFT JOIN information_schema.referential_constraints rc
ON tc.constraint_catalog = rc.constraint_catalog
AND tc.constraint_schema = rc.constraint_schema
AND tc.constraint_name = rc.constraint_name
LEFT JOIN information_schema.constraint_column_usage ccu
ON rc.unique_constraint_catalog = ccu.constraint_catalog
AND rc.unique_constraint_schema = ccu.constraint_schema
AND rc.unique_constraint_name = ccu.constraint_name
where tc.table_name = lower('{0}')
and lower(tc.constraint_type) in ('primary key')
and kcu.column_name is not null
;", m_Realm);
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn))
{
conn.Open();
using (NpgsqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// query produces 0 to many rows of single column, so always add the first item in each row
constraints.Add((string)rdr[0]);
}
}
return constraints;
}
}
public virtual T[] Get(string field, string key)
{
return Get(new string[] { field }, new string[] { key });
}
public virtual T[] Get(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return new T[0];
List<string> terms = new List<string>();
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
for (int i = 0; i < fields.Length; i++)
{
if ( m_FieldTypes.ContainsKey(fields[i]) )
cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]]));
else
cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
terms.Add(" \"" + fields[i] + "\" = :" + fields[i]);
}
string where = String.Join(" AND ", terms.ToArray());
string query = String.Format("SELECT * FROM {0} WHERE {1}",
m_Realm, where);
cmd.Connection = conn;
cmd.CommandText = query;
conn.Open();
return DoQuery(cmd);
}
}
protected T[] DoQuery(NpgsqlCommand cmd)
{
List<T> result = new List<T>();
if (cmd.Connection == null)
{
cmd.Connection = new NpgsqlConnection(m_connectionString);
}
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
if (reader == null)
return new T[0];
CheckColumnNames(reader);
while (reader.Read())
{
T row = new T();
foreach (string name in m_Fields.Keys)
{
if (m_Fields[name].GetValue(row) is bool)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v != 0 ? true : false);
}
else if (m_Fields[name].GetValue(row) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(reader[name].ToString(), out uuid);
m_Fields[name].SetValue(row, uuid);
}
else if (m_Fields[name].GetValue(row) is int)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else
{
m_Fields[name].SetValue(row, reader[name]);
}
}
if (m_DataField != null)
{
Dictionary<string, string> data =
new Dictionary<string, string>();
foreach (string col in m_ColumnNames)
{
data[col] = reader[col].ToString();
if (data[col] == null)
data[col] = String.Empty;
}
m_DataField.SetValue(row, data);
}
result.Add(row);
}
return result.ToArray();
}
}
public virtual T[] Get(string where)
{
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
string query = String.Format("SELECT * FROM {0} WHERE {1}",
m_Realm, where);
cmd.Connection = conn;
cmd.CommandText = query;
//m_log.WarnFormat("[PGSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where);
conn.Open();
return DoQuery(cmd);
}
}
public virtual bool Store(T row)
{
List<string> constraintFields = GetConstraints();
List<KeyValuePair<string, string>> constraints = new List<KeyValuePair<string, string>>();
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
StringBuilder query = new StringBuilder();
List<String> names = new List<String>();
List<String> values = new List<String>();
foreach (FieldInfo fi in m_Fields.Values)
{
names.Add(fi.Name);
values.Add(":" + fi.Name);
// Temporarily return more information about what field is unexpectedly null for
// http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the
// InventoryTransferModule or we may be required to substitute a DBNull here.
if (fi.GetValue(row) == null)
throw new NullReferenceException(
string.Format(
"[PGSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null",
fi.Name, row));
if (constraintFields.Count > 0 && constraintFields.Contains(fi.Name))
{
constraints.Add(new KeyValuePair<string, string>(fi.Name, fi.GetValue(row).ToString() ));
}
if (m_FieldTypes.ContainsKey(fi.Name))
cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row), m_FieldTypes[fi.Name]));
else
cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row)));
}
if (m_DataField != null)
{
Dictionary<string, string> data =
(Dictionary<string, string>)m_DataField.GetValue(row);
foreach (KeyValuePair<string, string> kvp in data)
{
if (constraintFields.Count > 0 && constraintFields.Contains(kvp.Key))
{
constraints.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Key));
}
names.Add(kvp.Key);
values.Add(":" + kvp.Key);
if (m_FieldTypes.ContainsKey(kvp.Key))
cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value, m_FieldTypes[kvp.Key]));
else
cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value));
}
}
query.AppendFormat("UPDATE {0} SET ", m_Realm);
int i = 0;
for (i = 0; i < names.Count - 1; i++)
{
query.AppendFormat("\"{0}\" = {1}, ", names[i], values[i]);
}
query.AppendFormat("\"{0}\" = {1} ", names[i], values[i]);
if (constraints.Count > 0)
{
List<string> terms = new List<string>();
for (int j = 0; j < constraints.Count; j++)
{
terms.Add(String.Format(" \"{0}\" = :{0}", constraints[j].Key));
}
string where = String.Join(" AND ", terms.ToArray());
query.AppendFormat(" WHERE {0} ", where);
}
cmd.Connection = conn;
cmd.CommandText = query.ToString();
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
//m_log.WarnFormat("[PGSQLGenericTable]: Updating {0}", m_Realm);
return true;
}
else
{
// assume record has not yet been inserted
query = new StringBuilder();
query.AppendFormat("INSERT INTO {0} (\"", m_Realm);
query.Append(String.Join("\",\"", names.ToArray()));
query.Append("\") values (" + String.Join(",", values.ToArray()) + ")");
cmd.Connection = conn;
cmd.CommandText = query.ToString();
// m_log.WarnFormat("[PGSQLGenericTable]: Inserting into {0} sql {1}", m_Realm, cmd.CommandText);
if (conn.State != ConnectionState.Open)
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
return true;
}
return false;
}
}
public virtual bool Delete(string field, string key)
{
return Delete(new string[] { field }, new string[] { key });
}
public virtual bool Delete(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return false;
List<string> terms = new List<string>();
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
for (int i = 0; i < fields.Length; i++)
{
if (m_FieldTypes.ContainsKey(fields[i]))
cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]]));
else
cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
terms.Add(" \"" + fields[i] + "\" = :" + fields[i]);
}
string where = String.Join(" AND ", terms.ToArray());
string query = String.Format("DELETE FROM {0} WHERE {1}", m_Realm, where);
cmd.Connection = conn;
cmd.CommandText = query;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
//m_log.Warn("[PGSQLGenericTable]: " + deleteCommand);
return true;
}
return false;
}
}
public long GetCount(string field, string key)
{
return GetCount(new string[] { field }, new string[] { key });
}
public long GetCount(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return 0;
List<string> terms = new List<string>();
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
for (int i = 0; i < fields.Length; i++)
{
cmd.Parameters.AddWithValue(fields[i], keys[i]);
terms.Add("\"" + fields[i] + "\" = :" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("select count(*) from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
Object result = DoQueryScalar(cmd);
return Convert.ToInt64(result);
}
}
public long GetCount(string where)
{
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
string query = String.Format("select count(*) from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
object result = DoQueryScalar(cmd);
return Convert.ToInt64(result);
}
}
public object DoQueryScalar(NpgsqlCommand cmd)
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(m_ConnectionString))
{
dbcon.Open();
cmd.Connection = dbcon;
return cmd.ExecuteScalar();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Xunit;
using Http2.Hpack;
namespace HpackTests
{
public class EncoderTests
{
const int MaxFrameSize = 65535;
struct EncodeResult
{
public byte[] Bytes;
public int FieldCount;
}
private EncodeResult EncodeToTempBuf(
Encoder encoder, IEnumerable<HeaderField> headers, int maxSize)
{
var buf = new byte[maxSize];
var res = encoder.EncodeInto(new ArraySegment<byte>(buf), headers);
// Clamp the bytes
var newBuf = new byte[res.UsedBytes];
Array.Copy(buf, 0, newBuf, 0, res.UsedBytes);
return new EncodeResult
{
Bytes = newBuf,
FieldCount = res.FieldCount,
};
}
[Fact]
public void ShouldHaveADefaultDynamicTableSizeOf4096()
{
var encoder = new Encoder();
Assert.Equal(4096, encoder.DynamicTableSize);
}
[Fact]
public void ShouldAllowToAdjustTheDynamicTableSizeThroughConstructor()
{
var encoder = new Encoder(new Encoder.Options{
DynamicTableSize = 0,
});
Assert.Equal(0, encoder.DynamicTableSize);
}
[Fact]
public void ShouldAllowToAdjustTheDynamicTableSizeThroughPropertySetter()
{
var encoder = new Encoder();
encoder.DynamicTableSize = 200;
Assert.Equal(200, encoder.DynamicTableSize);
}
[Theory]
[InlineData(0)]
[InlineData(30)]
[InlineData(16535)]
public void SizeUpdatesShouldBeEncodedWithinNextHeaderBlock(
int newSize)
{
var encoder = new Encoder(new Encoder.Options{
HuffmanStrategy = HuffmanStrategy.Never,
});
encoder.DynamicTableSize = newSize;
var expectedTableUpdateBytes = IntEncoder.Encode(newSize, 0x20, 5);
var fields = new HeaderField[] {
new HeaderField{ Name = "ab", Value = "cd", Sensitive = true }
};
var result = new Buffer();
result.WriteBytes(expectedTableUpdateBytes);
result.AddHexString("1002");
result.WriteString("ab");
result.AddHexString("02");
result.WriteString("cd");
var res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(1, res.FieldCount);
Assert.Equal(0, encoder.DynamicTableUsedSize);
Assert.Equal(0, encoder.DynamicTableLength);
Assert.Equal(newSize, encoder.DynamicTableSize);
}
[Theory]
[InlineData(new int[]{0, 30}, "203e")]
[InlineData(new int[]{30, 0}, "20")]
[InlineData(new int[]{5000, 0, 30}, "203e")]
[InlineData(new int[]{5000, 0, 30, 0}, "20")]
[InlineData(new int[]{5000, 15, 30, 0}, "20")]
[InlineData(new int[]{5000, 15, 30, 7, 10}, "272a")]
public void IfSizeIsChangedMultipleTimesAllNecessaryUpdatesShouldBeEncoded(
int[] sizeChanges, string expectedTableUpdateHexBytes)
{
var encoder = new Encoder(new Encoder.Options{
HuffmanStrategy = HuffmanStrategy.Never,
});
foreach (var newSize in sizeChanges)
{
encoder.DynamicTableSize = newSize;
}
var fields = new HeaderField[] {
new HeaderField{ Name = "ab", Value = "cd", Sensitive = true }
};
var result = new Buffer();
result.AddHexString(expectedTableUpdateHexBytes);
result.AddHexString("1002");
result.WriteString("ab");
result.AddHexString("02");
result.WriteString("cd");
var res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(1, res.FieldCount);
Assert.Equal(0, encoder.DynamicTableUsedSize);
Assert.Equal(0, encoder.DynamicTableLength);
Assert.Equal(sizeChanges[sizeChanges.Length-1], encoder.DynamicTableSize);
// Encode a further header block
// This may not contain any tableupdate data
result = new Buffer();
result.AddHexString("1002");
result.WriteString("ab");
result.AddHexString("02");
result.WriteString("cd");
res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(1, res.FieldCount);
Assert.Equal(0, encoder.DynamicTableUsedSize);
Assert.Equal(0, encoder.DynamicTableLength);
Assert.Equal(sizeChanges[sizeChanges.Length-1], encoder.DynamicTableSize);
}
[Fact]
public void ShouldHandleExampleC2_1OfTheSpecificationCorrectly()
{
var encoder = new Encoder(new Encoder.Options{
HuffmanStrategy = HuffmanStrategy.Never,
});
var fields = new HeaderField[] {
new HeaderField{ Name = "custom-key", Value = "custom-header", Sensitive = false }
};
var result = new Buffer();
result.AddHexString(
"400a637573746f6d2d6b65790d637573" +
"746f6d2d686561646572");
var res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(1, res.FieldCount);
Assert.Equal(55, encoder.DynamicTableUsedSize);
Assert.Equal(1, encoder.DynamicTableLength);
}
[Fact]
public void ShouldHandleExampleC2_2OfTheSpecificationCorrectly()
{
var encoder = new Encoder(new Encoder.Options{
HuffmanStrategy = HuffmanStrategy.Never,
});
// Decrease table size to avoid using indexing
// This will enforce a table size update which we need to compensate for
encoder.DynamicTableSize = 0;
var fields = new HeaderField[] {
new HeaderField{ Name = ":path", Value = "/sample/path", Sensitive = false }
};
// first item with name :path
var result = new Buffer();
result.AddHexString("20040c2f73616d706c652f70617468");
var res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(1, res.FieldCount);
Assert.Equal(0, encoder.DynamicTableUsedSize);
Assert.Equal(0, encoder.DynamicTableLength);
}
[Fact]
public void ShouldHandleExampleC2_3OfTheSpecificationCorrectly()
{
var encoder = new Encoder(new Encoder.Options{
HuffmanStrategy = HuffmanStrategy.Never,
});
var fields = new HeaderField[] {
new HeaderField{ Name = "password", Value = "secret", Sensitive = true }
};
var result = new Buffer();
result.AddHexString("100870617373776f726406736563726574");
var res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(1, res.FieldCount);
Assert.Equal(0, encoder.DynamicTableUsedSize);
Assert.Equal(0, encoder.DynamicTableLength);
}
[Fact]
public void ShouldHandleExampleC2_4OfTheSpecificationCorrectly()
{
var encoder = new Encoder(new Encoder.Options{
HuffmanStrategy = HuffmanStrategy.Never,
});
var fields = new HeaderField[] {
new HeaderField{ Name = ":method", Value = "GET", Sensitive = false }
};
var result = new Buffer();
result.AddHexString("82");
var res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(1, res.FieldCount);
Assert.Equal(0, encoder.DynamicTableUsedSize);
Assert.Equal(0, encoder.DynamicTableLength);
}
[Fact]
public void ShouldHandleExampleC3OfTheSpecificationCorrectly()
{
var encoder = new Encoder(new Encoder.Options{
HuffmanStrategy = HuffmanStrategy.Never,
});
var fields = new HeaderField[] {
new HeaderField{ Name = ":method", Value ="GET", Sensitive = false },
new HeaderField{ Name = ":scheme", Value ="http", Sensitive = false },
new HeaderField{ Name = ":path", Value ="/", Sensitive = false },
new HeaderField{ Name = ":authority", Value ="www.example.com", Sensitive = false },
};
// C.3.1
var result = new Buffer();
result.AddHexString("828684410f7777772e6578616d706c652e636f6d");
var res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(4, res.FieldCount);
Assert.Equal(57, encoder.DynamicTableUsedSize);
Assert.Equal(1, encoder.DynamicTableLength);
// C.3.2
fields = new HeaderField[] {
new HeaderField{ Name = ":method", Value ="GET", Sensitive = false },
new HeaderField{ Name = ":scheme", Value ="http", Sensitive = false },
new HeaderField{ Name = ":path", Value ="/", Sensitive = false },
new HeaderField{ Name = ":authority", Value ="www.example.com", Sensitive = false },
new HeaderField{ Name = "cache-control", Value ="no-cache", Sensitive = false },
};
result = new Buffer();
result.AddHexString("828684be58086e6f2d6361636865");
res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(5, res.FieldCount);
Assert.Equal(110, encoder.DynamicTableUsedSize);
Assert.Equal(2, encoder.DynamicTableLength);
// C.3.3
fields = new HeaderField[] {
new HeaderField{ Name = ":method", Value ="GET", Sensitive = false },
new HeaderField{ Name = ":scheme", Value ="https", Sensitive = false },
new HeaderField{ Name = ":path", Value ="/index.html", Sensitive = false },
new HeaderField{ Name = ":authority", Value ="www.example.com", Sensitive = false },
new HeaderField{ Name = "custom-key", Value ="custom-value", Sensitive = false },
};
result = new Buffer();
result.AddHexString("828785bf400a637573746f6d2d6b65790c637573746f6d2d76616c7565");
res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(5, res.FieldCount);
Assert.Equal(164, encoder.DynamicTableUsedSize);
Assert.Equal(3, encoder.DynamicTableLength);
}
[Fact]
public void ShouldHandleExampleC4OfTheSpecificationCorrectly()
{
var encoder = new Encoder(new Encoder.Options{
HuffmanStrategy = HuffmanStrategy.Always,
});
var fields = new HeaderField[] {
new HeaderField{ Name = ":method", Value ="GET", Sensitive = false },
new HeaderField{ Name = ":scheme", Value ="http", Sensitive = false },
new HeaderField{ Name = ":path", Value ="/", Sensitive = false },
new HeaderField{ Name = ":authority", Value ="www.example.com", Sensitive = false },
};
// C.4.1
var result = new Buffer();
result.AddHexString("828684418cf1e3c2e5f23a6ba0ab90f4ff");
var res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(4, res.FieldCount);
Assert.Equal(57, encoder.DynamicTableUsedSize);
Assert.Equal(1, encoder.DynamicTableLength);
// C.4.2
fields = new HeaderField[] {
new HeaderField{ Name = ":method", Value ="GET", Sensitive = false },
new HeaderField{ Name = ":scheme", Value ="http", Sensitive = false },
new HeaderField{ Name = ":path", Value ="/", Sensitive = false },
new HeaderField{ Name = ":authority", Value ="www.example.com", Sensitive = false },
new HeaderField{ Name = "cache-control", Value ="no-cache", Sensitive = false },
};
result = new Buffer();
result.AddHexString("828684be5886a8eb10649cbf");
res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(5, res.FieldCount);
Assert.Equal(110, encoder.DynamicTableUsedSize);
Assert.Equal(2, encoder.DynamicTableLength);
// C.4.3
fields = new HeaderField[] {
new HeaderField{ Name = ":method", Value ="GET", Sensitive = false },
new HeaderField{ Name = ":scheme", Value ="https", Sensitive = false },
new HeaderField{ Name = ":path", Value ="/index.html", Sensitive = false },
new HeaderField{ Name = ":authority", Value ="www.example.com", Sensitive = false },
new HeaderField{ Name = "custom-key", Value ="custom-value", Sensitive = false },
};
result = new Buffer();
result.AddHexString("828785bf408825a849e95ba97d7f8925a849e95bb8e8b4bf");
res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(5, res.FieldCount);
Assert.Equal(164, encoder.DynamicTableUsedSize);
Assert.Equal(3, encoder.DynamicTableLength);
}
[Fact]
public void ShouldHandleExampleC5OfTheSpecificationCorrectly()
{
var encoder = new Encoder(new Encoder.Options{
HuffmanStrategy = HuffmanStrategy.Never,
DynamicTableSize = 256,
});
var fields = new HeaderField[] {
new HeaderField{ Name = ":status", Value ="302", Sensitive = false },
new HeaderField{ Name = "cache-control", Value ="private", Sensitive = false },
new HeaderField{ Name = "date", Value ="Mon, 21 Oct 2013 20:13:21 GMT", Sensitive = false },
new HeaderField{ Name = "location", Value ="https://www.example.com", Sensitive = false },
};
// C.5.1
var result = new Buffer();
result.AddHexString(
"4803333032580770726976617465611d" +
"4d6f6e2c203231204f63742032303133" +
"2032303a31333a323120474d546e1768" +
"747470733a2f2f7777772e6578616d70" +
"6c652e636f6d");
var res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(4, res.FieldCount);
Assert.Equal(222, encoder.DynamicTableUsedSize);
Assert.Equal(4, encoder.DynamicTableLength);
// C.5.2
fields = new HeaderField[] {
new HeaderField{ Name = ":status", Value ="307", Sensitive = false },
new HeaderField{ Name = "cache-control", Value ="private", Sensitive = false },
new HeaderField{ Name = "date", Value ="Mon, 21 Oct 2013 20:13:21 GMT", Sensitive = false },
new HeaderField{ Name = "location", Value ="https://www.example.com", Sensitive = false },
};
result = new Buffer();
result.AddHexString("4803333037c1c0bf");
res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(4, res.FieldCount);
Assert.Equal(222, encoder.DynamicTableUsedSize);
Assert.Equal(4, encoder.DynamicTableLength);
// C.5.3
fields = new HeaderField[] {
new HeaderField{ Name = ":status", Value ="200", Sensitive = false },
new HeaderField{ Name = "cache-control", Value ="private", Sensitive = false },
new HeaderField{ Name = "date", Value ="Mon, 21 Oct 2013 20:13:22 GMT", Sensitive = false },
new HeaderField{ Name = "location", Value ="https://www.example.com", Sensitive = false },
new HeaderField{ Name = "content-encoding", Value ="gzip", Sensitive = false },
new HeaderField{ Name = "set-cookie", Value ="foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", Sensitive = false },
};
result = new Buffer();
result.AddHexString(
"88c1611d4d6f6e2c203231204f637420" +
"323031332032303a31333a323220474d" +
"54c05a04677a69707738666f6f3d4153" +
"444a4b48514b425a584f5157454f5049" +
"5541585157454f49553b206d61782d61" +
"67653d333630303b2076657273696f6e" +
"3d31");
res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(6, res.FieldCount);
Assert.Equal(215, encoder.DynamicTableUsedSize);
Assert.Equal(3, encoder.DynamicTableLength);
}
[Fact]
public void ShouldHandleExampleC6OfTheSpecificationCorrectly()
{
var encoder = new Encoder(new Encoder.Options{
HuffmanStrategy = HuffmanStrategy.Always,
DynamicTableSize = 256,
});
var fields = new HeaderField[] {
new HeaderField{ Name = ":status", Value ="302", Sensitive = false },
new HeaderField{ Name = "cache-control", Value ="private", Sensitive = false },
new HeaderField{ Name = "date", Value ="Mon, 21 Oct 2013 20:13:21 GMT", Sensitive = false },
new HeaderField{ Name = "location", Value ="https://www.example.com", Sensitive = false },
};
// C.6.1
var result = new Buffer();
result.AddHexString(
"488264025885aec3771a4b6196d07abe" +
"941054d444a8200595040b8166e082a6" +
"2d1bff6e919d29ad171863c78f0b97c8" +
"e9ae82ae43d3");
var res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(4, res.FieldCount);
Assert.Equal(222, encoder.DynamicTableUsedSize);
Assert.Equal(4, encoder.DynamicTableLength);
// C.6.2
fields = new HeaderField[] {
new HeaderField{ Name = ":status", Value ="307", Sensitive = false },
new HeaderField{ Name = "cache-control", Value ="private", Sensitive = false },
new HeaderField{ Name = "date", Value ="Mon, 21 Oct 2013 20:13:21 GMT", Sensitive = false },
new HeaderField{ Name = "location", Value ="https://www.example.com", Sensitive = false },
};
result = new Buffer();
result.AddHexString("4883640effc1c0bf");
res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(4, res.FieldCount);
Assert.Equal(222, encoder.DynamicTableUsedSize);
Assert.Equal(4, encoder.DynamicTableLength);
// C.6.3
fields = new HeaderField[] {
new HeaderField{ Name = ":status", Value ="200", Sensitive = false },
new HeaderField{ Name = "cache-control", Value ="private", Sensitive = false },
new HeaderField{ Name = "date", Value ="Mon, 21 Oct 2013 20:13:22 GMT", Sensitive = false },
new HeaderField{ Name = "location", Value ="https://www.example.com", Sensitive = false },
new HeaderField{ Name = "content-encoding", Value ="gzip", Sensitive = false },
new HeaderField{ Name = "set-cookie", Value ="foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", Sensitive = false },
};
result = new Buffer();
result.AddHexString(
"88c16196d07abe941054d444a8200595" +
"040b8166e084a62d1bffc05a839bd9ab" +
"77ad94e7821dd7f2e6c7b335dfdfcd5b" +
"3960d5af27087f3672c1ab270fb5291f" +
"9587316065c003ed4ee5b1063d5007");
res = EncodeToTempBuf(encoder, fields, MaxFrameSize);
Assert.Equal(result.Bytes, res.Bytes);
Assert.Equal(6, res.FieldCount);
Assert.Equal(215, encoder.DynamicTableUsedSize);
Assert.Equal(3, encoder.DynamicTableLength);
}
// TODO: Add tests to verify that the encoder stops encoding when data
// doesn't fit into a heaer block
// Ideally check at various positions, since the out-of-memory-problem
// can happen anywhere.
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void RoundToPositiveInfinityScalarSingle()
{
var test = new SimpleBinaryOpTest__RoundToPositiveInfinityScalarSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__RoundToPositiveInfinityScalarSingle
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Single);
private const int Op2ElementCount = VectorSize / sizeof(Single);
private const int RetElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static SimpleBinaryOpTest__RoundToPositiveInfinityScalarSingle()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__RoundToPositiveInfinityScalarSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.RoundToPositiveInfinityScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.RoundToPositiveInfinityScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.RoundToPositiveInfinityScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToPositiveInfinityScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToPositiveInfinityScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToPositiveInfinityScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.RoundToPositiveInfinityScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse41.RoundToPositiveInfinityScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.RoundToPositiveInfinityScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.RoundToPositiveInfinityScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__RoundToPositiveInfinityScalarSingle();
var result = Sse41.RoundToPositiveInfinityScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.RoundToPositiveInfinityScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Ceiling(right[0])))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.RoundToPositiveInfinityScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows.Media;
using Antlr4.Runtime;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using VisualRust.Project;
namespace VisualRust
{
[Export(typeof(ICompletionSourceProvider))]
[ContentType("rust")]
[Name("rustCompletion")]
internal class RustCompletionSourceProvider : ICompletionSourceProvider
{
[Import]
internal ITextStructureNavigatorSelectorService NavigatorService { get; set; }
[Import]
internal IGlyphService GlyphService { get; set; }
public ICompletionSource TryCreateCompletionSource(ITextBuffer textBuffer)
{
return new RustCompletionSource(textBuffer, GlyphService);
}
}
internal class RustCompletionSource : ICompletionSource
{
// These are returned by racer in the fifths column of a complete call.
private enum CompletableLanguageElement
{
Struct,
Module,
Function,
Crate,
Let,
StructField,
Impl,
Enum,
EnumVariant,
Type,
FnArg,
Trait,
Static,
}
private readonly IGlyphService glyphService;
private readonly ITextBuffer buffer;
private bool disposed;
private readonly IEnumerable<Completion> keywordCompletions = GetKeywordCompletions();
/// <summary>
/// Get completions list filtered by prefix
/// </summary>
/// <param name="prefix">
/// String with prefix before caret in source code
/// </param>
/// <returns>
/// List completions
/// </returns>
private static IEnumerable<Completion> GetKeywordCompletions(string prefix = null)
{
var keywords = Utils.Keywords;
var resultKeywords = string.IsNullOrEmpty(prefix) ? keywords : keywords.Where(x => x.StartsWith(prefix));
var completions = resultKeywords.Select(k => new Completion(k, k + " ", "", null, ""));
return completions;
}
public RustCompletionSource(ITextBuffer buffer, IGlyphService glyphService)
{
this.buffer = buffer;
this.glyphService = glyphService;
}
private ImageSource GetCompletionIcon(CompletableLanguageElement elType)
{
switch (elType)
{
case CompletableLanguageElement.Struct:
return glyphService.GetGlyph(StandardGlyphGroup.GlyphGroupStruct, StandardGlyphItem.GlyphItemPublic);
case CompletableLanguageElement.Module:
return glyphService.GetGlyph(StandardGlyphGroup.GlyphAssembly, StandardGlyphItem.GlyphItemPublic);
case CompletableLanguageElement.Function:
return glyphService.GetGlyph(StandardGlyphGroup.GlyphExtensionMethod,
StandardGlyphItem.GlyphItemPublic);
case CompletableLanguageElement.Crate:
return glyphService.GetGlyph(StandardGlyphGroup.GlyphAssembly, StandardGlyphItem.GlyphItemPublic);
case CompletableLanguageElement.Let:
return glyphService.GetGlyph(StandardGlyphGroup.GlyphGroupConstant,
StandardGlyphItem.GlyphItemPublic);
case CompletableLanguageElement.StructField:
return glyphService.GetGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPublic);
case CompletableLanguageElement.Impl:
return glyphService.GetGlyph(StandardGlyphGroup.GlyphGroupTypedef, StandardGlyphItem.GlyphItemPublic);
case CompletableLanguageElement.Enum:
return glyphService.GetGlyph(StandardGlyphGroup.GlyphGroupEnum, StandardGlyphItem.GlyphItemPublic);
case CompletableLanguageElement.EnumVariant:
return glyphService.GetGlyph(StandardGlyphGroup.GlyphGroupEnumMember,
StandardGlyphItem.GlyphItemPublic);
case CompletableLanguageElement.Type:
return glyphService.GetGlyph(StandardGlyphGroup.GlyphGroupTypedef, StandardGlyphItem.GlyphItemPublic);
case CompletableLanguageElement.Trait:
return glyphService.GetGlyph(StandardGlyphGroup.GlyphGroupInterface,
StandardGlyphItem.GlyphItemPublic);
case CompletableLanguageElement.Static:
return null;
case CompletableLanguageElement.FnArg:
return null;
default:
ProjectUtil.DebugPrintToOutput("Unhandled language element found in racer autocomplete response: {0}", elType);
return null;
}
}
/// <summary>
/// Fetches auto complete suggestions and appends to the completion sets of the current completion session.
/// </summary>
/// <param name="session">The active completion session, initiated from the completion command handler.</param>
/// <param name="completionSets">A list of completion sets that may be augmented by this source.</param>
public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
{
if (disposed)
throw new ObjectDisposedException(GetType().Name);
ITextSnapshot snapshot = buffer.CurrentSnapshot;
SnapshotPoint? sp = session.GetTriggerPoint(snapshot);
if (!sp.HasValue)
return;
var triggerPoint = sp.Value;
var line = triggerPoint.GetContainingLine();
int col = triggerPoint.Position - line.Start.Position;
if (line.GetText() == "" || col == 0 || char.IsWhiteSpace(line.GetText()[col - 1]))
{
// On empty rows or without a prefix, return only completions for rust keywords.
var location = snapshot.CreateTrackingSpan(col + line.Start.Position, 0, SpanTrackingMode.EdgeInclusive);
completionSets.Add(new RustCompletionSet("All", "All", location, keywordCompletions, null));
return;
}
// Get token under cursor.
var activeToken = GetActiveToken(col, line);
if (activeToken == null)
return;
RustTokenTypes tokenType = Utils.LexerTokenToRustToken(activeToken.Text, activeToken.Type);
// Establish the extents of the current token left of the cursor.
var extent = new TextExtent(
new SnapshotSpan(
new SnapshotPoint(snapshot, activeToken.StartIndex + line.Start.Position),
triggerPoint),
tokenType != RustTokenTypes.WHITESPACE);
var span = snapshot.CreateTrackingSpan(extent.Span, SpanTrackingMode.EdgeInclusive);
// Fetch racer completions & return in a completion set.
string prefix;
var completions = GetCompletions(RunRacer(snapshot, triggerPoint), out prefix).ToList();
completions.AddRange(GetKeywordCompletions(prefix));
completionSets.Add(new RustCompletionSet("All", "All", span, completions, null));
}
private static IToken GetActiveToken(int columnIndex, ITextSnapshotLine line)
{
var tokens = Utils.LexString(line.GetText());
if (columnIndex == line.Length)
{
var lastToken = tokens.Last();
if (lastToken.Type == RustLexer.RustLexer.IDENT)
return lastToken;
// fake token for an ident not yet started at the end of the line.
return new CommonToken(new Tuple<ITokenSource, ICharStream>(lastToken.TokenSource, lastToken.TokenSource.InputStream),
RustLexer.RustLexer.IDENT, 0, columnIndex, columnIndex);
}
IToken token = null;
IToken previousToken = null;
foreach (var currentToken in tokens)
{
if (currentToken.StartIndex <= columnIndex && columnIndex <= currentToken.StopIndex)
{
token = currentToken;
break;
}
previousToken = currentToken;
}
if (token == null)
{
return null;
}
if (token.Type == RustLexer.RustLexer.IDENT)
{
return token;
}
// if current token isn't identifier and caret at end of ident token
if (token.StartIndex == columnIndex && previousToken != null && previousToken.Type == RustLexer.RustLexer.IDENT)
{
return previousToken;
}
// fake token for position between 2 non-ident tokens
return new CommonToken(new Tuple<ITokenSource, ICharStream>(token.TokenSource, token.TokenSource.InputStream), 1, 0, token.StartIndex, token.StartIndex - 1);
}
private static int GetColumn(SnapshotPoint point)
{
var line = point.GetContainingLine();
int col = point.Position - line.Start.Position;
return col;
}
private static string RunRacer(ITextSnapshot snapshot, SnapshotPoint point)
{
using (var tmpFile = new TemporaryFile(snapshot.GetText()))
{
// Build racer command line: "racer.exe complete lineNo columnNo rustfile
int lineNumber = point.GetContainingLine().LineNumber;
int charNumber = GetColumn(point);
string args = string.Format("complete {0} {1} {2}", lineNumber + 1, charNumber, tmpFile.Path);
return Racer.AutoCompleter.Run(args);
}
}
// Parses racer output into completions.
private IEnumerable<Completion> GetCompletions(string racerResponse, out string prefix)
{
// Completions from racer.
var lines = racerResponse.Split(new[] { '\n' }, StringSplitOptions.None);
prefix = GetPrefix(lines[0]);
return GetCompletions(lines);
}
private IEnumerable<Completion> GetCompletions(string[] lines)
{
var matches = lines.Where(l => l.StartsWith("MATCH")).Distinct(StringComparer.Ordinal);
foreach (var matchLine in matches)
{
var tokens = matchLine.Substring(6).Split(',');
var text = tokens[0];
var langElemText = tokens[4];
var descriptionStartIndex = tokens[0].Length + tokens[1].Length + tokens[2].Length + tokens[3].Length + tokens[4].Length + 11;
var description = matchLine.Substring(descriptionStartIndex);
CompletableLanguageElement elType;
if (!Enum.TryParse(langElemText, out elType))
{
ProjectUtil.DebugPrintToOutput("Failed to parse language element found in racer autocomplete response: {0}", langElemText);
continue;
}
var insertionText = text;
var icon = GetCompletionIcon(elType);
yield return new Completion(text, insertionText, description, icon, "");
}
}
private string GetPrefix(string line)
{
var tokens = line.Split(',');
if(tokens.Length != 3)
return null;
var prefix = tokens[2];
return prefix;
}
public void Dispose()
{
if (!disposed)
{
GC.SuppressFinalize(this);
disposed = true;
}
}
}
internal class RustCompletionSet : CompletionSet
{
public RustCompletionSet(string moniker, string name, ITrackingSpan applicableTo,
IEnumerable<Completion> completions, IEnumerable<Completion> completionBuilders)
: base(moniker, name, applicableTo, completions, completionBuilders)
{
}
public override void Filter()
{
Filter(CompletionMatchType.MatchInsertionText, true);
}
}
}
| |
/*
* IsolatedStorageFileStream.cs - Implementation of the
* "System.IO.IsolatedStorage.IsolatedStorageFileStream" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.IO.IsolatedStorage
{
#if CONFIG_ISOLATED_STORAGE
using System.IO;
using System.Security.Permissions;
public class IsolatedStorageFileStream : FileStream
{
// Internal state.
private FileStream realStream;
private IsolatedStorageFile storeToClose;
// Constructors.
public IsolatedStorageFileStream(String path, FileMode mode)
: this(path, mode, (mode == FileMode.Append
? FileAccess.Write
: FileAccess.ReadWrite),
FileShare.None, BUFSIZ, null)
{
// Nothing to do here.
}
public IsolatedStorageFileStream(String path, FileMode mode,
IsolatedStorageFile sf)
: this(path, mode, (mode == FileMode.Append
? FileAccess.Write
: FileAccess.ReadWrite),
FileShare.None, BUFSIZ, sf)
{
// Nothing to do here.
}
public IsolatedStorageFileStream(String path, FileMode mode,
FileAccess access)
: this(path, mode, access, FileShare.None, BUFSIZ, null)
{
// Nothing to do here.
}
public IsolatedStorageFileStream(String path, FileMode mode,
FileAccess access,
IsolatedStorageFile sf)
: this(path, mode, access, FileShare.None, BUFSIZ, sf)
{
// Nothing to do here.
}
public IsolatedStorageFileStream(String path, FileMode mode,
FileAccess access, FileShare share)
: this(path, mode, access, share, BUFSIZ, null)
{
// Nothing to do here.
}
public IsolatedStorageFileStream(String path, FileMode mode,
FileAccess access, FileShare share,
IsolatedStorageFile sf)
: this(path, mode, access, share, BUFSIZ, sf)
{
// Nothing to do here.
}
public IsolatedStorageFileStream(String path, FileMode mode,
FileAccess access, FileShare share,
int bufferSize)
: this(path, mode, access, share, bufferSize, null)
{
// Nothing to do here.
}
public IsolatedStorageFileStream(String path, FileMode mode,
FileAccess access, FileShare share,
int bufferSize,
IsolatedStorageFile sf)
: base(path)
{
// Validate the parameters.
if(path == null)
{
throw new ArgumentNullException("path");
}
if(sf == null)
{
sf = IsolatedStorageFile.GetUserStoreForDomain();
storeToClose = sf;
}
// Get the base directory for the isolated storage area.
String baseDir = sf.BaseDirectory;
#if CONFIG_PERMISSIONS
// Assert that we have permission to do this.
(new FileIOPermission
(FileIOPermissionAccess.AllAccess, baseDir)).Assert();
#endif
// Open the real stream.
realStream = new FileStream
(baseDir + Path.DirectorySeparatorChar + path,
mode, access, share, bufferSize, false);
}
// Properties.
public override bool CanRead
{
get
{
return realStream.CanRead;
}
}
public override bool CanSeek
{
get
{
return realStream.CanSeek;
}
}
public override bool CanWrite
{
get
{
return realStream.CanWrite;
}
}
public override IntPtr Handle
{
get
{
// Cannot get isolated storage file handles.
throw new IsolatedStorageException
(_("Exception_IsolatedStorage"));
}
}
public override bool IsAsync
{
get
{
return realStream.IsAsync;
}
}
public override long Length
{
get
{
return realStream.Length;
}
}
public override long Position
{
get
{
return realStream.Position;
}
set
{
realStream.Position = value;
}
}
// Begin an asynchronous read operation.
public override IAsyncResult BeginRead
(byte[] buffer, int offset, int numBytes,
AsyncCallback userCallback, Object stateObject)
{
return realStream.BeginRead
(buffer, offset, numBytes, userCallback, stateObject);
}
// Begin an asynchronous write operation.
public override IAsyncResult BeginWrite
(byte[] buffer, int offset, int numBytes,
AsyncCallback userCallback, Object stateObject)
{
return realStream.BeginWrite
(buffer, offset, numBytes, userCallback, stateObject);
}
// Close this stream.
public override void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Dispose of this stream.
protected override void Dispose(bool disposing)
{
realStream.Close();
if(storeToClose != null)
{
storeToClose.Close();
}
base.Dispose(disposing);
}
// End an asynchronous read operation.
public override int EndRead(IAsyncResult asyncResult)
{
return realStream.EndRead(asyncResult);
}
// End an asynchronous write operation
public override void EndWrite(IAsyncResult asyncResult)
{
realStream.EndWrite(asyncResult);
}
// Flush this stream.
public override void Flush()
{
realStream.Flush();
}
// Read from this stream.
public override int Read(byte[] buffer, int offset, int count)
{
return realStream.Read(buffer, offset, count);
}
// Read a byte from this stream.
public override int ReadByte()
{
return realStream.ReadByte();
}
// Seek within this stream.
public override long Seek(long offset, SeekOrigin origin)
{
return realStream.Seek(offset, origin);
}
// Set the length of this stream.
public override void SetLength(long value)
{
realStream.SetLength(value);
}
// Write to this stream.
public override void Write(byte[] buffer, int offset, int count)
{
realStream.Write(buffer, offset, count);
}
// Write a byte to this stream.
public override void WriteByte(byte value)
{
realStream.WriteByte(value);
}
}; // class IsolatedStorageFileStream
#endif // CONFIG_ISOLATED_STORAGE
}; // namespace System.IO.IsolatedStorage
| |
// 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 partial 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 static readonly 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))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16928")] //Test hang forever in desktop.
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))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16928")] //Test hang forever in desktop.
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))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16928")] //Test hang forever in desktop.
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))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16928")] //Test hang forever in desktop.
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))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16928")] //Test hang forever in desktop.
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))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16928")] //Test hang forever in desktop.
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))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16928")] //Test hang forever in desktop.
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));
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotFedoraOrRedHatOrCentos))] // #16201
[MemberData(nameof(EchoServers))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16928")] //Test hang forever in desktop.
public async Task GetResponseAsync_UseDefaultCredentials_ExpectSuccess(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UseDefaultCredentials = true;
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))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16928")] //Test hang forever in desktop.
public async Task HaveResponse_GetResponseAsync_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebResponse response = await request.GetResponseAsync();
Assert.True(request.HaveResponse);
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotFedoraOrRedHatOrCentos))] // #16201
[MemberData(nameof(EchoServers))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16928")] //Test hang forever in desktop.
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))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16928")] //Test hang forever in desktop.
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.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
namespace System.IO
{
public sealed partial class DirectoryInfo : FileSystemInfo
{
[System.Security.SecuritySafeCritical]
public DirectoryInfo(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
OriginalPath = PathHelpers.ShouldReviseDirectoryPathToCurrent(path) ? "." : path;
FullPath = Path.GetFullPath(path);
DisplayPath = GetDisplayName(OriginalPath);
}
[System.Security.SecuritySafeCritical]
internal DirectoryInfo(String fullPath, String originalPath)
{
Debug.Assert(Path.IsPathRooted(fullPath), "fullPath must be fully qualified!");
// Fast path when we know a DirectoryInfo exists.
OriginalPath = originalPath ?? Path.GetFileName(fullPath);
FullPath = fullPath;
DisplayPath = GetDisplayName(OriginalPath);
}
public override String Name
{
get
{
return GetDirName(FullPath);
}
}
public DirectoryInfo Parent
{
[System.Security.SecuritySafeCritical]
get
{
string s = FullPath;
// FullPath might end in either "parent\child" or "parent\child", and in either case we want
// the parent of child, not the child. Trim off an ending directory separator if there is one,
// but don't mangle the root.
if (!PathHelpers.IsRoot(s))
{
s = PathHelpers.TrimEndingDirectorySeparator(s);
}
string parentName = Path.GetDirectoryName(s);
return parentName != null ?
new DirectoryInfo(parentName, null) :
null;
}
}
[System.Security.SecuritySafeCritical]
public DirectoryInfo CreateSubdirectory(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
return CreateSubdirectoryHelper(path);
}
[System.Security.SecurityCritical] // auto-generated
private DirectoryInfo CreateSubdirectoryHelper(String path)
{
Contract.Requires(path != null);
PathHelpers.ThrowIfEmptyOrRootedPath(path);
String newDirs = Path.Combine(FullPath, path);
String fullPath = Path.GetFullPath(newDirs);
if (0 != String.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.StringComparison))
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath), nameof(path));
}
FileSystem.Current.CreateDirectory(fullPath);
// Check for read permission to directory we hand back by calling this constructor.
return new DirectoryInfo(fullPath);
}
[System.Security.SecurityCritical]
public void Create()
{
FileSystem.Current.CreateDirectory(FullPath);
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
public override bool Exists
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
try
{
return FileSystemObject.Exists;
}
catch
{
return false;
}
}
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
[SecurityCritical]
public FileInfo[] GetFiles(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public FileInfo[] GetFiles(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetFiles(searchPattern, searchOption);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
private FileInfo[] InternalGetFiles(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileInfo> enumerable = (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files);
return EnumerableHelpers.ToArray(enumerable);
}
// Returns an array of Files in the DirectoryInfo specified by path
public FileInfo[] GetFiles()
{
return InternalGetFiles("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current directory.
public DirectoryInfo[] GetDirectories()
{
return InternalGetDirectories("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt").
public FileSystemInfo[] GetFileSystemInfos(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt").
public FileSystemInfo[] GetFileSystemInfos(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetFileSystemInfos(searchPattern, searchOption);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt").
private FileSystemInfo[] InternalGetFileSystemInfos(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileSystemInfo> enumerable = FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both);
return EnumerableHelpers.ToArray(enumerable);
}
// Returns an array of strongly typed FileSystemInfo entries which will contain a listing
// of all the files and directories.
public FileSystemInfo[] GetFileSystemInfos()
{
return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "System*" could match the System & System32
// directories).
public DirectoryInfo[] GetDirectories(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "System*" could match the System & System32
// directories).
public DirectoryInfo[] GetDirectories(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetDirectories(searchPattern, searchOption);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "System*" could match the System & System32
// directories).
private DirectoryInfo[] InternalGetDirectories(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories);
return EnumerableHelpers.ToArray(enumerable);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories()
{
return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateDirectories(searchPattern, searchOption);
}
private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories);
}
public IEnumerable<FileInfo> EnumerateFiles()
{
return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileInfo> EnumerateFiles(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileInfo> EnumerateFiles(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateFiles(searchPattern, searchOption);
}
private IEnumerable<FileInfo> InternalEnumerateFiles(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos()
{
return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateFileSystemInfos(searchPattern, searchOption);
}
private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both);
}
// Returns the root portion of the given path. The resulting string
// consists of those rightmost characters of the path that constitute the
// root of the path. Possible patterns for the resulting string are: An
// empty string (a relative path on the current drive), "\" (an absolute
// path on the current drive), "X:" (a relative path on a given drive,
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
// The resulting string is null if path is null.
//
public DirectoryInfo Root
{
[System.Security.SecuritySafeCritical]
get
{
String rootPath = Path.GetPathRoot(FullPath);
return new DirectoryInfo(rootPath);
}
}
[System.Security.SecuritySafeCritical]
public void MoveTo(String destDirName)
{
if (destDirName == null)
throw new ArgumentNullException(nameof(destDirName));
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName));
Contract.EndContractBlock();
String fullDestDirName = Path.GetFullPath(destDirName);
if (fullDestDirName[fullDestDirName.Length - 1] != Path.DirectorySeparatorChar)
fullDestDirName = fullDestDirName + PathHelpers.DirectorySeparatorCharAsString;
String fullSourcePath;
if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar)
fullSourcePath = FullPath;
else
fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString;
if (PathInternal.IsDirectoryTooLong(fullSourcePath))
throw new PathTooLongException(SR.IO_PathTooLong);
if (PathInternal.IsDirectoryTooLong(fullDestDirName))
throw new PathTooLongException(SR.IO_PathTooLong);
StringComparison pathComparison = PathInternal.StringComparison;
if (String.Equals(fullSourcePath, fullDestDirName, pathComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
String sourceRoot = Path.GetPathRoot(fullSourcePath);
String destinationRoot = Path.GetPathRoot(fullDestDirName);
if (!String.Equals(sourceRoot, destinationRoot, pathComparison))
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
FileSystem.Current.MoveDirectory(FullPath, fullDestDirName);
FullPath = fullDestDirName;
OriginalPath = destDirName;
DisplayPath = GetDisplayName(OriginalPath);
// Flush any cached information about the directory.
Invalidate();
}
[System.Security.SecuritySafeCritical]
public override void Delete()
{
FileSystem.Current.RemoveDirectory(FullPath, false);
}
[System.Security.SecuritySafeCritical]
public void Delete(bool recursive)
{
FileSystem.Current.RemoveDirectory(FullPath, recursive);
}
/// <summary>
/// Returns the original path. Use FullPath or Name properties for the path / directory name.
/// </summary>
public override String ToString()
{
return DisplayPath;
}
private static String GetDisplayName(String originalPath)
{
Debug.Assert(originalPath != null);
// Desktop documents that the path returned by ToString() should be the original path.
// For SL/Phone we only gave the directory name regardless of what was passed in.
return PathHelpers.ShouldReviseDirectoryPathToCurrent(originalPath) ?
"." :
originalPath;
}
private static String GetDirName(String fullPath)
{
Debug.Assert(fullPath != null);
return PathHelpers.IsRoot(fullPath) ?
fullPath :
Path.GetFileName(PathHelpers.TrimEndingDirectorySeparator(fullPath));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions;
using Microsoft.Build.Framework;
using Mono.Cecil;
using Avalonia.Utilities;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using XamlX;
using XamlX.Ast;
using XamlX.Parsers;
using XamlX.Transform;
using XamlX.TypeSystem;
using FieldAttributes = Mono.Cecil.FieldAttributes;
using MethodAttributes = Mono.Cecil.MethodAttributes;
using TypeAttributes = Mono.Cecil.TypeAttributes;
using XamlX.IL;
namespace Avalonia.Build.Tasks
{
public static partial class XamlCompilerTaskExecutor
{
static bool CheckXamlName(IResource r) => r.Name.ToLowerInvariant().EndsWith(".xaml")
|| r.Name.ToLowerInvariant().EndsWith(".paml")
|| r.Name.ToLowerInvariant().EndsWith(".axaml");
public class CompileResult
{
public bool Success { get; set; }
public bool WrittenFile { get; }
public CompileResult(bool success, bool writtenFile = false)
{
Success = success;
WrittenFile = writtenFile;
}
}
public static CompileResult Compile(IBuildEngine engine, string input, string[] references,
string projectDirectory,
string output, bool verifyIl, MessageImportance logImportance, string strongNameKey, bool patchCom,
bool skipXamlCompilation)
{
var typeSystem = new CecilTypeSystem(references
.Where(r => !r.ToLowerInvariant().EndsWith("avalonia.build.tasks.dll"))
.Concat(new[] { input }), input);
var asm = typeSystem.TargetAssemblyDefinition;
if (!skipXamlCompilation)
{
var compileRes = CompileCore(engine, typeSystem, projectDirectory, verifyIl, logImportance);
if (compileRes == null && !patchCom)
return new CompileResult(true);
if (compileRes == false)
return new CompileResult(false);
}
if (patchCom)
ComInteropHelper.PatchAssembly(asm, typeSystem);
var writerParameters = new WriterParameters { WriteSymbols = asm.MainModule.HasSymbols };
if (!string.IsNullOrWhiteSpace(strongNameKey))
writerParameters.StrongNameKeyBlob = File.ReadAllBytes(strongNameKey);
asm.Write(output, writerParameters);
return new CompileResult(true, true);
}
static bool? CompileCore(IBuildEngine engine, CecilTypeSystem typeSystem,
string projectDirectory, bool verifyIl,
MessageImportance logImportance)
{
var asm = typeSystem.TargetAssemblyDefinition;
var emres = new EmbeddedResources(asm);
var avares = new AvaloniaResources(asm, projectDirectory);
if (avares.Resources.Count(CheckXamlName) == 0 && emres.Resources.Count(CheckXamlName) == 0)
// Nothing to do
return null;
var clrPropertiesDef = new TypeDefinition("CompiledAvaloniaXaml", "XamlIlHelpers",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
asm.MainModule.Types.Add(clrPropertiesDef);
var indexerAccessorClosure = new TypeDefinition("CompiledAvaloniaXaml", "!IndexerAccessorFactoryClosure",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
asm.MainModule.Types.Add(indexerAccessorClosure);
var (xamlLanguage , emitConfig) = AvaloniaXamlIlLanguage.Configure(typeSystem);
var compilerConfig = new AvaloniaXamlIlCompilerConfiguration(typeSystem,
typeSystem.TargetAssembly,
xamlLanguage,
XamlXmlnsMappings.Resolve(typeSystem, xamlLanguage),
AvaloniaXamlIlLanguage.CustomValueConverter,
new XamlIlClrPropertyInfoEmitter(typeSystem.CreateTypeBuilder(clrPropertiesDef)),
new XamlIlPropertyInfoAccessorFactoryEmitter(typeSystem.CreateTypeBuilder(indexerAccessorClosure)),
new DeterministicIdGenerator());
var contextDef = new TypeDefinition("CompiledAvaloniaXaml", "XamlIlContext",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
asm.MainModule.Types.Add(contextDef);
var contextClass = XamlILContextDefinition.GenerateContextClass(typeSystem.CreateTypeBuilder(contextDef), typeSystem,
xamlLanguage, emitConfig);
var compiler = new AvaloniaXamlIlCompiler(compilerConfig, emitConfig, contextClass) { EnableIlVerification = verifyIl };
var editorBrowsableAttribute = typeSystem
.GetTypeReference(typeSystem.FindType("System.ComponentModel.EditorBrowsableAttribute"))
.Resolve();
var editorBrowsableCtor =
asm.MainModule.ImportReference(editorBrowsableAttribute.GetConstructors()
.First(c => c.Parameters.Count == 1));
var runtimeHelpers = typeSystem.GetType("Avalonia.Markup.Xaml.XamlIl.Runtime.XamlIlRuntimeHelpers");
var createRootServiceProviderMethod = asm.MainModule.ImportReference(
typeSystem.GetTypeReference(runtimeHelpers).Resolve().Methods
.First(x => x.Name == "CreateRootServiceProviderV2"));
var loaderDispatcherDef = new TypeDefinition("CompiledAvaloniaXaml", "!XamlLoader",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
loaderDispatcherDef.CustomAttributes.Add(new CustomAttribute(editorBrowsableCtor)
{
ConstructorArguments = {new CustomAttributeArgument(editorBrowsableCtor.Parameters[0].ParameterType, 1)}
});
var loaderDispatcherMethod = new MethodDefinition("TryLoad",
MethodAttributes.Static | MethodAttributes.Public,
asm.MainModule.TypeSystem.Object)
{
Parameters = {new ParameterDefinition(asm.MainModule.TypeSystem.String)}
};
loaderDispatcherDef.Methods.Add(loaderDispatcherMethod);
asm.MainModule.Types.Add(loaderDispatcherDef);
var stringEquals = asm.MainModule.ImportReference(asm.MainModule.TypeSystem.String.Resolve().Methods.First(
m =>
m.IsStatic && m.Name == "Equals" && m.Parameters.Count == 2 &&
m.ReturnType.FullName == "System.Boolean"
&& m.Parameters[0].ParameterType.FullName == "System.String"
&& m.Parameters[1].ParameterType.FullName == "System.String"));
bool CompileGroup(IResourceGroup group)
{
var typeDef = new TypeDefinition("CompiledAvaloniaXaml", "!"+ group.Name,
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
typeDef.CustomAttributes.Add(new CustomAttribute(editorBrowsableCtor)
{
ConstructorArguments = {new CustomAttributeArgument(editorBrowsableCtor.Parameters[0].ParameterType, 1)}
});
asm.MainModule.Types.Add(typeDef);
var builder = typeSystem.CreateTypeBuilder(typeDef);
foreach (var res in group.Resources.Where(CheckXamlName).OrderBy(x=>x.FilePath.ToLowerInvariant()))
{
try
{
engine.LogMessage($"XAMLIL: {res.Name} -> {res.Uri}", logImportance);
// StreamReader is needed here to handle BOM
var xaml = new StreamReader(new MemoryStream(res.FileContents)).ReadToEnd();
var parsed = XDocumentXamlParser.Parse(xaml);
var initialRoot = (XamlAstObjectNode)parsed.Root;
var precompileDirective = initialRoot.Children.OfType<XamlAstXmlDirective>()
.FirstOrDefault(d => d.Namespace == XamlNamespaces.Xaml2006 && d.Name == "Precompile");
if (precompileDirective != null)
{
var precompileText = (precompileDirective.Values[0] as XamlAstTextNode)?.Text.Trim()
.ToLowerInvariant();
if (precompileText == "false")
continue;
if (precompileText != "true")
throw new XamlParseException("Invalid value for x:Precompile", precompileDirective);
}
var classDirective = initialRoot.Children.OfType<XamlAstXmlDirective>()
.FirstOrDefault(d => d.Namespace == XamlNamespaces.Xaml2006 && d.Name == "Class");
IXamlType classType = null;
if (classDirective != null)
{
if (classDirective.Values.Count != 1 || !(classDirective.Values[0] is XamlAstTextNode tn))
throw new XamlParseException("x:Class should have a string value", classDirective);
classType = typeSystem.TargetAssembly.FindType(tn.Text);
if (classType == null)
throw new XamlParseException($"Unable to find type `{tn.Text}`", classDirective);
compiler.OverrideRootType(parsed,
new XamlAstClrTypeReference(classDirective, classType, false));
initialRoot.Children.Remove(classDirective);
}
compiler.Transform(parsed);
var populateName = classType == null ? "Populate:" + res.Name : "!XamlIlPopulate";
var buildName = classType == null ? "Build:" + res.Name : null;
var classTypeDefinition =
classType == null ? null : typeSystem.GetTypeReference(classType).Resolve();
var populateBuilder = classTypeDefinition == null ?
builder :
typeSystem.CreateTypeBuilder(classTypeDefinition);
compiler.Compile(parsed, contextClass,
compiler.DefinePopulateMethod(populateBuilder, parsed, populateName,
classTypeDefinition == null),
buildName == null ? null : compiler.DefineBuildMethod(builder, parsed, buildName, true),
builder.DefineSubType(compilerConfig.WellKnownTypes.Object, "NamespaceInfo:" + res.Name,
true),
(closureName, closureBaseType) =>
populateBuilder.DefineSubType(closureBaseType, closureName, false),
res.Uri, res
);
if (classTypeDefinition != null)
{
var compiledPopulateMethod = typeSystem.GetTypeReference(populateBuilder).Resolve()
.Methods.First(m => m.Name == populateName);
var designLoaderFieldType = typeSystem
.GetType("System.Action`1")
.MakeGenericType(typeSystem.GetType("System.Object"));
var designLoaderFieldTypeReference = (GenericInstanceType)typeSystem.GetTypeReference(designLoaderFieldType);
designLoaderFieldTypeReference.GenericArguments[0] =
asm.MainModule.ImportReference(designLoaderFieldTypeReference.GenericArguments[0]);
designLoaderFieldTypeReference = (GenericInstanceType)
asm.MainModule.ImportReference(designLoaderFieldTypeReference);
var designLoaderLoad =
typeSystem.GetMethodReference(
designLoaderFieldType.Methods.First(m => m.Name == "Invoke"));
designLoaderLoad =
asm.MainModule.ImportReference(designLoaderLoad);
designLoaderLoad.DeclaringType = designLoaderFieldTypeReference;
var designLoaderField = new FieldDefinition("!XamlIlPopulateOverride",
FieldAttributes.Static | FieldAttributes.Private, designLoaderFieldTypeReference);
classTypeDefinition.Fields.Add(designLoaderField);
const string TrampolineName = "!XamlIlPopulateTrampoline";
var trampoline = new MethodDefinition(TrampolineName,
MethodAttributes.Static | MethodAttributes.Private, asm.MainModule.TypeSystem.Void);
trampoline.Parameters.Add(new ParameterDefinition(classTypeDefinition));
classTypeDefinition.Methods.Add(trampoline);
var regularStart = Instruction.Create(OpCodes.Call, createRootServiceProviderMethod);
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldsfld, designLoaderField));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse, regularStart));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldsfld, designLoaderField));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Call, designLoaderLoad));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
trampoline.Body.Instructions.Add(regularStart);
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Call, compiledPopulateMethod));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
CopyDebugDocument(trampoline, compiledPopulateMethod);
var foundXamlLoader = false;
// Find AvaloniaXamlLoader.Load(this) and replace it with !XamlIlPopulateTrampoline(this)
foreach (var method in classTypeDefinition.Methods
.Where(m => !m.Attributes.HasFlag(MethodAttributes.Static)))
{
var i = method.Body.Instructions;
for (var c = 1; c < i.Count; c++)
{
if (i[c].OpCode == OpCodes.Call)
{
var op = i[c].Operand as MethodReference;
// TODO: Throw an error
// This usually happens when same XAML resource was added twice for some weird reason
// We currently support it for dual-named default theme resource
if (op != null
&& op.Name == TrampolineName)
{
foundXamlLoader = true;
break;
}
if (op != null
&& op.Name == "Load"
&& op.Parameters.Count == 1
&& op.Parameters[0].ParameterType.FullName == "System.Object"
&& op.DeclaringType.FullName == "Avalonia.Markup.Xaml.AvaloniaXamlLoader")
{
if (MatchThisCall(i, c - 1))
{
i[c].Operand = trampoline;
foundXamlLoader = true;
}
}
}
}
}
if (!foundXamlLoader)
{
var ctors = classTypeDefinition.GetConstructors()
.Where(c => !c.IsStatic).ToList();
// We can inject xaml loader into default constructor
if (ctors.Count == 1 && ctors[0].Body.Instructions.Count(o=>o.OpCode != OpCodes.Nop) == 3)
{
var i = ctors[0].Body.Instructions;
var retIdx = i.IndexOf(i.Last(x => x.OpCode == OpCodes.Ret));
i.Insert(retIdx, Instruction.Create(OpCodes.Call, trampoline));
i.Insert(retIdx, Instruction.Create(OpCodes.Ldarg_0));
}
else
{
throw new InvalidProgramException(
$"No call to AvaloniaXamlLoader.Load(this) call found anywhere in the type {classType.FullName} and type seems to have custom constructors.");
}
}
}
if (buildName != null || classTypeDefinition != null)
{
var compiledBuildMethod = buildName == null ?
null :
typeSystem.GetTypeReference(builder).Resolve()
.Methods.First(m => m.Name == buildName);
var parameterlessConstructor = compiledBuildMethod != null ?
null :
classTypeDefinition.GetConstructors().FirstOrDefault(c =>
c.IsPublic && !c.IsStatic && !c.HasParameters);
if (compiledBuildMethod != null || parameterlessConstructor != null)
{
var i = loaderDispatcherMethod.Body.Instructions;
var nop = Instruction.Create(OpCodes.Nop);
i.Add(Instruction.Create(OpCodes.Ldarg_0));
i.Add(Instruction.Create(OpCodes.Ldstr, res.Uri));
i.Add(Instruction.Create(OpCodes.Call, stringEquals));
i.Add(Instruction.Create(OpCodes.Brfalse, nop));
if (parameterlessConstructor != null)
i.Add(Instruction.Create(OpCodes.Newobj, parameterlessConstructor));
else
{
i.Add(Instruction.Create(OpCodes.Call, createRootServiceProviderMethod));
i.Add(Instruction.Create(OpCodes.Call, compiledBuildMethod));
}
i.Add(Instruction.Create(OpCodes.Ret));
i.Add(nop);
}
}
}
catch (Exception e)
{
int lineNumber = 0, linePosition = 0;
if (e is XamlParseException xe)
{
lineNumber = xe.LineNumber;
linePosition = xe.LinePosition;
}
engine.LogErrorEvent(new BuildErrorEventArgs("Avalonia", "XAMLIL", res.FilePath,
lineNumber, linePosition, lineNumber, linePosition,
e.Message, "", "Avalonia"));
return false;
}
res.Remove();
}
// Technically that's a hack, but it fixes corert incompatibility caused by deterministic builds
int dupeCounter = 1;
foreach (var grp in typeDef.NestedTypes.GroupBy(x => x.Name))
{
if (grp.Count() > 1)
{
foreach (var dupe in grp)
dupe.Name += "_dup" + dupeCounter++;
}
}
return true;
}
if (emres.Resources.Count(CheckXamlName) != 0)
if (!CompileGroup(emres))
return false;
if (avares.Resources.Count(CheckXamlName) != 0)
{
if (!CompileGroup(avares))
return false;
avares.Save();
}
loaderDispatcherMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldnull));
loaderDispatcherMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
return true;
}
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Collections;
using NUnit.Framework;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// AssertionHelper is an optional base class for user tests,
/// allowing the use of shorter names for constraints and
/// asserts and avoiding conflict with the definition of
/// <see cref="Is"/>, from which it inherits much of its
/// behavior, in certain mock object frameworks.
/// </summary>
public class AssertionHelper : ConstraintFactory
{
#region Assert
//private Assertions assert = new Assertions();
//public virtual Assertions Assert
//{
// get { return assert; }
//}
#endregion
#region Expect
#region Object
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure. Works
/// identically to <see cref="NUnit.Framework.Assert.That(object, IResolveConstraint)"/>
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
public void Expect(object actual, IResolveConstraint constraint)
{
Assert.That(actual, constraint, null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure. Works
/// identically to <see cref="NUnit.Framework.Assert.That(object, IResolveConstraint, string)"/>
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
public void Expect(object actual, IResolveConstraint constraint, string message)
{
Assert.That(actual, constraint, message, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure. Works
/// identically to <see cref="NUnit.Framework.Assert.That(object, IResolveConstraint, string, object[])"/>
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public void Expect(object actual, IResolveConstraint constraint, string message, params object[] args)
{
Assert.That(actual, constraint, message, args);
}
#endregion
#region ActualValueDelegate
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
public void Expect(ActualValueDelegate del, IResolveConstraint expr)
{
Assert.That(del, expr.Resolve(), null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="message">The message that will be displayed on failure</param>
public void Expect(ActualValueDelegate del, IResolveConstraint expr, string message)
{
Assert.That(del, expr.Resolve(), message, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public void Expect(ActualValueDelegate del, IResolveConstraint expr, string message, params object[] args)
{
Assert.That(del, expr, message, args);
}
#endregion
#region ref Object
#if NET_2_0
/// <summary>
/// Apply a constraint to a referenced value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
public void Expect<T>(ref T actual, IResolveConstraint constraint)
{
Assert.That(ref actual, constraint.Resolve(), null, null);
}
/// <summary>
/// Apply a constraint to a referenced value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
public void Expect<T>(ref T actual, IResolveConstraint constraint, string message)
{
Assert.That(ref actual, constraint.Resolve(), message, null);
}
/// <summary>
/// Apply a constraint to a referenced value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="expression">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public void Expect<T>(ref T actual, IResolveConstraint expression, string message, params object[] args)
{
Assert.That(ref actual, expression, message, args);
}
#else
/// <summary>
/// Apply a constraint to a referenced boolean, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
public void Expect(ref bool actual, IResolveConstraint constraint)
{
Assert.That(ref actual, constraint.Resolve(), null, null);
}
/// <summary>
/// Apply a constraint to a referenced value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
public void Expect(ref bool actual, IResolveConstraint constraint, string message)
{
Assert.That(ref actual, constraint.Resolve(), message, null);
}
/// <summary>
/// Apply a constraint to a referenced value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="constraint">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public void Expect(ref bool actual, IResolveConstraint expression, string message, params object[] args)
{
Assert.That( ref actual, expression, message, args );
}
#endif
#endregion
#region Boolean
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>. Works Identically to
/// <see cref="Assert.That(bool, string, object[])"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="message">The message to display if the condition is false</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public void Expect(bool condition, string message, params object[] args)
{
Assert.That(condition, Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>. Works Identically to
/// <see cref="Assert.That(bool, string)"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="message">The message to display if the condition is false</param>
public void Expect(bool condition, string message)
{
Assert.That(condition, Is.True, message, null);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>. Works Identically to <see cref="Assert.That(bool)"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
public void Expect(bool condition)
{
Assert.That(condition, Is.True, null, null);
}
#endregion
/// <summary>
/// Asserts that the code represented by a delegate throws an exception
/// that satisfies the constraint provided.
/// </summary>
/// <param name="code">A TestDelegate to be executed</param>
/// <param name="constraint">A ThrowsConstraint used in the test</param>
public void Expect(TestDelegate code, IResolveConstraint constraint)
{
Assert.That((object)code, constraint);
}
#endregion
#region Map
/// <summary>
/// Returns a ListMapper based on a collection.
/// </summary>
/// <param name="original">The original collection</param>
/// <returns></returns>
public ListMapper Map( ICollection original )
{
return new ListMapper( original );
}
#endregion
}
}
| |
using Signum.Utilities.DataStructures;
using Signum.Engine.Maps;
namespace Signum.Test.LinqProvider;
/// <summary>
/// Summary description for LinqProvider
/// </summary>
public class SelectTest
{
public SelectTest()
{
MusicStarter.StartAndLoad();
Connector.CurrentLogger = new DebugTextWriter();
}
[Fact]
public void Select()
{
var list = Database.Query<AlbumEntity>().Select(a => a.Name).ToList();
}
[Fact]
public void SelectIndex()
{
var list = Database.Query<AlbumEntity>().Select((a, i) => a.Name + i).ToList();
}
[Fact]
public void SelectIds()
{
var first = Database.Query<BandEntity>().Select(b => b.Id).ToList();
}
[Fact]
public void SelectFirstId()
{
var first = Database.Query<BandEntity>().Select(b => b.Id).First();
}
[Fact]
public void SelectExpansion()
{
var list = Database.Query<AlbumEntity>().Select(a => a.Label.Name).ToList();
}
[Fact]
public void SelectLetExpansion()
{
var list = (from a in Database.Query<AlbumEntity>()
let l = a.Label
select l.Name).ToList();
}
[Fact]
public void SelectLetExpansionRedundant()
{
var list = (from a in Database.Query<AlbumEntity>()
let label = a.Label
select new
{
Artist = label.Country.Name,
Author = a.Label.Name
}).ToList();
Assert.Equal(Database.Query<AlbumEntity>().Count(), list.Count);
}
[Fact]
public void SelectWhereExpansion()
{
var list = Database.Query<AlbumEntity>().Where(a => a.Label != null).Select(a => a.Label.Name).ToList();
}
[Fact]
public void SelectAnonymous()
{
var list = Database.Query<AlbumEntity>().Select(a => new { a.Name, a.Year }).ToList();
}
[Fact]
public void SelectNoColumns()
{
var list = Database.Query<AlbumEntity>().Select(a => new { Clock.Now, Album = (AlbumEntity?)null, Artist = (Lite<ArtistEntity>?)null }).ToList();
}
[Fact]
public void SelectCount()
{
var list = Database.Query<AlbumEntity>().Select(a => (int?)a.Songs.Count).ToList();
}
[Fact]
public void SelectLite()
{
var list = Database.Query<AlbumEntity>().Select(a => a.ToLite()).ToList();
}
[Fact]
public void SelectLiteToStr()
{
var list = Database.Query<AlbumEntity>().Select(a => a.ToLite(a.Label.Name)).ToList();
}
[Fact]
public void SelectBool()
{
var list = Database.Query<ArtistEntity>().Select(a => a.Dead).ToList();
}
[Fact]
public void SelectConditionToBool()
{
var list = Database.Query<AlbumEntity>().Select(a => a.Year < 1990).ToList();
}
[Fact]
public void SelectConditionalMember()
{
var list = (from l in Database.Query<LabelEntity>()
select (l.Owner == null ? l : l.Owner.Entity).Name).ToList();
}
[Fact]
public void SelectConditionalToLite()
{
var list = (from l in Database.Query<LabelEntity>()
select (l.Owner == null ? l : l.Owner.Entity).ToLite()).ToList();
}
#pragma warning disable IDE0029 // Use coalesce expression
[Fact]
public void SelectConditionalToLiteNull()
{
var list = (from l in Database.Query<LabelEntity>()
let owner = (l.Owner == null ? null : l.Owner)!.Entity
select owner.ToLite(owner.Name)).ToList();
}
#pragma warning restore IDE0029 // Use coalesce expression
[Fact]
public void SelectConditionalGetType()
{
var list = (from l in Database.Query<LabelEntity>()
select (l.Owner == null ? l : l.Owner.Entity).GetType()).ToList();
}
[Fact]
public void SelectCoalesceMember()
{
var list = (from l in Database.Query<LabelEntity>()
select (l.Owner!.Entity ?? l).Name).ToList();
}
[Fact]
public void SelectCoalesceToLite()
{
var list = (from l in Database.Query<LabelEntity>()
select (l.Owner!.Entity ?? l).ToLite()).ToList();
}
[Fact]
public void SelectCoalesceGetType()
{
var list = (from l in Database.Query<LabelEntity>()
select (l.Owner!.Entity ?? l).GetType()).ToList();
}
[Fact]
public void SelectUpCast()
{
var list = (from n in Database.Query<ArtistEntity>()
select (IAuthorEntity)n).ToList(); //Just to full-nominate
}
[Fact]
public void SelectEntityEquals()
{
ArtistEntity michael = Database.Query<ArtistEntity>().SingleEx(a => a.Dead);
var list = Database.Query<AlbumEntity>().Select(a => a.Author == michael).ToList();
}
[Fact]
public void SelectBoolExpression()
{
ArtistEntity michael = Database.Query<ArtistEntity>().SingleEx(a => a.Dead);
var list = Database.Query<AlbumEntity>().Select(a => a.Author == michael).ToList();
}
[Fact]
public void SelectExpressionProperty()
{
var list = Database.Query<ArtistEntity>().Where(a => a.IsMale).ToArray();
}
[Fact]
public void SelectExpressionMethod()
{
var list = Database.Query<ArtistEntity>().Select(a => new { a.Name, Count = a.AlbumCount() }).ToArray();
}
[Fact]
public void SelectPolyExpressionPropertyUnion()
{
var list = Database.Query<AlbumEntity>().Select(a => a.Author.CombineUnion().FullName).ToArray();
}
[Fact]
public void SelectPolyExpressionPropertySwitch()
{
var list = Database.Query<AlbumEntity>().Select(a => a.Author.CombineCase().FullName).ToArray();
}
[Fact]
public void SelectPolyExpressionMethodUnion()
{
var list = Database.Query<AlbumEntity>().Select(a => a.Author.CombineUnion().Lonely()).ToArray();
}
[Fact]
public void SelectPolyExpressionMethodSwitch()
{
var list = Database.Query<AlbumEntity>().Select(a => a.Author.CombineCase().Lonely()).ToArray();
}
[Fact]
public void SelectPolyExpressionMethodManual()
{
var list = Database.Query<AlbumEntity>().Select(a => a.Author is BandEntity ? ((BandEntity)a.Author).Lonely() : ((ArtistEntity)a.Author).Lonely()).ToArray();
}
[Fact]
public void SelectThrowIntNullable()
{
Assert.Throws<FieldReaderException>(() =>
Database.Query<AlbumEntity>().Select(a => ((ArtistEntity)a.Author).Id).ToArray());
}
[Fact]
public void SelectThrowBoolNullable()
{
Assert.Throws<FieldReaderException>(() =>
Database.Query<AlbumEntity>().Select(a => ((ArtistEntity)a.Author).Dead).ToArray());
}
[Fact]
public void SelectThrowEnumNullable()
{
Assert.Throws<FieldReaderException>(() =>
Database.Query<AlbumEntity>().Select(a => ((ArtistEntity)a.Author).Sex).ToArray());
}
[Fact]
public void SelectIntNullable()
{
var list = Database.Query<AlbumEntity>().Select(a => (int?)((ArtistEntity)a.Author).Id).ToArray();
}
[Fact]
public void SelectBoolNullable()
{
var list = Database.Query<AlbumEntity>().Select(a => (bool?)((ArtistEntity)a.Author).Dead).ToArray();
}
[Fact]
public void SelectEnumNullable()
{
var list = Database.Query<ArtistEntity>().Select(a => a.Status).ToArray();
}
[Fact]
public void SelectEnumNullableNullable()
{
var list = Database.Query<AlbumEntity>().Select(a => ((ArtistEntity)a.Author).Status).ToArray();
}
[Fact]
public void SelectThrowsIntSumNullable()
{
Assert.Throws<FieldReaderException>(() =>
Database.Query<AlbumEntity>().Select(a => (int)a.Id + (int)((ArtistEntity)a.Author).Id).ToArray());
}
[Fact]
public void SelectThrowaIntSumNullableCasting()
{
Assert.Throws<FieldReaderException>(() =>
Database.Query<AlbumEntity>().Select(a => (int?)((int)a.Id + (int)((ArtistEntity)a.Author).Id)).ToArray());
}
[Fact]
public void SelectThrowaIntSumNullableCastingInSql()
{
var list = Database.Query<AlbumEntity>().Select(a => (int?)((int)a.Id + (int)((ArtistEntity)a.Author).Id).InSql()).ToArray();
}
[Fact]
public void SelectEnumNullableBullableCast()
{
var list = Database.Query<AlbumEntity>().Select(a => (Sex?)((ArtistEntity)a.Author).Sex).ToArray();
}
[Fact]
public void SelectEnumNullableValue()
{
var list = Database.Query<AlbumEntity>().Where(a => a.Author is ArtistEntity)
.Select(a => ((Sex?)((ArtistEntity)a.Author).Sex).Value).ToArray();
}
[Fact]
public void CoallesceNullable()
{
var list = Database.Query<ArtistEntity>()
.Where(a => a.Status != null)
.Select(a => (a.Status ?? a.Status)!.Value)
.ToArray();
}
[Fact]
public void SelectEmbeddedNullable()
{
var bonusTracks = Database.Query<AlbumEntity>().Select(a => a.BonusTrack).ToArray();
}
[Fact]
public void SelectMixinThrows()
{
var e = Assert.Throws<InvalidOperationException>(() =>
Database.Query<NoteWithDateEntity>().Select(a => a.Mixin<CorruptMixin>()).ToArray());
Assert.Contains("without their main entity", e.Message);
}
[Fact]
public void SelectMixinField()
{
Database.Query<NoteWithDateEntity>().Select(a => a.Mixin<CorruptMixin>().Corrupt).ToArray();
}
[Fact]
public void SelectMixinWhere()
{
Database.Query<NoteWithDateEntity>().Where(a => a.Mixin<CorruptMixin>().Corrupt == true).ToArray();
}
[Fact]
public void SelectMixinCollection()
{
var result = (from n in Database.Query<NoteWithDateEntity>()
from c in n.Mixin<ColaboratorsMixin>().Colaborators
select c).ToArray();
}
[Fact]
public void SelectNullable()
{
var durations = (from a in Database.Query<AlbumEntity>()
from s in a.Songs
where s.Seconds.HasValue
select s.Seconds!.Value).ToArray();
}
[Fact]
public void SelectIsNull()
{
var durations = (from a in Database.Query<AlbumEntity>()
from s in a.Songs
where s.Seconds.HasValue
select s.Seconds == null).ToArray();
}
[Fact]
public void SelectAvoidNominate()
{
var durations =
(from a in Database.Query<AlbumEntity>()
select new
{
a.Name,
Value = 3,
}).ToList();
}
[Fact]
public void SelectAvoidNominateEntity()
{
var durations =
(from a in Database.Query<AlbumEntity>()
select new
{
a.Name,
Friend = (Lite<BandEntity>?)null
}).ToList();
}
[Fact]
public void SelectSingleCellAggregate()
{
var list = Database.Query<BandEntity>()
.Select(b => new
{
b.Members.Count,
AnyDead = b.Members.Any(m => m.Dead),
DeadCount = b.Members.Count(m => m.Dead),
MinId = b.Members.Min(m => m.Id),
MaxId = b.Members.Max(m => m.Id),
AvgId = b.Members.Average(m => (int)m.Id),
SumId = b.Members.Sum(m => (int)m.Id),
}).ToList();
}
[Fact]
public void SelectMemoryEntity()
{
var artist = Database.Query<ArtistEntity>().FirstEx();
var songs = Database.Query<AlbumEntity>().Select(a => new
{
Lite = a.ToLite(),
Memory = artist,
}).ToList();
}
[Fact]
public void SelectMemoryLite()
{
var artist = Database.Query<ArtistEntity>().Select(a => a.ToLite()).FirstEx();
var songs = Database.Query<AlbumEntity>().Select(a => new
{
Lite = a.ToLite(),
MemoryLite = artist,
}).ToList();
}
[Fact]
public void SelectOutsideStringNull()
{
var awards = Database.Query<GrammyAwardEntity>().Select(a => ((AmericanMusicAwardEntity)(AwardEntity)a).Category).ToList();
}
[Fact]
public void SelectOutsideLiteNull()
{
var awards = Database.Query<GrammyAwardEntity>().Select(a => ((AmericanMusicAwardEntity)(AwardEntity)a).ToLite()).ToList();
}
[Fact]
public void SelectMListLite()
{
var lists = (from mle in Database.MListQuery((ArtistEntity a) => a.Friends)
select new { Artis = mle.Parent.Name, Friend = mle.Element.Entity.Name }).ToList();
}
[Fact]
public void SelectMListEntity()
{
var lists = (from mle in Database.MListQuery((BandEntity a) => a.Members)
select new { Band = mle.Parent.Name, Artis = mle.Element.Name }).ToList();
}
[Fact]
public void SelectMListEmbedded()
{
var lists = (from mle in Database.MListQuery((AlbumEntity a) => a.Songs)
select mle).ToList();
}
[Fact]
public void SelectMListEmbeddedToList()
{
var lists = (from a in Database.Query<AlbumEntity>()
select new
{
a.Name,
Songs = a.Songs.ToList(),
}).ToList();
}
[Fact]
public void SelectMListPotentialDuplicates()
{
var sp = (from alb in Database.Query<AlbumEntity>()
let mich = ((ArtistEntity)alb.Author)
where mich.Name.Contains("Michael")
select mich).ToList();
var single = sp.Distinct(ReferenceEqualityComparer<ArtistEntity>.Default).SingleEx();
Assert.Equal(single.Friends.Distinct().Count(), single.Friends.Count);
}
[Fact]
public void SelectIBAId()
{
var list = Database.Query<ArtistEntity>().Select(a => a.LastAward.Try(la => la.Id)).ToList();
}
[Fact]
public void SelectIBAIdObject()
{
var e = Assert.Throws<InvalidOperationException>(() =>
Database.Query<ArtistEntity>().Select(a => a.LastAward.Try(la => (int?)la.Id).InSql()).ToList());
Assert.Contains("translated", e.Message);
}
[Fact]
public void SelectToStrField()
{
var list = Database.Query<NoteWithDateEntity>().Select(a => a.ToStringProperty).ToList();
}
[Fact]
public void SelectFakedToString()
{
var list = Database.Query<AlbumEntity>().Select(a => a.ToStringProperty).ToList();
}
[Fact]
public void SelectConditionFormat()
{
var list = Database.Query<AlbumEntity>().Select(a =>
new
{
Wrong = a.Author.GetType() == typeof(BandEntity) ?
"Band {0}".FormatWith(((BandEntity)a.Author).ToString()) :
"Artist {0}".FormatWith(((ArtistEntity)a.Author).ToString()),
Right = a.Author is BandEntity ?
"Band {0}".FormatWith(((BandEntity)a.Author).ToString()) :
"Artist {0}".FormatWith(((ArtistEntity)a.Author).ToString()),
}).ToList();
}
[Fact]
public void SelectToString()
{
var list = Database.Query<AlbumEntity>().Select(a => a.ToString()).ToList();
}
[Fact]
public void SelectToStringLite()
{
var list = Database.Query<AlbumEntity>().Select(a => a.ToLite().ToString()).ToList();
}
[Fact]
public void SelectConditionEnum()
{
var results = from b in Database.Query<BandEntity>()
let ga = (GrammyAwardEntity?)b.LastAward
select (AwardResult?)(ga.Result < ga.Result ? (int)ga.Result : (int)ga.Result).InSql();
results.ToList();
}
[Fact]
public void SelectMListId()
{
var list = Database.Query<ArtistEntity>().SelectMany(a => a.Friends).Select(a => a.Id).ToList();
}
[Fact]
public void SelectMListIdCovariance()
{
var list = Database.Query<ArtistEntity>().SelectMany(a => a.FriendsCovariant()).Select(a => a.Id).ToList();
}
[Fact]
public void SelectEmbeddedListNotNullableNull()
{
var list = (from a in Database.Query<AlbumEntity>()
from s in a.Songs.Where(s => s.Seconds < 0).DefaultIfEmpty()
select new { a, s }).ToList();
Assert.True(list.All(p => p.s == null));
}
[Fact]
public void SelectEmbeddedListElementNotNullableNull()
{
var list = (from a in Database.Query<AlbumEntity>()
from s in a.MListElements(_ => _.Songs).Where(s => s.Element.Seconds < 0).DefaultIfEmpty()
select new { a, s }).ToList();
Assert.True(list.All(p => p.s == null));
}
[Fact]
public void SelectWhereExpressionInSelectMany()
{
var max = 0;
Expression<Func<AlbumEntity, bool>> blas = a => a.Id > max;
var list = (from a in Database.Query<AlbumEntity>()
from s in Database.Query<AlbumEntity>().Where(blas)
select new { a, s }).ToList();
}
[Fact]
public void SelectExplicitInterfaceImplementedField()
{
var list = (from a in Database.Query<AlbumEntity>()
select ((ISecretContainer)a).Secret.InSql()).ToList();
}
[Fact]
public void SelectEmbedded()
{
var list = Database.Query<AlbumEntity>().SelectMany(a => a.Songs).ToList();
}
[Fact]
public void SelectView()
{
if (Schema.Current.Settings.IsPostgres)
{
var list = Database.View<Signum.Engine.PostgresCatalog.PgClass>().ToList();
}
else
{
var list = Database.View<Signum.Engine.SchemaInfoTables.SysDatabases>().ToList();
}
}
[Fact]
public void SelectRetrieve()
{
var e = Assert.Throws<InvalidOperationException>(() => Database.Query<LabelEntity>().Select(l => l.Owner!.RetrieveAndRemember()).ToList());
Assert.Contains("not supported", e.Message);
}
[Fact]
public void SelectWithHint()
{
if (!Schema.Current.Settings.IsPostgres)
{
var list = Database.Query<AlbumEntity>().WithHint("INDEX(IX_Album_LabelID)").Select(a => a.Label.Name).ToList();
}
}
[Fact]
public void SelectAverageBool()
{
Expression<Func<AlbumEntity, bool>> selector = a => a.Id > 10;
Expression<Func<AlbumEntity, double>> selectorDouble = Expression.Lambda<Func<AlbumEntity, double>>(Expression.Convert(selector.Body, typeof(double)), selector.Parameters.SingleEx());
var list = Database.Query<AlbumEntity>().Average(selectorDouble);
}
[Fact]
public void SelectVirtualMListNoDistinct()
{
var list = Database.Query<ArtistEntity>().ToList();
Assert.True(!Database.Query<ArtistEntity>().QueryText().Contains("DISTINCT"));
}
[Fact]
public void AvoidDecimalCastinInSql()
{
var list = Database.Query<ArtistEntity>()
.Select(a => ((int)a.Id / 10m))
.Select(a => ((decimal?)a).InSql()) //Avoid Cast( as decimal) in SQL because of https://stackoverflow.com/questions/4169520/casting-as-decimal-and-rounding
.ToList();
Assert.Contains(list, a => a!.Value != Math.Round(a!.Value)); //Decimal places are preserved
}
}
public static class AuthorExtensions
{
[AutoExpressionField]
public static int AlbumCount(this IAuthorEntity author) =>
As.Expression(() => Database.Query<AlbumEntity>().Count(a => a.Author == author));
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace BreadTalk.WebAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Linq;
namespace Anima2D
{
public class ContextMenu
{
[MenuItem("Assets/Create/Anima2D/SpriteMesh", true)]
static bool ValidateCreateSpriteMesh(MenuCommand menuCommand)
{
bool valid = false;
Sprite sprite = Selection.activeObject as Sprite;
if(sprite && !SpriteMeshPostprocessor.GetSpriteMeshFromSprite(sprite))
{
valid = true;
}
List<Texture2D> selectedTextures = Selection.objects.ToList().Where( o => o is Texture2D).ToList().ConvertAll( o => o as Texture2D);
valid = valid || selectedTextures.Count > 0;
return valid;
}
[MenuItem("Assets/Create/Anima2D/SpriteMesh", false)]
static void CreateSpriteMesh(MenuCommand menuCommand)
{
List<Texture2D> selectedTextures = Selection.objects.ToList().Where( o => o is Texture2D).ToList().ConvertAll( o => o as Texture2D);
foreach(Texture2D texture in selectedTextures)
{
SpriteMeshUtils.CreateSpriteMesh(texture);
}
if(selectedTextures.Count == 0)
{
SpriteMeshUtils.CreateSpriteMesh(Selection.activeObject as Sprite);
}
}
[MenuItem("GameObject/2D Object/SpriteMesh", false, 10)]
static void ContextCreateSpriteMesh(MenuCommand menuCommand)
{
GameObject spriteRendererGO = Selection.activeGameObject;
SpriteRenderer spriteRenderer = null;
SpriteMesh spriteMesh = null;
int sortingLayerID = 0;
int sortingOrder = 0;
if(spriteRendererGO)
{
spriteRenderer = spriteRendererGO.GetComponent<SpriteRenderer>();
}
if(spriteRenderer &&
spriteRenderer.sprite)
{
sortingLayerID = spriteRenderer.sortingLayerID;
sortingOrder = spriteRenderer.sortingOrder;
SpriteMesh overrideSpriteMesh = SpriteMeshPostprocessor.GetSpriteMeshFromSprite(spriteRenderer.sprite);
if(overrideSpriteMesh)
{
spriteMesh = overrideSpriteMesh;
}else{
spriteMesh = SpriteMeshUtils.CreateSpriteMesh(spriteRenderer.sprite);
}
}
if(spriteMesh)
{
Undo.SetCurrentGroupName("create SpriteMeshInstance");
Undo.DestroyObjectImmediate(spriteRenderer);
SpriteMeshInstance spriteMeshInstance = SpriteMeshUtils.CreateSpriteMeshInstance(spriteMesh,spriteRendererGO,true);
spriteMeshInstance.sortingLayerID = sortingLayerID;
spriteMeshInstance.sortingOrder = sortingOrder;
Selection.activeGameObject = spriteRendererGO;
}else{
Debug.Log("Select a SpriteRenderer with a Sprite to convert to SpriteMesh");
}
}
[MenuItem("GameObject/2D Object/Bone &#b", false, 10)]
public static void CreateBone(MenuCommand menuCommand)
{
GameObject bone = new GameObject("New bone");
Bone2D boneComponent = bone.AddComponent<Bone2D>();
Undo.RegisterCreatedObjectUndo(bone, "Create bone");
bone.transform.position = GetDefaultInstantiatePosition();
GameObject selectedGO = Selection.activeGameObject;
if(selectedGO)
{
bone.transform.parent = selectedGO.transform;
Vector3 localPosition = bone.transform.localPosition;
localPosition.z = 0f;
bone.transform.localPosition = localPosition;
bone.transform.localRotation = Quaternion.identity;
bone.transform.localScale = Vector3.one;
Bone2D selectedBone = selectedGO.GetComponent<Bone2D>();
if(selectedBone)
{
if(!selectedBone.child)
{
bone.transform.position = selectedBone.endPosition;
selectedBone.child = boneComponent;
}
}
}
Selection.activeGameObject = bone;
}
[MenuItem("GameObject/2D Object/IK CCD &#k", false, 10)]
static void CreateIkCCD(MenuCommand menuCommand)
{
GameObject ikCCD = new GameObject("New Ik CCD");
Undo.RegisterCreatedObjectUndo(ikCCD,"Crate Ik CCD");
IkCCD2D ikCCDComponent = ikCCD.AddComponent<IkCCD2D>();
ikCCD.transform.position = GetDefaultInstantiatePosition();
GameObject selectedGO = Selection.activeGameObject;
if(selectedGO)
{
ikCCD.transform.parent = selectedGO.transform;
ikCCD.transform.localPosition = Vector3.zero;
Bone2D selectedBone = selectedGO.GetComponent<Bone2D>();
if(selectedBone)
{
ikCCD.transform.parent = selectedBone.root.transform.parent;
ikCCD.transform.position = selectedBone.endPosition;
if(selectedBone.child)
{
ikCCD.transform.rotation = selectedBone.child.transform.rotation;
}
ikCCDComponent.numBones = selectedBone.chainLength;
ikCCDComponent.target = selectedBone;
}
}
ikCCD.transform.localScale = Vector3.one;
EditorUtility.SetDirty(ikCCDComponent);
Selection.activeGameObject = ikCCD;
}
[MenuItem("GameObject/2D Object/IK Limb &#l", false, 10)]
static void CreateIkLimb(MenuCommand menuCommand)
{
GameObject ikLimb = new GameObject("New Ik Limb");
Undo.RegisterCreatedObjectUndo(ikLimb,"Crate Ik Limb");
IkLimb2D ikLimbComponent = ikLimb.AddComponent<IkLimb2D>();
ikLimb.transform.position = GetDefaultInstantiatePosition();
GameObject selectedGO = Selection.activeGameObject;
if(selectedGO)
{
ikLimb.transform.parent = selectedGO.transform;
ikLimb.transform.localPosition = Vector3.zero;
Bone2D selectedBone = selectedGO.GetComponent<Bone2D>();
if(selectedBone)
{
ikLimb.transform.parent = selectedBone.root.transform.parent;
ikLimb.transform.position = selectedBone.endPosition;
if(selectedBone.child)
{
ikLimb.transform.rotation = selectedBone.child.transform.rotation;
}
ikLimbComponent.numBones = selectedBone.chainLength;
ikLimbComponent.target = selectedBone;
}
}
ikLimb.transform.localScale = Vector3.one;
EditorUtility.SetDirty(ikLimbComponent);
Selection.activeGameObject = ikLimb;
}
[MenuItem("GameObject/2D Object/Control &#c", false, 10)]
static void CreateControl(MenuCommand menuCommand)
{
GameObject control = new GameObject("New control");
Undo.RegisterCreatedObjectUndo(control,"Crate Control");
Control controlComponent = control.AddComponent<Control>();
control.transform.position = GetDefaultInstantiatePosition();
GameObject selectedGO = Selection.activeGameObject;
if(selectedGO)
{
control.transform.parent = selectedGO.transform;
control.transform.localPosition = Vector3.zero;
control.transform.localRotation = Quaternion.identity;
Bone2D selectedBone = selectedGO.GetComponent<Bone2D>();
if(selectedBone)
{
control.name = "Control " + selectedBone.name;
controlComponent.bone = selectedBone;
control.transform.parent = selectedBone.root.transform.parent;
}
}
EditorUtility.SetDirty(controlComponent);
Selection.activeGameObject = control;
}
[MenuItem("Assets/Create/Anima2D/Pose")]
public static void CreatePose(MenuCommand menuCommand)
{
string path = AssetDatabase.GetAssetPath(Selection.activeObject);
if(System.IO.File.Exists(path))
{
path = System.IO.Path.GetDirectoryName(path);
}
path += "/";
if(System.IO.Directory.Exists(path))
{
path += "New pose.asset";
ScriptableObjectUtility.CreateAsset<Pose>(path);
}
}
static Vector3 GetDefaultInstantiatePosition()
{
Vector3 result = Vector3.zero;
if (SceneView.lastActiveSceneView)
{
if (SceneView.lastActiveSceneView.in2DMode)
{
result = SceneView.lastActiveSceneView.camera.transform.position;
result.z = 0f;
}
else
{
PropertyInfo prop = typeof(SceneView).GetProperty("cameraTargetPosition",BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
result = (Vector3) prop.GetValue(SceneView.lastActiveSceneView,null);
}
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
using System;
using System.Collections;
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.NonSerializedAttribute))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.SerializableAttribute))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Serialization.IDeserializationCallback))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Serialization.IFormatterConverter))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Serialization.ISerializable))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Serialization.SerializationEntry))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Serialization.SerializationInfo))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Serialization.SerializationInfoEnumerator))]
namespace System.Runtime.Serialization
{
[System.CLSCompliantAttribute(false)]
public abstract partial class Formatter : System.Runtime.Serialization.IFormatter
{
protected System.Runtime.Serialization.ObjectIDGenerator m_idGenerator;
protected System.Collections.Queue m_objectQueue;
protected Formatter() { }
public abstract System.Runtime.Serialization.SerializationBinder Binder { get; set; }
public abstract System.Runtime.Serialization.StreamingContext Context { get; set; }
public abstract System.Runtime.Serialization.ISurrogateSelector SurrogateSelector { get; set; }
public abstract object Deserialize(System.IO.Stream serializationStream);
protected virtual object GetNext(out long objID) { objID = default(long); return default(object); }
protected virtual long Schedule(object obj) { return default(long); }
public abstract void Serialize(System.IO.Stream serializationStream, object graph);
protected abstract void WriteArray(object obj, string name, System.Type memberType);
protected abstract void WriteBoolean(bool val, string name);
protected abstract void WriteByte(byte val, string name);
protected abstract void WriteChar(char val, string name);
protected abstract void WriteDateTime(System.DateTime val, string name);
protected abstract void WriteDecimal(decimal val, string name);
protected abstract void WriteDouble(double val, string name);
protected abstract void WriteInt16(short val, string name);
protected abstract void WriteInt32(int val, string name);
protected abstract void WriteInt64(long val, string name);
protected virtual void WriteMember(string memberName, object data) { }
protected abstract void WriteObjectRef(object obj, string name, System.Type memberType);
[System.CLSCompliantAttribute(false)]
protected abstract void WriteSByte(sbyte val, string name);
protected abstract void WriteSingle(float val, string name);
protected abstract void WriteTimeSpan(System.TimeSpan val, string name);
[System.CLSCompliantAttribute(false)]
protected abstract void WriteUInt16(ushort val, string name);
[System.CLSCompliantAttribute(false)]
protected abstract void WriteUInt32(uint val, string name);
[System.CLSCompliantAttribute(false)]
protected abstract void WriteUInt64(ulong val, string name);
protected abstract void WriteValueType(object obj, string name, System.Type memberType);
}
public partial class FormatterConverter : System.Runtime.Serialization.IFormatterConverter
{
public FormatterConverter() { }
public object Convert(object value, System.Type type) { return default(object); }
public object Convert(object value, System.TypeCode typeCode) { return default(object); }
public bool ToBoolean(object value) { return default(bool); }
public byte ToByte(object value) { return default(byte); }
public char ToChar(object value) { return default(char); }
public System.DateTime ToDateTime(object value) { return default(System.DateTime); }
public decimal ToDecimal(object value) { return default(decimal); }
public double ToDouble(object value) { return default(double); }
public short ToInt16(object value) { return default(short); }
public int ToInt32(object value) { return default(int); }
public long ToInt64(object value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public sbyte ToSByte(object value) { return default(sbyte); }
public float ToSingle(object value) { return default(float); }
public string ToString(object value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public ushort ToUInt16(object value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public uint ToUInt32(object value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public ulong ToUInt64(object value) { return default(ulong); }
}
public static partial class FormatterServices
{
public static void CheckTypeSecurity(System.Type t, System.Runtime.Serialization.Formatters.TypeFilterLevel securityLevel) { }
public static object[] GetObjectData(object obj, System.Reflection.MemberInfo[] members) { return default(object[]); }
public static object GetSafeUninitializedObject(System.Type type) { return default(object); }
public static System.Reflection.MemberInfo[] GetSerializableMembers(System.Type type) { return default(System.Reflection.MemberInfo[]); }
public static System.Reflection.MemberInfo[] GetSerializableMembers(System.Type type, System.Runtime.Serialization.StreamingContext context) { return default(System.Reflection.MemberInfo[]); }
public static System.Runtime.Serialization.ISerializationSurrogate GetSurrogateForCyclicalReference(System.Runtime.Serialization.ISerializationSurrogate innerSurrogate) { return default(System.Runtime.Serialization.ISerializationSurrogate); }
public static System.Type GetTypeFromAssembly(System.Reflection.Assembly assem, string name) { return default(System.Type); }
public static object GetUninitializedObject(System.Type type) { return default(object); }
public static object PopulateObjectMembers(object obj, System.Reflection.MemberInfo[] members, object[] data) { return default(object); }
}
public partial interface IFormatter
{
System.Runtime.Serialization.SerializationBinder Binder { get; set; }
System.Runtime.Serialization.StreamingContext Context { get; set; }
System.Runtime.Serialization.ISurrogateSelector SurrogateSelector { get; set; }
object Deserialize(System.IO.Stream serializationStream);
void Serialize(System.IO.Stream serializationStream, object graph);
}
public partial interface ISerializationSurrogate
{
void GetObjectData(object obj, System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
object SetObjectData(object obj, System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.ISurrogateSelector selector);
}
public partial interface ISurrogateSelector
{
void ChainSelector(System.Runtime.Serialization.ISurrogateSelector selector);
System.Runtime.Serialization.ISurrogateSelector GetNextSelector();
System.Runtime.Serialization.ISerializationSurrogate GetSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, out System.Runtime.Serialization.ISurrogateSelector selector);
}
public partial class ObjectIDGenerator
{
public ObjectIDGenerator() { }
public virtual long GetId(object obj, out bool firstTime) { firstTime = default(bool); return default(long); }
public virtual long HasId(object obj, out bool firstTime) { firstTime = default(bool); return default(long); }
}
public partial class ObjectManager
{
public ObjectManager(System.Runtime.Serialization.ISurrogateSelector selector, System.Runtime.Serialization.StreamingContext context) { }
public virtual void DoFixups() { }
public virtual object GetObject(long objectID) { return default(object); }
public virtual void RaiseDeserializationEvent() { }
public void RaiseOnDeserializingEvent(object obj) { }
public virtual void RecordArrayElementFixup(long arrayToBeFixed, int index, long objectRequired) { }
public virtual void RecordArrayElementFixup(long arrayToBeFixed, int[] indices, long objectRequired) { }
public virtual void RecordDelayedFixup(long objectToBeFixed, string memberName, long objectRequired) { }
public virtual void RecordFixup(long objectToBeFixed, System.Reflection.MemberInfo member, long objectRequired) { }
public virtual void RegisterObject(object obj, long objectID) { }
public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info) { }
public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info, long idOfContainingObj, System.Reflection.MemberInfo member) { }
public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info, long idOfContainingObj, System.Reflection.MemberInfo member, int[] arrayIndex) { }
}
public abstract partial class SerializationBinder
{
protected SerializationBinder() { }
public virtual void BindToName(System.Type serializedType, out string assemblyName, out string typeName) { assemblyName = default(string); typeName = default(string); }
public abstract System.Type BindToType(string assemblyName, string typeName);
}
public sealed partial class SerializationObjectManager
{
public SerializationObjectManager(System.Runtime.Serialization.StreamingContext context) { }
public void RaiseOnSerializedEvent() { }
public void RegisterObject(object obj) { }
}
public partial class SurrogateSelector : System.Runtime.Serialization.ISurrogateSelector
{
public SurrogateSelector() { }
public virtual void AddSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.ISerializationSurrogate surrogate) { }
public virtual void ChainSelector(System.Runtime.Serialization.ISurrogateSelector selector) { }
public virtual System.Runtime.Serialization.ISurrogateSelector GetNextSelector() { return default(System.Runtime.Serialization.ISurrogateSelector); }
public virtual System.Runtime.Serialization.ISerializationSurrogate GetSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, out System.Runtime.Serialization.ISurrogateSelector selector) { selector = default(System.Runtime.Serialization.ISurrogateSelector); return default(System.Runtime.Serialization.ISerializationSurrogate); }
public virtual void RemoveSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context) { }
}
} // end of System.Runtime.Serialization
namespace System.Runtime.Serialization.Formatters
{
public enum FormatterAssemblyStyle
{
Full = 1,
Simple = 0,
}
public enum FormatterTypeStyle
{
TypesAlways = 1,
TypesWhenNeeded = 0,
XsdString = 2,
}
public partial interface IFieldInfo
{
string[] FieldNames { get; set; }
System.Type[] FieldTypes { get; set; }
}
public enum TypeFilterLevel
{
Full = 3,
Low = 2,
}
} // end of System.Runtime.Serialization.Formatters
namespace System.Runtime.Serialization.Formatters.Binary
{
public sealed partial class BinaryFormatter : System.Runtime.Serialization.IFormatter
{
public BinaryFormatter() { }
public BinaryFormatter(System.Runtime.Serialization.ISurrogateSelector selector, System.Runtime.Serialization.StreamingContext context) { }
public System.Runtime.Serialization.Formatters.FormatterAssemblyStyle AssemblyFormat { get { return default(System.Runtime.Serialization.Formatters.FormatterAssemblyStyle); } set { } }
public System.Runtime.Serialization.SerializationBinder Binder { get { return default(System.Runtime.Serialization.SerializationBinder); } set { } }
public System.Runtime.Serialization.StreamingContext Context { get { return default(System.Runtime.Serialization.StreamingContext); } set { } }
public System.Runtime.Serialization.Formatters.TypeFilterLevel FilterLevel { get { return default(System.Runtime.Serialization.Formatters.TypeFilterLevel); } set { } }
public System.Runtime.Serialization.ISurrogateSelector SurrogateSelector { get { return default(System.Runtime.Serialization.ISurrogateSelector); } set { } }
public System.Runtime.Serialization.Formatters.FormatterTypeStyle TypeFormat { get { return default(System.Runtime.Serialization.Formatters.FormatterTypeStyle); } set { } }
public object Deserialize(System.IO.Stream serializationStream) { return default(object); }
public object Deserialize(System.IO.Stream serializationStream, System.Runtime.Remoting.Messaging.HeaderHandler handler) { return default(object); }
public void Serialize(System.IO.Stream serializationStream, object graph) { }
public void Serialize(System.IO.Stream serializationStream, object graph, System.Runtime.Remoting.Messaging.Header[] headers) { }
public object UnsafeDeserialize(System.IO.Stream serializationStream, System.Runtime.Remoting.Messaging.HeaderHandler handler) { return default(object); }
}
} // end of System.Runtime.Serialization.Formatters.Binary
namespace System.Runtime.Remoting.Messaging
{
public partial class Header
{
public string HeaderNamespace;
public bool MustUnderstand;
public string Name;
public object Value;
public Header(string _Name, object _Value) { }
public Header(string _Name, object _Value, bool _MustUnderstand) { }
public Header(string _Name, object _Value, bool _MustUnderstand, string _HeaderNamespace) { }
}
public delegate object HeaderHandler(System.Runtime.Remoting.Messaging.Header[] headers);
}
| |
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 BellTowerEscape.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;
}
}
}
| |
namespace Orleans.Serialization
{
using System;
using System.Reflection;
using System.Reflection.Emit;
internal class ILDelegateBuilder<TDelegate>
where TDelegate : class
{
private readonly DynamicMethod dynamicMethod;
private readonly ILGenerator il;
private readonly ILFieldBuilder fields;
/// <summary>Creates a new instance of the <see cref="ILDelegateBuilder{TDelegate}"/> class.</summary>
/// <param name="fields">The field builder.</param>
/// <param name="name">The name of the new delegate.</param>
/// <param name="methodInfo">
/// The method info for <typeparamref name="TDelegate"/> delegates, used for determining parameter types.
/// </param>
public ILDelegateBuilder(ILFieldBuilder fields, string name, MethodInfo methodInfo)
{
this.fields = fields;
var returnType = methodInfo.ReturnType;
var parameterTypes = GetParameterTypes(methodInfo);
this.dynamicMethod = new DynamicMethod(
name,
returnType,
parameterTypes,
typeof(ILDelegateBuilder<>).GetTypeInfo().Module,
true);
this.il = this.dynamicMethod.GetILGenerator();
}
/// <summary>
/// Declares a local variable with the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The newly declared local.</returns>
public Local DeclareLocal(Type type) => new IlGeneratorLocal(this.il.DeclareLocal(type));
/// <summary>
/// Loads the argument at the given index onto the stack.
/// </summary>
/// <param name="index">
/// The index of the argument to load.
/// </param>
public void LoadArgument(ushort index)
{
switch (index)
{
case 0:
this.il.Emit(OpCodes.Ldarg_0);
break;
case 1:
this.il.Emit(OpCodes.Ldarg_1);
break;
case 2:
this.il.Emit(OpCodes.Ldarg_2);
break;
case 3:
this.il.Emit(OpCodes.Ldarg_3);
break;
default:
if (index < 0xFF)
{
this.il.Emit(OpCodes.Ldarg_S, (byte)index);
}
else
{
this.il.Emit(OpCodes.Ldarg, index);
}
break;
}
}
/// <summary>
/// Loads the element from the array on the stack at the given index onto the stack.
/// </summary>
public void LoadReferenceElement()
{
this.il.Emit(OpCodes.Ldelem_Ref);
}
/// <summary>
/// Loads the provided constant integer value onto the stack.
/// </summary>
public void LoadConstant(int value)
{
switch (value)
{
case 0:
this.il.Emit(OpCodes.Ldc_I4_0);
break;
case 1:
this.il.Emit(OpCodes.Ldc_I4_1);
break;
case 2:
this.il.Emit(OpCodes.Ldc_I4_2);
break;
case 3:
this.il.Emit(OpCodes.Ldc_I4_3);
break;
case 4:
this.il.Emit(OpCodes.Ldc_I4_4);
break;
case 5:
this.il.Emit(OpCodes.Ldc_I4_5);
break;
case 6:
this.il.Emit(OpCodes.Ldc_I4_6);
break;
case 7:
this.il.Emit(OpCodes.Ldc_I4_7);
break;
case 8:
this.il.Emit(OpCodes.Ldc_I4_8);
break;
default:
if (value < 0xFF)
{
this.il.Emit(OpCodes.Ldc_I4_S, (byte) value);
}
else
{
this.il.Emit(OpCodes.Ldc_I4, value);
}
break;
}
}
/// <summary>
/// Pops the stack and stores it in the specified local.
/// </summary>
/// <param name="local">The local variable to store into.</param>
public void StoreLocal(Local local)
{
var loc = (IlGeneratorLocal)local;
var index = loc.Value.LocalIndex;
switch (index)
{
case 0:
this.il.Emit(OpCodes.Stloc_0);
break;
case 1:
this.il.Emit(OpCodes.Stloc_1);
break;
case 2:
this.il.Emit(OpCodes.Stloc_2);
break;
case 3:
this.il.Emit(OpCodes.Stloc_3);
break;
default:
if (index < 0xFF)
{
this.il.Emit(OpCodes.Stloc_S, (byte)index);
}
else
{
this.il.Emit(OpCodes.Stloc, loc);
}
break;
}
}
/// <summary>
/// Pushes the specified local onto the stack.
/// </summary>
/// <param name="local">The local variable to load from.</param>
public void LoadLocal(Local local)
{
var loc = (IlGeneratorLocal)local;
var index = loc.Value.LocalIndex;
switch (index)
{
case 0:
this.il.Emit(OpCodes.Ldloc_0);
break;
case 1:
this.il.Emit(OpCodes.Ldloc_1);
break;
case 2:
this.il.Emit(OpCodes.Ldloc_2);
break;
case 3:
this.il.Emit(OpCodes.Ldloc_3);
break;
default:
if (index < 0xFF)
{
this.il.Emit(OpCodes.Ldloc_S, (byte)index);
}
else
{
this.il.Emit(OpCodes.Ldloc, loc);
}
break;
}
}
/// <summary>
/// Loads the specified field onto the stack from the referenced popped from the stack.
/// </summary>
/// <param name="field">The field.</param>
public void LoadField(FieldInfo field)
{
if (field.IsStatic)
{
this.il.Emit(OpCodes.Ldsfld, field);
}
else
{
this.il.Emit(OpCodes.Ldfld, field);
}
}
/// <summary>
/// Boxes the value on the top of the stack.
/// </summary>
/// <param name="type">The value type.</param>
public void Box(Type type) => this.il.Emit(OpCodes.Box, type);
/// <summary>
/// Loads the specified type and pushes it onto the stack.
/// </summary>
/// <param name="type">The type to load.</param>
public void LoadType(Type type)
{
var field = this.fields.GetOrCreateStaticField(type);
this.il.Emit(OpCodes.Ldsfld, field);
}
/// <summary>
/// Calls the specified method.
/// </summary>
/// <param name="method">The method to call.</param>
public void Call(MethodInfo method)
{
if (method.IsFinal || !method.IsVirtual) this.il.Emit(OpCodes.Call, method);
else this.il.Emit(OpCodes.Callvirt, method);
}
/// <summary>
/// Returns from the current method.
/// </summary>
public void Return() => this.il.Emit(OpCodes.Ret);
/// <summary>
/// Pops the value on the top of the stack and stores it in the specified field on the object popped from the top of the stack.
/// </summary>
/// <param name="field">The field to store into.</param>
public void StoreField(FieldInfo field)
{
if (field.IsStatic)
{
this.il.Emit(OpCodes.Stsfld, field);
}
else
{
this.il.Emit(OpCodes.Stfld, field);
}
}
/// <summary>
/// Pushes the address of the specified local onto the stack.
/// </summary>
/// <param name="local">The local variable.</param>
public void LoadLocalAddress(Local local)
{
var loc = (IlGeneratorLocal)local;
var index = loc.Value.LocalIndex;
if (index < 0xFF)
{
this.il.Emit(OpCodes.Ldloca_S, (byte)index);
}
else
{
this.il.Emit(OpCodes.Ldloca, loc);
}
}
/// <summary>
/// Unboxes the value on the top of the stack.
/// </summary>
/// <param name="type">The value type.</param>
public void UnboxAny(Type type) => this.il.Emit(OpCodes.Unbox_Any, type);
/// <summary>
/// Casts the object on the top of the stack to the specified type.
/// </summary>
/// <param name="type">The type.</param>
public void CastClass(Type type) => this.il.Emit(OpCodes.Castclass, type);
/// <summary>
/// Initializes the value type on the stack, setting all fields to their default value.
/// </summary>
/// <param name="type">The value type.</param>
public void InitObject(Type type) => this.il.Emit(OpCodes.Initobj, type);
/// <summary>
/// Constructs a new instance of the object with the specified constructor.
/// </summary>
/// <param name="constructor">The constructor to call.</param>
public void NewObject(ConstructorInfo constructor)
{
this.il.Emit(OpCodes.Newobj, constructor);
}
/// <summary>
/// Builds a delegate from the previously emitted instructions.
/// </summary>
/// <returns>The delegate.</returns>
public TDelegate CreateDelegate()
{
return this.dynamicMethod.CreateDelegate(typeof(TDelegate)) as TDelegate;
}
/// <summary>
/// Pushes the specified local variable as a reference onto the stack.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="local">The local.</param>
public void LoadLocalAsReference(Type type, Local local)
{
if (type.GetTypeInfo().IsValueType)
{
this.LoadLocalAddress(local);
}
else
{
this.LoadLocal(local);
}
}
/// <summary>
/// Boxes the value on the top of the stack if it's a value type.
/// </summary>
/// <param name="type">The type.</param>
public void BoxIfValueType(Type type)
{
if (type.GetTypeInfo().IsValueType)
{
this.Box(type);
}
}
/// <summary>
/// Casts or unboxes the value at the top of the stack into the specified type.
/// </summary>
/// <param name="type">The type.</param>
public void CastOrUnbox(Type type)
{
if (type.GetTypeInfo().IsValueType)
{
this.UnboxAny(type);
}
else
{
this.CastClass(type);
}
}
/// <summary>
/// Creates a new instance of the specified type and stores it in the specified local.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="local">The local.</param>
/// <param name="getUninitializedObject">The method used to get an uninitialized instance of a type.</param>
public void CreateInstance(Type type, Local local, MethodInfo getUninitializedObject)
{
var constructorInfo = type.GetConstructor(Type.EmptyTypes);
if (type.GetTypeInfo().IsValueType)
{
this.LoadLocalAddress(local);
this.InitObject(type);
}
else if (constructorInfo != null)
{
// Use the default constructor.
this.NewObject(constructorInfo);
this.StoreLocal(local);
}
else
{
this.LoadType(type);
this.Call(getUninitializedObject);
this.CastClass(type);
this.StoreLocal(local);
}
}
private static Type[] GetParameterTypes(MethodInfo method)
{
var parameters = method.GetParameters();
var result = new Type[parameters.Length];
for (var i = 0; i < parameters.Length; ++i)
{
result[i] = parameters[i].ParameterType;
}
return result;
}
/// <summary>
/// Represents a local variable created via a call to <see cref="DeclareLocal"/>.
/// </summary>
internal abstract class Local
{
}
private class IlGeneratorLocal : Local
{
public readonly LocalBuilder Value;
public IlGeneratorLocal(LocalBuilder value)
{
this.Value = value;
}
public static implicit operator LocalBuilder(IlGeneratorLocal local) => local.Value;
}
}
}
| |
using System.Collections.Generic;
using System.Drawing;
namespace GuiLabs.Canvas.DrawStyle
{
using GuiLabs.Canvas.Renderer;
using StyleDic = Dictionary<string, IShapeStyle>;
using System.Xml;
using GuiLabs.Utils;
/// <summary>
/// Globally visible singleton collection of all Styles for all Layouts.
/// </summary>
public class StyleFactory : IStyleFactory
{
#region AddStyle
public void AddStyle(string name, IShapeStyle existingStyleToAdd)
{
//existingStyleToAdd.Name = name;
Add(name, existingStyleToAdd);
}
public void AddStyle(
string name,
Color fillColor)
{
Add(name,
new ShapeStyle(fillColor));
}
public void AddStyle(
string name,
Color borderColor,
Color fillColor)
{
Add(name,
new ShapeStyle(borderColor, fillColor));
}
public void AddStyle(
string name,
Color borderColor,
IFillStyleInfo fill)
{
Add(name,
new ShapeStyle(borderColor, fill));
}
public void AddStyle(
string name,
Color borderColor,
Color fillColor,
Color fontColor)
{
ShapeStyle s = new ShapeStyle();
s.FontStyleInfo.ForeColor = fontColor;
s.LineColor = borderColor;
s.FillColor = fillColor;
Add(name, s);
}
public void AddStyle(
string name,
Color borderColor,
Color fillColor,
Color fontColor,
string fontName)
{
AddStyle(
name,
borderColor,
fillColor,
fontColor,
fontName,
ShapeStyle.DefaultFontSize,
FontStyle.Regular);
}
public void AddStyle(
string name,
Color borderColor,
Color fillColor,
Color fontColor,
int fontSize)
{
AddStyle(
name,
borderColor,
fillColor,
fontColor,
ShapeStyle.DefaultFont,
fontSize,
FontStyle.Regular);
}
public void AddStyle(
string name,
Color borderColor,
Color fillColor,
Color fontColor,
FontStyle fontStyle)
{
AddStyle(
name,
borderColor,
fillColor,
fontColor,
ShapeStyle.DefaultFont,
ShapeStyle.DefaultFontSize,
fontStyle);
}
public void AddStyle(
string name,
Color borderColor,
Color fillColor,
Color fontColor,
string fontName,
int fontSize,
FontStyle fontStyle)
{
ShapeStyle s = new ShapeStyle();
s.LineColor = borderColor;
s.FillColor = fillColor;
s.FontStyleInfo = RendererSingleton.StyleFactory.ProduceNewFontStyleInfo(fontName, fontSize, fontStyle);
s.FontStyleInfo.ForeColor = fontColor;
Add(name, s);
}
public void AddStyle(
string name,
Color borderColor,
Color fillColor,
Color gradientColor,
FillMode gradientMode)
{
Add(name,
new ShapeStyle(
borderColor,
fillColor,
gradientColor,
gradientMode));
}
#endregion
#region Singleton Instances
private static StyleFactory mInstance;
public static StyleFactory Instance
{
get
{
if (mInstance == null)
{
mInstance = new StyleFactory();
}
return mInstance;
}
set
{
mInstance = value;
}
}
#endregion
#region Hash
/// <summary>
/// (String -> ShapeStyle) hashtable.
/// Not visible from outside.
/// </summary>
private StyleDic mStyleList = new StyleDic();
private StyleDic StyleList
{
get
{
return mStyleList;
}
}
public void Clear()
{
StyleList.Clear();
}
#endregion
/// <param name="shapeType">Typically Layout.StyleName</param>
/// <returns>ShapeStyle with the specified name, if it exists, null otherwise.
/// </returns>
public IShapeStyle GetStyle(string shapeType)
{
// It's OK when there are no styles, GetStyle will just return null.
/*if (!IsInit)
{
Init();
}
*/
IShapeStyle result = null;
StyleList.TryGetValue(shapeType, out result);
return result;
}
#region AddAlias
public void AddAliasAndSelected(string name, string existingStyleName)
{
AddAlias(name, existingStyleName);
AddAlias(name + "_selected", existingStyleName + "_selected");
}
public void AddAlias(string name, string existingStyleName)
{
IShapeStyle existing = GetStyle(existingStyleName);
if (existing != null)
{
Add(name, existing);
}
}
#endregion
#region Add
public void Add(string name, IShapeStyle existingStyle)
{
if (existingStyle == null)
{
return;
}
if (string.IsNullOrEmpty(existingStyle.Name))
{
existingStyle.Name = name;
}
StyleList.Add(name, existingStyle);
}
#endregion
#region Enumerator
public IEnumerator<IShapeStyle> GetEnumerator()
{
return StyleList.Values.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region SaveToFile
public void SaveToFile(string fileName)
{
CreateSnapshot().SaveToFile(fileName);
}
public Memento CreateSnapshot()
{
Memento result = new Memento();
result.NodeType = "ShapeStyles";
foreach (KeyValuePair<string, IShapeStyle> pair in StyleList)
{
Memento styleSnapshot = pair.Value.CreateSnapshot();
styleSnapshot["name"] = pair.Key;
result.Add(styleSnapshot);
}
return result;
}
public static StyleFactory LoadFromFile(string fileName)
{
StyleFactory result = new StyleFactory();
Memento styles = Memento.ReadFromFile(fileName);
foreach (Memento s in styles.Children)
{
ShapeStyle newStyle = ShapeStyle.CreateFromMemento(s);
result.Add(newStyle.Name, newStyle);
}
return result;
}
#endregion
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace Dynastream.Fit
{
/// <summary>
/// Implements the Activity profile message.
/// </summary>
public class ActivityMesg : Mesg
{
#region Fields
#endregion
#region Constructors
public ActivityMesg() : base(Profile.mesgs[Profile.ActivityIndex])
{
}
public ActivityMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the Timestamp field</summary>
/// <returns>Returns DateTime representing the Timestamp field</returns>
public DateTime GetTimestamp()
{
return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set Timestamp field</summary>
/// <param name="timestamp_">Nullable field value to be set</param>
public void SetTimestamp(DateTime timestamp_)
{
SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TotalTimerTime field
/// Units: s
/// Comment: Exclude pauses</summary>
/// <returns>Returns nullable float representing the TotalTimerTime field</returns>
public float? GetTotalTimerTime()
{
return (float?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TotalTimerTime field
/// Units: s
/// Comment: Exclude pauses</summary>
/// <param name="totalTimerTime_">Nullable field value to be set</param>
public void SetTotalTimerTime(float? totalTimerTime_)
{
SetFieldValue(0, 0, totalTimerTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the NumSessions field</summary>
/// <returns>Returns nullable ushort representing the NumSessions field</returns>
public ushort? GetNumSessions()
{
return (ushort?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set NumSessions field</summary>
/// <param name="numSessions_">Nullable field value to be set</param>
public void SetNumSessions(ushort? numSessions_)
{
SetFieldValue(1, 0, numSessions_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Type field</summary>
/// <returns>Returns nullable Activity enum representing the Type field</returns>
new public Activity? GetType()
{
object obj = GetFieldValue(2, 0, Fit.SubfieldIndexMainField);
Activity? value = obj == null ? (Activity?)null : (Activity)obj;
return value;
}
/// <summary>
/// Set Type field</summary>
/// <param name="type_">Nullable field value to be set</param>
public void SetType(Activity? type_)
{
SetFieldValue(2, 0, type_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Event field</summary>
/// <returns>Returns nullable Event enum representing the Event field</returns>
public Event? GetEvent()
{
object obj = GetFieldValue(3, 0, Fit.SubfieldIndexMainField);
Event? value = obj == null ? (Event?)null : (Event)obj;
return value;
}
/// <summary>
/// Set Event field</summary>
/// <param name="event_">Nullable field value to be set</param>
public void SetEvent(Event? event_)
{
SetFieldValue(3, 0, event_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the EventType field</summary>
/// <returns>Returns nullable EventType enum representing the EventType field</returns>
public EventType? GetEventType()
{
object obj = GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
EventType? value = obj == null ? (EventType?)null : (EventType)obj;
return value;
}
/// <summary>
/// Set EventType field</summary>
/// <param name="eventType_">Nullable field value to be set</param>
public void SetEventType(EventType? eventType_)
{
SetFieldValue(4, 0, eventType_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the LocalTimestamp field
/// Comment: timestamp epoch expressed in local time, used to convert activity timestamps to local time </summary>
/// <returns>Returns nullable uint representing the LocalTimestamp field</returns>
public uint? GetLocalTimestamp()
{
return (uint?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set LocalTimestamp field
/// Comment: timestamp epoch expressed in local time, used to convert activity timestamps to local time </summary>
/// <param name="localTimestamp_">Nullable field value to be set</param>
public void SetLocalTimestamp(uint? localTimestamp_)
{
SetFieldValue(5, 0, localTimestamp_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the EventGroup field</summary>
/// <returns>Returns nullable byte representing the EventGroup field</returns>
public byte? GetEventGroup()
{
return (byte?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set EventGroup field</summary>
/// <param name="eventGroup_">Nullable field value to be set</param>
public void SetEventGroup(byte? eventGroup_)
{
SetFieldValue(6, 0, eventGroup_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
// 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.Linq;
using System.Net.Sockets;
using System.Net.Test.Common;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.NetworkInformation.Tests
{
[PlatformSpecific(TestPlatforms.OSX)]
public class IPInterfacePropertiesTest_OSX
{
private readonly ITestOutputHelper _log;
public IPInterfacePropertiesTest_OSX()
{
_log = TestLogging.GetInstance();
}
[Fact]
public void IPInfoTest_AccessAllProperties_NoErrors()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("Nic: " + nic.Name);
_log.WriteLine("- Supports IPv4: " + nic.Supports(NetworkInterfaceComponent.IPv4));
_log.WriteLine("- Supports IPv6: " + nic.Supports(NetworkInterfaceComponent.IPv6));
IPInterfaceProperties ipProperties = nic.GetIPProperties();
Assert.NotNull(ipProperties);
Assert.Throws<PlatformNotSupportedException>(() => ipProperties.AnycastAddresses);
Assert.Throws<PlatformNotSupportedException>(() => ipProperties.DhcpServerAddresses);
try
{
Assert.NotNull(ipProperties.DnsAddresses);
_log.WriteLine("- Dns Addresses: " + ipProperties.DnsAddresses.Count);
foreach (IPAddress dns in ipProperties.DnsAddresses)
{
_log.WriteLine("-- " + dns.ToString());
}
Assert.NotNull(ipProperties.DnsSuffix);
_log.WriteLine("- Dns Suffix: " + ipProperties.DnsSuffix);
}
// If /etc/resolv.conf does not exist, DNS values cannot be retrieved.
catch (PlatformNotSupportedException) { }
Assert.NotNull(ipProperties.GatewayAddresses);
_log.WriteLine("- Gateway Addresses: " + ipProperties.GatewayAddresses.Count);
foreach (GatewayIPAddressInformation gateway in ipProperties.GatewayAddresses)
{
_log.WriteLine("-- " + gateway.Address.ToString());
}
Assert.Throws<PlatformNotSupportedException>(() => ipProperties.IsDnsEnabled);
Assert.Throws<PlatformNotSupportedException>(() => ipProperties.IsDynamicDnsEnabled);
Assert.NotNull(ipProperties.MulticastAddresses);
_log.WriteLine("- Multicast Addresses: " + ipProperties.MulticastAddresses.Count);
foreach (IPAddressInformation multi in ipProperties.MulticastAddresses)
{
_log.WriteLine("-- " + multi.Address.ToString());
Assert.Throws<PlatformNotSupportedException>(() => multi.IsDnsEligible);
Assert.Throws<PlatformNotSupportedException>(() => multi.IsTransient);
}
Assert.NotNull(ipProperties.UnicastAddresses);
_log.WriteLine("- Unicast Addresses: " + ipProperties.UnicastAddresses.Count);
foreach (UnicastIPAddressInformation uni in ipProperties.UnicastAddresses)
{
_log.WriteLine("-- " + uni.Address.ToString());
Assert.Throws<PlatformNotSupportedException>(() => uni.AddressPreferredLifetime);
Assert.Throws<PlatformNotSupportedException>(() => uni.AddressValidLifetime);
Assert.Throws<PlatformNotSupportedException>(() => uni.DhcpLeaseLifetime);
Assert.Throws<PlatformNotSupportedException>(() => uni.DuplicateAddressDetectionState);
Assert.NotNull(uni.IPv4Mask);
_log.WriteLine("--- IPv4 Mask: " + uni.IPv4Mask);
Assert.Throws<PlatformNotSupportedException>(() => uni.IsDnsEligible);
Assert.Throws<PlatformNotSupportedException>(() => uni.IsTransient);
Assert.Throws<PlatformNotSupportedException>(() => uni.PrefixOrigin);
Assert.Throws<PlatformNotSupportedException>(() => uni.SuffixOrigin);
// Prefix Length
_log.WriteLine("--- PrefixLength: " + uni.PrefixLength);
Assert.True(uni.PrefixLength > 0);
Assert.True((uni.Address.AddressFamily == AddressFamily.InterNetwork ? 33 : 129) > uni.PrefixLength);
}
Assert.Throws<PlatformNotSupportedException>(() => ipProperties.WinsServersAddresses);
}
}
[Fact]
public void IPInfoTest_AccessAllIPv4Properties_NoErrors()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("Nic: " + nic.Name);
IPInterfaceProperties ipProperties = nic.GetIPProperties();
_log.WriteLine("IPv4 Properties:");
IPv4InterfaceProperties ipv4Properties = ipProperties.GetIPv4Properties();
_log.WriteLine("Index: " + ipv4Properties.Index);
Assert.Throws<PlatformNotSupportedException>(() => ipv4Properties.IsAutomaticPrivateAddressingActive);
Assert.Throws<PlatformNotSupportedException>(() => ipv4Properties.IsAutomaticPrivateAddressingEnabled);
Assert.Throws<PlatformNotSupportedException>(() => ipv4Properties.IsDhcpEnabled);
Assert.Throws<PlatformNotSupportedException>(() => ipv4Properties.IsForwardingEnabled);
_log.WriteLine("Mtu: " + ipv4Properties.Mtu);
Assert.Throws<PlatformNotSupportedException>(() => ipv4Properties.UsesWins);
}
}
[Fact]
public void IPInfoTest_AccessAllIPv6Properties_NoErrors()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("Nic: " + nic.Name);
IPInterfaceProperties ipProperties = nic.GetIPProperties();
_log.WriteLine("IPv6 Properties:");
IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties();
if (ipv6Properties == null)
{
_log.WriteLine("IPv6Properties is null");
continue;
}
_log.WriteLine("Index: " + ipv6Properties.Index);
_log.WriteLine("Mtu: " + ipv6Properties.Mtu);
Assert.Throws<PlatformNotSupportedException>(() => ipv6Properties.GetScopeId(ScopeLevel.Link));
}
}
[Fact]
[Trait("IPv6", "true")]
public void IPv6ScopeId_AccessAllValues_Success()
{
Assert.True(Capability.IPv6Support());
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("Nic: " + nic.Name);
if (!nic.Supports(NetworkInterfaceComponent.IPv6))
{
continue;
}
IPInterfaceProperties ipProperties = nic.GetIPProperties();
IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties();
Array values = Enum.GetValues(typeof(ScopeLevel));
foreach (ScopeLevel level in values)
{
Assert.Throws<PlatformNotSupportedException>(() => ipv6Properties.GetScopeId(level));
}
}
}
[Fact]
[Trait("IPv4", "true")]
public void IPInfoTest_IPv4Loopback_ProperAddress()
{
Assert.True(Capability.IPv4Support());
_log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex);
NetworkInterface loopback = NetworkInterface.GetAllNetworkInterfaces().First(ni => ni.Name == "lo0");
Assert.NotNull(loopback);
foreach (UnicastIPAddressInformation unicast in loopback.GetIPProperties().UnicastAddresses)
{
if (unicast.Address.Equals(IPAddress.Loopback))
{
Assert.Equal(IPAddress.Parse("255.0.0.0"), unicast.IPv4Mask);
Assert.Equal(8, unicast.PrefixLength);
break;
}
}
}
[Fact]
[Trait("IPv6", "true")]
public void IPInfoTest_IPv6Loopback_ProperAddress()
{
Assert.True(Capability.IPv6Support());
_log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex);
NetworkInterface loopback = NetworkInterface.GetAllNetworkInterfaces().First(ni => ni.Name == "lo0");
Assert.NotNull(loopback);
foreach (UnicastIPAddressInformation unicast in loopback.GetIPProperties().UnicastAddresses)
{
if (unicast.Address.Equals(IPAddress.IPv6Loopback))
{
Assert.Equal(128, unicast.PrefixLength);
break;
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.