context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMoq;
using FizzWare.NBuilder;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NerdBudget.Core.Models;
using NerdBudget.Core.Services;
using NerdBudget.Web;
using NerdBudget.Web.ApiControllers;
using Newtonsoft.Json;
namespace NerdBudget.Tests.Web.ApiControllers
{
[TestClass]
public class LedgersControllerTests : ControllerTestHelper<Ledger>
{
#region Helpers/Test Initializers
private AutoMoqer Mocker { get; set; }
private Mock<IAccountService> MockService { get; set; }
private LedgersController SubjectUnderTest { get; set; }
[TestInitialize]
public void TestInitialize()
{
Mocker = new AutoMoqer();
SubjectUnderTest = Mocker.Create<LedgersController>();
SubjectUnderTest.Request = new HttpRequestMessage();
SubjectUnderTest.Configuration = new HttpConfiguration();
MockService = Mocker.GetMock<IAccountService>();
}
private Account GetAccount(bool includeLedgers)
{
var account = Builder<Account>.CreateNew().With(x => x.Id = "x").Build();
if (includeLedgers)
{
var ledgers = new[] { new Ledger { OriginalText = Helpers.OriginalLedgerText } };
account.Ledgers.AddRange(ledgers);
}
var category = Builder<Category>.CreateNew().Build();
account.Categories.Add(category);
var budget = Builder<Budget>.CreateNew().Build();
category.Budgets.Add(budget);
return account;
}
private JsonSerializerSettings GetPayloadSettings()
{
return PayloadManager
.AddPayload<Account>("Id,Name")
.AddPayload<Budget>("Id,FullName")
.AddStandardPayload<Ledger>()
.ToSettings();
}
#endregion
#region Tests - Importing
[TestMethod]
public void LedgersController_PostImport_Should_SendOk()
{
// arrange
var account = GetAccount(false);
var text = "02/09/2015 NN NNNNN 9999 NNN# 9999993 99999 NNNNNNN NNNN $1,499.99 $1,138.52 NNNNNNNNNNN NNNNNNN";
var trx = new LedgersController.Trx { Transactions = text };
MockService.Setup(x => x.Get(account.Id)).Returns(account);
MockService.Setup(x => x.Save(account.Ledgers));
MockService.Setup(x => x.Save(account.Balances));
// act
var msg = SubjectUnderTest.PostImport(account.Id, trx).ToMessage();
// assert
Assert.IsTrue(msg.IsSuccessStatusCode);
Assert.AreEqual(1, account.Ledgers.Count);
// month-end, and week-end for 2/9
Assert.AreEqual(2, account.Balances.Count);
MockService.VerifyAll();
}
[TestMethod]
public void LedgersController_PostImport_Should_NotFound()
{
// arrange
var account = GetAccount(false);
var text = "02/09/2015 NN NNNNN 9999 NNN# 9999993 99999 NNNNNNN NNNN $1,499.99 $1,138.52 NNNNNNNNNNN NNNNNNN";
var trx = new LedgersController.Trx { Transactions = text };
MockService.Setup(x => x.Get(account.Id)).Returns(null as Account);
// act
var msg = SubjectUnderTest.PostImport(account.Id, trx).ToMessage();
// assert
Assert.IsTrue(msg.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
}
#endregion
#region Tests - Get Many
[TestMethod]
public void LedgersController_GetMany_Should_SendOk()
{
// arrange
var account = GetAccount(true);
var ledger = account.Ledgers.Last();
ledger.BudgetId = account.Categories.First().Budgets.First().Id;
var settings = GetPayloadSettings();
MockService.Setup(x => x.Get(account.Id)).Returns(account);
// act
var msg = SubjectUnderTest.GetLedgers(ledger.AccountId, ledger.BudgetId, ledger.Date).ToMessage();
// assert
Assert.IsTrue(msg.IsSuccessStatusCode);
msg.Content.AssertJsonObjectEquality(account.Ledgers, settings);
MockService.VerifyAll();
}
[TestMethod]
public void LedgersController_GetMany_Should_SendEmptySet()
{
// arrange
var account = GetAccount(true);
var ledger = account.Ledgers.Last();
ledger.BudgetId = account.Categories.First().Budgets.First().Id;
var settings = GetPayloadSettings();
MockService.Setup(x => x.Get(account.Id)).Returns(account);
// act
var msg = SubjectUnderTest.GetLedgers(ledger.AccountId, ledger.BudgetId, ledger.Date.AddDays(7)).ToMessage();
// assert
Assert.IsTrue(msg.IsSuccessStatusCode);
msg.Content.AssertJsonObjectEquality(new Ledger[0], settings);
MockService.VerifyAll();
}
[TestMethod]
public void LedgersController_GetMany_Should_SendNotFound_Account()
{
// arrange
var account = GetAccount(true);
var ledger = account.Ledgers.Last();
MockService.Setup(x => x.Get(account.Id)).Returns(null as Account);
// act
var msg = SubjectUnderTest.Get(ledger.AccountId, ledger.Id, ledger.Date).ToMessage();
// assert
Assert.IsTrue(msg.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
}
#endregion
#region Tests - Get One
[TestMethod]
public void LedgersController_GetOne_Should_SendOk()
{
// arrange
var account = GetAccount(true);
var ledger = account.Ledgers.Last();
var settings = GetPayloadSettings();
var model = new
{
account = account,
budgets = account.Categories.SelectMany(x => x.Budgets),
ledger = ledger
};
MockService.Setup(x => x.Get(account.Id)).Returns(account);
// act
var msg = SubjectUnderTest.Get(ledger.AccountId, ledger.Id, ledger.Date).ToMessage();
// assert
Assert.IsTrue(msg.IsSuccessStatusCode);
msg.Content.AssertJsonObjectEquality(model, settings);
MockService.VerifyAll();
}
[TestMethod]
public void LedgersController_GetOne_Should_SendNotFound_Account()
{
// arrange
var account = GetAccount(true);
var ledger = account.Ledgers.Last();
MockService.Setup(x => x.Get(account.Id)).Returns(null as Account);
// act
var msg = SubjectUnderTest.Get(ledger.AccountId, ledger.Id, ledger.Date).ToMessage();
// assert
Assert.IsTrue(msg.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
}
[TestMethod]
public void LedgersController_GetOne_Should_SendNotFound_Ledger()
{
// arrange
var account = GetAccount(true);
var ledger = account.Ledgers.Last();
account.Ledgers.Clear();
MockService.Setup(x => x.Get(account.Id)).Returns(account);
// act
var msg = SubjectUnderTest.Get(ledger.AccountId, ledger.Id, ledger.Date).ToMessage();
// assert
Assert.IsTrue(msg.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
}
#endregion
#region Tests - Put One
[TestMethod]
public void LedgersController_PutOne_Should_SendOk()
{
// arrange
var account = GetAccount(true);
var ledger = account.Ledgers.Last();
ledger.BudgetId = account.Categories.First().Budgets.First().Id;
MockService.Setup(x => x.Get(account.Id)).Returns(account);
MockService.Setup(x => x.Save(account.Ledgers));
MockService.Setup(x => x.Save(account.Maps));
// act
var msg = SubjectUnderTest.Put(ledger.AccountId, ledger.Id, ledger.Date, ledger).ToMessage();
// assert
Assert.IsTrue(msg.IsSuccessStatusCode);
MockService.VerifyAll();
}
[TestMethod]
public void LedgersController_PutOne_Should_SendNotFound_Account()
{
// arrange
var account = GetAccount(true);
var ledger = account.Ledgers.Last();
MockService.Setup(x => x.Get(account.Id)).Returns(null as Account);
// act
var msg = SubjectUnderTest.Put(ledger.AccountId, ledger.Id, ledger.Date, ledger).ToMessage();
// assert
Assert.IsTrue(msg.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
}
[TestMethod]
public void LedgersController_PutOne_Should_SendNotFound_Ledger()
{
// arrange
var account = GetAccount(true);
var ledger = account.Ledgers.Last();
account.Ledgers.Clear();
MockService.Setup(x => x.Get(account.Id)).Returns(account);
// act
var msg = SubjectUnderTest.Put(ledger.AccountId, ledger.Id, ledger.Date, ledger).ToMessage();
// assert
Assert.IsTrue(msg.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
}
#endregion
}
}
| |
namespace System.Workflow.ComponentModel.Design
{
using System;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Runtime.Serialization;
using System.Workflow.ComponentModel.Compiler;
using System.ComponentModel.Design.Serialization;
using System.Workflow.ComponentModel.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Diagnostics.CodeAnalysis;
internal class XomlComponentSerializationService : ComponentSerializationService
{
private IServiceProvider serviceProvider = null;
internal XomlComponentSerializationService(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public override SerializationStore CreateStore()
{
return new WorkflowMarkupSerializationStore(this.serviceProvider);
}
public override SerializationStore LoadStore(Stream stream)
{
if (stream == null) throw new ArgumentNullException("stream");
BinaryFormatter f = new BinaryFormatter();
return (WorkflowMarkupSerializationStore)f.Deserialize(stream);
}
// error CS0534: 'System.Workflow.ComponentModel.Design.XomlComponentSerializationService' does not implement inherited abstract member 'System.ComponentModel.Design.Serialization.ComponentSerializationService.SerializeAbsolute(System.ComponentModel.Design.Serialization.SerializationStore, object)'
public override void SerializeAbsolute(SerializationStore store, object value)
{
this.Serialize(store, value);
}
public override void Serialize(SerializationStore store, object value)
{
if (store == null) throw new ArgumentNullException("store");
if (value == null) throw new ArgumentNullException("value");
WorkflowMarkupSerializationStore xomlStore = store as WorkflowMarkupSerializationStore;
if (xomlStore == null) throw new InvalidOperationException(SR.GetString(SR.Error_UnknownSerializationStore));
xomlStore.AddObject(value);
}
//error CS0534: 'System.Workflow.ComponentModel.Design.XomlComponentSerializationService' does not implement inherited abstract member 'System.ComponentModel.Design.Serialization.ComponentSerializationService.SerializeMemberAbsolute(System.ComponentModel.Design.Serialization.SerializationStore, object, System.ComponentModel.MemberDescriptor)'
public override void SerializeMemberAbsolute(SerializationStore store, object owningObject, MemberDescriptor member)
{
this.SerializeMember(store, owningObject, member);
}
public override void SerializeMember(SerializationStore store, object owningObject, MemberDescriptor member)
{
if (store == null) throw new ArgumentNullException("store");
if (owningObject == null) throw new ArgumentNullException("owningObject");
if (member == null) throw new ArgumentNullException("member");
WorkflowMarkupSerializationStore xomlStore = store as WorkflowMarkupSerializationStore;
if (xomlStore == null) throw new InvalidOperationException(SR.GetString(SR.Error_UnknownSerializationStore));
xomlStore.AddMember(owningObject, member);
}
public override ICollection Deserialize(SerializationStore store)
{
if (store == null) throw new ArgumentNullException("store");
WorkflowMarkupSerializationStore xomlStore = store as WorkflowMarkupSerializationStore;
if (xomlStore == null) throw new InvalidOperationException(SR.GetString(SR.Error_UnknownSerializationStore));
return (ICollection)xomlStore.Deserialize(this.serviceProvider);
}
public override ICollection Deserialize(SerializationStore store, IContainer container)
{
if (store == null) throw new ArgumentNullException("store");
if (container == null) throw new ArgumentNullException("container");
WorkflowMarkupSerializationStore xomlStore = store as WorkflowMarkupSerializationStore;
if (xomlStore == null) throw new InvalidOperationException(SR.GetString(SR.Error_UnknownSerializationStore));
return xomlStore.Deserialize(this.serviceProvider, container);
}
// build 40409
// error CS0115: 'System.Workflow.ComponentModel.Design.XomlComponentSerializationService.DeserializeTo(System.ComponentModel.Design.Serialization.SerializationStore, System.ComponentModel.IContainer)': no suitable method found to override
// build 40420
// error CS0506: 'System.Workflow.ComponentModel.Design.XomlComponentSerializationService.DeserializeTo(System.ComponentModel.Design.Serialization.SerializationStore, System.ComponentModel.IContainer, bool)': cannot override inherited member 'System.ComponentModel.Design.Serialization.ComponentSerializationService.DeserializeTo(System.ComponentModel.Design.Serialization.SerializationStore, System.ComponentModel.IContainer, bool)' because it is not marked virtual, abstract, or override
public override void DeserializeTo(SerializationStore store, IContainer container, bool validateRecycledTypes, bool applyDefaults)
{
//
if (store == null) throw new ArgumentNullException("store");
if (container == null) throw new ArgumentNullException("container");
WorkflowMarkupSerializationStore xomlStore = store as WorkflowMarkupSerializationStore;
if (xomlStore == null) throw new InvalidOperationException(SR.GetString(SR.Error_UnknownSerializationStore));
xomlStore.DeserializeTo(this.serviceProvider, container);
}
internal static PropertyInfo GetProperty(Type type, string name, BindingFlags bindingFlags)
{
PropertyInfo propertyInfo = null;
try
{
propertyInfo = type.GetProperty(name, bindingFlags);
}
catch (AmbiguousMatchException)
{
// this will ensure properties with "new" keyword are detected
PropertyInfo[] properties = type.GetProperties(bindingFlags);
foreach (PropertyInfo prop in properties)
{
if (prop.Name.Equals(name, StringComparison.Ordinal))
{
propertyInfo = prop;
break;
}
}
}
return propertyInfo;
}
}
[Serializable]
internal class WorkflowMarkupSerializationStore : SerializationStore,
ISerializable
{
// keys used to persist data in binary stream
private const string SerializedXmlString = "XmlString";
private const string AssembliesKey = "Assemblies";
// these field are only used for Store creation.
private IServiceProvider serviceProvider = null;
private List<Activity> activities = new List<Activity>();
private List<string> parentObjectNameList = new List<string>();
private List<MemberDescriptor> memberList = new List<MemberDescriptor>();
// these fields persist across the store
private string serializedXmlString;
private AssemblyName[] assemblies;
internal WorkflowMarkupSerializationStore(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
private WorkflowMarkupSerializationStore(SerializationInfo info, StreamingContext context)
{
this.serializedXmlString = (String)info.GetValue(SerializedXmlString, typeof(String));
this.assemblies = (AssemblyName[])info.GetValue(AssembliesKey, typeof(AssemblyName[]));
}
private AssemblyName[] AssemblyNames
{
get
{
return this.assemblies;
}
}
internal void AddObject(object value)
{
if (this.serializedXmlString != null)
throw new InvalidOperationException(DR.GetString(DR.InvalidOperationStoreAlreadyClosed));
Activity activity = value as Activity;
if (activity == null)
throw new ArgumentException("value");
this.activities.Add(activity);
}
internal void AddMember(object value, MemberDescriptor member)
{
if (value == null)
throw new ArgumentNullException("value");
if (member == null)
throw new ArgumentNullException("member");
if (this.serializedXmlString != null)
throw new InvalidOperationException(DR.GetString(DR.InvalidOperationStoreAlreadyClosed));
IReferenceService referenceService = this.serviceProvider.GetService(typeof(IReferenceService)) as IReferenceService;
this.parentObjectNameList.Add(referenceService.GetName(value));
this.memberList.Add(member);
}
internal IList Deserialize(IServiceProvider serviceProvider)
{
DesignerSerializationManager serializationManager = new LocalDesignerSerializationManager(this, serviceProvider);
using (serializationManager.CreateSession())
{
ArrayList objects = new ArrayList();
WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(serializationManager);
XmlTextReader reader = new XmlTextReader(this.serializedXmlString, XmlNodeType.Element, null);
reader.MoveToElement();
do
{
if (!reader.Read())
return objects;
xomlSerializationManager.FoundDefTag += delegate(object sender, WorkflowMarkupElementEventArgs eventArgs)
{
if (eventArgs.XmlReader.LookupNamespace(eventArgs.XmlReader.Prefix) == StandardXomlKeys.Definitions_XmlNs &&
xomlSerializationManager.Context.Current is Activity
)
WorkflowMarkupSerializationHelpers.ProcessDefTag(xomlSerializationManager, eventArgs.XmlReader, xomlSerializationManager.Context.Current as Activity, true, string.Empty);
};
WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();
object activityDecl = xomlSerializer.DeserializeObject(xomlSerializationManager, reader);
if (activityDecl == null)
throw new InvalidOperationException(DR.GetString(DR.InvalidOperationDeserializationReturnedNonActivity));
if (activityDecl is Activity)
(activityDecl as Activity).UserData.Remove(UserDataKeys.CustomActivity);
objects.Add(activityDecl);
} while (true);
}
}
internal ICollection Deserialize(IServiceProvider serviceProvider, IContainer container)
{
throw new NotImplementedException();
}
internal void DeserializeTo(IServiceProvider serviceProvider, IContainer container)
{
DesignerSerializationManager serializationManager = new LocalDesignerSerializationManager(this, serviceProvider);
using (serializationManager.CreateSession())
{
WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(serializationManager);
PropertySegmentSerializationProvider propertySegmentSerializationProvider = new PropertySegmentSerializationProvider();
xomlSerializationManager.AddSerializationProvider(propertySegmentSerializationProvider);
StringReader stringReader = new StringReader(this.serializedXmlString);
using (XmlTextReader reader = new XmlTextReader(stringReader))
{
while (reader.NodeType != XmlNodeType.Element && reader.NodeType != XmlNodeType.ProcessingInstruction && reader.Read());
IReferenceService referenceService = this.serviceProvider.GetService(typeof(IReferenceService)) as IReferenceService;
IComponentChangeService componentChangeService = this.serviceProvider.GetService(typeof(IComponentChangeService)) as IComponentChangeService;
for (int loop = 0; loop < this.memberList.Count; loop++)
{
object obj = referenceService.GetReference(this.parentObjectNameList[loop]);
if (obj != null)
{
bool needChangeEvent = (componentChangeService != null) && (!(obj is IComponent) || (((IComponent)obj).Site == null));
PropertyDescriptor member = this.memberList[loop] as PropertyDescriptor;
if (needChangeEvent)
componentChangeService.OnComponentChanging(obj, member);
xomlSerializationManager.Context.Push(obj);
PropertySegmentSerializer serializer = new PropertySegmentSerializer(null);
PropertySegment propertySegment = serializer.DeserializeObject(xomlSerializationManager, reader) as PropertySegment;
System.Diagnostics.Debug.Assert(obj == xomlSerializationManager.Context.Current, "Serialization Store did not remove object which it pushed onto the stack.");
xomlSerializationManager.Context.Pop();
if (needChangeEvent)
componentChangeService.OnComponentChanged(obj, member, null, null);
}
}
}
xomlSerializationManager.RemoveSerializationProvider(propertySegmentSerializationProvider);
}
}
#region ISerializable implementation
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(SerializedXmlString, this.serializedXmlString);
info.AddValue(AssembliesKey, this.assemblies);
}
#endregion
#region SerializationStore overrides
public override void Save(Stream stream)
{
Close();
BinaryFormatter f = new BinaryFormatter();
f.Serialize(stream, this);
}
public override void Close()
{
if (this.serializedXmlString != null)
return;
DesignerSerializationManager serializationManager = new LocalDesignerSerializationManager(this, serviceProvider);
using (serializationManager.CreateSession())
{
// serialize all objects
WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(serializationManager);
StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
using (XmlTextWriter writer = new XmlTextWriter(stringWriter))
{
if (this.memberList.Count == 0)
{
WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();
foreach (Activity activity in this.activities)
xomlSerializer.SerializeObject(xomlSerializationManager, activity, writer);
}
else
{
PropertySegmentSerializationProvider propertySegmentSerializationProvider = new PropertySegmentSerializationProvider();
xomlSerializationManager.AddSerializationProvider(propertySegmentSerializationProvider);
xomlSerializationManager.Context.Push(new StringWriter(CultureInfo.InvariantCulture));
IReferenceService referenceService = this.serviceProvider.GetService(typeof(IReferenceService)) as IReferenceService;
if (referenceService != null)
{
for (int loop = 0; loop < this.memberList.Count; loop++)
{
object obj = referenceService.GetReference(this.parentObjectNameList[loop]);
PropertySegmentSerializer serializer = new PropertySegmentSerializer(null);
if (this.memberList[loop] is PropertyDescriptor)
{
PropertyInfo propertyInfo = XomlComponentSerializationService.GetProperty(obj.GetType(), (this.memberList[loop] as PropertyDescriptor).Name, BindingFlags.Public | BindingFlags.Instance);
if (propertyInfo != null)
serializer.SerializeObject(xomlSerializationManager, new PropertySegment(this.serviceProvider, obj, propertyInfo), writer);
else
serializer.SerializeObject(xomlSerializationManager, new PropertySegment(this.serviceProvider, obj, this.memberList[loop] as PropertyDescriptor), writer);
}
else if (this.memberList[loop] is EventDescriptor)
{
// Events.
IEventBindingService eventBindingService = this.serviceProvider.GetService(typeof(IEventBindingService)) as IEventBindingService;
if (eventBindingService != null)
{
PropertySegment propertySegment = new PropertySegment(serviceProvider, obj, eventBindingService.GetEventProperty(this.memberList[loop] as EventDescriptor));
serializer.SerializeObject(xomlSerializationManager, propertySegment, writer);
}
}
}
}
xomlSerializationManager.Context.Pop();
xomlSerializationManager.RemoveSerializationProvider(propertySegmentSerializationProvider);
}
}
this.serializedXmlString = stringWriter.ToString();
// store all the assembly names
List<AssemblyName> assemblyList = new List<AssemblyName>();
foreach (Activity activity in this.activities)
{
Assembly a = activity.GetType().Assembly;
assemblyList.Add(a.GetName(true));
}
this.assemblies = assemblyList.ToArray();
this.activities.Clear();
this.activities = null;
}
}
public override System.Collections.ICollection Errors
{
get
{
return null;
}
}
#endregion
#region Class LocalDesignerSerializationManager
private class LocalDesignerSerializationManager : DesignerSerializationManager
{
private WorkflowMarkupSerializationStore store;
internal LocalDesignerSerializationManager(WorkflowMarkupSerializationStore store, IServiceProvider provider)
: base(provider)
{
this.store = store;
}
[SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", MessageId = "System.String.IndexOf(System.String)", Justification = "This is not a security issue because its a design time class")]
protected override Type GetType(string name)
{
Type t = base.GetType(name);
if (t == null)
{
//When we try to load type from an assembly we need only the type name and not
//assembly qualified type name
int index = name.IndexOf(",");
if (index != -1)
name = name.Substring(0, index);
AssemblyName[] names = this.store.AssemblyNames;
foreach (AssemblyName n in names)
{
Assembly a = Assembly.Load(n);
if (a != null)
{
t = a.GetType(name);
if (t != null)
break;
}
}
if (t == null)
{
// Failing that go after their dependencies.
foreach (AssemblyName n in names)
{
Assembly a = Assembly.Load(n);
if (a != null)
{
foreach (AssemblyName dep in a.GetReferencedAssemblies())
{
Assembly aDep = Assembly.Load(dep);
if (aDep != null)
{
t = aDep.GetType(name);
if (t != null)
break;
}
}
if (t != null)
break;
}
}
}
}
return t;
}
}
#endregion
}
#region Class PropertySegment
internal sealed class PropertySegment
{
private IServiceProvider serviceProvider = null;
private object obj = null;
private PropertyInfo property = null;
private PropertyDescriptor propertyDescriptor = null;
public PropertySegment(IServiceProvider serviceProvider, object obj)
{
this.serviceProvider = serviceProvider;
this.obj = obj;
}
internal PropertySegment(IServiceProvider serviceProvider, object obj, PropertyInfo property)
{
this.serviceProvider = serviceProvider;
this.obj = obj;
this.property = property;
}
internal PropertySegment(IServiceProvider serviceProvider, object obj, PropertyDescriptor propertyDescriptor)
{
this.serviceProvider = serviceProvider;
this.obj = obj;
this.propertyDescriptor = propertyDescriptor;
}
internal object Object
{
get { return this.obj; }
}
internal IServiceProvider ServiceProvider
{
get
{
return this.serviceProvider;
}
}
internal PropertyDescriptor PropertyDescriptor
{
get
{
PropertyDescriptor propertyDesc = this.propertyDescriptor;
if (propertyDesc == null && this.obj != null && this.property != null)
propertyDesc = TypeDescriptor.GetProperties(this.obj)[this.property.Name];
return propertyDesc;
}
}
internal PropertyInfo[] GetProperties(IServiceProvider serviceProvider)
{
ArrayList properties = new ArrayList(GetType().GetProperties());
if (this.property != null)
{
properties.Add(new PropertySegmentPropertyInfo(this, this.property));
}
else if (this.propertyDescriptor != null)
{
properties.Add(new PropertySegmentPropertyInfo(this, this.propertyDescriptor));
}
else if (this.obj != null)
{
PropertyDescriptorCollection props = null;
TypeConverter converter = TypeDescriptor.GetConverter(this.obj);
if (converter != null && converter.GetPropertiesSupported())
{
DummyTypeDescriptorContext dummyContext = new DummyTypeDescriptorContext(this.serviceProvider, GetComponent(this.obj, serviceProvider), null);
props = converter.GetProperties(dummyContext, this.obj, new Attribute[] { });
}
else
props = TypeDescriptor.GetProperties(this.obj);
foreach (PropertyDescriptor propDesc in props)
{
PropertyInfo propInfo = XomlComponentSerializationService.GetProperty(this.obj.GetType(), propDesc.Name, BindingFlags.Public | BindingFlags.Instance);
if (propInfo != null)
{
if (Helpers.GetSerializationVisibility(propInfo) == DesignerSerializationVisibility.Hidden)
continue;
properties.Add(new PropertySegmentPropertyInfo(this, propInfo));
}
else
{
properties.Add(new PropertySegmentPropertyInfo(this, propDesc));
if (propDesc.Converter != null)
{
DummyTypeDescriptorContext dummyContext = new DummyTypeDescriptorContext(this.serviceProvider, GetComponent(this.obj, serviceProvider), propDesc);
if (propDesc.Converter.GetPropertiesSupported(dummyContext))
{
foreach (PropertyDescriptor childDesc in propDesc.Converter.GetProperties(dummyContext, this.obj, new Attribute[] { }))
{
properties.Add(new PropertySegmentPropertyInfo(this, childDesc));
}
}
}
}
}
}
return properties.ToArray(typeof(PropertyInfo)) as PropertyInfo[];
}
private IComponent GetComponent(object obj, IServiceProvider serviceProvider)
{
IComponent component = obj as IComponent;
if ((component == null || component.Site == null) && serviceProvider != null)
{
IReferenceService rs = serviceProvider.GetService(typeof(IReferenceService)) as IReferenceService;
if (rs != null)
component = rs.GetComponent(obj);
}
return component;
}
}
#endregion
#region Class DummyTypeDescriptorContext
internal class DummyTypeDescriptorContext : ITypeDescriptorContext
{
private IServiceProvider serviceProvider;
private object component = null;
private PropertyDescriptor propDescriptor = null;
public DummyTypeDescriptorContext(IServiceProvider serviceProvider, object component, PropertyDescriptor propDescriptor)
{
this.serviceProvider = serviceProvider;
this.propDescriptor = propDescriptor;
this.component = component;
}
public IContainer Container { get { return null; } }
public object Instance { get { return this.component; } }
public PropertyDescriptor PropertyDescriptor { get { return this.propDescriptor; } }
public void OnComponentChanged() { }
public bool OnComponentChanging() { return true; }
public object GetService(Type serviceType)
{
if (this.serviceProvider != null)
return this.serviceProvider.GetService(serviceType);
else
return null;
}
}
#endregion
#region Class PropertySegmentPropertyInfo
internal sealed class PropertySegmentPropertyInfo : PropertyInfo
{
private PropertyInfo realPropInfo = null;
private PropertyDescriptor realPropDesc = null;
private PropertySegment propertySegment;
internal PropertySegmentPropertyInfo(PropertySegment propertySegment, PropertyInfo realPropInfo)
{
this.realPropInfo = realPropInfo;
this.propertySegment = propertySegment;
}
internal PropertySegmentPropertyInfo(PropertySegment propertySegment, PropertyDescriptor realPropDesc)
{
this.realPropDesc = realPropDesc;
this.propertySegment = propertySegment;
}
internal PropertySegment PropertySegment
{
get
{
return this.propertySegment;
}
}
#region Property Info overrides
public override Type PropertyType
{
get
{
if (this.realPropInfo != null)
return this.realPropInfo.PropertyType;
else if (this.realPropDesc != null)
return this.realPropDesc.PropertyType;
return null;
}
}
public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
{
DependencyProperty dependencyProperty = null;
Activity activity = null;
if (this.propertySegment != null)
activity = this.propertySegment.Object as Activity;
if (activity != null)
{
string propertyName = Name;
Type propertyType = DeclaringType;
if (!String.IsNullOrEmpty(propertyName) && propertyType != null)
dependencyProperty = DependencyProperty.FromName(propertyName, propertyType);
}
object value = null;
object targetObj = (this.propertySegment == null) ? obj : this.propertySegment.Object;
if (dependencyProperty != null && !dependencyProperty.DefaultMetadata.IsMetaProperty)
{
// If this is not a Bind, we retrieve the value through the property descriptor.
// If we have directly assigned the value to the property then GetBinding is going to return null
// If that happens then we need to make sure that we get at the actual value
if (activity.IsBindingSet(dependencyProperty))
value = activity.GetBinding(dependencyProperty);
else if (!dependencyProperty.IsEvent)
value = activity.GetValue(dependencyProperty);
else
value = activity.GetHandler(dependencyProperty);
}
if (value == null)
{
if (this.realPropInfo != null)
value = this.realPropInfo.GetValue(targetObj, invokeAttr, binder, index, culture);
else if (this.realPropDesc != null)
value = this.realPropDesc.GetValue(targetObj);
}
return value;
}
public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
{
if (obj == null)
throw new ArgumentNullException("obj");
string propertyName = Name;
DependencyProperty dependencyProperty = null;
PropertySegment propertySegment = obj as PropertySegment;
Activity activity = (propertySegment != null) ? propertySegment.Object as Activity : obj as Activity;
if (activity != null)
{
Type propertyType = DeclaringType;
if (!String.IsNullOrEmpty(propertyName) && propertyType != null)
dependencyProperty = DependencyProperty.FromName(propertyName, propertyType);
}
PropertyDescriptor propertyDescriptor = null;
object destnObject = null;
if (propertySegment != null)
{
PropertyDescriptorCollection props = null;
TypeConverter converter = TypeDescriptor.GetConverter(propertySegment.Object);
if (converter != null && converter.GetPropertiesSupported())
{
DummyTypeDescriptorContext dummyContext = new DummyTypeDescriptorContext(propertySegment.ServiceProvider, propertySegment.Object, this.realPropDesc);
props = converter.GetProperties(dummyContext, propertySegment.Object, new Attribute[] { });
}
else
props = TypeDescriptor.GetProperties(propertySegment.Object);
foreach (PropertyDescriptor propDesc in props)
{
if (propDesc.Name == propertyName)
{
propertyDescriptor = propDesc;
}
else if (propDesc.Converter != null)
{
DummyTypeDescriptorContext dummyContext = new DummyTypeDescriptorContext(propertySegment.ServiceProvider, propertySegment.Object, propDesc);
if (propDesc.GetValue(propertySegment.Object) != null && propDesc.Converter.GetPropertiesSupported(dummyContext))
{
foreach (PropertyDescriptor childDesc in propDesc.Converter.GetProperties(dummyContext, propDesc.GetValue(propertySegment.Object), new Attribute[] { }))
{
if (childDesc.Name == propertyName)
propertyDescriptor = childDesc;
}
}
}
}
destnObject = propertySegment.Object;
}
else
{
propertyDescriptor = TypeDescriptor.GetProperties(obj)[propertyName];
destnObject = obj;
}
if (propertyDescriptor != null && destnObject != null)
propertyDescriptor.SetValue(destnObject, value);
}
public override MethodInfo[] GetAccessors(bool nonPublic)
{
if (this.realPropInfo != null)
return this.realPropInfo.GetAccessors(nonPublic);
return new MethodInfo[0];
}
public override MethodInfo GetGetMethod(bool nonPublic)
{
if (this.realPropInfo != null)
return this.realPropInfo.GetGetMethod(nonPublic);
return null;
}
public override MethodInfo GetSetMethod(bool nonPublic)
{
if (this.realPropInfo != null)
return this.realPropInfo.GetSetMethod(nonPublic);
return null;
}
public override ParameterInfo[] GetIndexParameters()
{
if (this.realPropInfo != null)
return this.realPropInfo.GetIndexParameters();
return new ParameterInfo[0];
}
public override PropertyAttributes Attributes
{
get
{
if (this.realPropInfo != null)
return this.realPropInfo.Attributes;
return PropertyAttributes.None;
}
}
public override bool CanRead
{
get
{
if (this.realPropInfo != null)
return this.realPropInfo.CanRead;
return true;
}
}
public override bool CanWrite
{
get
{
if (this.realPropInfo != null)
return this.realPropInfo.CanWrite;
else if (this.realPropDesc != null)
return !(this.realPropDesc.IsReadOnly);
return false;
}
}
public override string Name
{
get
{
if (this.realPropInfo != null)
return this.realPropInfo.Name;
else if (this.realPropDesc != null)
return this.realPropDesc.Name;
return String.Empty;
}
}
public override Type DeclaringType
{
get
{
if (this.realPropInfo != null)
return this.realPropInfo.DeclaringType;
else if (this.realPropDesc != null)
return this.realPropDesc.ComponentType;
return null;
}
}
public override Type ReflectedType
{
get
{
if (this.realPropInfo != null)
return this.realPropInfo.ReflectedType;
return null;
}
}
#endregion
#region MemberInfo Overrides
public override object[] GetCustomAttributes(bool inherit)
{
if (this.realPropInfo != null)
return this.realPropInfo.GetCustomAttributes(inherit);
return new AttributeInfoAttribute[0];
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (this.realPropInfo != null)
return this.realPropInfo.GetCustomAttributes(attributeType, inherit);
return new AttributeInfoAttribute[0];
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (this.realPropInfo != null)
return this.realPropInfo.IsDefined(attributeType, inherit);
return false;
}
#endregion
}
#endregion
}
| |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Diagnostics;
using System.Globalization;
namespace CartographerLibrary
{
/// <summary>
/// Base class for all graphics objects.
/// </summary>
public abstract class GraphicsBase : DrawingVisual
{
#region Class Members
protected double graphicsLineWidth;
protected Color graphicsObjectColor;
protected double graphicsActualScale;
protected bool selected;
// Allows to write Undo - Redo functions and don't care about
// objects order in the list.
int objectId;
protected const double HitTestWidth = 8.0;
protected const double HandleSize = 12.0;
// Objects used to draw handles. I want to keep them all time program runs,
// therefore I don't use pens, because actual pen size can change.
// external rectangle
static SolidColorBrush handleBrush1 = new SolidColorBrush(Color.FromArgb(200, 0, 0, 0));
// middle
static SolidColorBrush handleBrush2 = new SolidColorBrush(Color.FromArgb(200, 255, 255, 255));
// internal
static SolidColorBrush handleBrush3 = new SolidColorBrush(Color.FromArgb(200, 0, 0, 255));
#endregion Class Members
#region Constructor
protected GraphicsBase()
{
objectId = this.GetHashCode();
}
#endregion Constructor
#region Properties
public bool IsSelected
{
get
{
return selected;
}
set
{
selected = value;
RefreshDrawing();
}
}
public double LineWidth
{
get
{
return graphicsLineWidth;
}
set
{
graphicsLineWidth = value;
RefreshDrawing();
}
}
public Color ObjectColor
{
get
{
return graphicsObjectColor;
}
set
{
graphicsObjectColor = value;
RefreshDrawing();
}
}
public double ActualScale
{
get
{
return graphicsActualScale;
}
set
{
graphicsActualScale = value;
RefreshDrawing();
}
}
protected double ActualLineWidth
{
get
{
return graphicsActualScale <= 0 ? graphicsLineWidth : graphicsLineWidth / graphicsActualScale;
}
}
protected double LineHitTestWidth
{
get
{
// Ensure that hit test area is not too narrow
return Math.Max(8.0, ActualLineWidth);
}
}
/// <summary>
/// Object ID
/// </summary>
public int Id
{
get { return objectId; }
set { objectId = value; }
}
#endregion Properties
#region Abstract Methods and Properties
/// <summary>
/// Returns number of handles
/// </summary>
public abstract int HandleCount
{
get;
}
/// <summary>
/// Hit test, should be overwritten in derived classes.
/// </summary>
public abstract bool Contains(Point point);
/// <summary>
/// Create object for serialization
/// </summary>
public abstract PropertiesGraphicsBase CreateSerializedObject();
/// <summary>
/// Get handle point by 1-based number
/// </summary>
public abstract Point GetHandle(int handleNumber);
/// <summary>
/// Hit test.
/// Return value: -1 - no hit
/// 0 - hit anywhere
/// > 1 - handle number
/// </summary>
public abstract int MakeHitTest(Point point);
/// <summary>
/// Test whether object intersects with rectangle
/// </summary>
public abstract bool IntersectsWith(Rect rectangle);
/// <summary>
/// Move object
/// </summary>
public abstract void MoveBy(double deltaX, double deltaY);
public abstract void MoveTo(Point point);
/// <summary>
/// Move handle to the point
/// </summary>
public abstract void MoveHandleTo(Point point, int handleNumber);
/// <summary>
/// Get cursor for the handle
/// </summary>
public abstract Cursor GetHandleCursor(int handleNumber);
#endregion Abstract Methods and Properties
#region Virtual Methods
/// <summary>
/// Normalize object.
/// Call this function in the end of object resizing,
/// </summary>
public virtual void Normalize()
{
// Empty implementation is OK for classes which don't require
// normalization, like line.
// Normalization is required for rectangle-based classes.
}
/// <summary>
/// Implements actual drawing code.
///
/// Call GraphicsBase.Draw in the end of every derived class Draw
/// function to draw tracker if necessary.
/// </summary>
public virtual void Draw(DrawingContext drawingContext)
{
if ( IsSelected )
{
DrawTracker(drawingContext);
}
}
/// <summary>
/// Draw tracker for selected object.
/// </summary>
public virtual void DrawTracker(DrawingContext drawingContext)
{
for (int i = 1; i <= HandleCount; i++)
{
DrawTrackerRectangle(drawingContext, GetHandleRectangle(i));
}
}
/// <summary>
/// Dump (for debugging)
/// </summary>
[Conditional("DEBUG")]
public virtual void Dump()
{
Trace.WriteLine(this.GetType().Name);
Trace.WriteLine("ID = " + objectId.ToString(CultureInfo.InvariantCulture) +
" Selected = " + selected.ToString(CultureInfo.InvariantCulture));
Trace.WriteLine("objectColor = " + ColorToDisplay(graphicsObjectColor) +
" lineWidth = " + DoubleForDisplay(graphicsLineWidth));
}
#endregion Virtual Methods
#region Other Methods
/// <summary>
/// Draw tracker rectangle
/// </summary>
static void DrawTrackerRectangle(DrawingContext drawingContext, Rect rectangle)
{
// External rectangle
drawingContext.DrawRectangle(handleBrush1, null, rectangle);
// Middle
drawingContext.DrawRectangle(handleBrush2, null,
new Rect(rectangle.Left + rectangle.Width/8,
rectangle.Top + rectangle.Height/8,
rectangle.Width* 6 / 8,
rectangle.Height* 6 / 8));
// Internal
drawingContext.DrawRectangle(handleBrush3, null,
new Rect(rectangle.Left + rectangle.Width / 4,
rectangle.Top + rectangle.Height / 4,
rectangle.Width / 2,
rectangle.Height / 2));
}
/// <summary>
/// Refresh drawing.
/// Called after change of any object property.
/// </summary>
public void RefreshDrawing()
{
DrawingContext dc = this.RenderOpen();
Draw(dc);
dc.Close();
}
/// <summary>
/// Get handle rectangle by 1-based number
/// </summary>
public Rect GetHandleRectangle(int handleNumber)
{
Point point = GetHandle(handleNumber);
// Handle rectangle should have constant size, except of the case
// when line is too width.
double size = Math.Max(HandleSize / graphicsActualScale, ActualLineWidth * 1.1);
return new Rect(point.X - size / 2, point.Y - size / 2,
size, size);
}
/// <summary>
/// Helper function used for Dump
/// </summary>
static string DoubleForDisplay(double value)
{
return ((float)value).ToString("f2", CultureInfo.InvariantCulture);
}
/// <summary>
/// Helper function used for Dump
/// </summary>
static string ColorToDisplay(Color value)
{
//return "A:" + value.A.ToString() +
return "R:" + value.R.ToString(CultureInfo.InvariantCulture) +
" G:" + value.G.ToString(CultureInfo.InvariantCulture) +
" B:" + value.B.ToString(CultureInfo.InvariantCulture);
}
#endregion Other Methods
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="_Events.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization {
using System.IO;
using System;
using System.Collections;
using System.ComponentModel;
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventHandler"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public delegate void XmlAttributeEventHandler(object sender, XmlAttributeEventArgs e);
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlAttributeEventArgs : EventArgs {
object o;
XmlAttribute attr;
string qnames;
int lineNumber;
int linePosition;
internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePosition, object o, string qnames) {
this.attr = attr;
this.o = o;
this.qnames = qnames;
this.lineNumber = lineNumber;
this.linePosition = linePosition;
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.ObjectBeingDeserialized"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object ObjectBeingDeserialized {
get { return o; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.Attr"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlAttribute Attr {
get { return attr; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.LineNumber"]/*' />
/// <devdoc>
/// <para>
/// Gets the current line number.
/// </para>
/// </devdoc>
public int LineNumber {
get { return lineNumber; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.LinePosition"]/*' />
/// <devdoc>
/// <para>
/// Gets the current line position.
/// </para>
/// </devdoc>
public int LinePosition {
get { return linePosition; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.Attributes"]/*' />
/// <devdoc>
/// <para>
/// List the qnames of attributes expected in the current context.
/// </para>
/// </devdoc>
public string ExpectedAttributes {
get { return qnames == null ? string.Empty : qnames; }
}
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventHandler"]/*' />
public delegate void XmlElementEventHandler(object sender, XmlElementEventArgs e);
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs"]/*' />
public class XmlElementEventArgs : EventArgs {
object o;
XmlElement elem;
string qnames;
int lineNumber;
int linePosition;
internal XmlElementEventArgs(XmlElement elem, int lineNumber, int linePosition, object o, string qnames) {
this.elem = elem;
this.o = o;
this.qnames = qnames;
this.lineNumber = lineNumber;
this.linePosition = linePosition;
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs.ObjectBeingDeserialized"]/*' />
public object ObjectBeingDeserialized {
get { return o; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs.Attr"]/*' />
public XmlElement Element {
get { return elem; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs.LineNumber"]/*' />
public int LineNumber {
get { return lineNumber; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs.LinePosition"]/*' />
public int LinePosition {
get { return linePosition; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.ExpectedElements"]/*' />
/// <devdoc>
/// <para>
/// List of qnames of elements expected in the current context.
/// </para>
/// </devdoc>
public string ExpectedElements {
get { return qnames == null ? string.Empty : qnames; }
}
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventHandler"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public delegate void XmlNodeEventHandler(object sender, XmlNodeEventArgs e);
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlNodeEventArgs : EventArgs {
object o;
XmlNode xmlNode;
int lineNumber;
int linePosition;
internal XmlNodeEventArgs(XmlNode xmlNode, int lineNumber, int linePosition, object o) {
this.o = o;
this.xmlNode = xmlNode;
this.lineNumber = lineNumber;
this.linePosition = linePosition;
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.ObjectBeingDeserialized"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object ObjectBeingDeserialized {
get { return o; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.NodeType"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlNodeType NodeType {
get { return xmlNode.NodeType; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.Name"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string Name {
get { return xmlNode.Name; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.LocalName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string LocalName {
get { return xmlNode.LocalName; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.NamespaceURI"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string NamespaceURI {
get { return xmlNode.NamespaceURI; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.Text"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string Text {
get { return xmlNode.Value; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.LineNumber"]/*' />
/// <devdoc>
/// <para>
/// Gets the current line number.
/// </para>
/// </devdoc>
public int LineNumber {
get { return lineNumber; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.LinePosition"]/*' />
/// <devdoc>
/// <para>
/// Gets the current line position.
/// </para>
/// </devdoc>
public int LinePosition {
get { return linePosition; }
}
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventHandler"]/*' />
public delegate void UnreferencedObjectEventHandler(object sender, UnreferencedObjectEventArgs e);
/// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventArgs"]/*' />
public class UnreferencedObjectEventArgs : EventArgs {
object o;
string id;
/// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventArgs.UnreferencedObjectEventArgs"]/*' />
public UnreferencedObjectEventArgs(object o, string id) {
this.o = o;
this.id = id;
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventArgs.UnreferencedObject"]/*' />
public object UnreferencedObject {
get { return o; }
}
/// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventArgs.UnreferencedId"]/*' />
public string UnreferencedId {
get { return id; }
}
}
}
| |
//*********************************************************
//
// 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 SDKTemplate;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Security.Authentication.Web.Core;
using Windows.Security.Credentials;
using Windows.Storage;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace Accounts
{
public sealed partial class MultipleAccountsScenario : Page
{
private MainPage rootPage;
const string AppSpecificProviderId = "myproviderid";
const string AppSpecificProviderName = "App specific provider";
const string AccountsContainer = "accountssettingscontainer";
const string ProviderIdSubContainer = "providers";
const string AuthoritySubContainer = "authorities";
const string MicrosoftProviderId = "https://login.microsoft.com";
const string MicrosoftAccountAuthority = "consumers";
const string AzureActiveDirectoryAuthority = "organizations";
const string MicrosoftAccountClientId = "none";
const string MicrosoftAccountScopeRequested = "wl.basic";
// To obtain azureAD tokens, you must register this app on the AzureAD portal, and obtain the client ID
const string AzureActiveDirectoryClientId = "";
const string AzureActiveDirectoryScopeRequested = "";
public MultipleAccountsScenario()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
CreateLocalDataContainers();
AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += OnAccountCommandsRequested;
IdentityChecker.SampleIdentityConfigurationCorrect(NotRegisteredWarning, AzureActiveDirectoryClientId);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= OnAccountCommandsRequested;
}
private void Button_ShowAccountSettings(object sender, RoutedEventArgs e)
{
((Button)sender).IsEnabled = false;
rootPage.NotifyUser("Launching AccountSettingsPane", NotifyType.StatusMessage);
AccountsSettingsPane.Show();
((Button)sender).IsEnabled = true;
}
private async void Button_Reset(object sender, RoutedEventArgs e)
{
((Button)sender).IsEnabled = false;
rootPage.NotifyUser("Resetting ", NotifyType.ErrorMessage);
await LogoffAndRemoveAllAccounts();
((Button)sender).IsEnabled = true;
}
private async Task<List<WebAccount>> GetAllAccounts()
{
List<WebAccount> accounts = new List<WebAccount>();
ApplicationDataContainer AccountListContainer = ApplicationData.Current.LocalSettings.Containers[AccountsContainer];
foreach (Object value in AccountListContainer.Containers[ProviderIdSubContainer].Values.Keys)
{
String accountID = value as String;
String providerID = AccountListContainer.Containers[ProviderIdSubContainer].Values[accountID] as String;
String authority = AccountListContainer.Containers[AuthoritySubContainer].Values[accountID] as String;
WebAccountProvider provider = await GetProvider(providerID, authority);
if (providerID == AppSpecificProviderId)
{
accounts.Add(new WebAccount(provider, accountID, WebAccountState.None));
}
else
{
WebAccount loadedAccount = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountID);
if(loadedAccount != null)
{
accounts.Add(loadedAccount);
}
else
{
// The account has been deleted
ApplicationDataContainer accountsContainer = ApplicationData.Current.LocalSettings.Containers[AccountsContainer];
accountsContainer.Containers[ProviderIdSubContainer].Values.Remove(accountID);
accountsContainer.Containers[AuthoritySubContainer].Values.Remove(accountID);
}
}
}
return accounts;
}
private async Task<List<WebAccountProvider>> GetAllProviders()
{
List<WebAccountProvider> providers = new List<WebAccountProvider>();
providers.Add(await GetProvider(MicrosoftProviderId, MicrosoftAccountAuthority));
providers.Add(await GetProvider(MicrosoftProviderId, AzureActiveDirectoryAuthority));
providers.Add(await GetProvider(AppSpecificProviderId));
return providers;
}
private async Task<WebAccountProvider> GetProvider(string ProviderID, string AuthorityId = "")
{
if (ProviderID == AppSpecificProviderId)
{
return new WebAccountProvider(AppSpecificProviderId, AppSpecificProviderName, new Uri(this.BaseUri, "Assets/smallTile-sdk.png"));
}
else
{
return await WebAuthenticationCoreManager.FindAccountProviderAsync(ProviderID, AuthorityId);
}
}
private async void OnAccountCommandsRequested(
AccountsSettingsPane sender,
AccountsSettingsPaneCommandsRequestedEventArgs e)
{
// In order to make async calls within this callback, the deferral object is needed
AccountsSettingsPaneEventDeferral deferral = e.GetDeferral();
// This scenario only supports a single account at one time.
// If there already is an account, we do not include a provider in the list
// This will prevent the add account button from showing up.
await AddWebAccountProvidersToPane(e);
await AddWebAccountsToPane(e);
AddLinksAndDescription(e);
deferral.Complete();
}
private void AddLinksAndDescription(AccountsSettingsPaneCommandsRequestedEventArgs e)
{
e.HeaderText = "Describe what adding an account to your application will do for the user";
// You can add links such as privacy policy, help, general account settings
e.Commands.Add(new SettingsCommand("privacypolicy", "Privacy policy", PrivacyPolicyInvoked));
e.Commands.Add(new SettingsCommand("otherlink", "Other link", OtherLinkInvoked));
}
private void OtherLinkInvoked(IUICommand command)
{
rootPage.NotifyUser("Other link pressed by user", NotifyType.StatusMessage);
}
private void PrivacyPolicyInvoked(IUICommand command)
{
rootPage.NotifyUser("Privacy policy clicked by user", NotifyType.StatusMessage);
}
private async Task AddWebAccountProvidersToPane(AccountsSettingsPaneCommandsRequestedEventArgs e)
{
// The order of providers displayed is determined by the order provided to the Accounts pane
List<WebAccountProvider> providers = await GetAllProviders();
foreach (WebAccountProvider provider in providers)
{
WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);
e.WebAccountProviderCommands.Add(providerCommand);
}
}
private async Task AddWebAccountsToPane(AccountsSettingsPaneCommandsRequestedEventArgs e)
{
List<WebAccount> accounts = await GetAllAccounts();
foreach (WebAccount account in accounts)
{
WebAccountCommand command = new WebAccountCommand(account, WebAccountInvoked, SupportedWebAccountActions.Remove | SupportedWebAccountActions.Manage);
e.WebAccountCommands.Add(command);
}
}
private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
{
if ((command.WebAccountProvider.Id == MicrosoftProviderId) && (command.WebAccountProvider.Authority == MicrosoftAccountAuthority))
{
// ClientID is ignored by MSA
await AuthenticateWithRequestToken(command.WebAccountProvider, MicrosoftAccountScopeRequested, MicrosoftAccountClientId);
}
else if ((command.WebAccountProvider.Id == MicrosoftProviderId) && (command.WebAccountProvider.Authority == AzureActiveDirectoryAuthority))
{
await AuthenticateWithRequestToken(command.WebAccountProvider, AzureActiveDirectoryScopeRequested, AzureActiveDirectoryClientId);
}
else if (command.WebAccountProvider.Id == AppSpecificProviderId)
{
// Show user registration/login for your app specific account type.
// Store the user if registration/login successful
StoreNewAccountDataLocally(new WebAccount(command.WebAccountProvider, "App Specific User(" + DateTime.Now + ")", WebAccountState.None));
}
}
public async Task AuthenticateWithRequestToken(WebAccountProvider Provider, String Scope, String ClientID)
{
try
{
WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID);
// Azure Active Directory requires a resource to return a token
if (Provider.Id == "https://login.microsoft.com" && Provider.Authority == "organizations")
{
webTokenRequest.Properties.Add("resource", "https://graph.windows.net");
}
// If the user selected a specific account, RequestTokenAsync will return a token for that account.
// The user may be prompted for credentials or to authorize using that account with your app
// If the user selected a provider, the user will be prompted for credentials to login to a new account
WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
{
StoreNewAccountDataLocally(webTokenRequestResult.ResponseData[0].WebAccount);
}
OutputTokenResult(webTokenRequestResult);
}
catch (Exception ex)
{
rootPage.NotifyUser("Web Token request failed: " + ex, NotifyType.ErrorMessage);
}
}
public void StoreNewAccountDataLocally(WebAccount account)
{
ApplicationDataContainer accountsContainer = ApplicationData.Current.LocalSettings.Containers[AccountsContainer];
if (account.Id != "")
{
accountsContainer.Containers[ProviderIdSubContainer].Values[account.Id] = account.WebAccountProvider.Id;
accountsContainer.Containers[AuthoritySubContainer].Values[account.Id] = account.WebAccountProvider.Authority;
}
else
{
accountsContainer.Containers[ProviderIdSubContainer].Values[account.UserName] = account.WebAccountProvider.Id;
}
}
public void OutputTokenResult(WebTokenRequestResult result)
{
if (result.ResponseStatus == WebTokenRequestStatus.Success)
{
rootPage.NotifyUser("Web Token request successful for user:" + result.ResponseData[0].WebAccount.UserName, NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Web Token request error: " + result.ResponseError, NotifyType.StatusMessage);
}
}
private async void WebAccountInvoked(WebAccountCommand command, WebAccountInvokedArgs args)
{
if (args.Action == WebAccountAction.Remove)
{
await LogoffAndRemoveAccount(command.WebAccount);
}
else if (args.Action == WebAccountAction.Manage)
{
// Display user management UI for this account
rootPage.NotifyUser("Manage invoked for user: " + command.WebAccount.UserName, NotifyType.StatusMessage);
}
}
private async Task LogoffAndRemoveAccount(WebAccount account)
{
ApplicationDataContainer accountsContainer = ApplicationData.Current.LocalSettings.Containers[AccountsContainer];
if(account.WebAccountProvider.Id != AppSpecificProviderId)
{
await account.SignOutAsync();
accountsContainer.Containers[ProviderIdSubContainer].Values.Remove(account.Id);
accountsContainer.Containers[AuthoritySubContainer].Values.Remove(account.Id);
}
else
{
//perform any actions needed to log off the app specific account
accountsContainer.Containers[ProviderIdSubContainer].Values.Remove(account.UserName);
}
}
private async Task LogoffAndRemoveAllAccounts()
{
List<WebAccount> accounts = await GetAllAccounts();
foreach(WebAccount account in accounts)
{
await LogoffAndRemoveAccount(account);
}
accounts = null;
}
private void CreateLocalDataContainers()
{
ApplicationData.Current.LocalSettings.CreateContainer(AccountsContainer, ApplicationDataCreateDisposition.Always);
ApplicationData.Current.LocalSettings.Containers[AccountsContainer].CreateContainer(ProviderIdSubContainer, ApplicationDataCreateDisposition.Always);
ApplicationData.Current.LocalSettings.Containers[AccountsContainer].CreateContainer(AuthoritySubContainer, ApplicationDataCreateDisposition.Always);
}
}
}
| |
// Copyright 2008 Adrian Akison
// Distributed under license terms of CPOL http://www.codeproject.com/info/cpol10.aspx
using System;
using System.Collections.Generic;
using System.Text;
namespace RaidScheduler.Domain.DomainModels.Combinations {
/// <summary>
/// Combinations defines a meta-collection, typically a list of lists, of all possible
/// subsets of a particular size from the set of values. This list is enumerable and
/// allows the scanning of all possible combinations using a simple foreach() loop.
/// Within the returned set, there is no prescribed order. This follows the mathematical
/// concept of choose. For example, put 10 dominoes in a hat and pick 5. The number of possible
/// combinations is defined as "10 choose 5", which is calculated as (10!) / ((10 - 5)! * 5!).
/// </summary>
/// <remarks>
/// The MetaCollectionType parameter of the constructor allows for the creation of
/// two types of sets, those with and without repetition in the output set when
/// presented with repetition in the input set.
///
/// When given a input collect {A B C} and lower index of 2, the following sets are generated:
/// MetaCollectionType.WithRepetition =>
/// {A A}, {A B}, {A C}, {B B}, {B C}, {C C}
/// MetaCollectionType.WithoutRepetition =>
/// {A B}, {A C}, {B C}
///
/// Input sets with multiple equal values will generate redundant combinations in proprotion
/// to the likelyhood of outcome. For example, {A A B B} and a lower index of 3 will generate:
/// {A A B} {A A B} {A B B} {A B B}
/// </remarks>
/// <typeparam name="T">The type of the values within the list.</typeparam>
public class Combinations<T> : IMetaCollection<T> {
#region Constructors
/// <summary>
/// No default constructor, must provided a list of values and size.
/// </summary>
protected Combinations() {
}
/// <summary>
/// Create a combination set from the provided list of values.
/// The upper index is calculated as values.Count, the lower index is specified.
/// Collection type defaults to MetaCollectionType.WithoutRepetition
/// </summary>
/// <param name="values">List of values to select combinations from.</param>
/// <param name="lowerIndex">The size of each combination set to return.</param>
public Combinations(IList<T> values, int lowerIndex) {
Initialize(values, lowerIndex, GenerateOption.WithoutRepetition);
}
/// <summary>
/// Create a combination set from the provided list of values.
/// The upper index is calculated as values.Count, the lower index is specified.
/// </summary>
/// <param name="values">List of values to select combinations from.</param>
/// <param name="lowerIndex">The size of each combination set to return.</param>
/// <param name="type">The type of Combinations set to generate.</param>
public Combinations(IList<T> values, int lowerIndex, GenerateOption type) {
Initialize(values, lowerIndex, type);
}
#endregion
#region IEnumerable Interface
/// <summary>
/// Gets an enumerator for collecting the list of combinations.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<IList<T>> GetEnumerator() {
return new Enumerator(this);
}
/// <summary>
/// Gets an enumerator for collecting the list of combinations.
/// </summary>
/// <returns>The enumerator.returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return new Enumerator(this);
}
#endregion
#region Enumerator Inner Class
/// <summary>
/// The enumerator that enumerates each meta-collection of the enclosing Combinations class.
/// </summary>
public class Enumerator : IEnumerator<IList<T>> {
#region Constructors
/// <summary>
/// Construct a enumerator with the parent object.
/// </summary>
/// <param name="source">The source combinations object.</param>
public Enumerator(Combinations<T> source) {
myParent = source;
myPermutationsEnumerator = (Permutations<bool>.Enumerator)myParent.myPermutations.GetEnumerator();
}
#endregion
#region IEnumerator interface
/// <summary>
/// Resets the combinations enumerator to the first combination.
/// </summary>
public void Reset() {
myPermutationsEnumerator.Reset();
}
/// <summary>
/// Advances to the next combination of items from the set.
/// </summary>
/// <returns>True if successfully moved to next combination, False if no more unique combinations exist.</returns>
/// <remarks>
/// The heavy lifting is done by the permutations object, the combination is generated
/// by creating a new list of those items that have a true in the permutation parrellel array.
/// </remarks>
public bool MoveNext() {
bool ret = myPermutationsEnumerator.MoveNext();
myCurrentList = null;
return ret;
}
/// <summary>
/// The current combination
/// </summary>
public IList<T> Current {
get {
ComputeCurrent();
return myCurrentList;
}
}
/// <summary>
/// The current combination
/// </summary>
object System.Collections.IEnumerator.Current {
get {
ComputeCurrent();
return myCurrentList;
}
}
/// <summary>
/// Cleans up non-managed resources, of which there are none used here.
/// </summary>
public void Dispose() {
;
}
#endregion
#region Heavy Lifting Members
/// <summary>
/// The only complex function of this entire wrapper, ComputeCurrent() creates
/// a list of original values from the bool permutation provided.
/// The exception for accessing current (InvalidOperationException) is generated
/// by the call to .Current on the underlying enumeration.
/// </summary>
/// <remarks>
/// To compute the current list of values, the underlying permutation object
/// which moves with this enumerator, is scanned differently based on the type.
/// The items have only two values, true and false, which have different meanings:
///
/// For type WithoutRepetition, the output is a straightforward subset of the input array.
/// E.g. 6 choose 3 without repetition
/// Input array: {A B C D E F}
/// Permutations: {0 1 0 0 1 1}
/// Generates set: {A C D }
/// Note: size of permutation is equal to upper index.
///
/// For type WithRepetition, the output is defined by runs of characters and when to
/// move to the next element.
/// E.g. 6 choose 5 with repetition
/// Input array: {A B C D E F}
/// Permutations: {0 1 0 0 1 1 0 0 1 1}
/// Generates set: {A B B D D }
/// Note: size of permutation is equal to upper index - 1 + lower index.
/// </remarks>
private void ComputeCurrent() {
if(myCurrentList == null) {
myCurrentList = new List<T>();
int index = 0;
IList<bool> currentPermutation = (IList<bool>)myPermutationsEnumerator.Current;
for(int i = 0; i < currentPermutation.Count; ++i) {
if(currentPermutation[i] == false) {
myCurrentList.Add(myParent.myValues[index]);
if(myParent.Type == GenerateOption.WithoutRepetition) {
++index;
}
}
else {
++index;
}
}
}
}
#endregion
#region Data
/// <summary>
/// Parent object this is an enumerator for.
/// </summary>
private Combinations<T> myParent;
/// <summary>
/// The current list of values, this is lazy evaluated by the Current property.
/// </summary>
private List<T> myCurrentList;
/// <summary>
/// An enumertor of the parents list of lexicographic orderings.
/// </summary>
private Permutations<bool>.Enumerator myPermutationsEnumerator;
#endregion
}
#endregion
#region IMetaList Interface
/// <summary>
/// The number of unique combinations that are defined in this meta-collection.
/// This value is mathematically defined as Choose(M, N) where M is the set size
/// and N is the subset size. This is M! / (N! * (M-N)!).
/// </summary>
public long Count {
get {
return myPermutations.Count;
}
}
/// <summary>
/// The type of Combinations set that is generated.
/// </summary>
public GenerateOption Type {
get {
return myMetaCollectionType;
}
}
/// <summary>
/// The upper index of the meta-collection, equal to the number of items in the initial set.
/// </summary>
public int UpperIndex {
get {
return myValues.Count;
}
}
/// <summary>
/// The lower index of the meta-collection, equal to the number of items returned each iteration.
/// </summary>
public int LowerIndex {
get {
return myLowerIndex;
}
}
#endregion
#region Heavy Lifting Members
/// <summary>
/// Initialize the combinations by settings a copy of the values from the
/// </summary>
/// <param name="values">List of values to select combinations from.</param>
/// <param name="lowerIndex">The size of each combination set to return.</param>
/// <param name="type">The type of Combinations set to generate.</param>
/// <remarks>
/// Copies the array and parameters and then creates a map of booleans that will
/// be used by a permutations object to refence the subset. This map is slightly
/// different based on whether the type is with or without repetition.
///
/// When the type is WithoutRepetition, then a map of upper index elements is
/// created with lower index false's.
/// E.g. 8 choose 3 generates:
/// Map: {1 1 1 1 1 0 0 0}
/// Note: For sorting reasons, false denotes inclusion in output.
///
/// When the type is WithRepetition, then a map of upper index - 1 + lower index
/// elements is created with the falses indicating that the 'current' element should
/// be included and the trues meaning to advance the 'current' element by one.
/// E.g. 8 choose 3 generates:
/// Map: {1 1 1 1 1 1 1 1 0 0 0} (7 trues, 3 falses).
/// </remarks>
private void Initialize(IList<T> values, int lowerIndex, GenerateOption type) {
myMetaCollectionType = type;
myLowerIndex = lowerIndex;
myValues = new List<T>();
myValues.AddRange(values);
List<bool> myMap = new List<bool>();
if(type == GenerateOption.WithoutRepetition) {
for(int i = 0; i < myValues.Count; ++i) {
if(i >= myValues.Count - myLowerIndex) {
myMap.Add(false);
}
else {
myMap.Add(true);
}
}
}
else {
for(int i = 0; i < values.Count - 1; ++i) {
myMap.Add(true);
}
for(int i = 0; i < myLowerIndex; ++i) {
myMap.Add(false);
}
}
myPermutations = new Permutations<bool>(myMap);
}
#endregion
#region Data
/// <summary>
/// Copy of values object is intialized with, required for enumerator reset.
/// </summary>
private List<T> myValues;
/// <summary>
/// Permutations object that handles permutations on booleans for combination inclusion.
/// </summary>
private Permutations<bool> myPermutations;
/// <summary>
/// The type of the combination collection.
/// </summary>
private GenerateOption myMetaCollectionType;
/// <summary>
/// The lower index defined in the constructor.
/// </summary>
private int myLowerIndex;
#endregion
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange (mailto:[email protected])
//
// Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Collections;
using System.Reflection;
using System.Text;
using System.IO;
using PdfSharp.Internal;
using PdfSharp.Pdf;
using PdfSharp.Pdf.Advanced;
using PdfSharp.Pdf.Internal;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.AcroForms;
using PdfSharp.Pdf.Security;
namespace PdfSharp.Pdf
{
/// <summary>
/// Represents a PDF document.
/// </summary>
[DebuggerDisplay("(Name={Name})")] // A name makes debugging easier
public sealed class PdfDocument : PdfObject, IDisposable
{
internal DocumentState state;
internal PdfDocumentOpenMode openMode;
#if DEBUG_
static PdfDocument()
{
PSSR.TestResourceMessages();
//string test = PSSR.ResMngr.GetString("SampleMessage1");
//test.GetType();
}
#endif
/// <summary>
/// Creates a new PDF document in memory.
/// To open an existing PDF file, use the PdfReader class.
/// </summary>
public PdfDocument()
{
//PdfDocument.Gob.AttatchDocument(this.Handle);
this.creation = DateTime.Now;
this.state = DocumentState.Created;
this.version = 14;
Initialize();
Info.CreationDate = this.creation;
}
/// <summary>
/// Creates a new PDF document with the specified file name. The file is immediately created and keeps
/// looked until the document is saved.
/// To open an existing PDF file and import it, use the PdfReader class.
/// </summary>
public PdfDocument(string filename)
{
//PdfDocument.Gob.AttatchDocument(this.Handle);
this.creation = DateTime.Now;
this.state = DocumentState.Created;
this.version = 14;
Initialize();
Info.CreationDate = this.creation;
this.outStream = new FileStream(filename, FileMode.Create);
}
/// <summary>
/// Creates a new PDF document using the specified stream.
/// To open an existing PDF file, use the PdfReader class.
/// </summary>
public PdfDocument(Stream outputStream)
{
//PdfDocument.Gob.AttatchDocument(this.Handle);
this.creation = DateTime.Now;
this.state = DocumentState.Created;
Initialize();
Info.CreationDate = this.creation;
this.outStream = outputStream;
}
internal PdfDocument(Lexer lexer)
{
//PdfDocument.Gob.AttatchDocument(this.Handle);
this.creation = DateTime.Now;
this.state = DocumentState.Imported;
//this.info = new PdfInfo(this);
//this.pages = new PdfPages(this);
//this.fontTable = new PdfFontTable();
//this.catalog = new PdfCatalog(this);
////this.font = new PdfFont();
//this.objects = new PdfObjectTable(this);
//this.trailer = new PdfTrailer(this);
this.irefTable = new PdfReferenceTable(this);
this.lexer = lexer;
}
void Initialize()
{
//this.info = new PdfInfo(this);
this.fontTable = new PdfFontTable(this);
this.imageTable = new PdfImageTable(this);
this.trailer = new PdfTrailer(this);
this.irefTable = new PdfReferenceTable(this);
this.trailer.CreateNewDocumentIDs();
}
//~PdfDocument()
//{
// Dispose(false);
//}
/// <summary>
/// Disposes all references to this document stored in other documents. This function should be called
/// for documents you finished importing pages from. Calling Dispose is technically not necessary but
/// useful for earlier reclaiming memory of documents you do not need anymore.
/// </summary>
public void Dispose()
{
Dispose(true);
//GC.SuppressFinalize(this);
}
void Dispose(bool disposing)
{
if (this.state != DocumentState.Disposed)
{
if (disposing)
{
// Dispose managed resources.
}
//PdfDocument.Gob.DetatchDocument(Handle);
}
this.state = DocumentState.Disposed;
}
/// <summary>
/// Gets or sets a user defined object that contains arbitrary information associated with this document.
/// The tag is not used by PDFsharp.
/// </summary>
public object Tag
{
get { return this.tag; }
set { this.tag = value; }
}
object tag;
/// <summary>
/// Gets or sets a value used to distinguish PdfDocument objects.
/// The name is not used by PDFsharp.
/// </summary>
string Name
{
get { return this.name; }
set { this.name = value; }
}
string name = NewName();
/// <summary>
/// Get a new default name for a new document.
/// </summary>
static string NewName()
{
#if DEBUG_
if (PdfDocument.nameCount == 57)
PdfDocument.nameCount.GetType();
#endif
return "Document " + nameCount++;
}
static int nameCount;
internal bool CanModify
{
//get {return this.state == DocumentState.Created || this.state == DocumentState.Modifyable;}
// THHO4STLA: TODO: correct implementation
get { return openMode == PdfDocumentOpenMode.Modify; } // TODO: correct implementation
}
/// <summary>
/// Closes this instance.
/// </summary>
public void Close()
{
if (!CanModify)
throw new InvalidOperationException(PSSR.CannotModify);
if (this.outStream != null)
{
// Get security handler if document gets encrypted
PdfStandardSecurityHandler securityHandler = null;
if (SecuritySettings.DocumentSecurityLevel != PdfDocumentSecurityLevel.None)
securityHandler = SecuritySettings.SecurityHandler;
PdfWriter writer = new PdfWriter(this.outStream, securityHandler);
try
{
DoSave(writer);
}
finally
{
writer.Close();
}
}
}
/// <summary>
/// Saves the document to the specified path. If a file already exists, it will be overwritten.
/// </summary>
public void Save(string path)
{
if (!CanModify)
throw new InvalidOperationException(PSSR.CannotModify);
Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write);
Save(stream);
}
/// <summary>
/// Saves the document to the specified stream.
/// </summary>
public void Save(Stream stream, bool closeStream)
{
if (!CanModify)
throw new InvalidOperationException(PSSR.CannotModify);
// TODO: more diagnostic checks
string message = "";
if (!CanSave(ref message))
throw new PdfSharpException(message);
// Get security handler if document gets encrypted
PdfStandardSecurityHandler securityHandler = null;
if (SecuritySettings.DocumentSecurityLevel != PdfDocumentSecurityLevel.None)
securityHandler = SecuritySettings.SecurityHandler;
PdfWriter writer = new PdfWriter(stream, securityHandler);
try
{
DoSave(writer);
}
finally
{
if (stream != null)
{
if (closeStream)
stream.Close();
else
stream.Position = 0; // Reset the stream position if the stream is left open.
}
if (writer != null)
writer.Close(closeStream);
}
}
/// <summary>
/// Saves the document to the specified stream and closes the stream.
/// </summary>
public void Save(Stream stream)
{
Save(stream, true);
}
/// <summary>
/// Implements saving a PDF file.
/// </summary>
void DoSave(PdfWriter writer)
{
if (this.pages == null || this.pages.Count == 0)
throw new InvalidOperationException("Cannot save a PDF document with no pages.");
try
{
bool encrypt = this.securitySettings.DocumentSecurityLevel != PdfDocumentSecurityLevel.None;
if (encrypt)
{
PdfStandardSecurityHandler securityHandler = this.securitySettings.SecurityHandler;
if (securityHandler.Reference == null)
this.irefTable.Add(securityHandler);
else
Debug.Assert(this.irefTable.Contains(securityHandler.ObjectID));
this.trailer.Elements[PdfTrailer.Keys.Encrypt] = this.securitySettings.SecurityHandler.Reference;
}
else
this.trailer.Elements.Remove(PdfTrailer.Keys.Encrypt);
PrepareForSave();
if (encrypt)
this.securitySettings.SecurityHandler.PrepareEncryption();
writer.WriteFileHeader(this);
PdfReference[] irefs = this.irefTable.AllReferences;
int count = irefs.Length;
for (int idx = 0; idx < count; idx++)
{
PdfReference iref = irefs[idx];
#if DEBUG_
if (iref.ObjectNumber == 378)
GetType();
#endif
iref.Position = writer.Position;
iref.Value.WriteObject(writer);
}
int startxref = writer.Position;
this.irefTable.WriteObject(writer);
writer.WriteRaw("trailer\n");
this.trailer.Elements.SetInteger("/Size", count + 1);
this.trailer.WriteObject(writer);
writer.WriteEof(this, startxref);
//if (encrypt)
//{
// this.state &= ~DocumentState.SavingEncrypted;
// //this.securitySettings.SecurityHandler.EncryptDocument();
//}
}
finally
{
if (writer != null)
{
writer.Stream.Flush();
// DO NOT CLOSE WRITER HERE
//writer.Close();
}
}
}
/// <summary>
/// Dispatches PrepareForSave to the objects that need it.
/// </summary>
internal override void PrepareForSave()
{
PdfDocumentInformation info = Info;
// Set Producer if value is undefined
if (info.Elements[PdfDocumentInformation.Keys.Producer] == null)
info.Producer = VersionInfo.Producer;
// Set Application if value is undefined
if (info.Elements[PdfDocumentInformation.Keys.Application] == null)
info.Application = VersionInfo.Producer;
// Prepare used fonts
if (this.fontTable != null)
this.fontTable.PrepareForSave();
// Let catalog do the rest
Catalog.PrepareForSave();
#if true
// Remove all unreachable objects (e.g. from deleted pages)
int removed = this.irefTable.Compact();
if (removed != 0)
Debug.WriteLine("PrepareForSave: Number of deleted unreachable objects: " + removed);
this.irefTable.Renumber();
#endif
}
/// <summary>
/// Determines whether the document can be saved.
/// </summary>
public bool CanSave(ref string message)
{
if (!SecuritySettings.CanSave(ref message))
return false;
return true;
}
internal bool HasVersion(string version)
{
return String.Compare(Catalog.Version, version) >= 0;
}
/// <summary>
/// Gets the document options used for saving the document.
/// </summary>
public PdfDocumentOptions Options
{
get
{
if (this.options == null)
this.options = new PdfDocumentOptions(this);
return this.options;
}
}
PdfDocumentOptions options;
/// <summary>
/// Gets PDF specific document settings.
/// </summary>
public PdfDocumentSettings Settings
{
get
{
if (this.settings == null)
this.settings = new PdfDocumentSettings(this);
return this.settings;
}
}
PdfDocumentSettings settings;
/// <summary>
/// NYI Indicates whether large objects are written immediately to the output stream to relieve
/// memory consumption.
/// </summary>
internal bool EarlyWrite
{
get { return false; }
}
/// <summary>
/// Gets or sets the PDF version number. Return value 14 e.g. means PDF 1.4 / Acrobat 5 etc.
/// </summary>
public int Version
{
get { return this.version; }
set
{
if (!CanModify)
throw new InvalidOperationException(PSSR.CannotModify);
if (value < 12 || value > 17) // TODO not really implemented
throw new ArgumentException(PSSR.InvalidVersionNumber, "value");
this.version = value;
}
}
internal int version;
/// <summary>
/// Gets the number of pages in the document.
/// </summary>
public int PageCount
{
get
{
if (CanModify)
return Pages.Count;
// PdfOpenMode is InformationOnly
PdfDictionary pageTreeRoot = (PdfDictionary)Catalog.Elements.GetObject(PdfCatalog.Keys.Pages);
return pageTreeRoot.Elements.GetInteger(PdfPages.Keys.Count);
}
}
/// <summary>
/// Gets the file size of the document.
/// </summary>
public long FileSize
{
get { return this.fileSize; }
}
internal long fileSize;
/// <summary>
/// Gets the full qualified file name if the document was read form a file, or an empty string otherwise.
/// </summary>
public string FullPath
{
get { return this.fullPath; }
}
internal string fullPath = String.Empty;
/// <summary>
/// Gets a Guid that uniquely identifies this instance of PdfDocument.
/// </summary>
public Guid Guid
{
get { return this.guid; }
}
Guid guid = Guid.NewGuid();
internal DocumentHandle Handle
{
get
{
if (this.handle == null)
this.handle = new DocumentHandle(this);
return this.handle;
}
}
DocumentHandle handle;
/// <summary>
/// Returns a value indicating whether the document was newly created or opened from an existing document.
/// Returns true if the document was opened with the PdfReader.Open function, false otherwise.
/// </summary>
public bool IsImported
{
get { return (this.state & DocumentState.Imported) != 0; }
}
/// <summary>
/// Returns a value indicating whether the document is read only or can be modified.
/// </summary>
public bool IsReadOnly
{
get { return (this.openMode != PdfDocumentOpenMode.Modify); }
}
internal Exception DocumentNotImported()
{
return new InvalidOperationException("Document not imported.");
}
/// <summary>
/// Gets information about the document.
/// </summary>
public PdfDocumentInformation Info
{
get
{
if (this.info == null)
this.info = this.trailer.Info;
return this.info;
}
}
PdfDocumentInformation info; // never changes if once created
/// <summary>
/// This function is intended to be undocumented.
/// </summary>
public PdfCustomValues CustomValues
{
get
{
if (this.customValues == null)
this.customValues = PdfCustomValues.Get(Catalog.Elements);
return this.customValues;
}
set
{
if (value != null)
throw new ArgumentException("Only null is allowed to clear all custom values.");
PdfCustomValues.Remove(Catalog.Elements);
this.customValues = null;
}
}
PdfCustomValues customValues;
/// <summary>
/// Get the pages dictionary.
/// </summary>
public PdfPages Pages
{
get
{
if (this.pages == null)
this.pages = Catalog.Pages;
return this.pages;
}
}
PdfPages pages; // never changes if once created
/// <summary>
/// Gets or sets a value specifying the page layout to be used when the document is opened.
/// </summary>
public PdfPageLayout PageLayout
{
get { return Catalog.PageLayout; }
set
{
if (!CanModify)
throw new InvalidOperationException(PSSR.CannotModify);
Catalog.PageLayout = value;
}
}
/// <summary>
/// Gets or sets a value specifying how the document should be displayed when opened.
/// </summary>
public PdfPageMode PageMode
{
get { return Catalog.PageMode; }
set
{
if (!CanModify)
throw new InvalidOperationException(PSSR.CannotModify);
Catalog.PageMode = value;
}
}
/// <summary>
/// Gets the viewer preferences of this document.
/// </summary>
public PdfViewerPreferences ViewerPreferences
{
get { return Catalog.ViewerPreferences; }
}
/// <summary>
/// Gets the root of the outline (or bookmark) tree.
/// </summary>
public PdfOutline.PdfOutlineCollection Outlines
{
get { return Catalog.Outlines; }
}
/// <summary>
/// Get the AcroForm dictionary.
/// </summary>
public PdfAcroForm AcroForm
{
get { return Catalog.AcroForm; }
}
/// <summary>
/// Gets or sets the default language of the document.
/// </summary>
public string Language
{
get { return Catalog.Elements.GetString(PdfCatalog.Keys.Lang); }
set { Catalog.Elements.SetString(PdfCatalog.Keys.Lang, value); }
}
/// <summary>
/// Gets the security settings of this document.
/// </summary>
public PdfSecuritySettings SecuritySettings
{
get
{
if (this.securitySettings == null)
this.securitySettings = new PdfSecuritySettings(this);
return this.securitySettings;
}
}
internal PdfSecuritySettings securitySettings;
/// <summary>
/// Gets the document font table that holds all fonts used in the current document.
/// </summary>
internal PdfFontTable FontTable
{
get
{
if (this.fontTable == null)
this.fontTable = new PdfFontTable(this);
return this.fontTable;
}
}
PdfFontTable fontTable;
/// <summary>
/// Gets the document image table that holds all images used in the current document.
/// </summary>
internal PdfImageTable ImageTable
{
get
{
if (this.imageTable == null)
this.imageTable = new PdfImageTable(this);
return this.imageTable;
}
}
PdfImageTable imageTable;
/// <summary>
/// Gets the document form table that holds all form external objects used in the current document.
/// </summary>
internal PdfFormXObjectTable FormTable
{
get
{
if (this.formTable == null)
this.formTable = new PdfFormXObjectTable(this);
return this.formTable;
}
}
PdfFormXObjectTable formTable;
/// <summary>
/// Gets the document ExtGState table that holds all form state objects used in the current document.
/// </summary>
internal PdfExtGStateTable ExtGStateTable
{
get
{
if (this.extGStateTable == null)
this.extGStateTable = new PdfExtGStateTable(this);
return this.extGStateTable;
}
}
PdfExtGStateTable extGStateTable;
/// <summary>
/// Gets the PdfCatalog of the current document.
/// </summary>
internal PdfCatalog Catalog
{
get
{
if (this.catalog == null)
this.catalog = this.trailer.Root;
return catalog;
}
}
PdfCatalog catalog; // never changes if once created
/// <summary>
/// Gets the PdfInternals object of this document, that grants access to some internal structures
/// which are not part of the public interface of PdfDocument.
/// </summary>
public new PdfInternals Internals
{
get
{
if (this.internals == null)
this.internals = new PdfInternals(this);
return this.internals;
}
}
PdfInternals internals;
/// <summary>
/// Creates a new page and adds it to this document.
/// </summary>
public PdfPage AddPage()
{
if (!CanModify)
throw new InvalidOperationException(PSSR.CannotModify);
return Catalog.Pages.Add();
}
/// <summary>
/// Adds the specified page to this document. If the page is from an external document,
/// it is imported to this document. In this case the returned page is not the same
/// object as the specified one.
/// </summary>
public PdfPage AddPage(PdfPage page)
{
if (!CanModify)
throw new InvalidOperationException(PSSR.CannotModify);
return Catalog.Pages.Add(page);
}
/// <summary>
/// Creates a new page and inserts it in this document at the specified position.
/// </summary>
public PdfPage InsertPage(int index)
{
if (!CanModify)
throw new InvalidOperationException(PSSR.CannotModify);
return Catalog.Pages.Insert(index);
}
/// <summary>
/// Inserts the specified page in this document. If the page is from an external document,
/// it is imported to this document. In this case the returned page is not the same
/// object as the specified one.
/// </summary>
public PdfPage InsertPage(int index, PdfPage page)
{
if (!CanModify)
throw new InvalidOperationException(PSSR.CannotModify);
return Catalog.Pages.Insert(index, page);
}
/// <summary>
/// Gets the security handler.
/// </summary>
public PdfStandardSecurityHandler SecurityHandler
{
get { return this.trailer.SecurityHandler; }
}
internal PdfTrailer trailer;
internal PdfReferenceTable irefTable;
internal Stream outStream;
// Imported Document
internal Lexer lexer;
internal DateTime creation;
/// <summary>
/// Occurs when the specified document is not used anymore for importing content.
/// </summary>
internal void OnExternalDocumentFinalized(PdfDocument.DocumentHandle handle)
{
if (tls != null)
{
//PdfDocument[] documents = tls.Documents;
tls.DetachDocument(handle);
}
if (this.formTable != null)
formTable.DetachDocument(handle);
}
//internal static GlobalObjectTable Gob = new GlobalObjectTable();
/// <summary>
/// Gets the ThreadLocalStorage object. It is used for caching objects that should created
/// only once.
/// </summary>
internal static ThreadLocalStorage Tls
{
get
{
if (tls == null)
tls = new ThreadLocalStorage();
return tls;
}
}
[ThreadStatic]
static ThreadLocalStorage tls;
[DebuggerDisplay("(ID={ID}, alive={IsAlive})")]
internal class DocumentHandle
{
public DocumentHandle(PdfDocument document)
{
this.weakRef = new WeakReference(document);
this.ID = document.guid.ToString("B").ToUpper();
}
public bool IsAlive
{
get { return this.weakRef.IsAlive; }
}
public PdfDocument Target
{
get { return this.weakRef.Target as PdfDocument; }
}
WeakReference weakRef;
public string ID;
public override bool Equals(object obj)
{
DocumentHandle handle = obj as DocumentHandle;
if (!Object.ReferenceEquals(handle, null))
return this.ID == handle.ID;
return false;
}
public override int GetHashCode()
{
return this.ID.GetHashCode();
}
public static bool operator ==(DocumentHandle left, DocumentHandle right)
{
if (Object.ReferenceEquals(left, null))
return Object.ReferenceEquals(right, null);
return left.Equals(right);
}
public static bool operator !=(DocumentHandle left, DocumentHandle right)
{
return !(left == right);
}
}
}
}
| |
namespace Simple.Data.SqlTest
{
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using NUnit.Framework;
using Resources;
[TestFixture]
public class UpsertTests
{
[TestFixtureSetUp]
public void Setup()
{
DatabaseHelper.Reset();
}
[Test]
public void TestUpsertWithNamedArgumentsAndExistingObject()
{
var db = DatabaseHelper.Open();
db.Users.UpsertById(Id: 1, Name: "Ford Prefect");
var user = db.Users.Get(1);
Assert.IsNotNull(user);
Assert.AreEqual(1, user.Id);
Assert.AreEqual("Ford Prefect", user.Name);
}
[Test]
public void TestUpsertWithNamedArgumentsAndExistingObjectUsingTransaction()
{
using (var tx = DatabaseHelper.Open().BeginTransaction())
{
tx.Users.UpsertById(Id: 1, Name: "Ford Prefect");
var user = tx.Users.Get(1);
tx.Commit();
Assert.IsNotNull(user);
Assert.AreEqual(1, user.Id);
Assert.AreEqual("Ford Prefect", user.Name);
}
}
[Test]
public void TestUpsertWithNamedArgumentsAndNewObject()
{
var db = DatabaseHelper.Open();
var user = db.Users.UpsertById(Id: 0, Name: "Ford Prefect", Password: "Foo", Age: 42);
Assert.IsNotNull(user);
Assert.AreNotEqual(0, user.Id);
Assert.AreEqual("Ford Prefect", user.Name);
Assert.AreEqual("Foo", user.Password);
Assert.AreEqual(42, user.Age);
}
[Test]
public void TestUpsertWithStaticTypeObject()
{
var db = DatabaseHelper.Open();
var user = new User {Id = 2, Name = "Charlie", Password = "foobar", Age = 42};
var actual = db.Users.Upsert(user);
Assert.IsNotNull(user);
Assert.AreEqual(2, actual.Id);
Assert.AreEqual("Charlie", actual.Name);
Assert.AreEqual("foobar", actual.Password);
Assert.AreEqual(42, actual.Age);
}
[Test]
public void TestUpsertByWithStaticTypeObject()
{
var db = DatabaseHelper.Open();
var user = new User {Id = 2, Name = "Charlie", Password = "foobar", Age = 42};
var actual = db.Users.UpsertById(user);
Assert.IsNotNull(user);
Assert.AreEqual(2, actual.Id);
Assert.AreEqual("Charlie", actual.Name);
Assert.AreEqual("foobar", actual.Password);
Assert.AreEqual(42, actual.Age);
}
[Test]
public void TestMultiUpsertWithStaticTypeObjectsForExistingRecords()
{
var db = DatabaseHelper.Open();
var users = new[]
{
new User { Id = 1, Name = "Slartibartfast", Password = "bistromathics", Age = 777 },
new User { Id = 2, Name = "Wowbagger", Password = "teatime", Age = int.MaxValue }
};
IList<User> actuals = db.Users.Upsert(users).ToList<User>();
Assert.AreEqual(2, actuals.Count);
Assert.AreEqual(1, actuals[0].Id);
Assert.AreEqual("Slartibartfast", actuals[0].Name);
Assert.AreEqual("bistromathics", actuals[0].Password);
Assert.AreEqual(777, actuals[0].Age);
Assert.AreEqual(2, actuals[1].Id);
Assert.AreEqual("Wowbagger", actuals[1].Name);
Assert.AreEqual("teatime", actuals[1].Password);
Assert.AreEqual(int.MaxValue, actuals[1].Age);
}
[Test]
public void TestMultiUpsertWithStaticTypeObjectsForNewRecords()
{
var db = DatabaseHelper.Open();
var users = new[]
{
new User { Name = "Slartibartfast", Password = "bistromathics", Age = 777 },
new User { Name = "Wowbagger", Password = "teatime", Age = int.MaxValue }
};
IList<User> actuals = db.Users.Upsert(users).ToList<User>();
Assert.AreEqual(2, actuals.Count);
Assert.AreNotEqual(0, actuals[0].Id);
Assert.AreEqual("Slartibartfast", actuals[0].Name);
Assert.AreEqual("bistromathics", actuals[0].Password);
Assert.AreEqual(777, actuals[0].Age);
Assert.AreNotEqual(0, actuals[1].Id);
Assert.AreEqual("Wowbagger", actuals[1].Name);
Assert.AreEqual("teatime", actuals[1].Password);
Assert.AreEqual(int.MaxValue, actuals[1].Age);
}
[Test]
public void TestMultiUpsertWithStaticTypeObjectsForMixedRecords()
{
var db = DatabaseHelper.Open();
var users = new[]
{
new User { Id = 1, Name = "Slartibartfast", Password = "bistromathics", Age = 777 },
new User { Name = "Wowbagger", Password = "teatime", Age = int.MaxValue }
};
IList<User> actuals = db.Users.Upsert(users).ToList<User>();
Assert.AreEqual(2, actuals.Count);
Assert.AreEqual(1, actuals[0].Id);
Assert.AreEqual("Slartibartfast", actuals[0].Name);
Assert.AreEqual("bistromathics", actuals[0].Password);
Assert.AreEqual(777, actuals[0].Age);
Assert.AreNotEqual(0, actuals[1].Id);
Assert.AreEqual("Wowbagger", actuals[1].Name);
Assert.AreEqual("teatime", actuals[1].Password);
Assert.AreEqual(int.MaxValue, actuals[1].Age);
}
[Test]
public void TestMultiUpsertWithStaticTypeObjectsAndNoReturn()
{
var db = DatabaseHelper.Open();
var users = new[]
{
new User { Name = "Slartibartfast", Password = "bistromathics", Age = 777 },
new User { Name = "Wowbagger", Password = "teatime", Age = int.MaxValue }
};
//IList<User> actuals = db.Users.Upsert(users).ToList<User>();
db.Users.Upsert(users);
var slartibartfast = db.Users.FindByName("Slartibartfast");
Assert.IsNotNull(slartibartfast);
Assert.AreNotEqual(0, slartibartfast.Id);
Assert.AreEqual("Slartibartfast", slartibartfast.Name);
Assert.AreEqual("bistromathics", slartibartfast.Password);
Assert.AreEqual(777, slartibartfast.Age);
var wowbagger = db.Users.FindByName("Wowbagger");
Assert.IsNotNull(wowbagger);
Assert.AreNotEqual(0, wowbagger.Id);
Assert.AreEqual("Wowbagger", wowbagger.Name);
Assert.AreEqual("teatime", wowbagger.Password);
Assert.AreEqual(int.MaxValue, wowbagger.Age);
}
[Test]
public void TestUpsertWithDynamicTypeObject()
{
var db = DatabaseHelper.Open();
dynamic user = new ExpandoObject();
user.Name = "Marvin";
user.Password = "diodes";
user.Age = 42000000;
var actual = db.Users.Upsert(user);
Assert.IsNotNull(user);
Assert.AreEqual("Marvin", actual.Name);
Assert.AreEqual("diodes", actual.Password);
Assert.AreEqual(42000000, actual.Age);
}
[Test]
public void TestMultiUpsertWithDynamicTypeObjects()
{
var db = DatabaseHelper.Open();
dynamic user1 = new ExpandoObject();
user1.Name = "Slartibartfast";
user1.Password = "bistromathics";
user1.Age = 777;
dynamic user2 = new ExpandoObject();
user2.Name = "Wowbagger";
user2.Password = "teatime";
user2.Age = int.MaxValue;
var users = new[] { user1, user2 };
IList<dynamic> actuals = db.Users.Upsert(users).ToList();
Assert.AreEqual(2, actuals.Count);
Assert.AreNotEqual(0, actuals[0].Id);
Assert.AreEqual("Slartibartfast", actuals[0].Name);
Assert.AreEqual("bistromathics", actuals[0].Password);
Assert.AreEqual(777, actuals[0].Age);
Assert.AreNotEqual(0, actuals[1].Id);
Assert.AreEqual("Wowbagger", actuals[1].Name);
Assert.AreEqual("teatime", actuals[1].Password);
Assert.AreEqual(int.MaxValue, actuals[1].Age);
}
[Test]
public void TestMultiUpsertWithErrorCallback()
{
var db = DatabaseHelper.Open();
dynamic user1 = new ExpandoObject();
user1.Name = "Slartibartfast";
user1.Password = "bistromathics";
user1.Age = 777;
dynamic user2 = new ExpandoObject();
user2.Name = null;
user2.Password = null;
user2.Age = null;
dynamic user3 = new ExpandoObject();
user3.Name = "Wowbagger";
user3.Password = "teatime";
user3.Age = int.MaxValue;
var users = new[] { user1, user2, user3 };
bool passed = false;
ErrorCallback onError = (o, exception) => passed = true;
IList<dynamic> actuals = db.Users.Upsert(users,onError).ToList();
Assert.IsTrue(passed, "Callback was not called.");
Assert.AreEqual(2, actuals.Count);
Assert.AreNotEqual(0, actuals[0].Id);
Assert.AreEqual("Slartibartfast", actuals[0].Name);
Assert.AreEqual("bistromathics", actuals[0].Password);
Assert.AreEqual(777, actuals[0].Age);
Assert.AreNotEqual(0, actuals[1].Id);
Assert.AreEqual("Wowbagger", actuals[1].Name);
Assert.AreEqual("teatime", actuals[1].Password);
Assert.AreEqual(int.MaxValue, actuals[1].Age);
}
[Test]
public void TestMultiUpsertWithErrorCallbackUsingTransaction()
{
IList<dynamic> actuals;
bool passed = false;
using (var tx = DatabaseHelper.Open().BeginTransaction())
{
dynamic user1 = new ExpandoObject();
user1.Name = "Slartibartfast";
user1.Password = "bistromathics";
user1.Age = 777;
dynamic user2 = new ExpandoObject();
user2.Name = null;
user2.Password = null;
user2.Age = null;
dynamic user3 = new ExpandoObject();
user3.Name = "Wowbagger";
user3.Password = "teatime";
user3.Age = int.MaxValue;
var users = new[] {user1, user2, user3};
ErrorCallback onError = (o, exception) => passed = true;
actuals = tx.Users.Upsert(users, onError).ToList();
}
Assert.IsTrue(passed, "Callback was not called.");
Assert.AreEqual(2, actuals.Count);
Assert.AreNotEqual(0, actuals[0].Id);
Assert.AreEqual("Slartibartfast", actuals[0].Name);
Assert.AreEqual("bistromathics", actuals[0].Password);
Assert.AreEqual(777, actuals[0].Age);
Assert.AreNotEqual(0, actuals[1].Id);
Assert.AreEqual("Wowbagger", actuals[1].Name);
Assert.AreEqual("teatime", actuals[1].Password);
Assert.AreEqual(int.MaxValue, actuals[1].Age);
}
[Test]
public void TestTransactionMultiUpsertWithErrorCallback()
{
var db = DatabaseHelper.Open();
IList<dynamic> actuals;
bool passed = false;
using (var tx = db.BeginTransaction())
{
dynamic user1 = new ExpandoObject();
user1.Name = "Slartibartfast";
user1.Password = "bistromathics";
user1.Age = 777;
dynamic user2 = new ExpandoObject();
user2.Name = null;
user2.Password = null;
user2.Age = null;
dynamic user3 = new ExpandoObject();
user3.Name = "Wowbagger";
user3.Password = "teatime";
user3.Age = int.MaxValue;
var users = new[] {user1, user2, user3};
ErrorCallback onError = (o, exception) => passed = true;
actuals = db.Users.Upsert(users, onError).ToList();
tx.Commit();
}
Assert.IsTrue(passed, "Callback was not called.");
Assert.AreEqual(2, actuals.Count);
Assert.AreNotEqual(0, actuals[0].Id);
Assert.AreEqual("Slartibartfast", actuals[0].Name);
Assert.AreEqual("bistromathics", actuals[0].Password);
Assert.AreEqual(777, actuals[0].Age);
Assert.AreNotEqual(0, actuals[1].Id);
Assert.AreEqual("Wowbagger", actuals[1].Name);
Assert.AreEqual("teatime", actuals[1].Password);
Assert.AreEqual(int.MaxValue, actuals[1].Age);
}
[Test]
public void TestWithImageColumn()
{
var db = DatabaseHelper.Open();
try
{
var image = GetImage.Image;
db.Images.Upsert(Id: 1, TheImage: image);
var img = (DbImage)db.Images.FindById(1);
Assert.IsTrue(image.SequenceEqual(img.TheImage));
}
finally
{
db.Images.DeleteById(1);
}
}
[Test]
public void TestUpsertWithVarBinaryMaxColumn()
{
var db = DatabaseHelper.Open();
var image = GetImage.Image;
var blob = new Blob
{
Id = 1,
Data = image
};
db.Blobs.Upsert(blob);
blob = db.Blobs.FindById(1);
Assert.IsTrue(image.SequenceEqual(blob.Data));
}
[Test]
public void TestUpsertWithSingleArgumentAndExistingObject()
{
var db = DatabaseHelper.Open();
var actual = db.Users.UpsertById(Id: 1);
Assert.IsNotNull(actual);
Assert.AreEqual(1, actual.Id);
Assert.IsNotNull(actual.Name);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection.Emit
{
using System;
using System.Globalization;
using System.Diagnostics.SymbolStore;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Security;
internal class DynamicILGenerator : ILGenerator
{
internal DynamicScope m_scope;
private int m_methodSigToken;
internal unsafe DynamicILGenerator(DynamicMethod method, byte[] methodSignature, int size)
: base(method, size)
{
m_scope = new DynamicScope();
m_methodSigToken = m_scope.GetTokenFor(methodSignature);
}
internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
{
dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
module,
m_methodBuilder.Name,
(byte[])m_scope[m_methodSigToken],
new DynamicResolver(this));
}
#if FEATURE_APPX
private bool ProfileAPICheck
{
get
{
return ((DynamicMethod)m_methodBuilder).ProfileAPICheck;
}
}
#endif // FEATURE_APPX
// *** ILGenerator api ***
public override LocalBuilder DeclareLocal(Type localType, bool pinned)
{
LocalBuilder localBuilder;
if (localType == null)
throw new ArgumentNullException(nameof(localType));
Contract.EndContractBlock();
RuntimeType rtType = localType as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
#if FEATURE_APPX
if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
#endif
localBuilder = new LocalBuilder(m_localCount, localType, m_methodBuilder);
// add the localType to local signature
m_localSignature.AddArgument(localType, pinned);
m_localCount++;
return localBuilder;
}
//
//
// Token resolution calls
//
//
public override void Emit(OpCode opcode, MethodInfo meth)
{
if (meth == null)
throw new ArgumentNullException(nameof(meth));
Contract.EndContractBlock();
int stackchange = 0;
int token = 0;
DynamicMethod dynMeth = meth as DynamicMethod;
if (dynMeth == null)
{
RuntimeMethodInfo rtMeth = meth as RuntimeMethodInfo;
if (rtMeth == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(meth));
RuntimeType declaringType = rtMeth.GetRuntimeType();
if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray))
token = GetTokenFor(rtMeth, declaringType);
else
token = GetTokenFor(rtMeth);
}
else
{
// rule out not allowed operations on DynamicMethods
if (opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn) || opcode.Equals(OpCodes.Ldvirtftn))
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOpCodeOnDynamicMethod"));
}
token = GetTokenFor(dynMeth);
}
EnsureCapacity(7);
InternalEmit(opcode);
if (opcode.StackBehaviourPush == StackBehaviour.Varpush
&& meth.ReturnType != typeof(void))
{
stackchange++;
}
if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
{
stackchange -= meth.GetParametersNoCopy().Length;
}
// Pop the "this" parameter if the method is non-static,
// and the instruction is not newobj/ldtoken/ldftn.
if (!meth.IsStatic &&
!(opcode.Equals(OpCodes.Newobj) || opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn)))
{
stackchange--;
}
UpdateStackSize(opcode, stackchange);
PutInteger4(token);
}
[System.Runtime.InteropServices.ComVisible(true)]
public override void Emit(OpCode opcode, ConstructorInfo con)
{
if (con == null)
throw new ArgumentNullException(nameof(con));
Contract.EndContractBlock();
RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo;
if (rtConstructor == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(con));
RuntimeType declaringType = rtConstructor.GetRuntimeType();
int token;
if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray))
// need to sort out the stack size story
token = GetTokenFor(rtConstructor, declaringType);
else
token = GetTokenFor(rtConstructor);
EnsureCapacity(7);
InternalEmit(opcode);
// need to sort out the stack size story
UpdateStackSize(opcode, 1);
PutInteger4(token);
}
public override void Emit(OpCode opcode, Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
int token = GetTokenFor(rtType);
EnsureCapacity(7);
InternalEmit(opcode);
PutInteger4(token);
}
public override void Emit(OpCode opcode, FieldInfo field)
{
if (field == null)
throw new ArgumentNullException(nameof(field));
Contract.EndContractBlock();
RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo;
if (runtimeField == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), nameof(field));
int token;
if (field.DeclaringType == null)
token = GetTokenFor(runtimeField);
else
token = GetTokenFor(runtimeField, runtimeField.GetRuntimeType());
EnsureCapacity(7);
InternalEmit(opcode);
PutInteger4(token);
}
public override void Emit(OpCode opcode, String str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
Contract.EndContractBlock();
int tempVal = GetTokenForString(str);
EnsureCapacity(7);
InternalEmit(opcode);
PutInteger4(tempVal);
}
//
//
// Signature related calls (vararg, calli)
//
//
public override void EmitCalli(OpCode opcode,
CallingConventions callingConvention,
Type returnType,
Type[] parameterTypes,
Type[] optionalParameterTypes)
{
int stackchange = 0;
SignatureHelper sig;
if (optionalParameterTypes != null)
if ((callingConvention & CallingConventions.VarArgs) == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
sig = GetMemberRefSignature(callingConvention,
returnType,
parameterTypes,
optionalParameterTypes);
EnsureCapacity(7);
Emit(OpCodes.Calli);
// If there is a non-void return type, push one.
if (returnType != typeof(void))
stackchange++;
// Pop off arguments if any.
if (parameterTypes != null)
stackchange -= parameterTypes.Length;
// Pop off vararg arguments.
if (optionalParameterTypes != null)
stackchange -= optionalParameterTypes.Length;
// Pop the this parameter if the method has a this parameter.
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
stackchange--;
// Pop the native function pointer.
stackchange--;
UpdateStackSize(OpCodes.Calli, stackchange);
int token = GetTokenForSig(sig.GetSignature(true));
PutInteger4(token);
}
public override void EmitCalli(OpCode opcode,
CallingConvention unmanagedCallConv,
Type returnType,
Type[] parameterTypes)
{
int stackchange = 0;
int cParams = 0;
int i;
SignatureHelper sig;
if (parameterTypes != null)
cParams = parameterTypes.Length;
sig = SignatureHelper.GetMethodSigHelper(unmanagedCallConv, returnType);
if (parameterTypes != null)
for (i = 0; i < cParams; i++)
sig.AddArgument(parameterTypes[i]);
// If there is a non-void return type, push one.
if (returnType != typeof(void))
stackchange++;
// Pop off arguments if any.
if (parameterTypes != null)
stackchange -= cParams;
// Pop the native function pointer.
stackchange--;
UpdateStackSize(OpCodes.Calli, stackchange);
EnsureCapacity(7);
Emit(OpCodes.Calli);
int token = GetTokenForSig(sig.GetSignature(true));
PutInteger4(token);
}
public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
{
if (methodInfo == null)
throw new ArgumentNullException(nameof(methodInfo));
if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), nameof(opcode));
if (methodInfo.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo));
if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo));
Contract.EndContractBlock();
int tk;
int stackchange = 0;
tk = GetMemberRefToken(methodInfo, optionalParameterTypes);
EnsureCapacity(7);
InternalEmit(opcode);
// Push the return value if there is one.
if (methodInfo.ReturnType != typeof(void))
stackchange++;
// Pop the parameters.
stackchange -= methodInfo.GetParameterTypes().Length;
// Pop the this parameter if the method is non-static and the
// instruction is not newobj.
if (!(methodInfo is SymbolMethod) && methodInfo.IsStatic == false && !(opcode.Equals(OpCodes.Newobj)))
stackchange--;
// Pop the optional parameters off the stack.
if (optionalParameterTypes != null)
stackchange -= optionalParameterTypes.Length;
UpdateStackSize(opcode, stackchange);
PutInteger4(tk);
}
public override void Emit(OpCode opcode, SignatureHelper signature)
{
if (signature == null)
throw new ArgumentNullException(nameof(signature));
Contract.EndContractBlock();
int stackchange = 0;
EnsureCapacity(7);
InternalEmit(opcode);
// The only IL instruction that has VarPop behaviour, that takes a
// Signature token as a parameter is calli. Pop the parameters and
// the native function pointer. To be conservative, do not pop the
// this pointer since this information is not easily derived from
// SignatureHelper.
if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
{
Debug.Assert(opcode.Equals(OpCodes.Calli),
"Unexpected opcode encountered for StackBehaviour VarPop.");
// Pop the arguments..
stackchange -= signature.ArgumentCount;
// Pop native function pointer off the stack.
stackchange--;
UpdateStackSize(opcode, stackchange);
}
int token = GetTokenForSig(signature.GetSignature(true)); ;
PutInteger4(token);
}
//
//
// Exception related generation
//
//
public override void BeginExceptFilterBlock()
{
// Begins an exception filter block. Emits a branch instruction to the end of the current exception block.
if (CurrExcStackCount == 0)
throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
__ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1];
Label endLabel = current.GetEndLabel();
Emit(OpCodes.Leave, endLabel);
UpdateStackSize(OpCodes.Nop, 1);
current.MarkFilterAddr(ILOffset);
}
public override void BeginCatchBlock(Type exceptionType)
{
if (CurrExcStackCount == 0)
throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
Contract.EndContractBlock();
__ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1];
RuntimeType rtType = exceptionType as RuntimeType;
if (current.GetCurrentState() == __ExceptionInfo.State_Filter)
{
if (exceptionType != null)
{
throw new ArgumentException(Environment.GetResourceString("Argument_ShouldNotSpecifyExceptionType"));
}
this.Emit(OpCodes.Endfilter);
current.MarkCatchAddr(ILOffset, null);
}
else
{
// execute this branch if previous clause is Catch or Fault
if (exceptionType == null)
throw new ArgumentNullException(nameof(exceptionType));
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
Label endLabel = current.GetEndLabel();
this.Emit(OpCodes.Leave, endLabel);
// if this is a catch block the exception will be pushed on the stack and we need to update the stack info
UpdateStackSize(OpCodes.Nop, 1);
current.MarkCatchAddr(ILOffset, exceptionType);
// this is relying on too much implementation details of the base and so it's highly breaking
// Need to have a more integrated story for exceptions
current.m_filterAddr[current.m_currentCatch - 1] = GetTokenFor(rtType);
}
}
//
//
// debugger related calls.
//
//
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void UsingNamespace(String ns)
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void MarkSequencePoint(ISymbolDocumentWriter document,
int startLine,
int startColumn,
int endLine,
int endColumn)
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
public override void BeginScope()
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
public override void EndScope()
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes)
{
Type[] parameterTypes;
if (optionalParameterTypes != null && (methodInfo.CallingConvention & CallingConventions.VarArgs) == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
RuntimeMethodInfo rtMeth = methodInfo as RuntimeMethodInfo;
DynamicMethod dm = methodInfo as DynamicMethod;
if (rtMeth == null && dm == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(methodInfo));
ParameterInfo[] paramInfo = methodInfo.GetParametersNoCopy();
if (paramInfo != null && paramInfo.Length != 0)
{
parameterTypes = new Type[paramInfo.Length];
for (int i = 0; i < paramInfo.Length; i++)
parameterTypes[i] = paramInfo[i].ParameterType;
}
else
{
parameterTypes = null;
}
SignatureHelper sig = GetMemberRefSignature(methodInfo.CallingConvention,
MethodBuilder.GetMethodBaseReturnType(methodInfo),
parameterTypes,
optionalParameterTypes);
if (rtMeth != null)
return GetTokenForVarArgMethod(rtMeth, sig);
else
return GetTokenForVarArgMethod(dm, sig);
}
internal override SignatureHelper GetMemberRefSignature(
CallingConventions call,
Type returnType,
Type[] parameterTypes,
Type[] optionalParameterTypes)
{
SignatureHelper sig = SignatureHelper.GetMethodSigHelper(call, returnType);
if (parameterTypes != null)
{
foreach (Type t in parameterTypes)
sig.AddArgument(t);
}
if (optionalParameterTypes != null && optionalParameterTypes.Length != 0)
{
// add the sentinel
sig.AddSentinel();
foreach (Type t in optionalParameterTypes)
sig.AddArgument(t);
}
return sig;
}
internal override void RecordTokenFixup()
{
// DynamicMethod doesn't need fixup.
}
#region GetTokenFor helpers
private int GetTokenFor(RuntimeType rtType)
{
#if FEATURE_APPX
if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
#endif
return m_scope.GetTokenFor(rtType.TypeHandle);
}
private int GetTokenFor(RuntimeFieldInfo runtimeField)
{
#if FEATURE_APPX
if (ProfileAPICheck)
{
RtFieldInfo rtField = runtimeField as RtFieldInfo;
if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
}
#endif
return m_scope.GetTokenFor(runtimeField.FieldHandle);
}
private int GetTokenFor(RuntimeFieldInfo runtimeField, RuntimeType rtType)
{
#if FEATURE_APPX
if (ProfileAPICheck)
{
RtFieldInfo rtField = runtimeField as RtFieldInfo;
if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
}
#endif
return m_scope.GetTokenFor(runtimeField.FieldHandle, rtType.TypeHandle);
}
private int GetTokenFor(RuntimeConstructorInfo rtMeth)
{
#if FEATURE_APPX
if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
#endif
return m_scope.GetTokenFor(rtMeth.MethodHandle);
}
private int GetTokenFor(RuntimeConstructorInfo rtMeth, RuntimeType rtType)
{
#if FEATURE_APPX
if (ProfileAPICheck)
{
if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
}
#endif
return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle);
}
private int GetTokenFor(RuntimeMethodInfo rtMeth)
{
#if FEATURE_APPX
if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
#endif
return m_scope.GetTokenFor(rtMeth.MethodHandle);
}
private int GetTokenFor(RuntimeMethodInfo rtMeth, RuntimeType rtType)
{
#if FEATURE_APPX
if (ProfileAPICheck)
{
if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
}
#endif
return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle);
}
private int GetTokenFor(DynamicMethod dm)
{
return m_scope.GetTokenFor(dm);
}
private int GetTokenForVarArgMethod(RuntimeMethodInfo rtMeth, SignatureHelper sig)
{
#if FEATURE_APPX
if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
#endif
VarArgMethod varArgMeth = new VarArgMethod(rtMeth, sig);
return m_scope.GetTokenFor(varArgMeth);
}
private int GetTokenForVarArgMethod(DynamicMethod dm, SignatureHelper sig)
{
VarArgMethod varArgMeth = new VarArgMethod(dm, sig);
return m_scope.GetTokenFor(varArgMeth);
}
private int GetTokenForString(String s)
{
return m_scope.GetTokenFor(s);
}
private int GetTokenForSig(byte[] sig)
{
return m_scope.GetTokenFor(sig);
}
#endregion
}
internal class DynamicResolver : Resolver
{
#region Private Data Members
private __ExceptionInfo[] m_exceptions;
private byte[] m_exceptionHeader;
private DynamicMethod m_method;
private byte[] m_code;
private byte[] m_localSignature;
private int m_stackSize;
private DynamicScope m_scope;
#endregion
#region Internal Methods
internal DynamicResolver(DynamicILGenerator ilGenerator)
{
m_stackSize = ilGenerator.GetMaxStackSize();
m_exceptions = ilGenerator.GetExceptions();
m_code = ilGenerator.BakeByteArray();
m_localSignature = ilGenerator.m_localSignature.InternalGetSignatureArray();
m_scope = ilGenerator.m_scope;
m_method = (DynamicMethod)ilGenerator.m_methodBuilder;
m_method.m_resolver = this;
}
internal DynamicResolver(DynamicILInfo dynamicILInfo)
{
m_stackSize = dynamicILInfo.MaxStackSize;
m_code = dynamicILInfo.Code;
m_localSignature = dynamicILInfo.LocalSignature;
m_exceptionHeader = dynamicILInfo.Exceptions;
//m_exceptions = dynamicILInfo.Exceptions;
m_scope = dynamicILInfo.DynamicScope;
m_method = dynamicILInfo.DynamicMethod;
m_method.m_resolver = this;
}
//
// We can destroy the unmanaged part of dynamic method only after the managed part is definitely gone and thus
// nobody can call the dynamic method anymore. A call to finalizer alone does not guarantee that the managed
// part is gone. A malicious code can keep a reference to DynamicMethod in long weak reference that survives finalization,
// or we can be running during shutdown where everything is finalized.
//
// The unmanaged resolver keeps a reference to the managed resolver in long weak handle. If the long weak handle
// is null, we can be sure that the managed part of the dynamic method is definitely gone and that it is safe to
// destroy the unmanaged part. (Note that the managed finalizer has to be on the same object that the long weak handle
// points to in order for this to work.) Unfortunately, we can not perform the above check when out finalizer
// is called - the long weak handle won't be cleared yet. Instead, we create a helper scout object that will attempt
// to do the destruction after next GC.
//
// The finalization does not have to be done using CriticalFinalizerObject. We have to go over all DynamicMethodDescs
// during AppDomain shutdown anyway to avoid leaks e.g. if somebody stores reference to DynamicMethod in static.
//
~DynamicResolver()
{
DynamicMethod method = m_method;
if (method == null)
return;
if (method.m_methodHandle == null)
return;
DestroyScout scout = null;
try
{
scout = new DestroyScout();
}
catch
{
// We go over all DynamicMethodDesc during AppDomain shutdown and make sure
// that everything associated with them is released. So it is ok to skip reregistration
// for finalization during appdomain shutdown
if (!Environment.HasShutdownStarted &&
!AppDomain.CurrentDomain.IsFinalizingForUnload())
{
// Try again later.
GC.ReRegisterForFinalize(this);
}
return;
}
// We can never ever have two active destroy scouts for the same method. We need to initialize the scout
// outside the try/reregister block to avoid possibility of reregistration for finalization with active scout.
scout.m_methodHandle = method.m_methodHandle.Value;
}
private class DestroyScout
{
internal RuntimeMethodHandleInternal m_methodHandle;
~DestroyScout()
{
if (m_methodHandle.IsNullHandle())
return;
// It is not safe to destroy the method if the managed resolver is alive.
if (RuntimeMethodHandle.GetResolver(m_methodHandle) != null)
{
if (!Environment.HasShutdownStarted &&
!AppDomain.CurrentDomain.IsFinalizingForUnload())
{
// Somebody might have been holding a reference on us via weak handle.
// We will keep trying. It will be hopefully released eventually.
GC.ReRegisterForFinalize(this);
}
return;
}
RuntimeMethodHandle.Destroy(m_methodHandle);
}
}
// Keep in sync with vm/dynamicmethod.h
[Flags]
internal enum SecurityControlFlags
{
Default = 0x0,
SkipVisibilityChecks = 0x1,
RestrictedSkipVisibilityChecks = 0x2,
HasCreationContext = 0x4,
CanSkipCSEvaluation = 0x8,
}
internal override RuntimeType GetJitContext(ref int securityControlFlags)
{
RuntimeType typeOwner;
SecurityControlFlags flags = SecurityControlFlags.Default;
if (m_method.m_restrictedSkipVisibility)
flags |= SecurityControlFlags.RestrictedSkipVisibilityChecks;
else if (m_method.m_skipVisibility)
flags |= SecurityControlFlags.SkipVisibilityChecks;
typeOwner = m_method.m_typeOwner;
securityControlFlags = (int)flags;
return typeOwner;
}
private static int CalculateNumberOfExceptions(__ExceptionInfo[] excp)
{
int num = 0;
if (excp == null)
return 0;
for (int i = 0; i < excp.Length; i++)
num += excp[i].GetNumberOfCatches();
return num;
}
internal override byte[] GetCodeInfo(
ref int stackSize, ref int initLocals, ref int EHCount)
{
stackSize = m_stackSize;
if (m_exceptionHeader != null && m_exceptionHeader.Length != 0)
{
if (m_exceptionHeader.Length < 4)
throw new FormatException();
byte header = m_exceptionHeader[0];
if ((header & 0x40) != 0) // Fat
{
byte[] size = new byte[4];
for (int q = 0; q < 3; q++)
size[q] = m_exceptionHeader[q + 1];
EHCount = (BitConverter.ToInt32(size, 0) - 4) / 24;
}
else
EHCount = (m_exceptionHeader[1] - 2) / 12;
}
else
{
EHCount = CalculateNumberOfExceptions(m_exceptions);
}
initLocals = (m_method.InitLocals) ? 1 : 0;
return m_code;
}
internal override byte[] GetLocalsSignature()
{
return m_localSignature;
}
internal override unsafe byte[] GetRawEHInfo()
{
return m_exceptionHeader;
}
internal override unsafe void GetEHInfo(int excNumber, void* exc)
{
CORINFO_EH_CLAUSE* exception = (CORINFO_EH_CLAUSE*)exc;
for (int i = 0; i < m_exceptions.Length; i++)
{
int excCount = m_exceptions[i].GetNumberOfCatches();
if (excNumber < excCount)
{
// found the right exception block
exception->Flags = m_exceptions[i].GetExceptionTypes()[excNumber];
exception->TryOffset = m_exceptions[i].GetStartAddress();
if ((exception->Flags & __ExceptionInfo.Finally) != __ExceptionInfo.Finally)
exception->TryLength = m_exceptions[i].GetEndAddress() - exception->TryOffset;
else
exception->TryLength = m_exceptions[i].GetFinallyEndAddress() - exception->TryOffset;
exception->HandlerOffset = m_exceptions[i].GetCatchAddresses()[excNumber];
exception->HandlerLength = m_exceptions[i].GetCatchEndAddresses()[excNumber] - exception->HandlerOffset;
// this is cheating because the filter address is the token of the class only for light code gen
exception->ClassTokenOrFilterOffset = m_exceptions[i].GetFilterAddresses()[excNumber];
break;
}
excNumber -= excCount;
}
}
internal override String GetStringLiteral(int token) { return m_scope.GetString(token); }
internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle)
{
typeHandle = new IntPtr();
methodHandle = new IntPtr();
fieldHandle = new IntPtr();
Object handle = m_scope[token];
if (handle == null)
throw new InvalidProgramException();
if (handle is RuntimeTypeHandle)
{
typeHandle = ((RuntimeTypeHandle)handle).Value;
return;
}
if (handle is RuntimeMethodHandle)
{
methodHandle = ((RuntimeMethodHandle)handle).Value;
return;
}
if (handle is RuntimeFieldHandle)
{
fieldHandle = ((RuntimeFieldHandle)handle).Value;
return;
}
DynamicMethod dm = handle as DynamicMethod;
if (dm != null)
{
methodHandle = dm.GetMethodDescriptor().Value;
return;
}
GenericMethodInfo gmi = handle as GenericMethodInfo;
if (gmi != null)
{
methodHandle = gmi.m_methodHandle.Value;
typeHandle = gmi.m_context.Value;
return;
}
GenericFieldInfo gfi = handle as GenericFieldInfo;
if (gfi != null)
{
fieldHandle = gfi.m_fieldHandle.Value;
typeHandle = gfi.m_context.Value;
return;
}
VarArgMethod vaMeth = handle as VarArgMethod;
if (vaMeth != null)
{
if (vaMeth.m_dynamicMethod == null)
{
methodHandle = vaMeth.m_method.MethodHandle.Value;
typeHandle = vaMeth.m_method.GetDeclaringTypeInternal().GetTypeHandleInternal().Value;
}
else
methodHandle = vaMeth.m_dynamicMethod.GetMethodDescriptor().Value;
return;
}
}
internal override byte[] ResolveSignature(int token, int fromMethod)
{
return m_scope.ResolveSignature(token, fromMethod);
}
internal override MethodInfo GetDynamicMethod()
{
return m_method.GetMethodInfo();
}
#endregion
}
[System.Runtime.InteropServices.ComVisible(true)]
public class DynamicILInfo
{
#region Private Data Members
private DynamicMethod m_method;
private DynamicScope m_scope;
private byte[] m_exceptions;
private byte[] m_code;
private byte[] m_localSignature;
private int m_maxStackSize;
private int m_methodSignature;
#endregion
#region Constructor
internal DynamicILInfo(DynamicScope scope, DynamicMethod method, byte[] methodSignature)
{
m_method = method;
m_scope = scope;
m_methodSignature = m_scope.GetTokenFor(methodSignature);
m_exceptions = EmptyArray<Byte>.Value;
m_code = EmptyArray<Byte>.Value;
m_localSignature = EmptyArray<Byte>.Value;
}
#endregion
#region Internal Methods
internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
{
dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
module, m_method.Name, (byte[])m_scope[m_methodSignature], new DynamicResolver(this));
}
internal byte[] LocalSignature
{
get
{
if (m_localSignature == null)
m_localSignature = SignatureHelper.GetLocalVarSigHelper().InternalGetSignatureArray();
return m_localSignature;
}
}
internal byte[] Exceptions { get { return m_exceptions; } }
internal byte[] Code { get { return m_code; } }
internal int MaxStackSize { get { return m_maxStackSize; } }
#endregion
#region Public ILGenerator Methods
public DynamicMethod DynamicMethod { get { return m_method; } }
internal DynamicScope DynamicScope { get { return m_scope; } }
public void SetCode(byte[] code, int maxStackSize)
{
m_code = (code != null) ? (byte[])code.Clone() : EmptyArray<Byte>.Value;
m_maxStackSize = maxStackSize;
}
[CLSCompliant(false)]
public unsafe void SetCode(byte* code, int codeSize, int maxStackSize)
{
if (codeSize < 0)
throw new ArgumentOutOfRangeException(nameof(codeSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if (codeSize > 0 && code == null)
throw new ArgumentNullException(nameof(code));
Contract.EndContractBlock();
m_code = new byte[codeSize];
for (int i = 0; i < codeSize; i++)
{
m_code[i] = *code;
code++;
}
m_maxStackSize = maxStackSize;
}
public void SetExceptions(byte[] exceptions)
{
m_exceptions = (exceptions != null) ? (byte[])exceptions.Clone() : EmptyArray<Byte>.Value;
}
[CLSCompliant(false)]
public unsafe void SetExceptions(byte* exceptions, int exceptionsSize)
{
if (exceptionsSize < 0)
throw new ArgumentOutOfRangeException(nameof(exceptionsSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if (exceptionsSize > 0 && exceptions == null)
throw new ArgumentNullException(nameof(exceptions));
Contract.EndContractBlock();
m_exceptions = new byte[exceptionsSize];
for (int i = 0; i < exceptionsSize; i++)
{
m_exceptions[i] = *exceptions;
exceptions++;
}
}
public void SetLocalSignature(byte[] localSignature)
{
m_localSignature = (localSignature != null) ? (byte[])localSignature.Clone() : EmptyArray<Byte>.Value;
}
[CLSCompliant(false)]
public unsafe void SetLocalSignature(byte* localSignature, int signatureSize)
{
if (signatureSize < 0)
throw new ArgumentOutOfRangeException(nameof(signatureSize), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
if (signatureSize > 0 && localSignature == null)
throw new ArgumentNullException(nameof(localSignature));
Contract.EndContractBlock();
m_localSignature = new byte[signatureSize];
for (int i = 0; i < signatureSize; i++)
{
m_localSignature[i] = *localSignature;
localSignature++;
}
}
#endregion
#region Public Scope Methods
public int GetTokenFor(RuntimeMethodHandle method)
{
return DynamicScope.GetTokenFor(method);
}
public int GetTokenFor(DynamicMethod method)
{
return DynamicScope.GetTokenFor(method);
}
public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle contextType)
{
return DynamicScope.GetTokenFor(method, contextType);
}
public int GetTokenFor(RuntimeFieldHandle field)
{
return DynamicScope.GetTokenFor(field);
}
public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle contextType)
{
return DynamicScope.GetTokenFor(field, contextType);
}
public int GetTokenFor(RuntimeTypeHandle type)
{
return DynamicScope.GetTokenFor(type);
}
public int GetTokenFor(string literal)
{
return DynamicScope.GetTokenFor(literal);
}
public int GetTokenFor(byte[] signature)
{
return DynamicScope.GetTokenFor(signature);
}
#endregion
}
internal class DynamicScope
{
#region Private Data Members
internal List<Object> m_tokens;
#endregion
#region Constructor
internal unsafe DynamicScope()
{
m_tokens = new List<Object>();
m_tokens.Add(null);
}
#endregion
#region Internal Methods
internal object this[int token]
{
get
{
token &= 0x00FFFFFF;
if (token < 0 || token > m_tokens.Count)
return null;
return m_tokens[token];
}
}
internal int GetTokenFor(VarArgMethod varArgMethod)
{
m_tokens.Add(varArgMethod);
return m_tokens.Count - 1 | (int)MetadataTokenType.MemberRef;
}
internal string GetString(int token) { return this[token] as string; }
internal byte[] ResolveSignature(int token, int fromMethod)
{
if (fromMethod == 0)
return (byte[])this[token];
VarArgMethod vaMethod = this[token] as VarArgMethod;
if (vaMethod == null)
return null;
return vaMethod.m_signature.GetSignature(true);
}
#endregion
#region Public Methods
public int GetTokenFor(RuntimeMethodHandle method)
{
IRuntimeMethodInfo methodReal = method.GetMethodInfo();
RuntimeMethodHandleInternal rmhi = methodReal.Value;
if (methodReal != null && !RuntimeMethodHandle.IsDynamicMethod(rmhi))
{
RuntimeType type = RuntimeMethodHandle.GetDeclaringType(rmhi);
if ((type != null) && RuntimeTypeHandle.HasInstantiation(type))
{
// Do we really need to retrieve this much info just to throw an exception?
MethodBase m = RuntimeType.GetMethodBase(methodReal);
Type t = m.DeclaringType.GetGenericTypeDefinition();
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGenericLcg"), m, t));
}
}
m_tokens.Add(method);
return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef;
}
public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle typeContext)
{
m_tokens.Add(new GenericMethodInfo(method, typeContext));
return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef;
}
public int GetTokenFor(DynamicMethod method)
{
m_tokens.Add(method);
return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef;
}
public int GetTokenFor(RuntimeFieldHandle field)
{
m_tokens.Add(field);
return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef;
}
public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle typeContext)
{
m_tokens.Add(new GenericFieldInfo(field, typeContext));
return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef;
}
public int GetTokenFor(RuntimeTypeHandle type)
{
m_tokens.Add(type);
return m_tokens.Count - 1 | (int)MetadataTokenType.TypeDef;
}
public int GetTokenFor(string literal)
{
m_tokens.Add(literal);
return m_tokens.Count - 1 | (int)MetadataTokenType.String;
}
public int GetTokenFor(byte[] signature)
{
m_tokens.Add(signature);
return m_tokens.Count - 1 | (int)MetadataTokenType.Signature;
}
#endregion
}
internal sealed class GenericMethodInfo
{
internal RuntimeMethodHandle m_methodHandle;
internal RuntimeTypeHandle m_context;
internal GenericMethodInfo(RuntimeMethodHandle methodHandle, RuntimeTypeHandle context)
{
m_methodHandle = methodHandle;
m_context = context;
}
}
internal sealed class GenericFieldInfo
{
internal RuntimeFieldHandle m_fieldHandle;
internal RuntimeTypeHandle m_context;
internal GenericFieldInfo(RuntimeFieldHandle fieldHandle, RuntimeTypeHandle context)
{
m_fieldHandle = fieldHandle;
m_context = context;
}
}
internal sealed class VarArgMethod
{
internal RuntimeMethodInfo m_method;
internal DynamicMethod m_dynamicMethod;
internal SignatureHelper m_signature;
internal VarArgMethod(DynamicMethod dm, SignatureHelper signature)
{
m_dynamicMethod = dm;
m_signature = signature;
}
internal VarArgMethod(RuntimeMethodInfo method, SignatureHelper signature)
{
m_method = method;
m_signature = signature;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Globalization
{
/// <remarks>
/// Rules for the Hijri calendar:
/// - The Hijri calendar is a strictly Lunar calendar.
/// - Days begin at sunset.
/// - Islamic Year 1 (Muharram 1, 1 A.H.) is equivalent to absolute date
/// 227015 (Friday, July 16, 622 C.E. - Julian).
/// - Leap Years occur in the 2, 5, 7, 10, 13, 16, 18, 21, 24, 26, & 29th
/// years of a 30-year cycle. Year = leap iff ((11y+14) mod 30 < 11).
/// - There are 12 months which contain alternately 30 and 29 days.
/// - The 12th month, Dhu al-Hijjah, contains 30 days instead of 29 days
/// in a leap year.
/// - Common years have 354 days. Leap years have 355 days.
/// - There are 10,631 days in a 30-year cycle.
/// - The Islamic months are:
/// 1. Muharram (30 days) 7. Rajab (30 days)
/// 2. Safar (29 days) 8. Sha'ban (29 days)
/// 3. Rabi I (30 days) 9. Ramadan (30 days)
/// 4. Rabi II (29 days) 10. Shawwal (29 days)
/// 5. Jumada I (30 days) 11. Dhu al-Qada (30 days)
/// 6. Jumada II (29 days) 12. Dhu al-Hijjah (29 days) {30}
///
/// NOTENOTE
/// The calculation of the HijriCalendar is based on the absolute date. And the
/// absolute date means the number of days from January 1st, 1 A.D.
/// Therefore, we do not support the days before the January 1st, 1 A.D.
///
/// Calendar support range:
/// Calendar Minimum Maximum
/// ========== ========== ==========
/// Gregorian 0622/07/18 9999/12/31
/// Hijri 0001/01/01 9666/04/03
/// </remarks>
public partial class HijriCalendar : Calendar
{
public static readonly int HijriEra = 1;
private const int DatePartYear = 0;
private const int DatePartDayOfYear = 1;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
private const int MinAdvancedHijri = -2;
private const int MaxAdvancedHijri = 2;
private static readonly int[] s_hijriMonthDays = { 0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355 };
private int _hijriAdvance = int.MinValue;
// DateTime.MaxValue = Hijri calendar (year:9666, month: 4, day: 3).
private const int MaxCalendarYear = 9666;
private const int MaxCalendarMonth = 4;
// Hijri calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 7, day: 18)
// This is the minimal Gregorian date that we support in the HijriCalendar.
private static readonly DateTime s_calendarMinValue = new DateTime(622, 7, 18);
private static readonly DateTime s_calendarMaxValue = DateTime.MaxValue;
public override DateTime MinSupportedDateTime => s_calendarMinValue;
public override DateTime MaxSupportedDateTime => s_calendarMaxValue;
public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.LunarCalendar;
public HijriCalendar()
{
}
internal override CalendarId ID => CalendarId.HIJRI;
protected override int DaysInYearBeforeMinSupportedYear
{
get
{
// the year before the 1st year of the cycle would have been the 30th year
// of the previous cycle which is not a leap year. Common years have 354 days.
return 354;
}
}
private long GetAbsoluteDateHijri(int y, int m, int d)
{
return (long)(DaysUpToHijriYear(y) + s_hijriMonthDays[m - 1] + d - 1 - HijriAdjustment);
}
private long DaysUpToHijriYear(int HijriYear)
{
// Compute the number of years up to the current 30 year cycle.
int numYear30 = ((HijriYear - 1) / 30) * 30;
// Compute the number of years left. This is the number of years
// into the 30 year cycle for the given year.
int numYearsLeft = HijriYear - numYear30 - 1;
// Compute the number of absolute days up to the given year.
long numDays = ((numYear30 * 10631L) / 30L) + 227013L;
while (numYearsLeft > 0)
{
// Common year is 354 days, and leap year is 355 days.
numDays += 354 + (IsLeapYear(numYearsLeft, CurrentEra) ? 1 : 0);
numYearsLeft--;
}
return numDays;
}
public int HijriAdjustment
{
get
{
if (_hijriAdvance == int.MinValue)
{
// Never been set before. Use the system value from registry.
_hijriAdvance = GetHijriDateAdjustment();
}
return _hijriAdvance;
}
set
{
if (value < MinAdvancedHijri || value > MaxAdvancedHijri)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, MinAdvancedHijri, MaxAdvancedHijri));
}
VerifyWritable();
_hijriAdvance = value;
}
}
internal static void CheckTicksRange(long ticks)
{
if (ticks < s_calendarMinValue.Ticks || ticks > s_calendarMaxValue.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
ticks,
SR.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
s_calendarMinValue,
s_calendarMaxValue));
}
}
internal static void CheckEraRange(int era)
{
if (era != CurrentEra && era != HijriEra)
{
throw new ArgumentOutOfRangeException(nameof(era), era, SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal static void CheckYearRange(int year, int era)
{
CheckEraRange(era);
if (year < 1 || year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxCalendarYear));
}
}
internal static void CheckYearMonthRange(int year, int month, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
if (month > MaxCalendarMonth)
{
throw new ArgumentOutOfRangeException(
nameof(month),
month,
SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxCalendarMonth));
}
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), month, SR.ArgumentOutOfRange_Month);
}
}
/// <summary>
/// First, we get the absolute date (the number of days from January 1st, 1 A.C) for the given ticks.
/// Use the formula (((AbsoluteDate - 227013) * 30) / 10631) + 1, we can a rough value for the Hijri year.
/// In order to get the exact Hijri year, we compare the exact absolute date for HijriYear and (HijriYear + 1).
/// From here, we can get the correct Hijri year.
/// </summary>
internal virtual int GetDatePart(long ticks, int part)
{
CheckTicksRange(ticks);
// Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
// 1/1/0001 is absolute date 1.
long numDays = ticks / GregorianCalendar.TicksPerDay + 1;
// See how much we need to backup or advance
numDays += HijriAdjustment;
// Calculate the appromixate Hijri Year from this magic formula.
int hijriYear = (int)(((numDays - 227013) * 30) / 10631) + 1;
long daysToHijriYear = DaysUpToHijriYear(hijriYear); // The absolute date for HijriYear
long daysOfHijriYear = GetDaysInYear(hijriYear, CurrentEra); // The number of days for (HijriYear+1) year.
if (numDays < daysToHijriYear)
{
daysToHijriYear -= daysOfHijriYear;
hijriYear--;
}
else if (numDays == daysToHijriYear)
{
hijriYear--;
daysToHijriYear -= GetDaysInYear(hijriYear, CurrentEra);
}
else
{
if (numDays > daysToHijriYear + daysOfHijriYear)
{
daysToHijriYear += daysOfHijriYear;
hijriYear++;
}
}
if (part == DatePartYear)
{
return hijriYear;
}
// Calculate the Hijri Month.
int hijriMonth = 1;
numDays -= daysToHijriYear;
if (part == DatePartDayOfYear)
{
return ((int)numDays);
}
while ((hijriMonth <= 12) && (numDays > s_hijriMonthDays[hijriMonth - 1]))
{
hijriMonth++;
}
hijriMonth--;
if (part == DatePartMonth)
{
return hijriMonth;
}
// Calculate the Hijri Day.
int hijriDay = (int)(numDays - s_hijriMonthDays[hijriMonth - 1]);
if (part == DatePartDay)
{
return hijriDay;
}
// Incorrect part value.
throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
}
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
months,
SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000));
}
// Get the date in Hijri calendar.
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 days = GetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
long ticks = GetAbsoluteDateHijri(y, m, d) * TicksPerDay + (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)
{
CheckYearMonthRange(year, month, era);
if (month == 12)
{
// For the 12th month, leap year has 30 days, and common year has 29 days.
return IsLeapYear(year, CurrentEra) ? 30 : 29;
}
// Other months contain 30 and 29 days alternatively. The 1st month has 30 days.
return ((month % 2) == 1) ? 30 : 29;
}
public override int GetDaysInYear(int year, int era)
{
CheckYearRange(year, era);
// Common years have 354 days. Leap years have 355 days.
return IsLeapYear(year, CurrentEra) ? 355 : 354;
}
public override int GetEra(DateTime time)
{
CheckTicksRange(time.Ticks);
return HijriEra;
}
public override int[] Eras => new int[] { HijriEra };
public override int GetMonth(DateTime time)
{
return GetDatePart(time.Ticks, DatePartMonth);
}
public override int GetMonthsInYear(int year, int era)
{
CheckYearRange(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)
{
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
day,
SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month));
}
return IsLeapYear(year, era) && month == 12 && day == 30;
}
public override int GetLeapMonth(int year, int era)
{
CheckYearRange(year, era);
return 0;
}
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
return false;
}
public override bool IsLeapYear(int year, int era)
{
CheckYearRange(year, era);
return (((year * 11) + 14) % 30) < 11;
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
// The year/month/era checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
day,
SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month));
}
long lDate = GetAbsoluteDateHijri(year, month, day);
if (lDate < 0)
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
return new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond));
}
private const int DefaultTwoDigitYearMax = 1451;
public override int TwoDigitYearMax
{
get
{
if (_twoDigitYearMax == -1)
{
_twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DefaultTwoDigitYearMax);
}
return _twoDigitYearMax;
}
set
{
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.ArgumentOutOfRange_Range, 99, MaxCalendarYear));
}
_twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (year < 100)
{
return base.ToFourDigitYear(year);
}
if (year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
year,
SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxCalendarYear));
}
return year;
}
}
}
| |
using System;
using System.Text;
namespace Lucene.Net.Search
{
/*
* 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 AttributeSource = Lucene.Net.Util.AttributeSource;
using LevenshteinAutomata = Lucene.Net.Util.Automaton.LevenshteinAutomata;
using SingleTermsEnum = Lucene.Net.Index.SingleTermsEnum;
using Term = Lucene.Net.Index.Term;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
/// <summary>
/// Implements the fuzzy search query. The similarity measurement
/// is based on the Damerau-Levenshtein (optimal string alignment) algorithm,
/// though you can explicitly choose classic Levenshtein by passing <c>false</c>
/// to the <c>transpositions</c> parameter.
///
/// <para/>this query uses <see cref="MultiTermQuery.TopTermsScoringBooleanQueryRewrite"/>
/// as default. So terms will be collected and scored according to their
/// edit distance. Only the top terms are used for building the <see cref="BooleanQuery"/>.
/// It is not recommended to change the rewrite mode for fuzzy queries.
///
/// <para/>At most, this query will match terms up to
/// <see cref="Lucene.Net.Util.Automaton.LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE"/> edits.
/// Higher distances (especially with transpositions enabled), are generally not useful and
/// will match a significant amount of the term dictionary. If you really want this, consider
/// using an n-gram indexing technique (such as the SpellChecker in the
/// <a href="{@docRoot}/../suggest/overview-summary.html">suggest module</a>) instead.
///
/// <para/>NOTE: terms of length 1 or 2 will sometimes not match because of how the scaled
/// distance between two terms is computed. For a term to match, the edit distance between
/// the terms must be less than the minimum length term (either the input term, or
/// the candidate term). For example, <see cref="FuzzyQuery"/> on term "abcd" with maxEdits=2 will
/// not match an indexed term "ab", and <see cref="FuzzyQuery"/> on term "a" with maxEdits=2 will not
/// match an indexed term "abc".
/// </summary>
public class FuzzyQuery : MultiTermQuery
{
public const int DefaultMaxEdits = LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE;
public const int DefaultPrefixLength = 0;
public const int DefaultMaxExpansions = 50;
public const bool DefaultTranspositions = true;
private readonly int maxEdits;
private readonly int maxExpansions;
private readonly bool transpositions;
private readonly int prefixLength;
private readonly Term term;
/// <summary>
/// Create a new <see cref="FuzzyQuery"/> that will match terms with an edit distance
/// of at most <paramref name="maxEdits"/> to <paramref name="term"/>.
/// If a <paramref name="prefixLength"/> > 0 is specified, a common prefix
/// of that length is also required.
/// </summary>
/// <param name="term"> The term to search for </param>
/// <param name="maxEdits"> Must be >= 0 and <= <see cref="LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE"/>. </param>
/// <param name="prefixLength"> Length of common (non-fuzzy) prefix </param>
/// <param name="maxExpansions"> The maximum number of terms to match. If this number is
/// greater than <see cref="BooleanQuery.MaxClauseCount"/> when the query is rewritten,
/// then the maxClauseCount will be used instead. </param>
/// <param name="transpositions"> <c>true</c> if transpositions should be treated as a primitive
/// edit operation. If this is <c>false</c>, comparisons will implement the classic
/// Levenshtein algorithm. </param>
public FuzzyQuery(Term term, int maxEdits, int prefixLength, int maxExpansions, bool transpositions)
: base(term.Field)
{
if (maxEdits < 0 || maxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE)
{
throw new ArgumentException("maxEdits must be between 0 and " + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE);
}
if (prefixLength < 0)
{
throw new ArgumentException("prefixLength cannot be negative.");
}
if (maxExpansions < 0)
{
throw new ArgumentException("maxExpansions cannot be negative.");
}
this.term = term;
this.maxEdits = maxEdits;
this.prefixLength = prefixLength;
this.transpositions = transpositions;
this.maxExpansions = maxExpansions;
MultiTermRewriteMethod = new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(maxExpansions);
}
/// <summary>
/// Calls <see cref="FuzzyQuery.FuzzyQuery(Term, int, int, int, bool)">
/// FuzzyQuery(term, maxEdits, prefixLength, defaultMaxExpansions, defaultTranspositions)</see>.
/// </summary>
public FuzzyQuery(Term term, int maxEdits, int prefixLength)
: this(term, maxEdits, prefixLength, DefaultMaxExpansions, DefaultTranspositions)
{
}
/// <summary>
/// Calls <see cref="FuzzyQuery(Term, int, int)">FuzzyQuery(term, maxEdits, defaultPrefixLength)</see>.
/// </summary>
public FuzzyQuery(Term term, int maxEdits)
: this(term, maxEdits, DefaultPrefixLength)
{
}
/// <summary>
/// Calls <see cref="FuzzyQuery(Term, int)">FuzzyQuery(term, defaultMaxEdits)</see>.
/// </summary>
public FuzzyQuery(Term term)
: this(term, DefaultMaxEdits)
{
}
/// <returns> The maximum number of edit distances allowed for this query to match. </returns>
public virtual int MaxEdits => maxEdits;
/// <summary>
/// Returns the non-fuzzy prefix length. This is the number of characters at the start
/// of a term that must be identical (not fuzzy) to the query term if the query
/// is to match that term.
/// </summary>
public virtual int PrefixLength => prefixLength;
/// <summary>
/// Returns <c>true</c> if transpositions should be treated as a primitive edit operation.
/// If this is <c>false</c>, comparisons will implement the classic Levenshtein algorithm.
/// </summary>
public virtual bool Transpositions => transpositions;
protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
{
if (maxEdits == 0 || prefixLength >= term.Text().Length) // can only match if it's exact
{
return new SingleTermsEnum(terms.GetEnumerator(), term.Bytes);
}
return new FuzzyTermsEnum(terms, atts, Term, maxEdits, prefixLength, transpositions);
}
/// <summary>
/// Returns the pattern term.
/// </summary>
public virtual Term Term => term;
public override string ToString(string field)
{
var buffer = new StringBuilder();
if (!term.Field.Equals(field, StringComparison.Ordinal))
{
buffer.Append(term.Field);
buffer.Append(":");
}
buffer.Append(term.Text());
buffer.Append('~');
buffer.Append(Convert.ToString(maxEdits));
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
public override int GetHashCode()
{
const int prime = 31;
int result = base.GetHashCode();
result = prime * result + maxEdits;
result = prime * result + prefixLength;
result = prime * result + maxExpansions;
result = prime * result + (transpositions ? 0 : 1);
result = prime * result + ((term == null) ? 0 : term.GetHashCode());
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (!base.Equals(obj))
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
FuzzyQuery other = (FuzzyQuery)obj;
if (maxEdits != other.maxEdits)
{
return false;
}
if (prefixLength != other.prefixLength)
{
return false;
}
if (maxExpansions != other.maxExpansions)
{
return false;
}
if (transpositions != other.transpositions)
{
return false;
}
if (term == null)
{
if (other.term != null)
{
return false;
}
}
else if (!term.Equals(other.term))
{
return false;
}
return true;
}
/// @deprecated pass integer edit distances instead.
[Obsolete("pass integer edit distances instead.")]
public const float DefaultMinSimilarity = LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE;
/// <summary>
/// Helper function to convert from deprecated "minimumSimilarity" fractions
/// to raw edit distances.
/// <para/>
/// NOTE: this was floatToEdits() in Lucene
/// </summary>
/// <param name="minimumSimilarity"> Scaled similarity </param>
/// <param name="termLen"> Length (in unicode codepoints) of the term. </param>
/// <returns> Equivalent number of maxEdits </returns>
[Obsolete("pass integer edit distances instead.")]
public static int SingleToEdits(float minimumSimilarity, int termLen)
{
if (minimumSimilarity >= 1f)
{
return (int)Math.Min(minimumSimilarity, LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE);
}
else if (minimumSimilarity == 0.0f)
{
return 0; // 0 means exact, not infinite # of edits!
}
else
{
return Math.Min((int)((1D - minimumSimilarity) * termLen), LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE);
}
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Drawing;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using D3D = Microsoft.DirectX.Direct3D;
using Axiom.Graphics;
using Axiom.Media;
using VertexDeclaration = Axiom.Graphics.VertexDeclaration;
using Root = Axiom.Core.Root;
using System.Runtime.InteropServices;
using Axiom.Utility;
namespace Axiom.RenderSystems.DirectX9 {
/// <summary>
/// DirectX implementation of HardwarePixelBuffer
/// </summary>
public class D3DHardwarePixelBuffer : HardwarePixelBuffer {
#region Fields
protected static TimingMeter timingMeter = MeterManager.GetMeter("BlitFromMemory", "D3DHardwarePixelBuffer");
///<summary>
/// D3DDevice pointer
///</summary>
protected D3D.Device device;
///<summary>
/// Surface abstracted by this buffer
///</summary>
protected D3D.Surface surface;
///<summary>
/// Volume abstracted by this buffer
///</summary>
protected D3D.Volume volume;
///<summary>
/// Temporary surface in main memory if direct locking of mSurface is not possible
///</summary>
protected D3D.Surface tempSurface;
///<summary>
/// Temporary volume in main memory if direct locking of mVolume is not possible
///</summary>
protected D3D.Volume tempVolume;
///<summary>
/// Doing Mipmapping?
///</summary>
protected bool doMipmapGen;
///<summary>
/// Hardware Mipmaps?
///</summary>
protected bool HWMipmaps;
///<summary>
/// The Mipmap texture?
///</summary>
protected D3D.BaseTexture mipTex;
///<summary>
/// Render targets
///</summary>
protected List<RenderTexture> sliceTRT;
#endregion Fields
#region Constructors
public D3DHardwarePixelBuffer(BufferUsage usage) :
base(0, 0, 0, Axiom.Media.PixelFormat.Unknown, usage, false, false) {
device = null;
surface = null;
volume = null;
tempSurface = null;
tempVolume = null;
doMipmapGen = false;
HWMipmaps = false;
mipTex = null;
sliceTRT = new List<RenderTexture>();
}
#endregion Constructors
#region Properties
///<summary>
/// Accessor for surface
///</summary>
public D3D.Surface Surface {
get { return surface; }
}
#endregion Properties
#region Methods
///<summary>
/// Call this to associate a D3D surface with this pixel buffer
///</summary>
public void Bind(D3D.Device device, D3D.Surface surface, bool update) {
this.device = device;
this.surface = surface;
D3D.SurfaceDescription desc = surface.Description;
width = desc.Width;
height = desc.Height;
depth = 1;
format = D3DHelper.ConvertEnum(desc.Format);
// Default
rowPitch = width;
slicePitch = height * width;
sizeInBytes = PixelUtil.GetMemorySize(width, height, depth, format);
if (((int)usage & (int)TextureUsage.RenderTarget) != 0)
CreateRenderTextures(update);
}
///<summary>
/// Call this to associate a D3D volume with this pixel buffer
///</summary>
public void Bind(D3D.Device device, D3D.Volume volume, bool update) {
this.device = device;
this.volume = volume;
D3D.VolumeDescription desc = volume.Description;
width = desc.Width;
height = desc.Height;
depth = desc.Depth;
format = D3DHelper.ConvertEnum(desc.Format);
// Default
rowPitch = width;
slicePitch = height * width;
sizeInBytes = PixelUtil.GetMemorySize(width, height, depth, format);
if (((int)usage & (int)TextureUsage.RenderTarget) != 0)
CreateRenderTextures(update);
}
///<summary>
/// Util functions to convert a D3D locked rectangle to a pixel box
///</summary>
protected static void FromD3DLock(PixelBox rval, int pitch, GraphicsStream stream) {
rval.RowPitch = pitch / PixelUtil.GetNumElemBytes(rval.Format);
rval.SlicePitch = rval.RowPitch * rval.Height;
Debug.Assert((pitch % PixelUtil.GetNumElemBytes(rval.Format)) == 0);
rval.Data = stream.InternalData;
}
///<summary>
/// Util functions to convert a D3D LockedBox to a pixel box
///</summary>
protected static void FromD3DLock(PixelBox rval, D3D.LockedBox lbox, GraphicsStream stream)
{
rval.RowPitch = lbox.RowPitch / PixelUtil.GetNumElemBytes(rval.Format);
rval.SlicePitch = lbox.SlicePitch / PixelUtil.GetNumElemBytes(rval.Format);
Debug.Assert((lbox.RowPitch % PixelUtil.GetNumElemBytes(rval.Format)) == 0);
Debug.Assert((lbox.SlicePitch % PixelUtil.GetNumElemBytes(rval.Format)) == 0);
rval.Data = stream.InternalData;
}
///<summary>
/// Convert Ogre integer Box to D3D rectangle
///</summary>
protected static Rectangle ToD3DRectangle(BasicBox lockBox) {
Debug.Assert(lockBox.Depth == 1);
Rectangle r = new Rectangle();
r.X = lockBox.Left;
r.Width = lockBox.Width;
r.Y = lockBox.Top;
r.Height = lockBox.Height;
return r;
}
///<summary>
/// Convert Axiom Box to D3D box
///</summary>
protected static D3D.Box ToD3DBox(BasicBox lockBox) {
D3D.Box pbox = new D3D.Box();
pbox.Left = lockBox.Left;
pbox.Right = lockBox.Right;
pbox.Top = lockBox.Top;
pbox.Bottom = lockBox.Bottom;
pbox.Front = lockBox.Front;
pbox.Back = lockBox.Back;
return pbox;
}
///<summary>
/// Convert Axiom PixelBox extent to D3D rectangle
///</summary>
protected static Rectangle ToD3DRectangleExtent(PixelBox lockBox) {
Debug.Assert(lockBox.Depth == 1);
Rectangle r = new Rectangle();
r.X = 0;
r.Width = lockBox.Width;
r.X = 0;
r.Height = lockBox.Height;
return r;
}
///<summary>
/// Convert Axiom PixelBox extent to D3D box
///</summary>
protected static D3D.Box ToD3DBoxExtent(PixelBox lockBox) {
D3D.Box pbox = new D3D.Box();
pbox.Left = 0;
pbox.Right = lockBox.Width;
pbox.Top = 0;
pbox.Bottom = lockBox.Height;
pbox.Front = 0;
pbox.Back = lockBox.Depth;
return pbox;
}
///<summary>
/// Lock a box
///</summary>
public override PixelBox LockImpl(BasicBox lockBox, BufferLocking options) {
// Check for misuse
if (((int)usage & (int)TextureUsage.RenderTarget) != 0)
throw new Exception("DirectX does not allow locking of or directly writing to RenderTargets. Use BlitFromMemory if you need the contents; " +
"in D3D9HardwarePixelBuffer.LockImpl");
// Set extents and format
PixelBox rval = new PixelBox(lockBox, format);
// Set locking flags according to options
D3D.LockFlags flags = D3D.LockFlags.None;
switch(options) {
case BufferLocking.Discard:
// D3D only likes D3D.LockFlags.Discard if you created the texture with D3DUSAGE_DYNAMIC
// debug runtime flags this up, could cause problems on some drivers
if ((usage & BufferUsage.Dynamic) != 0)
flags |= D3D.LockFlags.Discard;
break;
case BufferLocking.ReadOnly:
flags |= D3D.LockFlags.ReadOnly;
break;
default:
break;
}
if (surface != null) {
// Surface
GraphicsStream data = null;
int pitch;
if (lockBox.Left == 0 && lockBox.Top == 0 &&
lockBox.Right == width && lockBox.Bottom == height) {
// Lock whole surface
data = surface.LockRectangle(flags, out pitch);
} else {
Rectangle prect = ToD3DRectangle(lockBox); // specify range to lock
data = surface.LockRectangle(prect, flags, out pitch);
}
if (data == null)
throw new Exception("Surface locking failed; in D3D9HardwarePixelBuffer.LockImpl");
FromD3DLock(rval, pitch, data);
} else {
// Volume
D3D.Box pbox = ToD3DBox(lockBox); // specify range to lock
D3D.LockedBox lbox; // Filled in by D3D
GraphicsStream data = volume.LockBox(pbox, flags, out lbox);
FromD3DLock(rval, lbox, data);
}
return rval;
}
///<summary>
/// Unlock a box
///</summary>
public override void UnlockImpl() {
if (surface != null)
// Surface
surface.UnlockRectangle();
else
// Volume
volume.UnlockBox();
if (doMipmapGen)
GenMipmaps();
}
///<summary>
/// Create (or update) render textures for slices
///</summary>
///<param name="update">are we updating an existing texture</param>
protected void CreateRenderTextures(bool update) {
if (update) {
Debug.Assert(sliceTRT.Count == depth);
foreach (D3DRenderTexture trt in sliceTRT)
trt.Rebind(this);
return;
}
DestroyRenderTextures();
if(surface == null)
throw new Exception("Rendering to 3D slices not supported yet for Direct3D; in " +
"D3D9HardwarePixelBuffer.CreateRenderTexture");
// Create render target for each slice
sliceTRT.Clear();
Debug.Assert(depth==1);
for(int zoffset=0; zoffset<depth; ++zoffset) {
string name = "rtt/" + this.ID;
RenderTexture trt = new D3DRenderTexture(name, this);
sliceTRT.Add(trt);
Root.Instance.RenderSystem.AttachRenderTarget(trt);
}
}
///<summary>
/// Destroy render textures for slices
///</summary>
protected void DestroyRenderTextures() {
if(sliceTRT.Count == 0)
return;
// Delete all render targets that are not yet deleted via _clearSliceRTT
for (int i = 0; i < sliceTRT.Count; ++i) {
RenderTexture trt = sliceTRT[i];
if (trt != null)
Root.Instance.RenderSystem.DestroyRenderTarget(trt.Name);
}
// sliceTRT.Clear();
}
///<summary>
/// @copydoc HardwarePixelBuffer.Blit
///</summary>
public override void Blit(HardwarePixelBuffer _src, BasicBox srcBox, BasicBox dstBox) {
D3DHardwarePixelBuffer src = (D3DHardwarePixelBuffer)_src;
if (surface != null && src.surface != null) {
// Surface-to-surface
Rectangle dsrcRect = ToD3DRectangle(srcBox);
Rectangle ddestRect = ToD3DRectangle(dstBox);
// D3DXLoadSurfaceFromSurface
SurfaceLoader.FromSurface(surface, ddestRect, src.surface, dsrcRect, Filter.None, 0);
} else if (volume != null && src.volume != null) {
// Volume-to-volume
Box dsrcBox = ToD3DBox(srcBox);
Box ddestBox = ToD3DBox(dstBox);
// D3DXLoadVolumeFromVolume
VolumeLoader.FromVolume(volume, ddestBox, src.volume, dsrcBox, Filter.None, 0);
} else
// Software fallback
base.Blit(_src, srcBox, dstBox);
}
///<summary>
/// @copydoc HardwarePixelBuffer.BlitFromMemory
///</summary>
public override void BlitFromMemory(PixelBox src, BasicBox dstBox) {
using (AutoTimer timer = new AutoTimer(timingMeter)) {
BlitFromMemoryImpl(src, dstBox);
}
}
protected void BlitFromMemoryImpl(PixelBox src, BasicBox dstBox) {
// TODO: This currently does way too many copies. We copy
// from src to a converted buffer (if needed), then from
// converted to a byte array, then into the temporary surface,
// and finally from the temporary surface to the real surface.
PixelBox converted = src;
IntPtr bufPtr = IntPtr.Zero;
GCHandle bufGCHandle = new GCHandle();
// convert to pixelbuffer's native format if necessary
if (D3DHelper.ConvertEnum(src.Format) == D3D.Format.Unknown) {
int bufSize = PixelUtil.GetMemorySize(src.Width, src.Height, src.Depth, format);
byte[] newBuffer = new byte[bufSize];
bufGCHandle = GCHandle.Alloc(newBuffer, GCHandleType.Pinned);
bufPtr = bufGCHandle.AddrOfPinnedObject();
converted = new PixelBox(src.Width, src.Height, src.Depth, format, bufPtr);
PixelUtil.BulkPixelConversion(src, converted);
}
// int formatBytes = PixelUtil.GetNumElemBytes(converted.Format);
Surface tmpSurface = device.CreateOffscreenPlainSurface(converted.Width, converted.Height, D3DHelper.ConvertEnum(converted.Format), Pool.Scratch);
int pitch;
// Ideally I would be using the Array mechanism here, but that doesn't seem to work
GraphicsStream buf = tmpSurface.LockRectangle(LockFlags.NoSystemLock, out pitch);
buf.Position = 0;
unsafe {
int bufSize = PixelUtil.GetMemorySize(converted.Width, converted.Height, converted.Depth, converted.Format);
byte* srcPtr = (byte*)converted.Data.ToPointer();
byte[] ugh = new byte[bufSize];
for (int i = 0; i < bufSize; ++i)
ugh[i] = srcPtr[i];
buf.Write(ugh);
}
tmpSurface.UnlockRectangle();
buf.Dispose();
//ImageInformation imageInfo = new ImageInformation();
//imageInfo.Format = D3DHelper.ConvertEnum(converted.Format);
//imageInfo.Width = converted.Width;
//imageInfo.Height = converted.Height;
//imageInfo.Depth = converted.Depth;
if (surface != null) {
// I'm trying to write to surface using the data in converted
Rectangle srcRect = ToD3DRectangleExtent(converted);
Rectangle destRect = ToD3DRectangle(dstBox);
SurfaceLoader.FromSurface(surface, destRect, tmpSurface, srcRect, Filter.None, 0);
} else {
D3D.Box srcBox = ToD3DBoxExtent(converted);
D3D.Box destBox = ToD3DBox(dstBox);
Debug.Assert(false, "Volume textures not yet supported");
// VolumeLoader.FromStream(volume, destBox, converted.Data, converted.RowPitch * converted.SlicePitch * formatBytes, srcBox, Filter.None, 0);
VolumeLoader.FromStream(volume, destBox, buf, srcBox, Filter.None, 0);
}
tmpSurface.Dispose();
// If we allocated a buffer for the temporary conversion, free it here
// If I used bufPtr to store my temporary data while I converted
// it, I need to free it here. This invalidates converted.
// My data has already been copied to tmpSurface and then to the
// real surface.
if (bufGCHandle.IsAllocated)
bufGCHandle.Free();
if (doMipmapGen)
GenMipmaps();
}
///<summary>
/// @copydoc HardwarePixelBuffer.BlitToMemory
///</summary>
public override void BlitToMemory(BasicBox srcBox, PixelBox dst) {
// Decide on pixel format of temp surface
PixelFormat tmpFormat = format;
if (D3DHelper.ConvertEnum(dst.Format) == D3D.Format.Unknown)
tmpFormat = dst.Format;
if (surface != null) {
Debug.Assert(srcBox.Depth == 1 && dst.Depth == 1);
// Create temp texture
D3D.Texture tmp =
new D3D.Texture(device, dst.Width, dst.Height,
1, // 1 mip level ie topmost, generate no mipmaps
0, D3DHelper.ConvertEnum(tmpFormat),
Pool.Scratch);
D3D.Surface subSurface = tmp.GetSurfaceLevel(0);
// Copy texture to this temp surface
Rectangle destRect, srcRect;
srcRect = ToD3DRectangle(srcBox);
destRect = ToD3DRectangleExtent(dst);
SurfaceLoader.FromSurface(subSurface, destRect, surface, srcRect, Filter.None, 0);
// Lock temp surface and copy it to memory
int pitch; // Filled in by D3D
GraphicsStream data = subSurface.LockRectangle(D3D.LockFlags.ReadOnly, out pitch);
// Copy it
PixelBox locked = new PixelBox(dst.Width, dst.Height, dst.Depth, tmpFormat);
FromD3DLock(locked, pitch, data);
PixelUtil.BulkPixelConversion(locked, dst);
subSurface.UnlockRectangle();
// Release temporary surface and texture
subSurface.Dispose();
tmp.Dispose();
}
else {
// Create temp texture
D3D.VolumeTexture tmp =
new D3D.VolumeTexture(device, dst.Width, dst.Height, dst.Depth,
0, D3D.Usage.None,
D3DHelper.ConvertEnum(tmpFormat),
Pool.Scratch);
D3D.Volume subVolume = tmp.GetVolumeLevel(0);
// Volume
D3D.Box ddestBox = ToD3DBoxExtent(dst);
D3D.Box dsrcBox = ToD3DBox(srcBox);
VolumeLoader.FromVolume(subVolume, ddestBox, volume, dsrcBox, Filter.None, 0);
// Lock temp surface and copy it to memory
D3D.LockedBox lbox; // Filled in by D3D
GraphicsStream data = subVolume.LockBox(LockFlags.ReadOnly, out lbox);
// Copy it
PixelBox locked = new PixelBox(dst.Width, dst.Height, dst.Depth, tmpFormat);
FromD3DLock(locked, lbox, data);
PixelUtil.BulkPixelConversion(locked, dst);
subVolume.UnlockBox();
// Release temporary surface and texture
subVolume.Dispose();
tmp.Dispose();
}
}
///<summary>
/// Internal function to update mipmaps on update of level 0
///</summary>
public void GenMipmaps() {
Debug.Assert(mipTex != null);
// Mipmapping
if (HWMipmaps)
// Hardware mipmaps
mipTex.GenerateMipSubLevels();
else {
// Software mipmaps
TextureLoader.FilterTexture(mipTex, 0, Filter.Box);
}
}
///<summary>
/// Function to set mipmap generation
///</summary>
public void SetMipmapping(bool doMipmapGen, bool HWMipmaps, D3D.BaseTexture mipTex) {
this.doMipmapGen = doMipmapGen;
this.HWMipmaps = HWMipmaps;
this.mipTex = mipTex;
}
///<summary>
/// Get rendertarget for z slice
///</summary>
public override RenderTexture GetRenderTarget(int zoffset) {
Debug.Assert(((int)usage & (int)TextureUsage.RenderTarget) != 0);
Debug.Assert(zoffset < depth);
return sliceTRT[zoffset];
}
///<summary>
/// Notify TextureBuffer of destruction of render target
///</summary>
public override void ClearSliceRTT(int zoffset) {
sliceTRT[zoffset] = null;
}
public override void Dispose() {
DestroyRenderTextures();
base.Dispose();
}
#endregion Methods
}
}
| |
namespace System.ComponentModel
{
using Moq;
using System;
using System.ComponentModel.Design;
using Xunit;
using static Moq.Times;
public class IServiceContainerExtensionsTest
{
[Fact]
public void add_service_should_register_callback()
{
// arrange
var container = new Mock<IServiceContainer>();
container.Setup( sc => sc.AddService( It.IsAny<Type>(), It.IsAny<ServiceCreatorCallback>(), It.IsAny<bool>() ) );
// act
container.Object.AddService<IFoo, Foo>( ( t, sc ) => new Foo() );
// assert
container.Verify( sc => sc.AddService( typeof( IFoo ), It.IsAny<ServiceCreatorCallback>(), false ), Once() );
}
[Fact]
public void add_service_should_register_callback_with_promotion()
{
// arrange
var container = new Mock<IServiceContainer>();
container.Setup( sc => sc.AddService( It.IsAny<Type>(), It.IsAny<ServiceCreatorCallback>(), It.IsAny<bool>() ) );
// act
container.Object.AddService<IFoo, Foo>( ( t, sc ) => new Foo(), true );
// assert
container.Verify( sc => sc.AddService( typeof( IFoo ), It.IsAny<ServiceCreatorCallback>(), true ), Once() );
}
[Fact]
public void add_service_should_register_instance()
{
// arrange
var container = new Mock<IServiceContainer>();
IFoo foo = new Foo();
container.Setup( sc => sc.AddService( It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<bool>() ) );
// act
container.Object.AddService( foo );
// assert
container.Verify( sc => sc.AddService( typeof( IFoo ), foo, false ), Once() );
}
[Fact]
public void add_service_should_register_instance_with_promotion()
{
// arrange
var container = new Mock<IServiceContainer>();
IFoo foo = new Foo();
container.Setup( sc => sc.AddService( It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<bool>() ) );
// act
container.Object.AddService( foo, true );
// assert
container.Verify( sc => sc.AddService( typeof( IFoo ), foo, true ), Once() );
}
[Fact]
public void add_service_should_register_instance_with_type_mapping()
{
// arrange
var container = new Mock<IServiceContainer>();
var foo = new Foo();
container.Setup( sc => sc.AddService( It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<bool>() ) );
// act
container.Object.AddService<IFoo, Foo>( foo );
// assert
container.Verify( sc => sc.AddService( typeof( IFoo ), foo, false ), Once() );
}
[Fact]
public void add_service_should_register_instance_with_type_mapping_and_promotion()
{
// arrange
var container = new Mock<IServiceContainer>();
var foo = new Foo();
container.Setup( sc => sc.AddService( It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<bool>() ) );
// act
container.Object.AddService<IFoo, Foo>( foo, true );
// assert
container.Verify( sc => sc.AddService( typeof( IFoo ), foo, true ), Once() );
}
[Fact]
public void remove_service_should_unregister_service_type()
{
// arrange
var container = new Mock<IServiceContainer>();
container.Setup( sc => sc.RemoveService( It.IsAny<Type>(), It.IsAny<bool>() ) );
// act
container.Object.RemoveService<IServiceProvider>();
// assert
container.Verify( sc => sc.RemoveService( typeof( IServiceProvider ), false ), Once() );
}
[Fact]
public void remove_service_should_unregister_service_type_with_promotion()
{
// arrange
var container = new Mock<IServiceContainer>();
container.Setup( sc => sc.RemoveService( It.IsAny<Type>(), It.IsAny<bool>() ) );
// act
container.Object.RemoveService<IServiceProvider>( true );
// assert
container.Verify( sc => sc.RemoveService( typeof( IServiceProvider ), true ), Once() );
}
[Fact]
public void replace_service_should_reX2Dregister_callback()
{
// arrange
var container = new Mock<IServiceContainer>();
container.Setup( sc => sc.AddService( It.IsAny<Type>(), It.IsAny<ServiceCreatorCallback>(), It.IsAny<bool>() ) );
container.Setup( sc => sc.RemoveService( It.IsAny<Type>(), It.IsAny<bool>() ) );
// act
container.Object.ReplaceService<IFoo, Foo>( ( t, sc ) => new Foo() );
// assert
container.Verify( sc => sc.RemoveService( typeof( IFoo ), false ), Once() );
container.Verify( sc => sc.AddService( typeof( IFoo ), It.IsAny<ServiceCreatorCallback>(), false ), Once() );
}
[Fact]
public void replace_service_should_reX2Dregister_callback_with_promotion()
{
// arrange
var container = new Mock<IServiceContainer>();
container.Setup( sc => sc.AddService( It.IsAny<Type>(), It.IsAny<ServiceCreatorCallback>(), It.IsAny<bool>() ) );
container.Setup( sc => sc.RemoveService( It.IsAny<Type>(), It.IsAny<bool>() ) );
// act
container.Object.ReplaceService<IFoo, Foo>( ( t, sc ) => new Foo(), true );
// assert
container.Verify( sc => sc.RemoveService( typeof( IFoo ), true ), Once() );
container.Verify( sc => sc.AddService( typeof( IFoo ), It.IsAny<ServiceCreatorCallback>(), true ), Once() );
}
[Fact]
public void replace_service_should_reX2Dregister_instance()
{
// arrange
var container = new Mock<IServiceContainer>();
var foo = new Foo();
container.Setup( sc => sc.AddService( It.IsAny<Type>(), It.IsAny<ServiceCreatorCallback>(), It.IsAny<bool>() ) );
container.Setup( sc => sc.RemoveService( It.IsAny<Type>(), It.IsAny<bool>() ) );
// act
container.Object.ReplaceService( foo );
// assert
container.Verify( sc => sc.RemoveService( typeof( Foo ), false ), Once() );
container.Verify( sc => sc.AddService( typeof( Foo ), foo, false ), Once() );
}
[Fact]
public void replace_service_should_reX2Dregister_instance_with_promotion()
{
// arrange
var container = new Mock<IServiceContainer>();
var foo = new Foo();
container.Setup( sc => sc.AddService( It.IsAny<Type>(), It.IsAny<ServiceCreatorCallback>(), It.IsAny<bool>() ) );
container.Setup( sc => sc.RemoveService( It.IsAny<Type>(), It.IsAny<bool>() ) );
// act
container.Object.ReplaceService( foo, true );
// assert
container.Verify( sc => sc.RemoveService( typeof( Foo ), true ), Once() );
container.Verify( sc => sc.AddService( typeof( Foo ), foo, true ), Once() );
}
[Fact]
public void replace_service_should_reX2Dregister_instance_with_type_mapping()
{
// arrange
var container = new Mock<IServiceContainer>();
var foo = new Foo();
container.Setup( sc => sc.AddService( It.IsAny<Type>(), It.IsAny<ServiceCreatorCallback>(), It.IsAny<bool>() ) );
container.Setup( sc => sc.RemoveService( It.IsAny<Type>(), It.IsAny<bool>() ) );
// act
container.Object.ReplaceService<IFoo, Foo>( foo, false );
// assert
container.Verify( sc => sc.RemoveService( typeof( IFoo ), false ), Once() );
container.Verify( sc => sc.AddService( typeof( IFoo ), foo, false ), Once() );
}
[Fact]
public void replace_service_should_reX2Dregister_instance_with_type_mapping_and_promotion()
{
// arrange
var container = new Mock<IServiceContainer>();
var foo = new Foo();
container.Setup( sc => sc.AddService( It.IsAny<Type>(), It.IsAny<ServiceCreatorCallback>(), It.IsAny<bool>() ) );
container.Setup( sc => sc.RemoveService( It.IsAny<Type>(), It.IsAny<bool>() ) );
// act
container.Object.ReplaceService<IFoo, Foo>( foo, true );
// assert
container.Verify( sc => sc.RemoveService( typeof( IFoo ), true ), Once() );
container.Verify( sc => sc.AddService( typeof( IFoo ), foo, true ), Once() );
}
interface IFoo { }
sealed class Foo : IFoo { }
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0
using System.Numerics;
#endif
using Newtonsoft.Json.Linq.JsonPath;
using Newtonsoft.Json.Tests.Bson;
#if HAVE_REGEX_TIMEOUTS
using System.Text.RegularExpressions;
#endif
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
using TestCaseSource = Xunit.MemberDataAttribute;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Linq;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Linq.JsonPath
{
[TestFixture]
public class JPathExecuteTests : TestFixtureBase
{
[Test]
public void GreaterThanIssue1518()
{
string statusJson = @"{""usingmem"": ""214376""}";//214,376
JObject jObj = JObject.Parse(statusJson);
var aa = jObj.SelectToken("$..[?(@.usingmem>10)]");//found,10
Assert.AreEqual(jObj, aa);
var bb = jObj.SelectToken("$..[?(@.usingmem>27000)]");//null, 27,000
Assert.AreEqual(jObj, bb);
var cc = jObj.SelectToken("$..[?(@.usingmem>21437)]");//found, 21,437
Assert.AreEqual(jObj, cc);
var dd = jObj.SelectToken("$..[?(@.usingmem>21438)]");//null,21,438
Assert.AreEqual(jObj, dd);
}
#if HAVE_REGEX_TIMEOUTS
[Test]
public void BacktrackingRegex_SingleMatch_TimeoutRespected()
{
const string RegexBacktrackingPattern = "(?<a>(.*?))[|].*(?<b>(.*?))[|].*(?<c>(.*?))[|].*(?<d>[1-3])[|].*(?<e>(.*?))[|].*[|].*[|].*(?<f>(.*?))[|].*[|].*(?<g>(.*?))[|].*(?<h>(.*))";
var regexBacktrackingData = new JArray();
regexBacktrackingData.Add(new JObject(new JProperty("b", @"15/04/2020 8:18:03 PM|1|System.String[]|3|Libero eligendi magnam ut inventore.. Quaerat et sit voluptatibus repellendus blanditiis aliquam ut.. Quidem qui ut sint in ex et tempore.|||.\iste.cpp||46018|-1")));
ExceptionAssert.Throws<RegexMatchTimeoutException>(() =>
{
regexBacktrackingData.SelectTokens(
$"[?(@.b =~ /{RegexBacktrackingPattern}/)]",
new JsonSelectSettings
{
RegexMatchTimeout = TimeSpan.FromSeconds(0.01)
}).ToArray();
});
}
#endif
[Test]
public void GreaterThanWithIntegerParameterAndStringValue()
{
string json = @"{
""persons"": [
{
""name"" : ""John"",
""age"": ""26""
},
{
""name"" : ""Jane"",
""age"": ""2""
}
]
}";
JObject models = JObject.Parse(json);
var results = models.SelectTokens("$.persons[?(@.age > 3)]").ToList();
Assert.AreEqual(1, results.Count);
}
[Test]
public void GreaterThanWithStringParameterAndIntegerValue()
{
string json = @"{
""persons"": [
{
""name"" : ""John"",
""age"": 26
},
{
""name"" : ""Jane"",
""age"": 2
}
]
}";
JObject models = JObject.Parse(json);
var results = models.SelectTokens("$.persons[?(@.age > '3')]").ToList();
Assert.AreEqual(1, results.Count);
}
[Test]
public void RecursiveWildcard()
{
string json = @"{
""a"": [
{
""id"": 1
}
],
""b"": [
{
""id"": 2
},
{
""id"": 3,
""c"": {
""id"": 4
}
}
],
""d"": [
{
""id"": 5
}
]
}";
JObject models = JObject.Parse(json);
var results = models.SelectTokens("$.b..*.id").ToList();
Assert.AreEqual(3, results.Count);
Assert.AreEqual(2, (int)results[0]);
Assert.AreEqual(3, (int)results[1]);
Assert.AreEqual(4, (int)results[2]);
}
[Test]
public void ScanFilter()
{
string json = @"{
""elements"": [
{
""id"": ""A"",
""children"": [
{
""id"": ""AA"",
""children"": [
{
""id"": ""AAA""
},
{
""id"": ""AAB""
}
]
},
{
""id"": ""AB""
}
]
},
{
""id"": ""B"",
""children"": []
}
]
}";
JObject models = JObject.Parse(json);
var results = models.SelectTokens("$.elements..[?(@.id=='AAA')]").ToList();
Assert.AreEqual(1, results.Count);
Assert.AreEqual(models["elements"][0]["children"][0]["children"][0], results[0]);
}
[Test]
public void FilterTrue()
{
string json = @"{
""elements"": [
{
""id"": ""A"",
""children"": [
{
""id"": ""AA"",
""children"": [
{
""id"": ""AAA""
},
{
""id"": ""AAB""
}
]
},
{
""id"": ""AB""
}
]
},
{
""id"": ""B"",
""children"": []
}
]
}";
JObject models = JObject.Parse(json);
var results = models.SelectTokens("$.elements[?(true)]").ToList();
Assert.AreEqual(2, results.Count);
Assert.AreEqual(results[0], models["elements"][0]);
Assert.AreEqual(results[1], models["elements"][1]);
}
[Test]
public void ScanFilterTrue()
{
string json = @"{
""elements"": [
{
""id"": ""A"",
""children"": [
{
""id"": ""AA"",
""children"": [
{
""id"": ""AAA""
},
{
""id"": ""AAB""
}
]
},
{
""id"": ""AB""
}
]
},
{
""id"": ""B"",
""children"": []
}
]
}";
JObject models = JObject.Parse(json);
var results = models.SelectTokens("$.elements..[?(true)]").ToList();
Assert.AreEqual(25, results.Count);
}
[Test]
public void ScanQuoted()
{
string json = @"{
""Node1"": {
""Child1"": {
""Name"": ""IsMe"",
""TargetNode"": {
""Prop1"": ""Val1"",
""Prop2"": ""Val2""
}
},
""My.Child.Node"": {
""TargetNode"": {
""Prop1"": ""Val1"",
""Prop2"": ""Val2""
}
}
},
""Node2"": {
""TargetNode"": {
""Prop1"": ""Val1"",
""Prop2"": ""Val2""
}
}
}";
JObject models = JObject.Parse(json);
int result = models.SelectTokens("$..['My.Child.Node']").Count();
Assert.AreEqual(1, result);
result = models.SelectTokens("..['My.Child.Node']").Count();
Assert.AreEqual(1, result);
}
[Test]
public void ScanMultipleQuoted()
{
string json = @"{
""Node1"": {
""Child1"": {
""Name"": ""IsMe"",
""TargetNode"": {
""Prop1"": ""Val1"",
""Prop2"": ""Val2""
}
},
""My.Child.Node"": {
""TargetNode"": {
""Prop1"": ""Val3"",
""Prop2"": ""Val4""
}
}
},
""Node2"": {
""TargetNode"": {
""Prop1"": ""Val5"",
""Prop2"": ""Val6""
}
}
}";
JObject models = JObject.Parse(json);
var results = models.SelectTokens("$..['My.Child.Node','Prop1','Prop2']").ToList();
Assert.AreEqual("Val1", (string)results[0]);
Assert.AreEqual("Val2", (string)results[1]);
Assert.AreEqual(JTokenType.Object, results[2].Type);
Assert.AreEqual("Val3", (string)results[3]);
Assert.AreEqual("Val4", (string)results[4]);
Assert.AreEqual("Val5", (string)results[5]);
Assert.AreEqual("Val6", (string)results[6]);
}
[Test]
public void ParseWithEmptyArrayContent()
{
var json = @"{
'controls': [
{
'messages': {
'addSuggestion': {
'en-US': 'Add'
}
}
},
{
'header': {
'controls': []
},
'controls': [
{
'controls': [
{
'defaultCaption': {
'en-US': 'Sort by'
},
'sortOptions': [
{
'label': {
'en-US': 'Name'
}
}
]
}
]
}
]
}
]
}";
JObject jToken = JObject.Parse(json);
IList<JToken> tokens = jToken.SelectTokens("$..en-US").ToList();
Assert.AreEqual(3, tokens.Count);
Assert.AreEqual("Add", (string)tokens[0]);
Assert.AreEqual("Sort by", (string)tokens[1]);
Assert.AreEqual("Name", (string)tokens[2]);
}
[Test]
public void SelectTokenAfterEmptyContainer()
{
string json = @"{
'cont': [],
'test': 'no one will find me'
}";
JObject o = JObject.Parse(json);
IList<JToken> results = o.SelectTokens("$..test").ToList();
Assert.AreEqual(1, results.Count);
Assert.AreEqual("no one will find me", (string)results[0]);
}
[Test]
public void EvaluatePropertyWithRequired()
{
string json = "{\"bookId\":\"1000\"}";
JObject o = JObject.Parse(json);
string bookId = (string)o.SelectToken("bookId", true);
Assert.AreEqual("1000", bookId);
}
[Test]
public void EvaluateEmptyPropertyIndexer()
{
JObject o = new JObject(
new JProperty("", 1));
JToken t = o.SelectToken("['']");
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateEmptyString()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("");
Assert.AreEqual(o, t);
t = o.SelectToken("['']");
Assert.AreEqual(null, t);
}
[Test]
public void EvaluateEmptyStringWithMatchingEmptyProperty()
{
JObject o = new JObject(
new JProperty(" ", 1));
JToken t = o.SelectToken("[' ']");
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateWhitespaceString()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken(" ");
Assert.AreEqual(o, t);
}
[Test]
public void EvaluateDollarString()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("$");
Assert.AreEqual(o, t);
}
[Test]
public void EvaluateDollarTypeString()
{
JObject o = new JObject(
new JProperty("$values", new JArray(1, 2, 3)));
JToken t = o.SelectToken("$values[1]");
Assert.AreEqual(2, (int)t);
}
[Test]
public void EvaluateSingleProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("Blah");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateWildcardProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1),
new JProperty("Blah2", 2));
IList<JToken> t = o.SelectTokens("$.*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
}
[Test]
public void QuoteName()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("['Blah']");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateMissingProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("Missing[1]");
Assert.IsNull(t);
}
[Test]
public void EvaluateIndexerOnObject()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("[1]");
Assert.IsNull(t);
}
[Test]
public void EvaluateIndexerOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[1]", true); }, @"Index 1 not valid on JObject.");
}
[Test]
public void EvaluateWildcardIndexOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[*]", true); }, @"Index * not valid on JObject.");
}
[Test]
public void EvaluateSliceOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[:]", true); }, @"Array slice is not valid on JObject.");
}
[Test]
public void EvaluatePropertyOnArray()
{
JArray a = new JArray(1, 2, 3, 4, 5);
JToken t = a.SelectToken("BlahBlah");
Assert.IsNull(t);
}
[Test]
public void EvaluateMultipleResultsError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[0, 1]"); }, @"Path returned multiple tokens.");
}
[Test]
public void EvaluatePropertyOnArrayWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("BlahBlah", true); }, @"Property 'BlahBlah' not valid on JArray.");
}
[Test]
public void EvaluateNoResultsWithMultipleArrayIndexes()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[9,10]", true); }, @"Index 9 outside the bounds of JArray.");
}
[Test]
public void EvaluateConstructorOutOfBoundsIndxerWithError()
{
JConstructor c = new JConstructor("Blah");
ExceptionAssert.Throws<JsonException>(() => { c.SelectToken("[1]", true); }, @"Index 1 outside the bounds of JConstructor.");
}
[Test]
public void EvaluateConstructorOutOfBoundsIndxer()
{
JConstructor c = new JConstructor("Blah");
Assert.IsNull(c.SelectToken("[1]"));
}
[Test]
public void EvaluateMissingPropertyWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("Missing", true); }, "Property 'Missing' does not exist on JObject.");
}
[Test]
public void EvaluatePropertyWithoutError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JValue v = (JValue)o.SelectToken("Blah", true);
Assert.AreEqual(1, v.Value);
}
[Test]
public void EvaluateMissingPropertyIndexWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("['Missing','Missing2']", true); }, "Property 'Missing' does not exist on JObject.");
}
[Test]
public void EvaluateMultiPropertyIndexOnArrayWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("['Missing','Missing2']", true); }, "Properties 'Missing', 'Missing2' not valid on JArray.");
}
[Test]
public void EvaluateArraySliceWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[99:]", true); }, "Array slice of 99 to * returned no results.");
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1:-19]", true); }, "Array slice of 1 to -19 returned no results.");
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:-19]", true); }, "Array slice of * to -19 returned no results.");
a = new JArray();
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:]", true); }, "Array slice of * to * returned no results.");
}
[Test]
public void EvaluateOutOfBoundsIndxer()
{
JArray a = new JArray(1, 2, 3, 4, 5);
JToken t = a.SelectToken("[1000].Ha");
Assert.IsNull(t);
}
[Test]
public void EvaluateArrayOutOfBoundsIndxerWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1000].Ha", true); }, "Index 1000 outside the bounds of JArray.");
}
[Test]
public void EvaluateArray()
{
JArray a = new JArray(1, 2, 3, 4);
JToken t = a.SelectToken("[1]");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(2, (int)t);
}
[Test]
public void EvaluateArraySlice()
{
JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9);
IList<JToken> t = null;
t = a.SelectTokens("[-3:]").ToList();
Assert.AreEqual(3, t.Count);
Assert.AreEqual(7, (int)t[0]);
Assert.AreEqual(8, (int)t[1]);
Assert.AreEqual(9, (int)t[2]);
t = a.SelectTokens("[-1:-2:-1]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(9, (int)t[0]);
t = a.SelectTokens("[-2:-1]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(8, (int)t[0]);
t = a.SelectTokens("[1:1]").ToList();
Assert.AreEqual(0, t.Count);
t = a.SelectTokens("[1:2]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(2, (int)t[0]);
t = a.SelectTokens("[::-1]").ToList();
Assert.AreEqual(9, t.Count);
Assert.AreEqual(9, (int)t[0]);
Assert.AreEqual(8, (int)t[1]);
Assert.AreEqual(7, (int)t[2]);
Assert.AreEqual(6, (int)t[3]);
Assert.AreEqual(5, (int)t[4]);
Assert.AreEqual(4, (int)t[5]);
Assert.AreEqual(3, (int)t[6]);
Assert.AreEqual(2, (int)t[7]);
Assert.AreEqual(1, (int)t[8]);
t = a.SelectTokens("[::-2]").ToList();
Assert.AreEqual(5, t.Count);
Assert.AreEqual(9, (int)t[0]);
Assert.AreEqual(7, (int)t[1]);
Assert.AreEqual(5, (int)t[2]);
Assert.AreEqual(3, (int)t[3]);
Assert.AreEqual(1, (int)t[4]);
}
[Test]
public void EvaluateWildcardArray()
{
JArray a = new JArray(1, 2, 3, 4);
List<JToken> t = a.SelectTokens("[*]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
Assert.AreEqual(3, (int)t[2]);
Assert.AreEqual(4, (int)t[3]);
}
[Test]
public void EvaluateArrayMultipleIndexes()
{
JArray a = new JArray(1, 2, 3, 4);
IEnumerable<JToken> t = a.SelectTokens("[1,2,0]");
Assert.IsNotNull(t);
Assert.AreEqual(3, t.Count());
Assert.AreEqual(2, (int)t.ElementAt(0));
Assert.AreEqual(3, (int)t.ElementAt(1));
Assert.AreEqual(1, (int)t.ElementAt(2));
}
[Test]
public void EvaluateScan()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JArray a = new JArray(o1, o2);
IList<JToken> t = a.SelectTokens("$..Name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
}
[Test]
public void EvaluateWildcardScan()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JArray a = new JArray(o1, o2);
IList<JToken> t = a.SelectTokens("$..*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(5, t.Count);
Assert.IsTrue(JToken.DeepEquals(a, t[0]));
Assert.IsTrue(JToken.DeepEquals(o1, t[1]));
Assert.AreEqual(1, (int)t[2]);
Assert.IsTrue(JToken.DeepEquals(o2, t[3]));
Assert.AreEqual(2, (int)t[4]);
}
[Test]
public void EvaluateScanNestResults()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } };
JArray a = new JArray(o1, o2, o3);
IList<JToken> t = a.SelectTokens("$..Name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[2]));
Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[3]));
}
[Test]
public void EvaluateWildcardScanNestResults()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } };
JArray a = new JArray(o1, o2, o3);
IList<JToken> t = a.SelectTokens("$..*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(9, t.Count);
Assert.IsTrue(JToken.DeepEquals(a, t[0]));
Assert.IsTrue(JToken.DeepEquals(o1, t[1]));
Assert.AreEqual(1, (int)t[2]);
Assert.IsTrue(JToken.DeepEquals(o2, t[3]));
Assert.AreEqual(2, (int)t[4]);
Assert.IsTrue(JToken.DeepEquals(o3, t[5]));
Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[6]));
Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[7]));
Assert.AreEqual(3, (int)t[8]);
}
[Test]
public void EvaluateSinglePropertyReturningArray()
{
JObject o = new JObject(
new JProperty("Blah", new[] { 1, 2, 3 }));
JToken t = o.SelectToken("Blah");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Array, t.Type);
t = o.SelectToken("Blah[2]");
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(3, (int)t);
}
[Test]
public void EvaluateLastSingleCharacterProperty()
{
JObject o2 = JObject.Parse("{'People':[{'N':'Jeff'}]}");
string a2 = (string)o2.SelectToken("People[0].N");
Assert.AreEqual("Jeff", a2);
}
[Test]
public void ExistsQuery()
{
JArray a = new JArray(new JObject(new JProperty("hi", "ho")), new JObject(new JProperty("hi2", "ha")));
IList<JToken> t = a.SelectTokens("[ ?( @.hi ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ho")), t[0]));
}
[Test]
public void EqualsQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", "ho")),
new JObject(new JProperty("hi", "ha")));
IList<JToken> t = a.SelectTokens("[ ?( @.['hi'] == 'ha' ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ha")), t[0]));
}
[Test]
public void NotEqualsQuery()
{
JArray a = new JArray(
new JArray(new JObject(new JProperty("hi", "ho"))),
new JArray(new JObject(new JProperty("hi", "ha"))));
IList<JToken> t = a.SelectTokens("[ ?( @..hi <> 'ha' ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JArray(new JObject(new JProperty("hi", "ho"))), t[0]));
}
[Test]
public void NoPathQuery()
{
JArray a = new JArray(1, 2, 3);
IList<JToken> t = a.SelectTokens("[ ?( @ > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(2, (int)t[0]);
Assert.AreEqual(3, (int)t[1]);
}
[Test]
public void MultipleQueries()
{
JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9);
// json path does item based evaluation - http://www.sitepen.com/blog/2008/03/17/jsonpath-support/
// first query resolves array to ints
// int has no children to query
IList<JToken> t = a.SelectTokens("[?(@ <> 1)][?(@ <> 4)][?(@ < 7)]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(0, t.Count);
}
[Test]
public void GreaterQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", 1)),
new JObject(new JProperty("hi", 2)),
new JObject(new JProperty("hi", 3)));
IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1]));
}
[Test]
public void LesserQuery_ValueFirst()
{
JArray a = new JArray(
new JObject(new JProperty("hi", 1)),
new JObject(new JProperty("hi", 2)),
new JObject(new JProperty("hi", 3)));
IList<JToken> t = a.SelectTokens("[ ?( 1 < @.hi ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1]));
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0
[Test]
public void GreaterQueryBigInteger()
{
JArray a = new JArray(
new JObject(new JProperty("hi", new BigInteger(1))),
new JObject(new JProperty("hi", new BigInteger(2))),
new JObject(new JProperty("hi", new BigInteger(3))));
IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1]));
}
#endif
[Test]
public void GreaterOrEqualQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", 1)),
new JObject(new JProperty("hi", 2)),
new JObject(new JProperty("hi", 2.0)),
new JObject(new JProperty("hi", 3)));
IList<JToken> t = a.SelectTokens("[ ?( @.hi >= 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 1)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[1]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2.0)), t[2]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[3]));
}
[Test]
public void NestedQuery()
{
JArray a = new JArray(
new JObject(
new JProperty("name", "Bad Boys"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Will Smith"))))),
new JObject(
new JProperty("name", "Independence Day"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Will Smith"))))),
new JObject(
new JProperty("name", "The Rock"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Nick Cage")))))
);
IList<JToken> t = a.SelectTokens("[?(@.cast[?(@.name=='Will Smith')])].name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual("Bad Boys", (string)t[0]);
Assert.AreEqual("Independence Day", (string)t[1]);
}
[Test]
public void PathWithConstructor()
{
JArray a = JArray.Parse(@"[
{
""Property1"": [
1,
[
[
[]
]
]
]
},
{
""Property2"": new Constructor1(
null,
[
1
]
)
}
]");
JValue v = (JValue)a.SelectToken("[1].Property2[1][0]");
Assert.AreEqual(1L, v.Value);
}
[Test]
public void MultiplePaths()
{
JArray a = JArray.Parse(@"[
{
""price"": 199,
""max_price"": 200
},
{
""price"": 200,
""max_price"": 200
},
{
""price"": 201,
""max_price"": 200
}
]");
var results = a.SelectTokens("[?(@.price > @.max_price)]").ToList();
Assert.AreEqual(1, results.Count);
Assert.AreEqual(a[2], results[0]);
}
[Test]
public void Exists_True()
{
JArray a = JArray.Parse(@"[
{
""price"": 199,
""max_price"": 200
},
{
""price"": 200,
""max_price"": 200
},
{
""price"": 201,
""max_price"": 200
}
]");
var results = a.SelectTokens("[?(true)]").ToList();
Assert.AreEqual(3, results.Count);
Assert.AreEqual(a[0], results[0]);
Assert.AreEqual(a[1], results[1]);
Assert.AreEqual(a[2], results[2]);
}
[Test]
public void Exists_Null()
{
JArray a = JArray.Parse(@"[
{
""price"": 199,
""max_price"": 200
},
{
""price"": 200,
""max_price"": 200
},
{
""price"": 201,
""max_price"": 200
}
]");
var results = a.SelectTokens("[?(true)]").ToList();
Assert.AreEqual(3, results.Count);
Assert.AreEqual(a[0], results[0]);
Assert.AreEqual(a[1], results[1]);
Assert.AreEqual(a[2], results[2]);
}
[Test]
public void WildcardWithProperty()
{
JObject o = JObject.Parse(@"{
""station"": 92000041000001,
""containers"": [
{
""id"": 1,
""text"": ""Sort system"",
""containers"": [
{
""id"": ""2"",
""text"": ""Yard 11""
},
{
""id"": ""92000020100006"",
""text"": ""Sort yard 12""
},
{
""id"": ""92000020100005"",
""text"": ""Yard 13""
}
]
},
{
""id"": ""92000020100011"",
""text"": ""TSP-1""
},
{
""id"":""92000020100007"",
""text"": ""Passenger 15""
}
]
}");
IList<JToken> tokens = o.SelectTokens("$..*[?(@.text)]").ToList();
int i = 0;
Assert.AreEqual("Sort system", (string)tokens[i++]["text"]);
Assert.AreEqual("TSP-1", (string)tokens[i++]["text"]);
Assert.AreEqual("Passenger 15", (string)tokens[i++]["text"]);
Assert.AreEqual("Yard 11", (string)tokens[i++]["text"]);
Assert.AreEqual("Sort yard 12", (string)tokens[i++]["text"]);
Assert.AreEqual("Yard 13", (string)tokens[i++]["text"]);
Assert.AreEqual(6, tokens.Count);
}
[Test]
public void QueryAgainstNonStringValues()
{
IList<object> values = new List<object>
{
"ff2dc672-6e15-4aa2-afb0-18f4f69596ad",
new Guid("ff2dc672-6e15-4aa2-afb0-18f4f69596ad"),
"http://localhost",
new Uri("http://localhost"),
"2000-12-05T05:07:59Z",
new DateTime(2000, 12, 5, 5, 7, 59, DateTimeKind.Utc),
#if !NET20
"2000-12-05T05:07:59-10:00",
new DateTimeOffset(2000, 12, 5, 5, 7, 59, -TimeSpan.FromHours(10)),
#endif
"SGVsbG8gd29ybGQ=",
Encoding.UTF8.GetBytes("Hello world"),
"365.23:59:59",
new TimeSpan(365, 23, 59, 59)
};
JObject o = new JObject(
new JProperty("prop",
new JArray(
values.Select(v => new JObject(new JProperty("childProp", v)))
)
)
);
IList<JToken> t = o.SelectTokens("$.prop[?(@.childProp =='ff2dc672-6e15-4aa2-afb0-18f4f69596ad')]").ToList();
Assert.AreEqual(2, t.Count);
t = o.SelectTokens("$.prop[?(@.childProp =='http://localhost')]").ToList();
Assert.AreEqual(2, t.Count);
t = o.SelectTokens("$.prop[?(@.childProp =='2000-12-05T05:07:59Z')]").ToList();
Assert.AreEqual(2, t.Count);
#if !NET20
t = o.SelectTokens("$.prop[?(@.childProp =='2000-12-05T05:07:59-10:00')]").ToList();
Assert.AreEqual(2, t.Count);
#endif
t = o.SelectTokens("$.prop[?(@.childProp =='SGVsbG8gd29ybGQ=')]").ToList();
Assert.AreEqual(2, t.Count);
t = o.SelectTokens("$.prop[?(@.childProp =='365.23:59:59')]").ToList();
Assert.AreEqual(2, t.Count);
}
[Test]
public void Example()
{
JObject o = JObject.Parse(@"{
""Stores"": [
""Lambton Quay"",
""Willis Street""
],
""Manufacturers"": [
{
""Name"": ""Acme Co"",
""Products"": [
{
""Name"": ""Anvil"",
""Price"": 50
}
]
},
{
""Name"": ""Contoso"",
""Products"": [
{
""Name"": ""Elbow Grease"",
""Price"": 99.95
},
{
""Name"": ""Headlight Fluid"",
""Price"": 4
}
]
}
]
}");
string name = (string)o.SelectToken("Manufacturers[0].Name");
// Acme Co
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
// 50
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
// Elbow Grease
Assert.AreEqual("Acme Co", name);
Assert.AreEqual(50m, productPrice);
Assert.AreEqual("Elbow Grease", productName);
IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
// Lambton Quay
// Willis Street
IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
// null
// Headlight Fluid
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
// 149.95
Assert.AreEqual(2, storeNames.Count);
Assert.AreEqual("Lambton Quay", storeNames[0]);
Assert.AreEqual("Willis Street", storeNames[1]);
Assert.AreEqual(2, firstProductNames.Count);
Assert.AreEqual(null, firstProductNames[0]);
Assert.AreEqual("Headlight Fluid", firstProductNames[1]);
Assert.AreEqual(149.95m, totalPrice);
}
[Test]
public void NotEqualsAndNonPrimativeValues()
{
string json = @"[
{
""name"": ""string"",
""value"": ""aString""
},
{
""name"": ""number"",
""value"": 123
},
{
""name"": ""array"",
""value"": [
1,
2,
3,
4
]
},
{
""name"": ""object"",
""value"": {
""1"": 1
}
}
]";
JArray a = JArray.Parse(json);
List<JToken> result = a.SelectTokens("$.[?(@.value!=1)]").ToList();
Assert.AreEqual(4, result.Count);
result = a.SelectTokens("$.[?(@.value!='2000-12-05T05:07:59-10:00')]").ToList();
Assert.AreEqual(4, result.Count);
result = a.SelectTokens("$.[?(@.value!=null)]").ToList();
Assert.AreEqual(4, result.Count);
result = a.SelectTokens("$.[?(@.value!=123)]").ToList();
Assert.AreEqual(3, result.Count);
result = a.SelectTokens("$.[?(@.value)]").ToList();
Assert.AreEqual(4, result.Count);
}
[Test]
public void RootInFilter()
{
string json = @"[
{
""store"" : {
""book"" : [
{
""category"" : ""reference"",
""author"" : ""Nigel Rees"",
""title"" : ""Sayings of the Century"",
""price"" : 8.95
},
{
""category"" : ""fiction"",
""author"" : ""Evelyn Waugh"",
""title"" : ""Sword of Honour"",
""price"" : 12.99
},
{
""category"" : ""fiction"",
""author"" : ""Herman Melville"",
""title"" : ""Moby Dick"",
""isbn"" : ""0-553-21311-3"",
""price"" : 8.99
},
{
""category"" : ""fiction"",
""author"" : ""J. R. R. Tolkien"",
""title"" : ""The Lord of the Rings"",
""isbn"" : ""0-395-19395-8"",
""price"" : 22.99
}
],
""bicycle"" : {
""color"" : ""red"",
""price"" : 19.95
}
},
""expensive"" : 10
}
]";
JArray a = JArray.Parse(json);
List<JToken> result = a.SelectTokens("$.[?($.[0].store.bicycle.price < 20)]").ToList();
Assert.AreEqual(1, result.Count);
result = a.SelectTokens("$.[?($.[0].store.bicycle.price < 10)]").ToList();
Assert.AreEqual(0, result.Count);
}
[Test]
public void RootInFilterWithRootObject()
{
string json = @"{
""store"" : {
""book"" : [
{
""category"" : ""reference"",
""author"" : ""Nigel Rees"",
""title"" : ""Sayings of the Century"",
""price"" : 8.95
},
{
""category"" : ""fiction"",
""author"" : ""Evelyn Waugh"",
""title"" : ""Sword of Honour"",
""price"" : 12.99
},
{
""category"" : ""fiction"",
""author"" : ""Herman Melville"",
""title"" : ""Moby Dick"",
""isbn"" : ""0-553-21311-3"",
""price"" : 8.99
},
{
""category"" : ""fiction"",
""author"" : ""J. R. R. Tolkien"",
""title"" : ""The Lord of the Rings"",
""isbn"" : ""0-395-19395-8"",
""price"" : 22.99
}
],
""bicycle"" : [
{
""color"" : ""red"",
""price"" : 19.95
}
]
},
""expensive"" : 10
}";
JObject a = JObject.Parse(json);
List<JToken> result = a.SelectTokens("$..book[?(@.price <= $['expensive'])]").ToList();
Assert.AreEqual(2, result.Count);
result = a.SelectTokens("$.store..[?(@.price > $.expensive)]").ToList();
Assert.AreEqual(3, result.Count);
}
[Test]
public void RootInFilterWithInitializers()
{
JObject rootObject = new JObject
{
{ "referenceDate", new JValue(DateTime.MinValue) },
{
"dateObjectsArray",
new JArray()
{
new JObject { { "date", new JValue(DateTime.MinValue) } },
new JObject { { "date", new JValue(DateTime.MaxValue) } },
new JObject { { "date", new JValue(DateTime.Now) } },
new JObject { { "date", new JValue(DateTime.MinValue) } },
}
}
};
List<JToken> result = rootObject.SelectTokens("$.dateObjectsArray[?(@.date == $.referenceDate)]").ToList();
Assert.AreEqual(2, result.Count);
}
[Test]
public void IdentityOperator()
{
JObject o = JObject.Parse(@"{
'Values': [{
'Coercible': 1,
'Name': 'Number'
}, {
'Coercible': '1',
'Name': 'String'
}]
}");
// just to verify expected behavior hasn't changed
IEnumerable<string> sanity1 = o.SelectTokens("Values[?(@.Coercible == '1')].Name").Select(x => (string)x);
IEnumerable<string> sanity2 = o.SelectTokens("Values[?(@.Coercible != '1')].Name").Select(x => (string)x);
// new behavior
IEnumerable<string> mustBeNumber1 = o.SelectTokens("Values[?(@.Coercible === 1)].Name").Select(x => (string)x);
IEnumerable<string> mustBeString1 = o.SelectTokens("Values[?(@.Coercible !== 1)].Name").Select(x => (string)x);
IEnumerable<string> mustBeString2 = o.SelectTokens("Values[?(@.Coercible === '1')].Name").Select(x => (string)x);
IEnumerable<string> mustBeNumber2 = o.SelectTokens("Values[?(@.Coercible !== '1')].Name").Select(x => (string)x);
// FAILS-- JPath returns { "String" }
//CollectionAssert.AreEquivalent(new[] { "Number", "String" }, sanity1);
// FAILS-- JPath returns { "Number" }
//Assert.IsTrue(!sanity2.Any());
Assert.AreEqual("Number", mustBeNumber1.Single());
Assert.AreEqual("String", mustBeString1.Single());
Assert.AreEqual("Number", mustBeNumber2.Single());
Assert.AreEqual("String", mustBeString2.Single());
}
[Test]
public void QueryWithEscapedPath()
{
JToken t = JToken.Parse(@"{
""Property"": [
{
""@Name"": ""x"",
""@Value"": ""y"",
""@Type"": ""FindMe""
}
]
}");
var tokens = t.SelectTokens("$..[?(@.['@Type'] == 'FindMe')]").ToList();
Assert.AreEqual(1, tokens.Count);
}
[Test]
public void Equals_FloatWithInt()
{
JToken t = JToken.Parse(@"{
""Values"": [
{
""Property"": 1
}
]
}");
Assert.IsNotNull(t.SelectToken(@"Values[?(@.Property == 1.0)]"));
}
#if DNXCORE50
[Theory]
#endif
[TestCaseSource(nameof(StrictMatchWithInverseTestData))]
public static void EqualsStrict(string value1, string value2, bool matchStrict)
{
string completeJson = @"{
""Values"": [
{
""Property"": " + value1 + @"
}
]
}";
string completeEqualsStrictPath = "$.Values[?(@.Property === " + value2 + ")]";
string completeNotEqualsStrictPath = "$.Values[?(@.Property !== " + value2 + ")]";
JToken t = JToken.Parse(completeJson);
bool hasEqualsStrict = t.SelectTokens(completeEqualsStrictPath).Any();
Assert.AreEqual(
matchStrict,
hasEqualsStrict,
$"Expected {value1} and {value2} to match: {matchStrict}"
+ Environment.NewLine + completeJson + Environment.NewLine + completeEqualsStrictPath);
bool hasNotEqualsStrict = t.SelectTokens(completeNotEqualsStrictPath).Any();
Assert.AreNotEqual(
matchStrict,
hasNotEqualsStrict,
$"Expected {value1} and {value2} to match: {!matchStrict}"
+ Environment.NewLine + completeJson + Environment.NewLine + completeEqualsStrictPath);
}
public static IEnumerable<object[]> StrictMatchWithInverseTestData()
{
foreach (var item in StrictMatchTestData())
{
yield return new object[] { item[0], item[1], item[2] };
if (!item[0].Equals(item[1]))
{
// Test the inverse
yield return new object[] { item[1], item[0], item[2] };
}
}
}
private static IEnumerable<object[]> StrictMatchTestData()
{
yield return new object[] { "1", "1", true };
yield return new object[] { "1", "1.0", true };
yield return new object[] { "1", "true", false };
yield return new object[] { "1", "'1'", false };
yield return new object[] { "'1'", "'1'", true };
yield return new object[] { "false", "false", true };
yield return new object[] { "true", "false", false };
yield return new object[] { "1", "1.1", false };
yield return new object[] { "1", "null", false };
yield return new object[] { "null", "null", true };
yield return new object[] { "null", "'null'", false };
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Security;
using System.ServiceModel;
using System.ServiceModel.Activation.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.Threading;
class TransportListener
{
// Double-checked locking pattern requires volatile for read/write synchronization
static volatile byte[] drainBuffer;
static Hashtable namedPipeInstances = new Hashtable();
static Hashtable tcpInstances = new Hashtable();
int count;
ListenerConnectionDemuxer demuxer;
ListenerConnectionDemuxer demuxerV6;
TransportType transportType;
EventTraceActivity eventTraceActvity;
TransportListener(IPEndPoint endPoint)
{
if (TD.TcpTransportListenerListeningStartIsEnabled())
{
TD.TcpTransportListenerListeningStart(this.EventTraceActivity, GetRemoteEndpointAddressPort(endPoint));
}
transportType = TransportType.Tcp;
SocketSettings socketSettings = new SocketSettings();
IConnectionListener connectionListener = null;
if (endPoint.Address.Equals(IPAddress.Broadcast))
{
if (Socket.OSSupportsIPv4)
{
connectionListener = new SocketConnectionListener(new IPEndPoint(IPAddress.Any, endPoint.Port), socketSettings, true);
demuxer = Go(connectionListener);
}
if (Socket.OSSupportsIPv6)
{
connectionListener = new SocketConnectionListener(new IPEndPoint(IPAddress.IPv6Any, endPoint.Port), socketSettings, true);
demuxerV6 = Go(connectionListener);
}
}
else
{
connectionListener = new SocketConnectionListener(endPoint, socketSettings, true);
demuxer = Go(connectionListener);
}
if (TD.TcpTransportListenerListeningStopIsEnabled())
{
TD.TcpTransportListenerListeningStop(this.EventTraceActivity);
}
}
TransportListener(BaseUriWithWildcard pipeUri)
{
if (TD.PipeTransportListenerListeningStartIsEnabled())
{
TD.PipeTransportListenerListeningStart(this.EventTraceActivity, (pipeUri.BaseAddress != null) ? pipeUri.BaseAddress.ToString() : string.Empty);
}
transportType = TransportType.NamedPipe;
IConnectionListener connectionListener = new PipeConnectionListener(pipeUri.BaseAddress, pipeUri.HostNameComparisonMode,
ListenerConstants.SharedConnectionBufferSize, null, false, int.MaxValue);
demuxer = Go(connectionListener);
if (TD.PipeTransportListenerListeningStopIsEnabled())
{
TD.PipeTransportListenerListeningStop(this.EventTraceActivity);
}
}
EventTraceActivity EventTraceActivity
{
get
{
if (this.eventTraceActvity == null)
{
this.eventTraceActvity = EventTraceActivity.GetFromThreadOrCreate();
}
return this.eventTraceActvity;
}
}
void AddRef()
{
++count;
}
int DelRef()
{
return --count;
}
internal ListenerConnectionDemuxer Go(IConnectionListener connectionListener)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Information, ListenerTraceCode.TransportListenerListenRequest, SR.GetString(SR.TraceCodeTransportListenerListenRequest), this);
}
ConnectionHandleDuplicated onDupHandle = new ConnectionHandleDuplicated(OnDupHandle);
ListenerConnectionDemuxer connectionDemuxer = null;
if (transportType == TransportType.Tcp)
{
connectionDemuxer = new ListenerConnectionDemuxer(connectionListener,
transportType,
ListenerConfig.NetTcp.MaxPendingAccepts,
ListenerConfig.NetTcp.MaxPendingConnections,
ListenerConfig.NetTcp.ReceiveTimeout,
onDupHandle);
}
else if (transportType == TransportType.NamedPipe)
{
connectionDemuxer = new ListenerConnectionDemuxer(connectionListener,
transportType,
ListenerConfig.NetPipe.MaxPendingAccepts,
ListenerConfig.NetPipe.MaxPendingConnections,
ListenerConfig.NetPipe.ReceiveTimeout,
onDupHandle);
}
if (ExecutionContext.IsFlowSuppressed())
{
if (SecurityContext.IsFlowSuppressed())
{
connectionDemuxer.StartDemuxing();
}
else
{
using (SecurityContext.SuppressFlow())
{
connectionDemuxer.StartDemuxing();
}
}
}
else
{
using (ExecutionContext.SuppressFlow())
{
if (SecurityContext.IsFlowSuppressed())
{
connectionDemuxer.StartDemuxing();
}
else
{
using (SecurityContext.SuppressFlow())
{
connectionDemuxer.StartDemuxing();
}
}
}
}
if (DiagnosticUtility.ShouldTraceInformation)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Information, ListenerTraceCode.TransportListenerListening, SR.GetString(SR.TraceCodeTransportListenerListening), this);
}
return connectionDemuxer;
}
internal static void Listen(IPEndPoint endPoint)
{
lock (tcpInstances)
{
TransportListener t = tcpInstances[endPoint] as TransportListener;
if (t != null)
{
// We use the shared TransportListener that is created earlier.
t.AddRef();
}
else
{
t = new TransportListener(endPoint);
tcpInstances.Add(endPoint, t);
t.AddRef();
}
}
}
internal static void Listen(BaseUriWithWildcard pipeUri)
{
lock (namedPipeInstances)
{
if (namedPipeInstances.ContainsKey(pipeUri))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.PipeAddressAlreadyUsed)));
}
else
{
TransportListener t = new TransportListener(pipeUri);
namedPipeInstances.Add(pipeUri, t);
}
}
}
static TransportType GetTransportTypeAndAddress(IConnection connection, out IPAddress address, out int port)
{
Socket socket = connection.GetCoreTransport() as Socket;
address = null;
port = -1;
TransportType transportType = TransportType.NamedPipe;
if (socket != null)
{
address = (socket.LocalEndPoint as IPEndPoint).Address;
port = (socket.LocalEndPoint as IPEndPoint).Port;
transportType = TransportType.Tcp;
}
return transportType;
}
internal void OnDupHandle(ListenerSessionConnection session)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Information, ListenerTraceCode.TransportListenerSessionsReceived, SR.GetString(SR.TraceCodeTransportListenerSessionsReceived), this);
}
if (TD.TransportListenerSessionsReceivedIsEnabled())
{
TD.TransportListenerSessionsReceived(session.EventTraceActivity, session.Via.ToString());
}
IPAddress address;
int port;
TransportType transportType = GetTransportTypeAndAddress(session.Connection, out address, out port);
Debug.Print("TransportListener.OnDupHandle() via: " + session.Via.ToString() + " transportType: " + transportType);
MessageQueue messageQueue = RoutingTable.Lookup(session.Via, address, port);
if (messageQueue != null)
{
messageQueue.EnqueueSessionAndDispatch(session);
}
else
{
TransportListener.SendFault(session.Connection, FramingEncodingString.EndpointNotFoundFault);
MessageQueue.OnDispatchFailure(transportType);
}
}
static object ThisStaticLock { get { return tcpInstances; } }
internal static void SendFault(IConnection connection, string fault)
{
if (drainBuffer == null)
{
lock (ThisStaticLock)
{
if (drainBuffer == null)
{
drainBuffer = new byte[1024];
}
}
}
try
{
InitialServerConnectionReader.SendFault(connection, fault, drainBuffer,
ListenerConstants.SharedSendTimeout, ListenerConstants.SharedMaxDrainSize);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
// We don't care the error when sending a fault.
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Warning);
}
}
void Stop()
{
if (demuxer != null)
{
demuxer.Dispose();
}
if (demuxerV6 != null)
{
demuxerV6.Dispose();
}
}
internal static void Stop(IPEndPoint endPoint)
{
lock (tcpInstances)
{
TransportListener t = tcpInstances[endPoint] as TransportListener;
if (t != null)
{
if (t.DelRef() == 0)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Information, ListenerTraceCode.TransportListenerStop, SR.GetString(SR.TraceCodeTransportListenerStop), t);
}
try
{
t.Stop();
}
finally
{
tcpInstances.Remove(endPoint);
}
}
}
}
}
internal static void Stop(BaseUriWithWildcard pipeUri)
{
lock (namedPipeInstances)
{
TransportListener t = namedPipeInstances[pipeUri] as TransportListener;
if (t != null)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Information, ListenerTraceCode.TransportListenerStop, SR.GetString(SR.TraceCodeTransportListenerStop), t);
}
try
{
t.Stop();
}
finally
{
namedPipeInstances.Remove(pipeUri);
}
}
}
}
static string GetRemoteEndpointAddressPort(Net.IPEndPoint iPEndPoint)
{
//We really don't want any exceptions out of TraceUtility.
if (iPEndPoint != null)
{
try
{
return iPEndPoint.Address.ToString() + ":" + iPEndPoint.Port;
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
//ignore and continue with all non-fatal exceptions.
}
}
return string.Empty;
}
}
}
| |
//
// MetadataServiceJob.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2006-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using Banshee.Kernel;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Streaming;
using Banshee.Networking;
using Banshee.ServiceStack;
namespace Banshee.Metadata
{
public class MetadataServiceJob : IMetadataLookupJob
{
private MetadataService service;
private bool cancelled;
private IBasicTrackInfo track;
private List<StreamTag> tags = new List<StreamTag>();
private IMetadataLookupJob current_job;
protected bool InternetConnected {
get { return ServiceManager.Get<Network> ().Connected; }
}
protected MetadataServiceJob()
{
}
public MetadataServiceJob(MetadataService service, IBasicTrackInfo track)
{
this.service = service;
this.track = track;
}
public virtual void Cancel ()
{
cancelled = true;
lock (this) {
if (current_job != null) {
current_job.Cancel ();
}
}
}
public virtual void Run()
{
foreach(IMetadataProvider provider in service.Providers) {
if (cancelled)
break;;
try {
lock (this) {
current_job = provider.CreateJob(track);
}
current_job.Run();
if (cancelled)
break;;
foreach(StreamTag tag in current_job.ResultTags) {
AddTag(tag);
}
lock (this) {
current_job = null;
}
} catch (System.Threading.ThreadAbortException) {
throw;
} catch(Exception e) {
Hyena.Log.Exception (e);
}
}
}
public virtual IBasicTrackInfo Track {
get { return track; }
protected set { track = value; }
}
public virtual IList<StreamTag> ResultTags {
get { return tags; }
}
protected void AddTag(StreamTag tag)
{
tags.Add(tag);
}
protected HttpWebResponse GetHttpStream(Uri uri)
{
return GetHttpStream(uri, null);
}
protected HttpWebResponse GetHttpStream(Uri uri, string [] ignoreMimeTypes)
{
if(!InternetConnected) {
throw new NetworkUnavailableException();
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri.AbsoluteUri);
request.UserAgent = Banshee.Web.Browser.UserAgent;
request.Timeout = 10 * 1000;
request.KeepAlive = false;
request.AllowAutoRedirect = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if(ignoreMimeTypes != null) {
string [] content_types = response.Headers.GetValues("Content-Type");
if(content_types != null) {
foreach(string content_type in content_types) {
for(int i = 0; i < ignoreMimeTypes.Length; i++) {
if(content_type == ignoreMimeTypes[i]) {
return null;
}
}
}
}
}
return response;
}
protected bool SaveHttpStream(Uri uri, string path)
{
return SaveHttpStream(uri, path, null);
}
protected bool SaveHttpStream(Uri uri, string path, string [] ignoreMimeTypes)
{
HttpWebResponse response = GetHttpStream(uri, ignoreMimeTypes);
Stream from_stream = response == null ? null : response.GetResponseStream ();
if(from_stream == null) {
if (response != null) {
response.Close ();
}
return false;
}
SaveAtomically (path, from_stream);
from_stream.Close ();
return true;
}
protected bool SaveHttpStreamCover (Uri uri, string albumArtistId, string [] ignoreMimeTypes)
{
return SaveHttpStream (uri, CoverArtSpec.GetPath (albumArtistId), ignoreMimeTypes);
}
protected void SaveAtomically (string path, Stream from_stream)
{
if (String.IsNullOrEmpty (path) || from_stream == null || !from_stream.CanRead) {
return;
}
SafeUri path_uri = new SafeUri (path);
if (Banshee.IO.File.Exists (path_uri)) {
return;
}
// Save the file to a temporary path while downloading/copying,
// so that nobody sees it and thinks it's ready for use before it is
SafeUri tmp_uri = new SafeUri (String.Format ("{0}.part", path));
try {
Banshee.IO.StreamAssist.Save (from_stream, Banshee.IO.File.OpenWrite (tmp_uri, true));
Banshee.IO.File.Move (tmp_uri, path_uri);
} catch (Exception e) {
Hyena.Log.Exception (e);
}
}
}
}
| |
// uScript Action Node
// (C) 2011 Detox Studios LLC
using UnityEngine;
using System.Collections;
[NodePath("Actions/Toggle")]
[NodeCopyright("Copyright 2011 by Detox Studios LLC")]
[NodeToolTip("Toggles the active state of a component on the Target GameObjects.")]
[NodeAuthor("Detox Studios LLC", "http://www.detoxstudios.com")]
[NodeHelp("http://docs.uscript.net/#3-Working_With_uScript/3.4-Nodes.htm")]
[FriendlyName("Toggle Component", "Toggles the active state of a component on the Target GameObjects. Ignores GameObjects missing the specified component.")]
public class uScriptAct_ToggleComponent : uScriptLogic
{
// ================================================================================
// Output Sockets
// ================================================================================
//
[FriendlyName("Turned On")]
public event System.EventHandler OnOut;
[FriendlyName("Turned Off")]
public event System.EventHandler OffOut;
[FriendlyName("Toggled")]
public event System.EventHandler ToggleOut;
public bool Out { get { return true; } }
private bool turnedOn = false;
private bool turnedOff = false;
// ================================================================================
// Input Sockets and Node Parameters
// ================================================================================
//
// Parameter Attributes are applied below in Toggle()
[FriendlyName("Turn On")]
public void TurnOn(GameObject[] Target, string[] ComponentName)
{
foreach ( GameObject currentTarget in Target)
{
if (currentTarget != null)
{
foreach (string currentComponentName in ComponentName)
{
if (currentComponentName.ToLower() == "collider" )
{
#if !UNITY_3_2 && !UNITY_3_3
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7)
if ( currentTarget.collider != null )
{
currentTarget.collider.enabled = true;
}
#else
if (currentTarget.GetComponent<Collider>() != null)
{
currentTarget.GetComponent<Collider>().enabled = true;
}
#endif
#endif
}
else if (currentComponentName.ToLower() == "meshrenderer" || currentComponentName.ToLower() == "renderer" || currentComponentName.ToLower() == "skinnedmeshrenderer" )
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7)
if ( currentTarget.renderer != null )
{
currentTarget.renderer.enabled = true;
}
#else
if (currentTarget.GetComponent<Renderer>() != null)
{
currentTarget.GetComponent<Renderer>().enabled = true;
}
#endif
}
else
{
EnableThis(currentTarget.GetComponent(currentComponentName), true);
}
}
}
}
if ( null != OnOut ) OnOut(this, new System.EventArgs());
}
// Parameter Attributes are applied below in Toggle()
[FriendlyName("Turn Off")]
public void TurnOff(GameObject[] Target, string[] ComponentName)
{
foreach (GameObject currentTarget in Target)
{
if (currentTarget != null)
{
foreach (string currentComponentName in ComponentName)
{
if (currentComponentName.ToLower() == "collider" )
{
#if !UNITY_3_2 && !UNITY_3_3
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7)
if ( currentTarget.collider != null )
{
currentTarget.collider.enabled = false;
}
#else
if (currentTarget.GetComponent<Collider>() != null)
{
currentTarget.GetComponent<Collider>().enabled = false;
}
#endif
#endif
}
else if (currentComponentName.ToLower() == "meshrenderer" || currentComponentName.ToLower() == "renderer" || currentComponentName.ToLower() == "skinnedmeshrenderer" )
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7)
if ( currentTarget.renderer != null )
{
currentTarget.renderer.enabled = false;
}
#else
if (currentTarget.GetComponent<Renderer>() != null)
{
currentTarget.GetComponent<Renderer>().enabled = false;
}
#endif
}
else
{
EnableThis(currentTarget.GetComponent(currentComponentName), false);
}
}
}
}
if ( null != OffOut ) OffOut(this, new System.EventArgs());
}
[FriendlyName("Toggle")]
public void Toggle(
[FriendlyName("Target", "The Target GameObject(s) to toggle component state on."), AutoLinkType(typeof(GameObject))]
GameObject[] Target,
[FriendlyName("Component Name", "The name of the component to toggle.")]
string[] ComponentName
)
{
turnedOn = false;
turnedOff = false;
foreach (GameObject currentTarget in Target)
{
if (currentTarget != null)
{
foreach (string currentComponentName in ComponentName)
{
if (currentComponentName.ToLower() == "collider" )
{
#if !UNITY_3_2 && !UNITY_3_3
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7)
if ( currentTarget.collider != null )
{
if (currentTarget.collider.enabled)
{
currentTarget.collider.enabled = false;
turnedOff = true;
}
else
{
currentTarget.collider.enabled = true;
turnedOn = true;
}
}
#else
if (currentTarget.GetComponent<Collider>() != null)
{
if (currentTarget.GetComponent<Collider>().enabled)
{
currentTarget.GetComponent<Collider>().enabled = false;
turnedOff = true;
}
else
{
currentTarget.GetComponent<Collider>().enabled = true;
turnedOn = true;
}
}
#endif
#endif
}
else if (currentComponentName.ToLower() == "meshrenderer" || currentComponentName.ToLower() == "renderer" || currentComponentName.ToLower() == "skinnedmeshrenderer" )
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7)
if ( currentTarget.renderer != null )
{
if (currentTarget.renderer.enabled)
{
currentTarget.renderer.enabled = false;
turnedOff = true;
}
else
{
currentTarget.renderer.enabled = true;
turnedOn = true;
}
}
#else
if (currentTarget.GetComponent<Renderer>() != null)
{
if (currentTarget.GetComponent<Renderer>().enabled)
{
currentTarget.GetComponent<Renderer>().enabled = false;
turnedOff = true;
}
else
{
currentTarget.GetComponent<Renderer>().enabled = true;
turnedOn = true;
}
}
#endif
}
else
{
turnedOn = ToggleThis(currentTarget.GetComponent(currentComponentName));
turnedOff = ! turnedOn;
}
}
}
}
if ( null != ToggleOut ) ToggleOut(this, new System.EventArgs());
if ( turnedOn && null != OnOut ) OnOut(this, new System.EventArgs());
if ( turnedOff && null != OffOut ) OffOut(this, new System.EventArgs());
}
// ================================================================================
// Miscellaneous Node Functionality
// ================================================================================
//
private void EnableThis(Component comp, bool enable)
{
Behaviour b = comp as Behaviour;
if (b != null)
{
b.enabled = enable;
return;
}
ParticleEmitter pe = comp as ParticleEmitter;
if (pe != null)
{
pe.enabled = enable;
return;
}
LineRenderer le = comp as LineRenderer;
if (le != null)
{
le.enabled = enable;
return;
}
}
private bool ToggleThis(Component comp)
{
Behaviour b = comp as Behaviour;
if (b != null)
{
b.enabled = ! b.enabled;
return b.enabled;
}
ParticleEmitter pe = comp as ParticleEmitter;
if (pe != null)
{
pe.enabled = ! pe.enabled;
return pe.enabled;
}
LineRenderer le = comp as LineRenderer;
if (le != null)
{
le.enabled = ! le.enabled;
return le.enabled;
}
return false;
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SchemaZen.Library.Models;
public class DatabaseDiff {
public List<SqlAssembly> AssembliesAdded = new();
public List<SqlAssembly> AssembliesDeleted = new();
public List<SqlAssembly> AssembliesDiff = new();
public Database Db;
public List<ForeignKey> ForeignKeysAdded = new();
public List<ForeignKey> ForeignKeysDeleted = new();
public List<ForeignKey> ForeignKeysDiff = new();
public List<Permission> PermissionsAdded = new();
public List<Permission> PermissionsDeleted = new();
public List<Permission> PermissionsDiff = new();
public List<DbProp> PropsChanged = new();
public List<Routine> RoutinesAdded = new();
public List<Routine> RoutinesDeleted = new();
public List<Routine> RoutinesDiff = new();
public List<Synonym> SynonymsAdded = new();
public List<Synonym> SynonymsDeleted = new();
public List<Synonym> SynonymsDiff = new();
public List<Table> TablesAdded = new();
public List<Table> TablesDeleted = new();
public List<TableDiff> TablesDiff = new();
public List<Table> TableTypesDiff = new();
public List<SqlUser> UsersAdded = new();
public List<SqlUser> UsersDeleted = new();
public List<SqlUser> UsersDiff = new();
public List<Constraint> ViewIndexesAdded = new();
public List<Constraint> ViewIndexesDeleted = new();
public List<Constraint> ViewIndexesDiff = new();
public bool IsDiff => PropsChanged.Count > 0
|| TablesAdded.Count > 0
|| TablesDiff.Count > 0
|| TableTypesDiff.Count > 0
|| TablesDeleted.Count > 0
|| RoutinesAdded.Count > 0
|| RoutinesDiff.Count > 0
|| RoutinesDeleted.Count > 0
|| ForeignKeysAdded.Count > 0
|| ForeignKeysDiff.Count > 0
|| ForeignKeysDeleted.Count > 0
|| AssembliesAdded.Count > 0
|| AssembliesDiff.Count > 0
|| AssembliesDeleted.Count > 0
|| UsersAdded.Count > 0
|| UsersDiff.Count > 0
|| UsersDeleted.Count > 0
|| ViewIndexesAdded.Count > 0
|| ViewIndexesDiff.Count > 0
|| ViewIndexesDeleted.Count > 0
|| SynonymsAdded.Count > 0
|| SynonymsDiff.Count > 0
|| SynonymsDeleted.Count > 0
|| PermissionsAdded.Count > 0
|| PermissionsDiff.Count > 0
|| PermissionsDeleted.Count > 0;
private static string Summarize(bool includeNames, List<string> changes, string caption) {
if (changes.Count == 0) return string.Empty;
return changes.Count + "x " + caption +
(includeNames ? "\r\n\t" + string.Join("\r\n\t", changes.ToArray()) : string.Empty) +
"\r\n";
}
public string SummarizeChanges(bool includeNames) {
var sb = new StringBuilder();
sb.Append(
Summarize(
includeNames,
AssembliesAdded.Select(o => o.Name).ToList(),
"assemblies in source but not in target"));
sb.Append(
Summarize(
includeNames,
AssembliesDeleted.Select(o => o.Name).ToList(),
"assemblies not in source but in target"));
sb.Append(
Summarize(
includeNames,
AssembliesDiff.Select(o => o.Name).ToList(),
"assemblies altered"));
sb.Append(
Summarize(
includeNames,
ForeignKeysAdded.Select(o => o.Name).ToList(),
"foreign keys in source but not in target"));
sb.Append(
Summarize(
includeNames,
ForeignKeysDeleted.Select(o => o.Name).ToList(),
"foreign keys not in source but in target"));
sb.Append(
Summarize(
includeNames,
ForeignKeysDiff.Select(o => o.Name).ToList(),
"foreign keys altered"));
sb.Append(
Summarize(
includeNames,
PropsChanged.Select(o => o.Name).ToList(),
"properties changed"));
sb.Append(
Summarize(
includeNames,
RoutinesAdded.Select(o => $"{o.RoutineType.ToString()} {o.Owner}.{o.Name}")
.ToList(),
"routines in source but not in target"));
sb.Append(
Summarize(
includeNames,
RoutinesDeleted.Select(o => $"{o.RoutineType.ToString()} {o.Owner}.{o.Name}")
.ToList(),
"routines not in source but in target"));
sb.Append(
Summarize(
includeNames,
RoutinesDiff.Select(o => $"{o.RoutineType.ToString()} {o.Owner}.{o.Name}").ToList(),
"routines altered"));
sb.Append(
Summarize(
includeNames,
TablesAdded.Where(o => !o.IsType).Select(o => $"{o.Owner}.{o.Name}").ToList(),
"tables in source but not in target"));
sb.Append(
Summarize(
includeNames,
TablesDeleted.Where(o => !o.IsType).Select(o => $"{o.Owner}.{o.Name}").ToList(),
"tables not in source but in target"));
sb.Append(
Summarize(
includeNames,
TablesDiff.Select(o => $"{o.Owner}.{o.Name}").ToList(),
"tables altered"));
sb.Append(
Summarize(
includeNames,
TablesAdded.Where(o => o.IsType).Select(o => $"{o.Owner}.{o.Name}").ToList(),
"table types in source but not in target"));
sb.Append(
Summarize(
includeNames,
TablesDeleted.Where(o => o.IsType).Select(o => $"{o.Owner}.{o.Name}").ToList(),
"table types not in source but in target"));
sb.Append(
Summarize(
includeNames,
TableTypesDiff.Select(o => $"{o.Owner}.{o.Name}").ToList(),
"table types altered"));
sb.Append(
Summarize(
includeNames,
UsersAdded.Select(o => o.Name).ToList(),
"users in source but not in target"));
sb.Append(
Summarize(
includeNames,
UsersDeleted.Select(o => o.Name).ToList(),
"users not in source but in target"));
sb.Append(
Summarize(
includeNames,
UsersDiff.Select(o => o.Name).ToList(),
"users altered"));
sb.Append(
Summarize(
includeNames,
ViewIndexesAdded.Select(o => o.Name).ToList(),
"view indexes in source but not in target"));
sb.Append(
Summarize(
includeNames,
ViewIndexesDeleted.Select(o => o.Name).ToList(),
"view indexes not in source but in target"));
sb.Append(
Summarize(
includeNames,
ViewIndexesDiff.Select(o => o.Name).ToList(),
"view indexes altered"));
sb.Append(
Summarize(
includeNames,
SynonymsAdded.Select(o => $"{o.Owner}.{o.Name}").ToList(),
"synonyms in source but not in target"));
sb.Append(
Summarize(
includeNames,
SynonymsDeleted.Select(o => $"{o.Owner}.{o.Name}").ToList(),
"synonyms not in source but in target"));
sb.Append(
Summarize(
includeNames,
SynonymsDiff.Select(o => $"{o.Owner}.{o.Name}").ToList(),
"synonyms altered"));
sb.Append(
Summarize(
includeNames,
PermissionsAdded.Select(o => $"{o.ObjectName}: {o.PermissionType} TO {o.UserName}")
.ToList(),
"permissions in source but not in target"));
sb.Append(
Summarize(
includeNames,
PermissionsDeleted
.Select(o => $"{o.ObjectName}: {o.PermissionType} TO {o.UserName}")
.ToList(),
"permissions not in source but in target"));
sb.Append(
Summarize(
includeNames,
PermissionsDiff.Select(o => $"{o.ObjectName}: {o.PermissionType} TO {o.UserName}")
.ToList(),
"permissions altered"));
return sb.ToString();
}
public string Script() {
var text = new StringBuilder();
//alter database props
//TODO need to check dependencies for collation change
//TODO how can collation be set to null at the server level?
if (PropsChanged.Count > 0) {
text.Append(Database.ScriptPropList(PropsChanged));
text.AppendLine("GO");
text.AppendLine();
}
//delete foreign keys
if (ForeignKeysDeleted.Count + ForeignKeysDiff.Count > 0) {
foreach (var fk in ForeignKeysDeleted) text.AppendLine(fk.ScriptDrop());
//delete modified foreign keys
foreach (var fk in ForeignKeysDiff) text.AppendLine(fk.ScriptDrop());
text.AppendLine("GO");
}
//delete tables
if (TablesDeleted.Count + TableTypesDiff.Count > 0) {
foreach (var t in TablesDeleted.Concat(TableTypesDiff)) text.AppendLine(t.ScriptDrop());
text.AppendLine("GO");
}
// TODO: table types drop will fail if anything references them... try to find a workaround?
//modify tables
if (TablesDiff.Count > 0) {
foreach (var t in TablesDiff) text.Append(t.Script());
text.AppendLine("GO");
}
//add tables
if (TablesAdded.Count + TableTypesDiff.Count > 0) {
foreach (var t in TablesAdded.Concat(TableTypesDiff)) text.Append(t.ScriptCreate());
text.AppendLine("GO");
}
//add foreign keys
if (ForeignKeysAdded.Count + ForeignKeysDiff.Count > 0) {
foreach (var fk in ForeignKeysAdded) text.AppendLine(fk.ScriptCreate());
//add modified foreign keys
foreach (var fk in ForeignKeysDiff) text.AppendLine(fk.ScriptCreate());
text.AppendLine("GO");
}
//add & delete procs, functions, & triggers
foreach (var r in RoutinesAdded) {
text.AppendLine(r.ScriptCreate());
text.AppendLine("GO");
}
foreach (var r in RoutinesDiff) // script alter if possible, otherwise drop and (re)create
try {
text.AppendLine(r.ScriptAlter(Db));
text.AppendLine("GO");
} catch {
text.AppendLine(r.ScriptDrop());
text.AppendLine("GO");
text.AppendLine(r.ScriptCreate());
text.AppendLine("GO");
}
foreach (var r in RoutinesDeleted) {
text.AppendLine(r.ScriptDrop());
text.AppendLine("GO");
}
//add & delete synonyms
foreach (var s in SynonymsAdded) {
text.AppendLine(s.ScriptCreate());
text.AppendLine("GO");
}
foreach (var s in SynonymsDiff) {
text.AppendLine(s.ScriptDrop());
text.AppendLine("GO");
text.AppendLine(s.ScriptCreate());
text.AppendLine("GO");
}
foreach (var s in SynonymsDeleted) {
text.AppendLine(s.ScriptDrop());
text.AppendLine("GO");
}
//add & delete permissions
foreach (var p in PermissionsAdded) {
text.AppendLine(p.ScriptCreate());
text.AppendLine("GO");
}
foreach (var p in PermissionsDiff) {
text.AppendLine(p.ScriptDrop());
text.AppendLine("GO");
text.AppendLine(p.ScriptCreate());
text.AppendLine("GO");
}
foreach (var p in PermissionsDeleted) {
text.AppendLine(p.ScriptDrop());
text.AppendLine("GO");
}
return text.ToString();
}
}
| |
/* ====================================================================
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// Summary description for ChartCtl.
/// </summary>
internal class ChartAxisCtl : Oranikle.ReportDesigner.Base.BaseControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
// change flags
bool fMonth, fVisible, fMajorTickMarks, fMargin,fReverse,fInterlaced;
bool fMajorGLWidth,fMajorGLColor,fMajorGLStyle;
bool fMinorGLWidth,fMinorGLColor,fMinorGLStyle;
bool fMajorInterval, fMinorInterval,fMax,fMin;
bool fMinorTickMarks,fScalar,fLogScale,fMajorGLShow, fMinorGLShow, fCanOmit;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private Oranikle.Studio.Controls.StyledCheckBox chkMonth;
private Oranikle.Studio.Controls.StyledCheckBox chkVisible;
private Oranikle.Studio.Controls.StyledComboBox cbMajorTickMarks;
private Oranikle.Studio.Controls.StyledCheckBox chkMargin;
private Oranikle.Studio.Controls.StyledCheckBox chkReverse;
private Oranikle.Studio.Controls.StyledCheckBox chkInterlaced;
private System.Windows.Forms.GroupBox groupBox1;
private Oranikle.Studio.Controls.CustomTextControl tbMajorGLWidth;
private Oranikle.Studio.Controls.StyledButton bMajorGLColor;
private Oranikle.Studio.Controls.StyledComboBox cbMajorGLColor;
private Oranikle.Studio.Controls.StyledComboBox cbMajorGLStyle;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.GroupBox groupBox2;
private Oranikle.Studio.Controls.CustomTextControl tbMinorGLWidth;
private Oranikle.Studio.Controls.StyledButton bMinorGLColor;
private Oranikle.Studio.Controls.StyledComboBox cbMinorGLColor;
private Oranikle.Studio.Controls.StyledComboBox cbMinorGLStyle;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label9;
private Oranikle.Studio.Controls.CustomTextControl tbMajorInterval;
private Oranikle.Studio.Controls.CustomTextControl tbMinorInterval;
private System.Windows.Forms.Label label10;
private Oranikle.Studio.Controls.CustomTextControl tbMax;
private System.Windows.Forms.Label label11;
private Oranikle.Studio.Controls.CustomTextControl tbMin;
private System.Windows.Forms.Label label12;
private Oranikle.Studio.Controls.StyledComboBox cbMinorTickMarks;
private Oranikle.Studio.Controls.StyledCheckBox chkScalar;
private Oranikle.Studio.Controls.StyledCheckBox chkLogScale;
private Oranikle.Studio.Controls.StyledCheckBox chkMajorGLShow;
private Oranikle.Studio.Controls.StyledCheckBox chkMinorGLShow;
private Oranikle.Studio.Controls.StyledButton bMinorIntervalExpr;
private Oranikle.Studio.Controls.StyledButton bMajorIntervalExpr;
private Oranikle.Studio.Controls.StyledButton bMinExpr;
private Oranikle.Studio.Controls.StyledButton bMaxExpr;
private Oranikle.Studio.Controls.StyledCheckBox chkCanOmit;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal ChartAxisCtl(DesignXmlDraw dxDraw, List<XmlNode> ris)
{
_ReportItems = ris;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
cbMajorGLColor.Items.AddRange(StaticLists.ColorList);
cbMinorGLColor.Items.AddRange(StaticLists.ColorList);
XmlNode node = _ReportItems[0];
chkMonth.Checked = _Draw.GetElementValue(node, "fyi:Month", "false").ToLower() == "true" ? true : false; //added checkbox for month category axis WP 12 may 2008
chkVisible.Checked = _Draw.GetElementValue(node, "Visible", "false").ToLower() == "true"? true: false;
chkMargin.Checked = _Draw.GetElementValue(node, "Margin", "false").ToLower() == "true"? true: false;
chkReverse.Checked = _Draw.GetElementValue(node, "Reverse", "false").ToLower() == "true"? true: false;
chkInterlaced.Checked = _Draw.GetElementValue(node, "Interlaced", "false").ToLower() == "true"? true: false;
chkScalar.Checked = _Draw.GetElementValue(node, "Scalar", "false").ToLower() == "true"? true: false;
chkLogScale.Checked = _Draw.GetElementValue(node, "LogScale", "false").ToLower() == "true"? true: false;
chkCanOmit.Checked = _Draw.GetElementValue(node, "fyi:CanOmit", "false").ToLower() == "true" ? true : false;
cbMajorTickMarks.Text = _Draw.GetElementValue(node, "MajorTickMarks", "None");
cbMinorTickMarks.Text = _Draw.GetElementValue(node, "MinorTickMarks", "None");
// Major Grid Lines
InitGridLines(node, "MajorGridLines", chkMajorGLShow, cbMajorGLColor, cbMajorGLStyle, tbMajorGLWidth);
// Minor Grid Lines
InitGridLines(node, "MinorGridLines", chkMinorGLShow, cbMinorGLColor, cbMinorGLStyle, tbMinorGLWidth);
tbMajorInterval.Text = _Draw.GetElementValue(node, "MajorInterval", "");
tbMinorInterval.Text = _Draw.GetElementValue(node, "MinorInterval", "");
tbMax.Text = _Draw.GetElementValue(node, "Max", "");
tbMin.Text = _Draw.GetElementValue(node, "Min", "");
fMonth = fVisible = fMajorTickMarks = fMargin=fReverse=fInterlaced=
fMajorGLWidth=fMajorGLColor=fMajorGLStyle=
fMinorGLWidth=fMinorGLColor=fMinorGLStyle=
fMajorInterval= fMinorInterval=fMax=fMin=
fMinorTickMarks=fScalar=fLogScale=fMajorGLShow=fMinorGLShow=fCanOmit=false;
}
private void InitGridLines(XmlNode node, string type, CheckBox show, ComboBox color, ComboBox style, TextBox width)
{
XmlNode m = _Draw.GetNamedChildNode(node, type);
if (m != null)
{
show.Checked = _Draw.GetElementValue(m, "ShowGridLines", "false").ToLower() == "true"? true: false;
XmlNode st = _Draw.GetNamedChildNode(m, "Style");
if (st != null)
{
XmlNode work = _Draw.GetNamedChildNode(st, "BorderColor");
if (work != null)
color.Text = _Draw.GetElementValue(work, "Default", "Black");
work = _Draw.GetNamedChildNode(st, "BorderStyle");
if (work != null)
style.Text = _Draw.GetElementValue(work, "Default", "Solid");
work = _Draw.GetNamedChildNode(st, "BorderWidth");
if (work != null)
width.Text = _Draw.GetElementValue(work, "Default", "1pt");
}
}
if (color.Text.Length == 0)
color.Text = "Black";
if (style.Text.Length == 0)
style.Text = "Solid";
if (width.Text.Length == 0)
width.Text = "1pt";
}
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.cbMajorTickMarks = new Oranikle.Studio.Controls.StyledComboBox();
this.cbMinorTickMarks = new Oranikle.Studio.Controls.StyledComboBox();
this.chkVisible = new Oranikle.Studio.Controls.StyledCheckBox();
this.chkMargin = new Oranikle.Studio.Controls.StyledCheckBox();
this.chkReverse = new Oranikle.Studio.Controls.StyledCheckBox();
this.chkInterlaced = new Oranikle.Studio.Controls.StyledCheckBox();
this.chkScalar = new Oranikle.Studio.Controls.StyledCheckBox();
this.chkLogScale = new Oranikle.Studio.Controls.StyledCheckBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.chkMajorGLShow = new Oranikle.Studio.Controls.StyledCheckBox();
this.tbMajorGLWidth = new Oranikle.Studio.Controls.CustomTextControl();
this.bMajorGLColor = new Oranikle.Studio.Controls.StyledButton();
this.cbMajorGLColor = new Oranikle.Studio.Controls.StyledComboBox();
this.cbMajorGLStyle = new Oranikle.Studio.Controls.StyledComboBox();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.chkMinorGLShow = new Oranikle.Studio.Controls.StyledCheckBox();
this.tbMinorGLWidth = new Oranikle.Studio.Controls.CustomTextControl();
this.bMinorGLColor = new Oranikle.Studio.Controls.StyledButton();
this.cbMinorGLColor = new Oranikle.Studio.Controls.StyledComboBox();
this.cbMinorGLStyle = new Oranikle.Studio.Controls.StyledComboBox();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.tbMajorInterval = new Oranikle.Studio.Controls.CustomTextControl();
this.tbMinorInterval = new Oranikle.Studio.Controls.CustomTextControl();
this.label10 = new System.Windows.Forms.Label();
this.tbMax = new Oranikle.Studio.Controls.CustomTextControl();
this.label11 = new System.Windows.Forms.Label();
this.tbMin = new Oranikle.Studio.Controls.CustomTextControl();
this.label12 = new System.Windows.Forms.Label();
this.bMinorIntervalExpr = new Oranikle.Studio.Controls.StyledButton();
this.bMajorIntervalExpr = new Oranikle.Studio.Controls.StyledButton();
this.bMinExpr = new Oranikle.Studio.Controls.StyledButton();
this.bMaxExpr = new Oranikle.Studio.Controls.StyledButton();
this.chkCanOmit = new Oranikle.Studio.Controls.StyledCheckBox();
this.chkMonth = new Oranikle.Studio.Controls.StyledCheckBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(104, 16);
this.label1.TabIndex = 1;
this.label1.Text = "Major Tick Marks";
//
// label2
//
this.label2.Location = new System.Drawing.Point(224, 8);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(112, 16);
this.label2.TabIndex = 3;
this.label2.Text = "Minor Tick Marks";
//
// cbMajorTickMarks
//
this.cbMajorTickMarks.AutoAdjustItemHeight = false;
this.cbMajorTickMarks.BorderColor = System.Drawing.Color.LightGray;
this.cbMajorTickMarks.ConvertEnterToTabForDialogs = false;
this.cbMajorTickMarks.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbMajorTickMarks.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbMajorTickMarks.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbMajorTickMarks.Items.AddRange(new object[] {
"None",
"Inside",
"Outside",
"Cross"});
this.cbMajorTickMarks.Location = new System.Drawing.Point(128, 8);
this.cbMajorTickMarks.Name = "cbMajorTickMarks";
this.cbMajorTickMarks.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbMajorTickMarks.SeparatorMargin = 1;
this.cbMajorTickMarks.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbMajorTickMarks.SeparatorWidth = 1;
this.cbMajorTickMarks.Size = new System.Drawing.Size(80, 21);
this.cbMajorTickMarks.TabIndex = 2;
this.cbMajorTickMarks.SelectedIndexChanged += new System.EventHandler(this.cbMajorTickMarks_SelectedIndexChanged);
//
// cbMinorTickMarks
//
this.cbMinorTickMarks.AutoAdjustItemHeight = false;
this.cbMinorTickMarks.BorderColor = System.Drawing.Color.LightGray;
this.cbMinorTickMarks.ConvertEnterToTabForDialogs = false;
this.cbMinorTickMarks.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbMinorTickMarks.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbMinorTickMarks.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbMinorTickMarks.Items.AddRange(new object[] {
"None",
"Inside",
"Outside",
"Cross"});
this.cbMinorTickMarks.Location = new System.Drawing.Point(336, 8);
this.cbMinorTickMarks.Name = "cbMinorTickMarks";
this.cbMinorTickMarks.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbMinorTickMarks.SeparatorMargin = 1;
this.cbMinorTickMarks.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbMinorTickMarks.SeparatorWidth = 1;
this.cbMinorTickMarks.Size = new System.Drawing.Size(80, 21);
this.cbMinorTickMarks.TabIndex = 4;
this.cbMinorTickMarks.SelectedIndexChanged += new System.EventHandler(this.cbMinorTickMarks_SelectedIndexChanged);
//
// chkVisible
//
this.chkVisible.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkVisible.ForeColor = System.Drawing.Color.Black;
this.chkVisible.Location = new System.Drawing.Point(24, 224);
this.chkVisible.Name = "chkVisible";
this.chkVisible.Size = new System.Drawing.Size(88, 24);
this.chkVisible.TabIndex = 19;
this.chkVisible.Text = "Visible";
this.chkVisible.CheckedChanged += new System.EventHandler(this.chkVisible_CheckedChanged);
//
// chkMargin
//
this.chkMargin.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkMargin.ForeColor = System.Drawing.Color.Black;
this.chkMargin.Location = new System.Drawing.Point(240, 224);
this.chkMargin.Name = "chkMargin";
this.chkMargin.Size = new System.Drawing.Size(60, 24);
this.chkMargin.TabIndex = 21;
this.chkMargin.Text = "Margin";
this.chkMargin.CheckedChanged += new System.EventHandler(this.chkMargin_CheckedChanged);
//
// chkReverse
//
this.chkReverse.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkReverse.ForeColor = System.Drawing.Color.Black;
this.chkReverse.Location = new System.Drawing.Point(108, 248);
this.chkReverse.Name = "chkReverse";
this.chkReverse.Size = new System.Drawing.Size(120, 24);
this.chkReverse.TabIndex = 23;
this.chkReverse.Text = "Reverse Direction";
this.chkReverse.CheckedChanged += new System.EventHandler(this.chkReverse_CheckedChanged);
//
// chkInterlaced
//
this.chkInterlaced.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkInterlaced.ForeColor = System.Drawing.Color.Black;
this.chkInterlaced.Location = new System.Drawing.Point(240, 248);
this.chkInterlaced.Name = "chkInterlaced";
this.chkInterlaced.Size = new System.Drawing.Size(88, 24);
this.chkInterlaced.TabIndex = 23;
this.chkInterlaced.Text = "Interlaced";
this.chkInterlaced.CheckedChanged += new System.EventHandler(this.chkInterlaced_CheckedChanged);
//
// chkScalar
//
this.chkScalar.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkScalar.ForeColor = System.Drawing.Color.Black;
this.chkScalar.Location = new System.Drawing.Point(24, 248);
this.chkScalar.Name = "chkScalar";
this.chkScalar.Size = new System.Drawing.Size(72, 24);
this.chkScalar.TabIndex = 22;
this.chkScalar.Text = "Scalar";
this.chkScalar.CheckedChanged += new System.EventHandler(this.chkScalar_CheckedChanged);
//
// chkLogScale
//
this.chkLogScale.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkLogScale.ForeColor = System.Drawing.Color.Black;
this.chkLogScale.Location = new System.Drawing.Point(108, 224);
this.chkLogScale.Name = "chkLogScale";
this.chkLogScale.Size = new System.Drawing.Size(120, 24);
this.chkLogScale.TabIndex = 20;
this.chkLogScale.Text = "Log Scale";
this.chkLogScale.CheckedChanged += new System.EventHandler(this.chkLogScale_CheckedChanged);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.chkMajorGLShow);
this.groupBox1.Controls.Add(this.tbMajorGLWidth);
this.groupBox1.Controls.Add(this.bMajorGLColor);
this.groupBox1.Controls.Add(this.cbMajorGLColor);
this.groupBox1.Controls.Add(this.cbMajorGLStyle);
this.groupBox1.Controls.Add(this.label7);
this.groupBox1.Controls.Add(this.label6);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Location = new System.Drawing.Point(16, 32);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(400, 48);
this.groupBox1.TabIndex = 5;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Major Grid Lines";
//
// chkMajorGLShow
//
this.chkMajorGLShow.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkMajorGLShow.ForeColor = System.Drawing.Color.Black;
this.chkMajorGLShow.Location = new System.Drawing.Point(8, 14);
this.chkMajorGLShow.Name = "chkMajorGLShow";
this.chkMajorGLShow.Size = new System.Drawing.Size(56, 24);
this.chkMajorGLShow.TabIndex = 0;
this.chkMajorGLShow.Text = "Show";
this.chkMajorGLShow.CheckedChanged += new System.EventHandler(this.chkMajorGLShow_CheckedChanged);
//
// tbMajorGLWidth
//
this.tbMajorGLWidth.AddX = 0;
this.tbMajorGLWidth.AddY = 0;
this.tbMajorGLWidth.AllowSpace = false;
this.tbMajorGLWidth.BorderColor = System.Drawing.Color.LightGray;
this.tbMajorGLWidth.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbMajorGLWidth.ChangeVisibility = false;
this.tbMajorGLWidth.ChildControl = null;
this.tbMajorGLWidth.ConvertEnterToTab = true;
this.tbMajorGLWidth.ConvertEnterToTabForDialogs = false;
this.tbMajorGLWidth.Decimals = 0;
this.tbMajorGLWidth.DisplayList = new object[0];
this.tbMajorGLWidth.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbMajorGLWidth.Location = new System.Drawing.Point(352, 16);
this.tbMajorGLWidth.Name = "tbMajorGLWidth";
this.tbMajorGLWidth.OnDropDownCloseFocus = true;
this.tbMajorGLWidth.SelectType = 0;
this.tbMajorGLWidth.Size = new System.Drawing.Size(40, 20);
this.tbMajorGLWidth.TabIndex = 7;
this.tbMajorGLWidth.UseValueForChildsVisibilty = false;
this.tbMajorGLWidth.Value = true;
this.tbMajorGLWidth.TextChanged += new System.EventHandler(this.tbMajorGLWidth_TextChanged);
//
// bMajorGLColor
//
this.bMajorGLColor.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bMajorGLColor.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bMajorGLColor.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bMajorGLColor.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bMajorGLColor.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bMajorGLColor.Font = new System.Drawing.Font("Arial", 9F);
this.bMajorGLColor.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bMajorGLColor.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMajorGLColor.Location = new System.Drawing.Point(288, 16);
this.bMajorGLColor.Name = "bMajorGLColor";
this.bMajorGLColor.OverriddenSize = null;
this.bMajorGLColor.Size = new System.Drawing.Size(24, 21);
this.bMajorGLColor.TabIndex = 5;
this.bMajorGLColor.Text = "...";
this.bMajorGLColor.UseVisualStyleBackColor = true;
this.bMajorGLColor.Click += new System.EventHandler(this.bMajorGLColor_Click);
//
// cbMajorGLColor
//
this.cbMajorGLColor.AutoAdjustItemHeight = false;
this.cbMajorGLColor.BorderColor = System.Drawing.Color.LightGray;
this.cbMajorGLColor.ConvertEnterToTabForDialogs = false;
this.cbMajorGLColor.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbMajorGLColor.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbMajorGLColor.Location = new System.Drawing.Point(208, 16);
this.cbMajorGLColor.Name = "cbMajorGLColor";
this.cbMajorGLColor.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbMajorGLColor.SeparatorMargin = 1;
this.cbMajorGLColor.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbMajorGLColor.SeparatorWidth = 1;
this.cbMajorGLColor.Size = new System.Drawing.Size(72, 21);
this.cbMajorGLColor.TabIndex = 4;
this.cbMajorGLColor.SelectedIndexChanged += new System.EventHandler(this.cbMajorGLColor_SelectedIndexChanged);
//
// cbMajorGLStyle
//
this.cbMajorGLStyle.AutoAdjustItemHeight = false;
this.cbMajorGLStyle.BorderColor = System.Drawing.Color.LightGray;
this.cbMajorGLStyle.ConvertEnterToTabForDialogs = false;
this.cbMajorGLStyle.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbMajorGLStyle.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbMajorGLStyle.Items.AddRange(new object[] {
"None",
"Dotted",
"Dashed",
"Solid",
"Double",
"Groove",
"Ridge",
"Inset",
"WindowInset",
"Outset"});
this.cbMajorGLStyle.Location = new System.Drawing.Point(96, 16);
this.cbMajorGLStyle.Name = "cbMajorGLStyle";
this.cbMajorGLStyle.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbMajorGLStyle.SeparatorMargin = 1;
this.cbMajorGLStyle.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbMajorGLStyle.SeparatorWidth = 1;
this.cbMajorGLStyle.Size = new System.Drawing.Size(72, 21);
this.cbMajorGLStyle.TabIndex = 2;
this.cbMajorGLStyle.SelectedIndexChanged += new System.EventHandler(this.cbMajorGLStyle_SelectedIndexChanged);
//
// label7
//
this.label7.Location = new System.Drawing.Point(176, 18);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(32, 16);
this.label7.TabIndex = 3;
this.label7.Text = "Color";
this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label6
//
this.label6.Location = new System.Drawing.Point(320, 18);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(36, 16);
this.label6.TabIndex = 6;
this.label6.Text = "Width";
this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label3
//
this.label3.Location = new System.Drawing.Point(64, 18);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(36, 16);
this.label3.TabIndex = 1;
this.label3.Text = "Style";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.chkMinorGLShow);
this.groupBox2.Controls.Add(this.tbMinorGLWidth);
this.groupBox2.Controls.Add(this.bMinorGLColor);
this.groupBox2.Controls.Add(this.cbMinorGLColor);
this.groupBox2.Controls.Add(this.cbMinorGLStyle);
this.groupBox2.Controls.Add(this.label4);
this.groupBox2.Controls.Add(this.label5);
this.groupBox2.Controls.Add(this.label8);
this.groupBox2.Location = new System.Drawing.Point(16, 88);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(400, 48);
this.groupBox2.TabIndex = 6;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Minor Grid Lines";
//
// chkMinorGLShow
//
this.chkMinorGLShow.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkMinorGLShow.ForeColor = System.Drawing.Color.Black;
this.chkMinorGLShow.Location = new System.Drawing.Point(8, 14);
this.chkMinorGLShow.Name = "chkMinorGLShow";
this.chkMinorGLShow.Size = new System.Drawing.Size(56, 24);
this.chkMinorGLShow.TabIndex = 0;
this.chkMinorGLShow.Text = "Show";
this.chkMinorGLShow.CheckedChanged += new System.EventHandler(this.chkMinorGLShow_CheckedChanged);
//
// tbMinorGLWidth
//
this.tbMinorGLWidth.AddX = 0;
this.tbMinorGLWidth.AddY = 0;
this.tbMinorGLWidth.AllowSpace = false;
this.tbMinorGLWidth.BorderColor = System.Drawing.Color.LightGray;
this.tbMinorGLWidth.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbMinorGLWidth.ChangeVisibility = false;
this.tbMinorGLWidth.ChildControl = null;
this.tbMinorGLWidth.ConvertEnterToTab = true;
this.tbMinorGLWidth.ConvertEnterToTabForDialogs = false;
this.tbMinorGLWidth.Decimals = 0;
this.tbMinorGLWidth.DisplayList = new object[0];
this.tbMinorGLWidth.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbMinorGLWidth.Location = new System.Drawing.Point(352, 16);
this.tbMinorGLWidth.Name = "tbMinorGLWidth";
this.tbMinorGLWidth.OnDropDownCloseFocus = true;
this.tbMinorGLWidth.SelectType = 0;
this.tbMinorGLWidth.Size = new System.Drawing.Size(40, 20);
this.tbMinorGLWidth.TabIndex = 7;
this.tbMinorGLWidth.UseValueForChildsVisibilty = false;
this.tbMinorGLWidth.Value = true;
this.tbMinorGLWidth.TextChanged += new System.EventHandler(this.tbMinorGLWidth_TextChanged);
//
// bMinorGLColor
//
this.bMinorGLColor.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bMinorGLColor.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bMinorGLColor.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bMinorGLColor.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bMinorGLColor.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bMinorGLColor.Font = new System.Drawing.Font("Arial", 9F);
this.bMinorGLColor.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bMinorGLColor.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMinorGLColor.Location = new System.Drawing.Point(288, 16);
this.bMinorGLColor.Name = "bMinorGLColor";
this.bMinorGLColor.OverriddenSize = null;
this.bMinorGLColor.Size = new System.Drawing.Size(24, 21);
this.bMinorGLColor.TabIndex = 5;
this.bMinorGLColor.Text = "...";
this.bMinorGLColor.UseVisualStyleBackColor = true;
this.bMinorGLColor.Click += new System.EventHandler(this.bMinorGLColor_Click);
//
// cbMinorGLColor
//
this.cbMinorGLColor.AutoAdjustItemHeight = false;
this.cbMinorGLColor.BorderColor = System.Drawing.Color.LightGray;
this.cbMinorGLColor.ConvertEnterToTabForDialogs = false;
this.cbMinorGLColor.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbMinorGLColor.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbMinorGLColor.Location = new System.Drawing.Point(208, 16);
this.cbMinorGLColor.Name = "cbMinorGLColor";
this.cbMinorGLColor.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbMinorGLColor.SeparatorMargin = 1;
this.cbMinorGLColor.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbMinorGLColor.SeparatorWidth = 1;
this.cbMinorGLColor.Size = new System.Drawing.Size(72, 21);
this.cbMinorGLColor.TabIndex = 4;
this.cbMinorGLColor.SelectedIndexChanged += new System.EventHandler(this.cbMinorGLColor_SelectedIndexChanged);
//
// cbMinorGLStyle
//
this.cbMinorGLStyle.AutoAdjustItemHeight = false;
this.cbMinorGLStyle.BorderColor = System.Drawing.Color.LightGray;
this.cbMinorGLStyle.ConvertEnterToTabForDialogs = false;
this.cbMinorGLStyle.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbMinorGLStyle.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbMinorGLStyle.Items.AddRange(new object[] {
"None",
"Dotted",
"Dashed",
"Solid",
"Double",
"Groove",
"Ridge",
"Inset",
"WindowInset",
"Outset"});
this.cbMinorGLStyle.Location = new System.Drawing.Point(96, 16);
this.cbMinorGLStyle.Name = "cbMinorGLStyle";
this.cbMinorGLStyle.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbMinorGLStyle.SeparatorMargin = 1;
this.cbMinorGLStyle.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbMinorGLStyle.SeparatorWidth = 1;
this.cbMinorGLStyle.Size = new System.Drawing.Size(72, 21);
this.cbMinorGLStyle.TabIndex = 2;
this.cbMinorGLStyle.SelectedIndexChanged += new System.EventHandler(this.cbMinorGLStyle_SelectedIndexChanged);
//
// label4
//
this.label4.Location = new System.Drawing.Point(176, 18);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(40, 16);
this.label4.TabIndex = 3;
this.label4.Text = "Color";
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label5
//
this.label5.Location = new System.Drawing.Point(320, 18);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(36, 16);
this.label5.TabIndex = 6;
this.label5.Text = "Width";
this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label8
//
this.label8.Location = new System.Drawing.Point(64, 18);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(40, 16);
this.label8.TabIndex = 1;
this.label8.Text = "Style";
this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label9
//
this.label9.Location = new System.Drawing.Point(16, 156);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(80, 16);
this.label9.TabIndex = 7;
this.label9.Text = "Major Interval";
//
// tbMajorInterval
//
this.tbMajorInterval.AddX = 0;
this.tbMajorInterval.AddY = 0;
this.tbMajorInterval.AllowSpace = false;
this.tbMajorInterval.BorderColor = System.Drawing.Color.LightGray;
this.tbMajorInterval.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbMajorInterval.ChangeVisibility = false;
this.tbMajorInterval.ChildControl = null;
this.tbMajorInterval.ConvertEnterToTab = true;
this.tbMajorInterval.ConvertEnterToTabForDialogs = false;
this.tbMajorInterval.Decimals = 0;
this.tbMajorInterval.DisplayList = new object[0];
this.tbMajorInterval.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbMajorInterval.Location = new System.Drawing.Point(104, 154);
this.tbMajorInterval.Name = "tbMajorInterval";
this.tbMajorInterval.OnDropDownCloseFocus = true;
this.tbMajorInterval.SelectType = 0;
this.tbMajorInterval.Size = new System.Drawing.Size(65, 20);
this.tbMajorInterval.TabIndex = 8;
this.tbMajorInterval.UseValueForChildsVisibilty = false;
this.tbMajorInterval.Value = true;
this.tbMajorInterval.TextChanged += new System.EventHandler(this.tbMajorInterval_TextChanged);
//
// tbMinorInterval
//
this.tbMinorInterval.AddX = 0;
this.tbMinorInterval.AddY = 0;
this.tbMinorInterval.AllowSpace = false;
this.tbMinorInterval.BorderColor = System.Drawing.Color.LightGray;
this.tbMinorInterval.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbMinorInterval.ChangeVisibility = false;
this.tbMinorInterval.ChildControl = null;
this.tbMinorInterval.ConvertEnterToTab = true;
this.tbMinorInterval.ConvertEnterToTabForDialogs = false;
this.tbMinorInterval.Decimals = 0;
this.tbMinorInterval.DisplayList = new object[0];
this.tbMinorInterval.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbMinorInterval.Location = new System.Drawing.Point(302, 154);
this.tbMinorInterval.Name = "tbMinorInterval";
this.tbMinorInterval.OnDropDownCloseFocus = true;
this.tbMinorInterval.SelectType = 0;
this.tbMinorInterval.Size = new System.Drawing.Size(65, 20);
this.tbMinorInterval.TabIndex = 11;
this.tbMinorInterval.UseValueForChildsVisibilty = false;
this.tbMinorInterval.Value = true;
this.tbMinorInterval.TextChanged += new System.EventHandler(this.tbMinorInterval_TextChanged);
//
// label10
//
this.label10.Location = new System.Drawing.Point(217, 156);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(80, 16);
this.label10.TabIndex = 10;
this.label10.Text = "Minor Interval";
//
// tbMax
//
this.tbMax.AddX = 0;
this.tbMax.AddY = 0;
this.tbMax.AllowSpace = false;
this.tbMax.BorderColor = System.Drawing.Color.LightGray;
this.tbMax.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbMax.ChangeVisibility = false;
this.tbMax.ChildControl = null;
this.tbMax.ConvertEnterToTab = true;
this.tbMax.ConvertEnterToTabForDialogs = false;
this.tbMax.Decimals = 0;
this.tbMax.DisplayList = new object[0];
this.tbMax.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbMax.Location = new System.Drawing.Point(302, 184);
this.tbMax.Name = "tbMax";
this.tbMax.OnDropDownCloseFocus = true;
this.tbMax.SelectType = 0;
this.tbMax.Size = new System.Drawing.Size(65, 20);
this.tbMax.TabIndex = 17;
this.tbMax.UseValueForChildsVisibilty = false;
this.tbMax.Value = true;
this.tbMax.TextChanged += new System.EventHandler(this.tbMax_TextChanged);
//
// label11
//
this.label11.Location = new System.Drawing.Point(216, 186);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(84, 16);
this.label11.TabIndex = 16;
this.label11.Text = "Maximum Value";
//
// tbMin
//
this.tbMin.AddX = 0;
this.tbMin.AddY = 0;
this.tbMin.AllowSpace = false;
this.tbMin.BorderColor = System.Drawing.Color.LightGray;
this.tbMin.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbMin.ChangeVisibility = false;
this.tbMin.ChildControl = null;
this.tbMin.ConvertEnterToTab = true;
this.tbMin.ConvertEnterToTabForDialogs = false;
this.tbMin.Decimals = 0;
this.tbMin.DisplayList = new object[0];
this.tbMin.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbMin.Location = new System.Drawing.Point(104, 184);
this.tbMin.Name = "tbMin";
this.tbMin.OnDropDownCloseFocus = true;
this.tbMin.SelectType = 0;
this.tbMin.Size = new System.Drawing.Size(65, 20);
this.tbMin.TabIndex = 14;
this.tbMin.UseValueForChildsVisibilty = false;
this.tbMin.Value = true;
this.tbMin.TextChanged += new System.EventHandler(this.tbMin_TextChanged);
//
// label12
//
this.label12.Location = new System.Drawing.Point(16, 186);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(88, 16);
this.label12.TabIndex = 13;
this.label12.Text = "Minimum Value";
//
// bMinorIntervalExpr
//
this.bMinorIntervalExpr.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bMinorIntervalExpr.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bMinorIntervalExpr.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bMinorIntervalExpr.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bMinorIntervalExpr.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bMinorIntervalExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bMinorIntervalExpr.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bMinorIntervalExpr.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMinorIntervalExpr.Location = new System.Drawing.Point(375, 154);
this.bMinorIntervalExpr.Name = "bMinorIntervalExpr";
this.bMinorIntervalExpr.OverriddenSize = null;
this.bMinorIntervalExpr.Size = new System.Drawing.Size(22, 21);
this.bMinorIntervalExpr.TabIndex = 12;
this.bMinorIntervalExpr.Tag = "minorinterval";
this.bMinorIntervalExpr.Text = "fx";
this.bMinorIntervalExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMinorIntervalExpr.UseVisualStyleBackColor = true;
this.bMinorIntervalExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bMajorIntervalExpr
//
this.bMajorIntervalExpr.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bMajorIntervalExpr.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bMajorIntervalExpr.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bMajorIntervalExpr.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bMajorIntervalExpr.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bMajorIntervalExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bMajorIntervalExpr.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bMajorIntervalExpr.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMajorIntervalExpr.Location = new System.Drawing.Point(177, 154);
this.bMajorIntervalExpr.Name = "bMajorIntervalExpr";
this.bMajorIntervalExpr.OverriddenSize = null;
this.bMajorIntervalExpr.Size = new System.Drawing.Size(22, 21);
this.bMajorIntervalExpr.TabIndex = 9;
this.bMajorIntervalExpr.Tag = "majorinterval";
this.bMajorIntervalExpr.Text = "fx";
this.bMajorIntervalExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMajorIntervalExpr.UseVisualStyleBackColor = true;
this.bMajorIntervalExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bMinExpr
//
this.bMinExpr.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bMinExpr.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bMinExpr.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bMinExpr.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bMinExpr.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bMinExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bMinExpr.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bMinExpr.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMinExpr.Location = new System.Drawing.Point(177, 184);
this.bMinExpr.Name = "bMinExpr";
this.bMinExpr.OverriddenSize = null;
this.bMinExpr.Size = new System.Drawing.Size(22, 21);
this.bMinExpr.TabIndex = 15;
this.bMinExpr.Tag = "min";
this.bMinExpr.Text = "fx";
this.bMinExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMinExpr.UseVisualStyleBackColor = true;
this.bMinExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bMaxExpr
//
this.bMaxExpr.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bMaxExpr.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bMaxExpr.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bMaxExpr.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bMaxExpr.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bMaxExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bMaxExpr.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bMaxExpr.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMaxExpr.Location = new System.Drawing.Point(376, 184);
this.bMaxExpr.Name = "bMaxExpr";
this.bMaxExpr.OverriddenSize = null;
this.bMaxExpr.Size = new System.Drawing.Size(22, 21);
this.bMaxExpr.TabIndex = 18;
this.bMaxExpr.Tag = "max";
this.bMaxExpr.Text = "fx";
this.bMaxExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMaxExpr.UseVisualStyleBackColor = true;
this.bMaxExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// chkCanOmit
//
this.chkCanOmit.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkCanOmit.ForeColor = System.Drawing.Color.Black;
this.chkCanOmit.Location = new System.Drawing.Point(334, 224);
this.chkCanOmit.Name = "chkCanOmit";
this.chkCanOmit.Size = new System.Drawing.Size(93, 48);
this.chkCanOmit.TabIndex = 24;
this.chkCanOmit.Text = "Can Omit Values on Truncation";
this.chkCanOmit.CheckedChanged += new System.EventHandler(this.chkCanOmit_CheckedChanged);
//
// chkMonth
//
this.chkMonth.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkMonth.ForeColor = System.Drawing.Color.Black;
this.chkMonth.Location = new System.Drawing.Point(24, 272);
this.chkMonth.Name = "chkMonth";
this.chkMonth.Size = new System.Drawing.Size(145, 24);
this.chkMonth.TabIndex = 25;
this.chkMonth.Text = "Month Category Scale";
this.chkMonth.CheckedChanged += new System.EventHandler(this.chkMonth_CheckedChanged);
//
// ChartAxisCtl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.Controls.Add(this.chkMonth);
this.Controls.Add(this.chkCanOmit);
this.Controls.Add(this.bMaxExpr);
this.Controls.Add(this.bMinExpr);
this.Controls.Add(this.bMajorIntervalExpr);
this.Controls.Add(this.bMinorIntervalExpr);
this.Controls.Add(this.tbMax);
this.Controls.Add(this.label11);
this.Controls.Add(this.tbMin);
this.Controls.Add(this.label12);
this.Controls.Add(this.tbMinorInterval);
this.Controls.Add(this.label10);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.chkLogScale);
this.Controls.Add(this.chkScalar);
this.Controls.Add(this.chkInterlaced);
this.Controls.Add(this.chkReverse);
this.Controls.Add(this.chkMargin);
this.Controls.Add(this.chkVisible);
this.Controls.Add(this.cbMinorTickMarks);
this.Controls.Add(this.cbMajorTickMarks);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.tbMajorInterval);
this.Controls.Add(this.label9);
this.Name = "ChartAxisCtl";
this.Size = new System.Drawing.Size(440, 303);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public bool IsValid()
{
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
fMonth = fVisible = fMajorTickMarks = fMargin=fReverse=fInterlaced=
fMajorGLWidth=fMajorGLColor=fMajorGLStyle=
fMinorGLWidth=fMinorGLColor=fMinorGLStyle=
fMajorInterval= fMinorInterval=fMax=fMin=
fMinorTickMarks=fScalar=fLogScale=fMajorGLShow=fMinorGLShow=fCanOmit=false;
}
public void ApplyChanges(XmlNode node)
{
if (fMonth)
{
_Draw.SetElement(node, "fyi:Month", this.chkMonth.Checked? "true" : "false");
}
if (fVisible)
{
_Draw.SetElement(node, "Visible", this.chkVisible.Checked? "true": "false");
}
if (fMajorTickMarks)
{
_Draw.SetElement(node, "MajorTickMarks", this.cbMajorTickMarks.Text);
}
if (fMargin)
{
_Draw.SetElement(node, "Margin", this.chkMargin.Checked? "true": "false");
}
if (fReverse)
{
_Draw.SetElement(node, "Reverse", this.chkReverse.Checked? "true": "false");
}
if (fInterlaced)
{
_Draw.SetElement(node, "Interlaced", this.chkInterlaced.Checked? "true": "false");
}
if (fMajorGLShow || fMajorGLWidth || fMajorGLColor || fMajorGLStyle)
{
ApplyGridLines(node, "MajorGridLines", chkMajorGLShow, cbMajorGLColor, cbMajorGLStyle, tbMajorGLWidth);
}
if (fMinorGLShow || fMinorGLWidth || fMinorGLColor || fMinorGLStyle)
{
ApplyGridLines(node, "MinorGridLines", chkMinorGLShow, cbMinorGLColor, cbMinorGLStyle, tbMinorGLWidth);
}
if (fMajorInterval)
{
_Draw.SetElement(node, "MajorInterval", this.tbMajorInterval.Text);
}
if (fMinorInterval)
{
_Draw.SetElement(node, "MinorInterval", this.tbMinorInterval.Text);
}
if (fMax)
{
_Draw.SetElement(node, "Max", this.tbMax.Text);
}
if (fMin)
{
_Draw.SetElement(node, "Min", this.tbMin.Text);
}
if (fMinorTickMarks)
{
_Draw.SetElement(node, "MinorTickMarks", this.cbMinorTickMarks.Text);
}
if (fScalar)
{
_Draw.SetElement(node, "Scalar", this.chkScalar.Checked? "true": "false");
}
if (fLogScale)
{
_Draw.SetElement(node, "LogScale", this.chkLogScale.Checked? "true": "false");
}
if (fCanOmit)
{
_Draw.SetElement(node, "fyi:CanOmit", this.chkCanOmit.Checked ? "true" : "false");
}
}
private void ApplyGridLines(XmlNode node, string type, CheckBox show, ComboBox color, ComboBox style, TextBox width)
{
XmlNode m = _Draw.GetNamedChildNode(node, type);
if (m == null)
{
m = _Draw.CreateElement(node, type, null);
}
_Draw.SetElement(m, "ShowGridLines", show.Checked? "true": "false");
XmlNode st = _Draw.GetNamedChildNode(m, "Style");
if (st == null)
st = _Draw.CreateElement(m, "Style", null);
XmlNode work = _Draw.GetNamedChildNode(st, "BorderColor");
if (work == null)
work = _Draw.CreateElement(st, "BorderColor", null);
_Draw.SetElement(work, "Default", color.Text);
work = _Draw.GetNamedChildNode(st, "BorderStyle");
if (work == null)
work = _Draw.CreateElement(st, "BorderStyle", null);
_Draw.SetElement(work, "Default", style.Text);
work = _Draw.GetNamedChildNode(st, "BorderWidth");
if (work == null)
work = _Draw.CreateElement(st, "BorderWidth", null);
_Draw.SetElement(work, "Default", width.Text);
}
private void cbMajorTickMarks_SelectedIndexChanged(object sender, System.EventArgs e)
{
fMajorTickMarks = true;
}
private void cbMinorTickMarks_SelectedIndexChanged(object sender, System.EventArgs e)
{
fMinorTickMarks = true;
}
private void cbMajorGLStyle_SelectedIndexChanged(object sender, System.EventArgs e)
{
fMajorGLStyle = true;
}
private void cbMajorGLColor_SelectedIndexChanged(object sender, System.EventArgs e)
{
fMajorGLColor = true;
}
private void tbMajorGLWidth_TextChanged(object sender, System.EventArgs e)
{
fMajorGLWidth = true;
}
private void cbMinorGLStyle_SelectedIndexChanged(object sender, System.EventArgs e)
{
fMinorGLStyle = true;
}
private void cbMinorGLColor_SelectedIndexChanged(object sender, System.EventArgs e)
{
fMinorGLColor = true;
}
private void tbMinorGLWidth_TextChanged(object sender, System.EventArgs e)
{
fMinorGLWidth = true;
}
private void tbMajorInterval_TextChanged(object sender, System.EventArgs e)
{
fMajorInterval = true;
}
private void tbMinorInterval_TextChanged(object sender, System.EventArgs e)
{
fMinorInterval = true;
}
private void tbMin_TextChanged(object sender, System.EventArgs e)
{
fMin = true;
}
private void tbMax_TextChanged(object sender, System.EventArgs e)
{
fMax = true;
}
private void chkMonth_CheckedChanged(object sender, System.EventArgs e)
{
fMonth = true;
}
private void chkVisible_CheckedChanged(object sender, System.EventArgs e)
{
fVisible = true;
}
private void chkLogScale_CheckedChanged(object sender, System.EventArgs e)
{
fLogScale = true;
}
private void chkCanOmit_CheckedChanged(object sender, System.EventArgs e)
{
fCanOmit = true;
}
private void chkMargin_CheckedChanged(object sender, System.EventArgs e)
{
fMargin = true;
}
private void chkScalar_CheckedChanged(object sender, System.EventArgs e)
{
fScalar = true;
}
private void chkReverse_CheckedChanged(object sender, System.EventArgs e)
{
fReverse = true;
}
private void chkInterlaced_CheckedChanged(object sender, System.EventArgs e)
{
fInterlaced = true;
}
private void chkMajorGLShow_CheckedChanged(object sender, System.EventArgs e)
{
fMajorGLShow = true;
}
private void chkMinorGLShow_CheckedChanged(object sender, System.EventArgs e)
{
fMinorGLShow = true;
}
private void bMajorGLColor_Click(object sender, System.EventArgs e)
{
SetColor(this.cbMajorGLColor);
}
private void bMinorGLColor_Click(object sender, System.EventArgs e)
{
SetColor(this.cbMinorGLColor);
}
private void SetColor(ComboBox cbColor)
{
ColorDialog cd = new ColorDialog();
cd.AnyColor = true;
cd.FullOpen = true;
cd.CustomColors = RdlDesigner.GetCustomColors();
cd.Color = DesignerUtility.ColorFromHtml(cbColor.Text, System.Drawing.Color.Empty);
try
{
if (cd.ShowDialog() != DialogResult.OK)
return;
RdlDesigner.SetCustomColors(cd.CustomColors);
cbColor.Text = ColorTranslator.ToHtml(cd.Color);
}
finally
{
cd.Dispose();
}
return;
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
bool bColor=false;
switch (b.Tag as string)
{
case "min":
c = this.tbMin;
break;
case "max":
c = this.tbMax;
break;
case "majorinterval":
c = this.tbMajorInterval;
break;
case "minorinterval":
c = this.tbMinorInterval;
break;
}
if (c == null)
return;
XmlNode sNode = _ReportItems[0];
DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode, bColor);
try
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
c.Text = ee.Expression;
}
finally
{
ee.Dispose();
}
return;
}
}
}
| |
// 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;
using System.Runtime.CompilerServices;
using static System.TestHelpers;
namespace System.SpanTests
{
public static partial class SpanTests
{
[Fact]
public static void ClearEmpty()
{
var span = Span<byte>.Empty;
span.Clear();
}
[Fact]
public static void ClearEmptyWithReference()
{
var span = Span<string>.Empty;
span.Clear();
}
[Fact]
public static void ClearByteLonger()
{
const byte initial = 5;
var actual = new byte[2048];
for (int i = 0; i < actual.Length; i++)
{
actual[i] = initial;
}
var expected = new byte[actual.Length];
var span = new Span<byte>(actual);
span.Clear();
Assert.Equal<byte>(expected, actual);
}
[Fact]
public static void ClearByteUnaligned()
{
const byte initial = 5;
const int length = 32;
var actualFull = new byte[length];
for (int i = 0; i < length; i++)
{
actualFull[i] = initial;
}
var expectedFull = new byte[length];
var start = 1;
var expectedSpan = new Span<byte>(expectedFull, start, length - start - 1);
var actualSpan = new Span<byte>(actualFull, start, length - start - 1);
actualSpan.Clear();
byte[] actual = actualSpan.ToArray();
byte[] expected = expectedSpan.ToArray();
Assert.Equal<byte>(expected, actual);
Assert.Equal(initial, actualFull[0]);
Assert.Equal(initial, actualFull[length - 1]);
}
[Fact]
public unsafe static void ClearByteUnalignedFixed()
{
const byte initial = 5;
const int length = 32;
var actualFull = new byte[length];
for (int i = 0; i < length; i++)
{
actualFull[i] = initial;
}
var expectedFull = new byte[length];
var start = 1;
var expectedSpan = new Span<byte>(expectedFull, start, length - start - 1);
fixed (byte* p = actualFull)
{
var actualSpan = new Span<byte>(p + start, length - start - 1);
actualSpan.Clear();
byte[] actual = actualSpan.ToArray();
byte[] expected = expectedSpan.ToArray();
Assert.Equal<byte>(expected, actual);
Assert.Equal(initial, actualFull[0]);
Assert.Equal(initial, actualFull[length - 1]);
}
}
[Fact]
public static void ClearIntPtrOffset()
{
IntPtr initial = IntPtr.Zero + 5;
const int length = 32;
var actualFull = new IntPtr[length];
for (int i = 0; i < length; i++)
{
actualFull[i] = initial;
}
var expectedFull = new IntPtr[length];
var start = 2;
var expectedSpan = new Span<IntPtr>(expectedFull, start, length - start - 1);
var actualSpan = new Span<IntPtr>(actualFull, start, length - start - 1);
actualSpan.Clear();
IntPtr[] actual = actualSpan.ToArray();
IntPtr[] expected = expectedSpan.ToArray();
Assert.Equal<IntPtr>(expected, actual);
Assert.Equal(initial, actualFull[0]);
Assert.Equal(initial, actualFull[length - 1]);
}
[Fact]
public static void ClearIntPtrLonger()
{
IntPtr initial = IntPtr.Zero + 5;
var actual = new IntPtr[2048];
for (int i = 0; i < actual.Length; i++)
{
actual[i] = initial;
}
var expected = new IntPtr[actual.Length];
var span = new Span<IntPtr>(actual);
span.Clear();
Assert.Equal<IntPtr>(expected, actual);
}
[Fact]
public static void ClearValueTypeWithoutReferences()
{
int[] actual = { 1, 2, 3 };
int[] expected = { 0, 0, 0 };
var span = new Span<int>(actual);
span.Clear();
Assert.Equal<int>(expected, actual);
}
[Fact]
public static void ClearValueTypeWithoutReferencesLonger()
{
int[] actual = new int[2048];
for (int i = 0; i < actual.Length; i++)
{
actual[i] = i + 1;
}
int[] expected = new int[actual.Length];
var span = new Span<int>(actual);
span.Clear();
Assert.Equal<int>(expected, actual);
}
[Fact]
public static void ClearValueTypeWithoutReferencesPointerSize()
{
long[] actual = new long[15];
for (int i = 0; i < actual.Length; i++)
{
actual[i] = i + 1;
}
long[] expected = new long[actual.Length];
var span = new Span<long>(actual);
span.Clear();
Assert.Equal<long>(expected, actual);
}
[Fact]
public static void ClearReferenceType()
{
string[] actual = { "a", "b", "c" };
string[] expected = { null, null, null };
var span = new Span<string>(actual);
span.Clear();
Assert.Equal<string>(expected, actual);
}
[Fact]
public static void ClearReferenceTypeLonger()
{
string[] actual = new string[2048];
for (int i = 0; i < actual.Length; i++)
{
actual[i] = (i + 1).ToString();
}
string[] expected = new string[actual.Length];
var span = new Span<string>(actual);
span.Clear();
Assert.Equal<string>(expected, actual);
}
[Fact]
public static void ClearEnumType()
{
TestEnum[] actual = { TestEnum.e0, TestEnum.e1, TestEnum.e2 };
TestEnum[] expected = { default, default, default };
var span = new Span<TestEnum>(actual);
span.Clear();
Assert.Equal<TestEnum>(expected, actual);
}
[Fact]
public static void ClearValueTypeWithReferences()
{
TestValueTypeWithReference[] actual = {
new TestValueTypeWithReference() { I = 1, S = "a" },
new TestValueTypeWithReference() { I = 2, S = "b" },
new TestValueTypeWithReference() { I = 3, S = "c" } };
TestValueTypeWithReference[] expected = {
default,
default,
default };
var span = new Span<TestValueTypeWithReference>(actual);
span.Clear();
Assert.Equal<TestValueTypeWithReference>(expected, actual);
}
// NOTE: ClearLongerThanUintMaxValueBytes test is constrained to run on Windows and MacOSX because it causes
// problems on Linux due to the way deferred memory allocation works. On Linux, the allocation can
// succeed even if there is not enough memory but then the test may get killed by the OOM killer at the
// time the memory is accessed which triggers the full memory allocation.
[Fact]
[OuterLoop]
[PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)]
unsafe static void ClearLongerThanUintMaxValueBytes()
{
if (sizeof(IntPtr) == sizeof(long))
{
// Arrange
IntPtr bytes = (IntPtr)(((long)int.MaxValue) * sizeof(int));
int length = (int)(((long)bytes) / sizeof(int));
if (!AllocationHelper.TryAllocNative(bytes, out IntPtr memory))
{
Console.WriteLine($"Span.Clear test {nameof(ClearLongerThanUintMaxValueBytes)} skipped (could not alloc memory).");
return;
}
try
{
ref int data = ref Unsafe.AsRef<int>(memory.ToPointer());
int initial = 5;
for (int i = 0; i < length; i++)
{
Unsafe.Add(ref data, i) = initial;
}
Span<int> span = new Span<int>(memory.ToPointer(), length);
// Act
span.Clear();
// Assert using custom code for perf and to avoid allocating extra memory
for (int i = 0; i < length; i++)
{
var actual = Unsafe.Add(ref data, i);
if (actual != 0)
{
Assert.Equal(0, actual);
}
}
}
finally
{
AllocationHelper.ReleaseNative(ref memory);
}
}
}
}
}
| |
/*
* 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 copyrightD
* 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.Linq;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps=OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Region.CoreModules.Framework
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "CapabilitiesModule")]
public class CapabilitiesModule : INonSharedRegionModule, ICapabilitiesModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_showCapsCommandFormat = " {0,-38} {1,-60}\n";
protected Scene m_scene;
/// <summary>
/// Each agent has its own capabilities handler.
/// </summary>
protected Dictionary<uint, Caps> m_capsObjects = new Dictionary<uint, Caps>();
protected Dictionary<UUID, string> m_capsPaths = new Dictionary<UUID, string>();
protected Dictionary<UUID, Dictionary<ulong, string>> m_childrenSeeds
= new Dictionary<UUID, Dictionary<ulong, string>>();
public void Initialise(IConfigSource source)
{
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<ICapabilitiesModule>(this);
MainConsole.Instance.Commands.AddCommand(
"Comms", false, "show caps list",
"show caps list",
"Shows list of registered capabilities for users.", HandleShowCapsListCommand);
MainConsole.Instance.Commands.AddCommand(
"Comms", false, "show caps stats by user",
"show caps stats by user [<first-name> <last-name>]",
"Shows statistics on capabilities use by user.",
"If a user name is given, then prints a detailed breakdown of caps use ordered by number of requests received.",
HandleShowCapsStatsByUserCommand);
MainConsole.Instance.Commands.AddCommand(
"Comms", false, "show caps stats by cap",
"show caps stats by cap [<cap-name>]",
"Shows statistics on capabilities use by capability.",
"If a capability name is given, then prints a detailed breakdown of use by each user.",
HandleShowCapsStatsByCapCommand);
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
m_scene.UnregisterModuleInterface<ICapabilitiesModule>(this);
}
public void PostInitialise()
{
}
public void Close() {}
public string Name
{
get { return "Capabilities Module"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void CreateCaps(UUID agentId, uint circuitCode)
{
int ts = Util.EnvironmentTickCount();
/* this as no business here...
* must be done elsewhere ( and is )
int flags = m_scene.GetUserFlags(agentId);
m_log.ErrorFormat("[CreateCaps]: banCheck {0} ", Util.EnvironmentTickCountSubtract(ts));
if (m_scene.RegionInfo.EstateSettings.IsBanned(agentId, flags))
return;
*/
Caps caps;
String capsObjectPath = GetCapsPath(agentId);
lock (m_capsObjects)
{
if (m_capsObjects.ContainsKey(circuitCode))
{
Caps oldCaps = m_capsObjects[circuitCode];
if (capsObjectPath == oldCaps.CapsObjectPath)
{
m_log.WarnFormat(
"[CAPS]: Reusing caps for agent {0} in region {1}. Old caps path {2}, new caps path {3}. ",
agentId, m_scene.RegionInfo.RegionName, oldCaps.CapsObjectPath, capsObjectPath);
return;
}
else
{
// not reusing add extra melanie cleanup
// Remove tge handlers. They may conflict with the
// new object created below
oldCaps.DeregisterHandlers();
// Better safe ... should not be needed but also
// no big deal
m_capsObjects.Remove(circuitCode);
}
}
// m_log.DebugFormat(
// "[CAPS]: Adding capabilities for agent {0} in {1} with path {2}",
// agentId, m_scene.RegionInfo.RegionName, capsObjectPath);
caps = new Caps(MainServer.Instance, m_scene.RegionInfo.ExternalHostName,
(MainServer.Instance == null) ? 0: MainServer.Instance.Port,
capsObjectPath, agentId, m_scene.RegionInfo.RegionName);
m_log.DebugFormat("[CreateCaps]: new caps agent {0}, circuit {1}, path {2}, time {3} ",agentId,
circuitCode,caps.CapsObjectPath, Util.EnvironmentTickCountSubtract(ts));
m_capsObjects[circuitCode] = caps;
}
m_scene.EventManager.TriggerOnRegisterCaps(agentId, caps);
// m_log.ErrorFormat("[CreateCaps]: end {0} ", Util.EnvironmentTickCountSubtract(ts));
}
public void RemoveCaps(UUID agentId, uint circuitCode)
{
m_log.DebugFormat("[CAPS]: Remove caps for agent {0} in region {1}", agentId, m_scene.RegionInfo.RegionName);
lock (m_childrenSeeds)
{
if (m_childrenSeeds.ContainsKey(agentId))
{
m_childrenSeeds.Remove(agentId);
}
}
lock (m_capsObjects)
{
if (m_capsObjects.ContainsKey(circuitCode))
{
m_capsObjects[circuitCode].DeregisterHandlers();
m_scene.EventManager.TriggerOnDeregisterCaps(agentId, m_capsObjects[circuitCode]);
m_capsObjects.Remove(circuitCode);
}
else
{
foreach (KeyValuePair<uint, Caps> kvp in m_capsObjects)
{
if (kvp.Value.AgentID == agentId)
{
kvp.Value.DeregisterHandlers();
m_scene.EventManager.TriggerOnDeregisterCaps(agentId, kvp.Value);
m_capsObjects.Remove(kvp.Key);
return;
}
}
m_log.WarnFormat(
"[CAPS]: Received request to remove CAPS handler for root agent {0} in {1}, but no such CAPS handler found!",
agentId, m_scene.RegionInfo.RegionName);
}
}
}
public Caps GetCapsForUser(uint circuitCode)
{
lock (m_capsObjects)
{
if (m_capsObjects.ContainsKey(circuitCode))
{
return m_capsObjects[circuitCode];
}
}
return null;
}
public void ActivateCaps(uint circuitCode)
{
lock (m_capsObjects)
{
if (m_capsObjects.ContainsKey(circuitCode))
{
m_capsObjects[circuitCode].Activate();
}
}
}
public void SetAgentCapsSeeds(AgentCircuitData agent)
{
lock (m_capsPaths)
m_capsPaths[agent.AgentID] = agent.CapsPath;
lock (m_childrenSeeds)
m_childrenSeeds[agent.AgentID]
= ((agent.ChildrenCapSeeds == null) ? new Dictionary<ulong, string>() : agent.ChildrenCapSeeds);
}
public string GetCapsPath(UUID agentId)
{
lock (m_capsPaths)
{
if (m_capsPaths.ContainsKey(agentId))
{
return m_capsPaths[agentId];
}
}
return null;
}
public Dictionary<ulong, string> GetChildrenSeeds(UUID agentID)
{
Dictionary<ulong, string> seeds = null;
lock (m_childrenSeeds)
if (m_childrenSeeds.TryGetValue(agentID, out seeds))
return seeds;
return new Dictionary<ulong, string>();
}
public void DropChildSeed(UUID agentID, ulong handle)
{
Dictionary<ulong, string> seeds;
lock (m_childrenSeeds)
{
if (m_childrenSeeds.TryGetValue(agentID, out seeds))
{
seeds.Remove(handle);
}
}
}
public string GetChildSeed(UUID agentID, ulong handle)
{
Dictionary<ulong, string> seeds;
string returnval;
lock (m_childrenSeeds)
{
if (m_childrenSeeds.TryGetValue(agentID, out seeds))
{
if (seeds.TryGetValue(handle, out returnval))
return returnval;
}
}
return null;
}
public void SetChildrenSeed(UUID agentID, Dictionary<ulong, string> seeds)
{
//m_log.DebugFormat(" !!! Setting child seeds in {0} to {1}", m_scene.RegionInfo.RegionName, seeds.Count);
lock (m_childrenSeeds)
m_childrenSeeds[agentID] = seeds;
}
public void DumpChildrenSeeds(UUID agentID)
{
m_log.Info("================ ChildrenSeed "+m_scene.RegionInfo.RegionName+" ================");
lock (m_childrenSeeds)
{
foreach (KeyValuePair<ulong, string> kvp in m_childrenSeeds[agentID])
{
uint x, y;
Util.RegionHandleToRegionLoc(kvp.Key, out x, out y);
m_log.Info(" >> "+x+", "+y+": "+kvp.Value);
}
}
}
private void HandleShowCapsListCommand(string module, string[] cmdParams)
{
if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_scene)
return;
StringBuilder capsReport = new StringBuilder();
capsReport.AppendFormat("Region {0}:\n", m_scene.RegionInfo.RegionName);
lock (m_capsObjects)
{
foreach (KeyValuePair<uint, Caps> kvp in m_capsObjects)
{
capsReport.AppendFormat("** Circuit {0}:\n", kvp.Key);
Caps caps = kvp.Value;
for (IDictionaryEnumerator kvp2 = caps.CapsHandlers.GetCapsDetails(false, null).GetEnumerator(); kvp2.MoveNext(); )
{
Uri uri = new Uri(kvp2.Value.ToString());
capsReport.AppendFormat(m_showCapsCommandFormat, kvp2.Key, uri.PathAndQuery);
}
foreach (KeyValuePair<string, PollServiceEventArgs> kvp2 in caps.GetPollHandlers())
capsReport.AppendFormat(m_showCapsCommandFormat, kvp2.Key, kvp2.Value.Url);
foreach (KeyValuePair<string, string> kvp3 in caps.ExternalCapsHandlers)
capsReport.AppendFormat(m_showCapsCommandFormat, kvp3.Key, kvp3.Value);
}
}
MainConsole.Instance.Output(capsReport.ToString());
}
private void HandleShowCapsStatsByCapCommand(string module, string[] cmdParams)
{
if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_scene)
return;
if (cmdParams.Length != 5 && cmdParams.Length != 6)
{
MainConsole.Instance.Output("Usage: show caps stats by cap [<cap-name>]");
return;
}
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Region {0}:\n", m_scene.Name);
if (cmdParams.Length == 5)
{
BuildSummaryStatsByCapReport(sb);
}
else if (cmdParams.Length == 6)
{
BuildDetailedStatsByCapReport(sb, cmdParams[5]);
}
MainConsole.Instance.Output(sb.ToString());
}
private void BuildDetailedStatsByCapReport(StringBuilder sb, string capName)
{
/*
sb.AppendFormat("Capability name {0}\n", capName);
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("User Name", 34);
cdt.AddColumn("Req Received", 12);
cdt.AddColumn("Req Handled", 12);
cdt.Indent = 2;
Dictionary<string, int> receivedStats = new Dictionary<string, int>();
Dictionary<string, int> handledStats = new Dictionary<string, int>();
m_scene.ForEachScenePresence(
sp =>
{
Caps caps = m_scene.CapsModule.GetCapsForUser(sp.UUID);
if (caps == null)
return;
Dictionary<string, IRequestHandler> capsHandlers = caps.CapsHandlers.GetCapsHandlers();
IRequestHandler reqHandler;
if (capsHandlers.TryGetValue(capName, out reqHandler))
{
receivedStats[sp.Name] = reqHandler.RequestsReceived;
handledStats[sp.Name] = reqHandler.RequestsHandled;
}
else
{
PollServiceEventArgs pollHandler = null;
if (caps.TryGetPollHandler(capName, out pollHandler))
{
receivedStats[sp.Name] = pollHandler.RequestsReceived;
handledStats[sp.Name] = pollHandler.RequestsHandled;
}
}
}
);
foreach (KeyValuePair<string, int> kvp in receivedStats.OrderByDescending(kp => kp.Value))
{
cdt.AddRow(kvp.Key, kvp.Value, handledStats[kvp.Key]);
}
sb.Append(cdt.ToString());
*/
}
private void BuildSummaryStatsByCapReport(StringBuilder sb)
{
/*
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("Name", 34);
cdt.AddColumn("Req Received", 12);
cdt.AddColumn("Req Handled", 12);
cdt.Indent = 2;
Dictionary<string, int> receivedStats = new Dictionary<string, int>();
Dictionary<string, int> handledStats = new Dictionary<string, int>();
m_scene.ForEachScenePresence(
sp =>
{
Caps caps = m_scene.CapsModule.GetCapsForUser(sp.UUID);
if (caps == null)
return;
foreach (IRequestHandler reqHandler in caps.CapsHandlers.GetCapsHandlers().Values)
{
string reqName = reqHandler.Name ?? "";
if (!receivedStats.ContainsKey(reqName))
{
receivedStats[reqName] = reqHandler.RequestsReceived;
handledStats[reqName] = reqHandler.RequestsHandled;
}
else
{
receivedStats[reqName] += reqHandler.RequestsReceived;
handledStats[reqName] += reqHandler.RequestsHandled;
}
}
foreach (KeyValuePair<string, PollServiceEventArgs> kvp in caps.GetPollHandlers())
{
string name = kvp.Key;
PollServiceEventArgs pollHandler = kvp.Value;
if (!receivedStats.ContainsKey(name))
{
receivedStats[name] = pollHandler.RequestsReceived;
handledStats[name] = pollHandler.RequestsHandled;
}
else
{
receivedStats[name] += pollHandler.RequestsReceived;
handledStats[name] += pollHandler.RequestsHandled;
}
}
}
);
foreach (KeyValuePair<string, int> kvp in receivedStats.OrderByDescending(kp => kp.Value))
cdt.AddRow(kvp.Key, kvp.Value, handledStats[kvp.Key]);
sb.Append(cdt.ToString());
*/
}
private void HandleShowCapsStatsByUserCommand(string module, string[] cmdParams)
{
/*
if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_scene)
return;
if (cmdParams.Length != 5 && cmdParams.Length != 7)
{
MainConsole.Instance.Output("Usage: show caps stats by user [<first-name> <last-name>]");
return;
}
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Region {0}:\n", m_scene.Name);
if (cmdParams.Length == 5)
{
BuildSummaryStatsByUserReport(sb);
}
else if (cmdParams.Length == 7)
{
string firstName = cmdParams[5];
string lastName = cmdParams[6];
ScenePresence sp = m_scene.GetScenePresence(firstName, lastName);
if (sp == null)
return;
BuildDetailedStatsByUserReport(sb, sp);
}
MainConsole.Instance.Output(sb.ToString());
*/
}
private void BuildDetailedStatsByUserReport(StringBuilder sb, ScenePresence sp)
{
/*
sb.AppendFormat("Avatar name {0}, type {1}\n", sp.Name, sp.IsChildAgent ? "child" : "root");
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("Cap Name", 34);
cdt.AddColumn("Req Received", 12);
cdt.AddColumn("Req Handled", 12);
cdt.Indent = 2;
Caps caps = m_scene.CapsModule.GetCapsForUser(sp.UUID);
if (caps == null)
return;
List<CapTableRow> capRows = new List<CapTableRow>();
foreach (IRequestHandler reqHandler in caps.CapsHandlers.GetCapsHandlers().Values)
capRows.Add(new CapTableRow(reqHandler.Name, reqHandler.RequestsReceived, reqHandler.RequestsHandled));
foreach (KeyValuePair<string, PollServiceEventArgs> kvp in caps.GetPollHandlers())
capRows.Add(new CapTableRow(kvp.Key, kvp.Value.RequestsReceived, kvp.Value.RequestsHandled));
foreach (CapTableRow ctr in capRows.OrderByDescending(ctr => ctr.RequestsReceived))
cdt.AddRow(ctr.Name, ctr.RequestsReceived, ctr.RequestsHandled);
sb.Append(cdt.ToString());
*/
}
private void BuildSummaryStatsByUserReport(StringBuilder sb)
{
/*
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("Name", 32);
cdt.AddColumn("Type", 5);
cdt.AddColumn("Req Received", 12);
cdt.AddColumn("Req Handled", 12);
cdt.Indent = 2;
m_scene.ForEachScenePresence(
sp =>
{
Caps caps = m_scene.CapsModule.GetCapsForUser(sp.UUID);
if (caps == null)
return;
Dictionary<string, IRequestHandler> capsHandlers = caps.CapsHandlers.GetCapsHandlers();
int totalRequestsReceived = 0;
int totalRequestsHandled = 0;
foreach (IRequestHandler reqHandler in capsHandlers.Values)
{
totalRequestsReceived += reqHandler.RequestsReceived;
totalRequestsHandled += reqHandler.RequestsHandled;
}
Dictionary<string, PollServiceEventArgs> capsPollHandlers = caps.GetPollHandlers();
foreach (PollServiceEventArgs handler in capsPollHandlers.Values)
{
totalRequestsReceived += handler.RequestsReceived;
totalRequestsHandled += handler.RequestsHandled;
}
cdt.AddRow(sp.Name, sp.IsChildAgent ? "child" : "root", totalRequestsReceived, totalRequestsHandled);
}
);
sb.Append(cdt.ToString());
*/
}
private class CapTableRow
{
public string Name { get; set; }
public int RequestsReceived { get; set; }
public int RequestsHandled { get; set; }
public CapTableRow(string name, int requestsReceived, int requestsHandled)
{
Name = name;
RequestsReceived = requestsReceived;
RequestsHandled = requestsHandled;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;
using System.Security.Permissions;
using System.Threading;
using System.Reflection;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using log4net;
using OpenSim.Framework;
using Aurora.ScriptEngine.AuroraDotNetEngine;
using Aurora.ScriptEngine.AuroraDotNetEngine.APIs.Interfaces;
using Aurora.ScriptEngine.AuroraDotNetEngine.CompilerTools;
namespace Aurora.ScriptEngine.AuroraDotNetEngine.Runtime
{
[Serializable]
public partial class ScriptBaseClass : MarshalByRefObject, IScript, IDisposable
{
private ScriptSponsor m_sponser;
private const int m_TimeToSleepInLoops = 3;
public ISponsor Sponsor
{
get
{
return m_sponser;
}
}
public IScene Scene = null;
public ISceneChildEntity Object = null;
public void SetSceneRefs(IScene scene, ISceneChildEntity child)
{
Scene = scene;
Object = child;
}
public override Object InitializeLifetimeService()
{
try
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
// Infinite : lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
//lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
//lease.RenewOnCallTime = TimeSpan.FromMinutes(10.0);
//lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
}
return lease;
}
catch (Exception)
{
return null;
}
}
public void UpdateLease(TimeSpan time)
{
ILease lease = (ILease)RemotingServices.GetLifetimeService(this as MarshalByRefObject);
if (lease != null)
lease.Renew(time);
}
#if DEBUG
// For tracing GC while debugging
public static bool GCDummy = false;
~ScriptBaseClass()
{
GCDummy = true;
}
#endif
public ScriptBaseClass()
{
m_Executor = new Executor(this);
m_sponser = new ScriptSponsor();
}
public Executor m_Executor = null;
public long GetStateEventFlags(string state)
{
return (long)m_Executor.GetStateEventFlags(state);
}
public void ExecuteEvent(string state, string FunctionName, object[] args)
{
m_Executor.ExecuteEvent(state, FunctionName, args);
}
private Dictionary<string, object> m_InitialValues =
new Dictionary<string, object>();
private Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
public Dictionary<string, IScriptApi> m_apis = new Dictionary<string, IScriptApi>();
public void InitApi(IScriptApi data)
{
/*ILease lease = (ILease)RemotingServices.GetLifetimeService(data as MarshalByRefObject);
if (lease != null)
lease.Register(m_sponser);*/
m_apis.Add(data.Name, data);
}
public void UpdateInitialValues()
{
m_InitialValues = GetVars();
}
public void Close()
{
m_sponser.Close();
}
public Dictionary<string, object> GetVars()
{
Dictionary<string, object> vars = new Dictionary<string, object>();
if (m_Fields == null)
return vars;
m_Fields.Clear();
Type t = GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo field in fields)
{
m_Fields[field.Name] = field;
if (field.FieldType == typeof(LSL_Types.list)) // ref type, copy
{
LSL_Types.list v = (LSL_Types.list)field.GetValue(this);
Object[] data = new Object[v.Data.Length];
Array.Copy(v.Data, 0, data, 0, v.Data.Length);
LSL_Types.list c = new LSL_Types.list();
c.Data = data;
vars[field.Name] = c;
}
else if (field.FieldType == typeof(LSL_Types.LSLInteger) ||
field.FieldType == typeof(LSL_Types.LSLString) ||
field.FieldType == typeof(LSL_Types.LSLFloat) ||
field.FieldType == typeof(Int32) ||
field.FieldType == typeof(Double) ||
field.FieldType == typeof(Single) ||
field.FieldType == typeof(String) ||
field.FieldType == typeof(Byte) ||
field.FieldType == typeof(short) ||
field.FieldType == typeof(LSL_Types.Vector3) ||
field.FieldType == typeof(LSL_Types.Quaternion))
{
vars[field.Name] = field.GetValue(this);
}
}
return vars;
}
public void SetVars(Dictionary<string, object> vars)
{
foreach (KeyValuePair<string, object> var in vars)
{
if (m_Fields.ContainsKey(var.Key))
{
if (m_Fields[var.Key].FieldType == typeof(LSL_Types.list))
{
LSL_Types.list v = (LSL_Types.list)m_Fields[var.Key].GetValue(this);
Object[] data = ((LSL_Types.list)(var.Value)).Data;
v.Data = new Object[data.Length];
Array.Copy(data, 0, v.Data, 0, data.Length);
m_Fields[var.Key].SetValue(this, v);
}
else if (m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLInteger) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLString) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLFloat) ||
m_Fields[var.Key].FieldType == typeof(Int32) ||
m_Fields[var.Key].FieldType == typeof(Double) ||
m_Fields[var.Key].FieldType == typeof(Single) ||
m_Fields[var.Key].FieldType == typeof(String) ||
m_Fields[var.Key].FieldType == typeof(Byte) ||
m_Fields[var.Key].FieldType == typeof(short) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.Vector3) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.Quaternion)
)
{
m_Fields[var.Key].SetValue(this, var.Value);
}
}
}
}
public string GetShortType(object o)
{
string tmp = o.GetType().ToString();
int i = tmp.LastIndexOf('+');
string type = tmp.Substring(i+1);
return type;
}
public string ListToString(object o)
{
string tmp = "";
string cur = "";
LSL_Types.list v = (LSL_Types.list)o;
foreach (object ob in v.Data)
{
if (ob.GetType() == typeof(LSL_Types.LSLInteger))
cur = "i" + ob.ToString();
else if (ob.GetType() == typeof(LSL_Types.LSLFloat))
cur = "f" + ob.ToString();
else if (ob.GetType() == typeof(LSL_Types.Vector3))
cur = "v" + ob.ToString();
else if (ob.GetType() == typeof(LSL_Types.Quaternion))
cur = "q" + ob.ToString();
else if (ob.GetType() == typeof(LSL_Types.LSLString))
cur = "\"" + ob.ToString() + "\"";
else if (ob.GetType() == typeof(LSL_Types.key))
cur = "k\"" + ob.ToString() + "\"";
else if (o.GetType() == typeof(LSL_Types.list))
cur = "{" + ListToString(ob) + "}";
if (tmp == "")
tmp = cur;
else
tmp += ", " + cur;
}
return tmp;
}
public Dictionary<string, object> GetStoreVars()
{
Dictionary<string, object> vars = new Dictionary<string, object>();
if (m_Fields == null)
return vars;
m_Fields.Clear();
Type t = GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo field in fields)
{
m_Fields[field.Name] = field;
if (field.FieldType == typeof(LSL_Types.list)) // ref type, copy
{
string tmp = "";
string cur = "";
LSL_Types.list v = (LSL_Types.list)field.GetValue(this);
foreach (object o in v.Data)
{
if (o.GetType() == typeof(LSL_Types.LSLInteger))
cur = "i" + o.ToString();
else if (o.GetType() == typeof(LSL_Types.LSLFloat))
cur = "f" + o.ToString();
else if (o.GetType() == typeof(LSL_Types.Vector3))
cur = "v" + o.ToString();
else if (o.GetType() == typeof(LSL_Types.Quaternion))
cur = "q" + o.ToString();
else if (o.GetType() == typeof(LSL_Types.LSLString))
cur = "\"" + o.ToString() + "\"";
else if (o.GetType() == typeof(LSL_Types.key))
cur = "k\"" + o.ToString() + "\"";
else if (o.GetType() == typeof(LSL_Types.list))
cur = "{" + ListToString(o) + "}";
if (tmp == "")
tmp = cur;
else
tmp += ", " + cur;
}
vars[field.Name] = (Object) tmp;
}
else if (field.FieldType == typeof(LSL_Types.LSLInteger) ||
field.FieldType == typeof(LSL_Types.LSLString) ||
field.FieldType == typeof(LSL_Types.LSLFloat) ||
field.FieldType == typeof(Int32) ||
field.FieldType == typeof(Double) ||
field.FieldType == typeof(Single) ||
field.FieldType == typeof(String) ||
field.FieldType == typeof(Byte) ||
field.FieldType == typeof(short) ||
field.FieldType == typeof(LSL_Types.Vector3) ||
field.FieldType == typeof(LSL_Types.Quaternion))
{
vars[field.Name] = field.GetValue(this).ToString();
}
}
return vars;
}
public LSL_Types.list ParseValueToList(string inval, int start, out int end)
{
LSL_Types.list v = new LSL_Types.list();
end = -1;
char c;
string tr = ",}";
char[] charany = tr.ToCharArray();
string param = "";
int totlen = inval.Length;
int len;
while (true)
{
try
{
if (inval.Length == 0)
v.Add(new LSL_Types.LSLString(""));
else
{
c = inval[start++];
switch (c)
{
case 'i':
end = inval.IndexOfAny(charany, start);
if (end > 0)
len = end - start;
else
len = totlen - start;
param = inval.Substring(start, len);
v.Add(new LSL_Types.LSLInteger(param));
break;
case 'f':
end = inval.IndexOfAny(charany, start);
if (end > 0)
len = end - start;
else
len = totlen - start;
param = inval.Substring(start, len);
v.Add(new LSL_Types.LSLFloat(param));
break;
case 'v':
end = inval.IndexOf('>', start);
if (end > 0)
len = end - start;
else
len = totlen - start;
param = inval.Substring(start, len);
v.Add(new LSL_Types.Vector3(param));
end++;
break;
case 'q':
end = inval.IndexOf('>', start);
if (end > 0)
len = end - start;
else
len = totlen - start;
param = inval.Substring(start, len);
v.Add(new LSL_Types.Quaternion(param));
end++;
break;
case '"':
end = inval.IndexOf('"', start);
if (end > 0)
len = end - start;
else
len = totlen - start;
param = inval.Substring(start, len);
v.Add(new LSL_Types.LSLString(param));
end++;
break;
case 'k':
start++;
end = inval.IndexOf('"', start);
if (end > 0)
len = end - start;
else
len = totlen - start;
param = inval.Substring(start, len);
v.Add(new LSL_Types.key(param));
end++;
break;
case '{':
v.Add(ParseValueToList(inval, start, out end));
end++;
break;
default:
break;
}
}
start = end;
if (start == -1 || start >= totlen || (inval[start] == '}'))
break;
else
while (inval[start] == ',' || inval[start] == ' ')
start++;
}
catch
{
}
}
return v;
}
public void SetStoreVars(Dictionary<string, object> vars)
{
foreach (KeyValuePair<string, object> var in vars)
{
if (m_Fields.ContainsKey(var.Key))
{
try
{
if (m_Fields[var.Key].FieldType == typeof(LSL_Types.list))
{
string val = var.Value.ToString();
int end;
LSL_Types.list v = ParseValueToList(val,0,out end);
m_Fields[var.Key].SetValue(this, v);
}
else if (m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLInteger))
{
int val = int.Parse(var.Value.ToString());
m_Fields[var.Key].SetValue(this, new LSL_Types.LSLInteger(val));
}
else if (m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLString))
{
string val = var.Value.ToString();
m_Fields[var.Key].SetValue(this, new LSL_Types.LSLString(val));
}
else if (m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLFloat))
{
float val = float.Parse(var.Value.ToString());
m_Fields[var.Key].SetValue(this, new LSL_Types.LSLFloat(val));
}
else if (m_Fields[var.Key].FieldType == typeof(Int32))
{
Int32 val = Int32.Parse(var.Value.ToString());
m_Fields[var.Key].SetValue(this, val);
}
else if (m_Fields[var.Key].FieldType == typeof(Double))
{
Double val = Double.Parse(var.Value.ToString());
m_Fields[var.Key].SetValue(this, val);
}
else if (m_Fields[var.Key].FieldType == typeof(Single))
{
Single val = Single.Parse(var.Value.ToString());
m_Fields[var.Key].SetValue(this, val);
}
else if (m_Fields[var.Key].FieldType == typeof(String))
{
String val = var.Value.ToString();
m_Fields[var.Key].SetValue(this, val);
}
else if (m_Fields[var.Key].FieldType == typeof(Byte))
{
Byte val = Byte.Parse(var.Value.ToString());
m_Fields[var.Key].SetValue(this, val);
}
else if (m_Fields[var.Key].FieldType == typeof(short))
{
short val = short.Parse(var.Value.ToString());
m_Fields[var.Key].SetValue(this, val);
}
else if (m_Fields[var.Key].FieldType == typeof(LSL_Types.Quaternion))
{
LSL_Types.Quaternion val = new LSL_Types.Quaternion(var.Value.ToString());
m_Fields[var.Key].SetValue(this, val);
}
else if (m_Fields[var.Key].FieldType == typeof(LSL_Types.Vector3))
{
LSL_Types.Vector3 val = new LSL_Types.Vector3(var.Value.ToString());
m_Fields[var.Key].SetValue(this, val);
}
}
catch (Exception) { }
}
}
}
public void ResetVars()
{
m_Executor.ResetStateEventFlags();
SetVars(m_InitialValues);
}
public void NoOp()
{
// Does what is says on the packet. Nowt, nada, nothing.
// Required for insertion after a jump label to do what it says on the packet!
// With a bit of luck the compiler may even optimize it out.
}
public void CheckSleep()
{
Thread.Sleep(m_TimeToSleepInLoops);
}
public string Name
{
get
{
return "ScriptBase";
}
}
public void Dispose()
{
}
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using dnlib.IO;
using dnlib.PE;
namespace dnlib.DotNet.Writer {
sealed class ManagedExportsWriter {
const uint DEFAULT_VTBL_FIXUPS_ALIGNMENT = 4;
const uint DEFAULT_SDATA_ALIGNMENT = 8;
const StubType stubType = StubType.Export;
readonly string moduleName;
readonly Machine machine;
readonly RelocDirectory relocDirectory;
readonly Metadata metadata;
readonly PEHeaders peHeaders;
readonly Action<string, object[]> logError;
readonly VtableFixupsChunk vtableFixups;
readonly StubsChunk stubsChunk;
readonly SdataChunk sdataChunk;
readonly ExportDir exportDir;
readonly List<VTableInfo> vtables;
readonly List<MethodInfo> allMethodInfos;
readonly List<MethodInfo> sortedOrdinalMethodInfos;
readonly List<MethodInfo> sortedNameMethodInfos;
readonly CpuArch cpuArch;
uint exportDirOffset;
bool Is64Bit => machine.Is64Bit();
FileOffset ExportDirOffset => sdataChunk.FileOffset + exportDirOffset;
RVA ExportDirRVA => sdataChunk.RVA + exportDirOffset;
uint ExportDirSize => 0x28;
internal bool HasExports => vtables.Count != 0;
sealed class ExportDir : IChunk {
readonly ManagedExportsWriter owner;
public FileOffset FileOffset => owner.ExportDirOffset;
public RVA RVA => owner.ExportDirRVA;
public ExportDir(ManagedExportsWriter owner) => this.owner = owner;
void IChunk.SetOffset(FileOffset offset, RVA rva) => throw new NotSupportedException();
public uint GetFileLength() => owner.ExportDirSize;
public uint GetVirtualSize() => GetFileLength();
void IChunk.WriteTo(DataWriter writer) => throw new NotSupportedException();
}
sealed class VtableFixupsChunk : IChunk {
readonly ManagedExportsWriter owner;
FileOffset offset;
RVA rva;
internal uint length;
public FileOffset FileOffset => offset;
public RVA RVA => rva;
public VtableFixupsChunk(ManagedExportsWriter owner) => this.owner = owner;
public void SetOffset(FileOffset offset, RVA rva) {
this.offset = offset;
this.rva = rva;
}
public uint GetFileLength() => length;
public uint GetVirtualSize() => GetFileLength();
public void WriteTo(DataWriter writer) => owner.WriteVtableFixups(writer);
}
sealed class StubsChunk : IChunk {
readonly ManagedExportsWriter owner;
FileOffset offset;
RVA rva;
internal uint length;
public FileOffset FileOffset => offset;
public RVA RVA => rva;
public StubsChunk(ManagedExportsWriter owner) => this.owner = owner;
public void SetOffset(FileOffset offset, RVA rva) {
this.offset = offset;
this.rva = rva;
}
public uint GetFileLength() => length;
public uint GetVirtualSize() => GetFileLength();
public void WriteTo(DataWriter writer) => owner.WriteStubs(writer);
}
sealed class SdataChunk : IChunk {
readonly ManagedExportsWriter owner;
FileOffset offset;
RVA rva;
internal uint length;
public FileOffset FileOffset => offset;
public RVA RVA => rva;
public SdataChunk(ManagedExportsWriter owner) => this.owner = owner;
public void SetOffset(FileOffset offset, RVA rva) {
this.offset = offset;
this.rva = rva;
}
public uint GetFileLength() => length;
public uint GetVirtualSize() => GetFileLength();
public void WriteTo(DataWriter writer) => owner.WriteSdata(writer);
}
public ManagedExportsWriter(string moduleName, Machine machine, RelocDirectory relocDirectory, Metadata metadata, PEHeaders peHeaders, Action<string, object[]> logError) {
this.moduleName = moduleName;
this.machine = machine;
this.relocDirectory = relocDirectory;
this.metadata = metadata;
this.peHeaders = peHeaders;
this.logError = logError;
vtableFixups = new VtableFixupsChunk(this);
stubsChunk = new StubsChunk(this);
sdataChunk = new SdataChunk(this);
exportDir = new ExportDir(this);
vtables = new List<VTableInfo>();
allMethodInfos = new List<MethodInfo>();
sortedOrdinalMethodInfos = new List<MethodInfo>();
sortedNameMethodInfos = new List<MethodInfo>();
// The error is reported later when we know that there's at least one exported method
CpuArch.TryGetCpuArch(machine, out cpuArch);
}
internal void AddTextChunks(PESection textSection) {
textSection.Add(vtableFixups, DEFAULT_VTBL_FIXUPS_ALIGNMENT);
if (cpuArch is not null)
textSection.Add(stubsChunk, cpuArch.GetStubAlignment(stubType));
}
internal void AddSdataChunks(PESection sdataSection) => sdataSection.Add(sdataChunk, DEFAULT_SDATA_ALIGNMENT);
internal void InitializeChunkProperties() {
if (allMethodInfos.Count == 0)
return;
peHeaders.ExportDirectory = exportDir;
peHeaders.ImageCor20Header.VtableFixups = vtableFixups;
}
internal void AddExportedMethods(List<MethodDef> methods, uint timestamp) {
if (methods.Count == 0)
return;
// Only check for an unsupported machine when we know there's at least one exported method
if (cpuArch is null) {
logError("The module has exported methods but the CPU architecture isn't supported: {0} (0x{1:X4})", new object[] { machine, (ushort)machine });
return;
}
if (methods.Count > 0x10000) {
logError("Too many methods have been exported. No more than 2^16 methods can be exported. Number of exported methods: {0}", new object[] { methods.Count });
return;
}
Initialize(methods, timestamp);
}
sealed class MethodInfo {
public readonly MethodDef Method;
public readonly uint StubChunkOffset;
public int FunctionIndex;
public uint ManagedVtblOffset;
public uint NameOffset;
public int NameIndex;
public byte[] NameBytes;
public MethodInfo(MethodDef method, uint stubChunkOffset) {
Method = method;
StubChunkOffset = stubChunkOffset;
}
}
sealed class VTableInfo {
public uint SdataChunkOffset { get; set; }
public readonly VTableFlags Flags;
public readonly List<MethodInfo> Methods;
public VTableInfo(VTableFlags flags) {
Flags = flags;
Methods = new List<MethodInfo>();
}
}
void Initialize(List<MethodDef> methods, uint timestamp) {
var dict = new Dictionary<int, List<VTableInfo>>();
var baseFlags = Is64Bit ? VTableFlags.Bit64 : VTableFlags.Bit32;
uint stubOffset = 0;
uint stubAlignment = cpuArch.GetStubAlignment(stubType);
uint stubCodeOffset = cpuArch.GetStubCodeOffset(stubType);
uint stubSize = cpuArch.GetStubSize(stubType);
foreach (var method in methods) {
var exportInfo = method.ExportInfo;
Debug.Assert(exportInfo is not null);
if (exportInfo is null)
continue;
var flags = baseFlags;
if ((exportInfo.Options & MethodExportInfoOptions.FromUnmanaged) != 0)
flags |= VTableFlags.FromUnmanaged;
if ((exportInfo.Options & MethodExportInfoOptions.FromUnmanagedRetainAppDomain) != 0)
flags |= VTableFlags.FromUnmanagedRetainAppDomain;
if ((exportInfo.Options & MethodExportInfoOptions.CallMostDerived) != 0)
flags |= VTableFlags.CallMostDerived;
if (!dict.TryGetValue((int)flags, out var list))
dict.Add((int)flags, list = new List<VTableInfo>());
if (list.Count == 0 || list[list.Count - 1].Methods.Count >= ushort.MaxValue)
list.Add(new VTableInfo(flags));
var info = new MethodInfo(method, stubOffset + stubCodeOffset);
allMethodInfos.Add(info);
list[list.Count - 1].Methods.Add(info);
stubOffset = (stubOffset + stubSize + stubAlignment - 1) & ~(stubAlignment - 1);
}
foreach (var kv in dict)
vtables.AddRange(kv.Value);
WriteSdataBlob(timestamp);
vtableFixups.length = (uint)vtables.Count * 8;
stubsChunk.length = stubOffset;
sdataChunk.length = (uint)sdataBytesInfo.Data.Length;
uint expectedOffset = 0;
foreach (var info in allMethodInfos) {
uint currentOffset = info.StubChunkOffset - stubCodeOffset;
if (expectedOffset != currentOffset)
throw new InvalidOperationException();
cpuArch.WriteStubRelocs(stubType, relocDirectory, stubsChunk, currentOffset);
expectedOffset = (currentOffset + stubSize + stubAlignment - 1) & ~(stubAlignment - 1);
}
if (expectedOffset != stubOffset)
throw new InvalidOperationException();
}
struct NamesBlob {
readonly Dictionary<string, NameInfo> nameOffsets;
readonly List<byte[]> names;
readonly List<uint> methodNameOffsets;
uint currentOffset;
int methodNamesCount;
bool methodNamesIsFrozen;
public int MethodNamesCount => methodNamesCount;
readonly struct NameInfo {
public readonly uint Offset;
public readonly byte[] Bytes;
public NameInfo(uint offset, byte[] bytes) {
Offset = offset;
Bytes = bytes;
}
}
public NamesBlob(bool dummy) {
nameOffsets = new Dictionary<string, NameInfo>(StringComparer.Ordinal);
names = new List<byte[]>();
methodNameOffsets = new List<uint>();
currentOffset = 0;
methodNamesCount = 0;
methodNamesIsFrozen = false;
}
public uint GetMethodNameOffset(string name, out byte[] bytes) {
if (methodNamesIsFrozen)
throw new InvalidOperationException();
methodNamesCount++;
uint offset = GetOffset(name, out bytes);
methodNameOffsets.Add(offset);
return offset;
}
public uint GetOtherNameOffset(string name) {
methodNamesIsFrozen = true;
return GetOffset(name, out var bytes);
}
uint GetOffset(string name, out byte[] bytes) {
if (nameOffsets.TryGetValue(name, out var nameInfo)) {
bytes = nameInfo.Bytes;
return nameInfo.Offset;
}
bytes = GetNameASCIIZ(name);
names.Add(bytes);
uint offset = currentOffset;
nameOffsets.Add(name, new NameInfo(offset, bytes));
currentOffset += (uint)bytes.Length;
return offset;
}
// If this method gets updated, also update the reader (MethodExportInfoProvider)
static byte[] GetNameASCIIZ(string name) {
Debug.Assert(name is not null);
int size = Encoding.UTF8.GetByteCount(name);
var bytes = new byte[size + 1];
Encoding.UTF8.GetBytes(name, 0, name.Length, bytes, 0);
if (bytes[bytes.Length - 1] != 0)
throw new ModuleWriterException();
return bytes;
}
public void Write(DataWriter writer) {
foreach (var name in names)
writer.WriteBytes(name);
}
public uint[] GetMethodNameOffsets() => methodNameOffsets.ToArray();
}
struct SdataBytesInfo {
public byte[] Data;
public uint namesBlobStreamOffset;
public uint moduleNameOffset;
public uint exportDirModuleNameStreamOffset;
public uint exportDirAddressOfFunctionsStreamOffset;
public uint addressOfFunctionsStreamOffset;
public uint addressOfNamesStreamOffset;
public uint addressOfNameOrdinalsStreamOffset;
public uint[] MethodNameOffsets;
}
SdataBytesInfo sdataBytesInfo;
/// <summary>
/// Writes the .sdata blob. We could write the data in any order, but we write the data in the same order as ILASM
/// </summary>
/// <param name="timestamp">PE timestamp</param>
void WriteSdataBlob(uint timestamp) {
var stream = new MemoryStream();
var writer = new DataWriter(stream);
// Write all vtables (referenced from the .text section)
Debug.Assert((writer.Position & 7) == 0);
foreach (var vtbl in vtables) {
vtbl.SdataChunkOffset = (uint)writer.Position;
foreach (var info in vtbl.Methods) {
info.ManagedVtblOffset = (uint)writer.Position;
writer.WriteUInt32(0x06000000 + metadata.GetRid(info.Method));
if ((vtbl.Flags & VTableFlags.Bit64) != 0)
writer.WriteUInt32(0);
}
}
var namesBlob = new NamesBlob(1 == 2);
int nameIndex = 0;
bool error = false;
foreach (var info in allMethodInfos) {
var exportInfo = info.Method.ExportInfo;
var name = exportInfo.Name;
if (name is null) {
if (exportInfo.Ordinal is not null) {
sortedOrdinalMethodInfos.Add(info);
continue;
}
name = info.Method.Name;
}
if (string.IsNullOrEmpty(name)) {
error = true;
logError("Exported method name is null or empty, method: {0} (0x{1:X8})", new object[] { info.Method, info.Method.MDToken.Raw });
continue;
}
info.NameOffset = namesBlob.GetMethodNameOffset(name, out info.NameBytes);
info.NameIndex = nameIndex++;
sortedNameMethodInfos.Add(info);
}
Debug.Assert(error || sortedOrdinalMethodInfos.Count + sortedNameMethodInfos.Count == allMethodInfos.Count);
sdataBytesInfo.MethodNameOffsets = namesBlob.GetMethodNameOffsets();
Debug.Assert(sortedNameMethodInfos.Count == sdataBytesInfo.MethodNameOffsets.Length);
sdataBytesInfo.moduleNameOffset = namesBlob.GetOtherNameOffset(moduleName);
sortedOrdinalMethodInfos.Sort((a, b) => a.Method.ExportInfo.Ordinal.Value.CompareTo(b.Method.ExportInfo.Ordinal.Value));
sortedNameMethodInfos.Sort((a, b) => CompareTo(a.NameBytes, b.NameBytes));
int ordinalBase, nextFreeOrdinal;
if (sortedOrdinalMethodInfos.Count == 0) {
ordinalBase = 0;
nextFreeOrdinal = 0;
}
else {
ordinalBase = sortedOrdinalMethodInfos[0].Method.ExportInfo.Ordinal.Value;
nextFreeOrdinal = sortedOrdinalMethodInfos[sortedOrdinalMethodInfos.Count - 1].Method.ExportInfo.Ordinal.Value + 1;
}
int nameFuncBaseIndex = nextFreeOrdinal - ordinalBase;
int lastFuncIndex = 0;
for (int i = 0; i < sortedOrdinalMethodInfos.Count; i++) {
int index = sortedOrdinalMethodInfos[i].Method.ExportInfo.Ordinal.Value - ordinalBase;
sortedOrdinalMethodInfos[i].FunctionIndex = index;
lastFuncIndex = index;
}
for (int i = 0; i < sortedNameMethodInfos.Count; i++) {
lastFuncIndex = nameFuncBaseIndex + i;
sortedNameMethodInfos[i].FunctionIndex = lastFuncIndex;
}
int funcSize = lastFuncIndex + 1;
if (funcSize > 0x10000) {
logError("Exported function array is too big", Array2.Empty<object>());
return;
}
// Write IMAGE_EXPORT_DIRECTORY
Debug.Assert((writer.Position & 3) == 0);
exportDirOffset = (uint)writer.Position;
writer.WriteUInt32(0); // Characteristics
writer.WriteUInt32(timestamp);
writer.WriteUInt32(0); // MajorVersion, MinorVersion
sdataBytesInfo.exportDirModuleNameStreamOffset = (uint)writer.Position;
writer.WriteUInt32(0); // Name
writer.WriteInt32(ordinalBase); // Base
writer.WriteUInt32((uint)funcSize); // NumberOfFunctions
writer.WriteInt32(sdataBytesInfo.MethodNameOffsets.Length); // NumberOfNames
sdataBytesInfo.exportDirAddressOfFunctionsStreamOffset = (uint)writer.Position;
writer.WriteUInt32(0); // AddressOfFunctions
writer.WriteUInt32(0); // AddressOfNames
writer.WriteUInt32(0); // AddressOfNameOrdinals
sdataBytesInfo.addressOfFunctionsStreamOffset = (uint)writer.Position;
writer.WriteZeroes(funcSize * 4);
sdataBytesInfo.addressOfNamesStreamOffset = (uint)writer.Position;
writer.WriteZeroes(sdataBytesInfo.MethodNameOffsets.Length * 4);
sdataBytesInfo.addressOfNameOrdinalsStreamOffset = (uint)writer.Position;
writer.WriteZeroes(sdataBytesInfo.MethodNameOffsets.Length * 2);
sdataBytesInfo.namesBlobStreamOffset = (uint)writer.Position;
namesBlob.Write(writer);
sdataBytesInfo.Data = stream.ToArray();
}
void WriteSdata(DataWriter writer) {
if (sdataBytesInfo.Data is null)
return;
PatchSdataBytesBlob();
writer.WriteBytes(sdataBytesInfo.Data);
}
void PatchSdataBytesBlob() {
uint rva = (uint)sdataChunk.RVA;
uint namesBaseOffset = rva + sdataBytesInfo.namesBlobStreamOffset;
var writer = new DataWriter(new MemoryStream(sdataBytesInfo.Data));
writer.Position = sdataBytesInfo.exportDirModuleNameStreamOffset;
writer.WriteUInt32(namesBaseOffset + sdataBytesInfo.moduleNameOffset);
writer.Position = sdataBytesInfo.exportDirAddressOfFunctionsStreamOffset;
writer.WriteUInt32(rva + sdataBytesInfo.addressOfFunctionsStreamOffset); // AddressOfFunctions
if (sdataBytesInfo.MethodNameOffsets.Length != 0) {
writer.WriteUInt32(rva + sdataBytesInfo.addressOfNamesStreamOffset); // AddressOfNames
writer.WriteUInt32(rva + sdataBytesInfo.addressOfNameOrdinalsStreamOffset); // AddressOfNameOrdinals
}
uint funcBaseRva = (uint)stubsChunk.RVA;
writer.Position = sdataBytesInfo.addressOfFunctionsStreamOffset;
int currentFuncIndex = 0;
foreach (var info in sortedOrdinalMethodInfos) {
int zeroes = info.FunctionIndex - currentFuncIndex;
if (zeroes < 0)
throw new InvalidOperationException();
while (zeroes-- > 0)
writer.WriteInt32(0);
writer.WriteUInt32(funcBaseRva + info.StubChunkOffset);
currentFuncIndex = info.FunctionIndex + 1;
}
foreach (var info in sortedNameMethodInfos) {
if (info.FunctionIndex != currentFuncIndex++)
throw new InvalidOperationException();
writer.WriteUInt32(funcBaseRva + info.StubChunkOffset);
}
var nameOffsets = sdataBytesInfo.MethodNameOffsets;
if (nameOffsets.Length != 0) {
writer.Position = sdataBytesInfo.addressOfNamesStreamOffset;
foreach (var info in sortedNameMethodInfos)
writer.WriteUInt32(namesBaseOffset + nameOffsets[info.NameIndex]);
writer.Position = sdataBytesInfo.addressOfNameOrdinalsStreamOffset;
foreach (var info in sortedNameMethodInfos)
writer.WriteUInt16((ushort)info.FunctionIndex);
}
}
void WriteVtableFixups(DataWriter writer) {
if (vtables.Count == 0)
return;
foreach (var vtbl in vtables) {
Debug.Assert(vtbl.Methods.Count <= ushort.MaxValue);
writer.WriteUInt32((uint)sdataChunk.RVA + vtbl.SdataChunkOffset);
writer.WriteUInt16((ushort)vtbl.Methods.Count);
writer.WriteUInt16((ushort)vtbl.Flags);
}
}
void WriteStubs(DataWriter writer) {
if (vtables.Count == 0)
return;
if (cpuArch is null)
return;
ulong imageBase = peHeaders.ImageBase;
uint stubsBaseRva = (uint)stubsChunk.RVA;
uint vtblBaseRva = (uint)sdataChunk.RVA;
uint expectedOffset = 0;
uint stubCodeOffset = cpuArch.GetStubCodeOffset(stubType);
uint stubSize = cpuArch.GetStubSize(stubType);
uint stubAlignment = cpuArch.GetStubAlignment(stubType);
int zeroes = (int)((stubSize + stubAlignment - 1 & ~(stubAlignment - 1)) - stubSize);
foreach (var info in allMethodInfos) {
uint currentOffset = info.StubChunkOffset - stubCodeOffset;
if (expectedOffset != currentOffset)
throw new InvalidOperationException();
var pos = writer.Position;
cpuArch.WriteStub(stubType, writer, imageBase, stubsBaseRva + currentOffset, vtblBaseRva + info.ManagedVtblOffset);
Debug.Assert(pos + stubSize == writer.Position, "The full stub wasn't written");
if (pos + stubSize != writer.Position)
throw new InvalidOperationException();
if (zeroes != 0)
writer.WriteZeroes(zeroes);
expectedOffset = (currentOffset + stubSize + stubAlignment - 1) & ~(stubAlignment - 1);
}
if (expectedOffset != stubsChunk.length)
throw new InvalidOperationException();
}
static int CompareTo(byte[] a, byte[] b) {
if (a == b)
return 0;
int max = Math.Min(a.Length, b.Length);
for (int i = 0; i < max; i++) {
int c = a[i] - b[i];
if (c != 0)
return c;
}
return a.Length - b.Length;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Msagl.Core;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.GraphAlgorithms;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Core.ProjectionSolver;
using Microsoft.Msagl.Routing;
namespace Microsoft.Msagl.Layout.Layered {
internal class TwoLayerFlatEdgeRouter : AlgorithmBase {
readonly int[] bottomLayer;
InteractiveEdgeRouter interactiveEdgeRouter;
double[] labelCenters;
Dictionary<Label, ICurve> labelsToLabelObstacles = new Dictionary<Label, ICurve>();
IntPair[] pairArray;
readonly Routing routing;
readonly int[] topLayer;
private SugiyamaLayoutSettings settings;
internal TwoLayerFlatEdgeRouter(SugiyamaLayoutSettings settings, Routing routing, int[] bottomLayer, int[] topLayer)
{
this.settings = settings;
this.topLayer = topLayer;
this.bottomLayer = bottomLayer;
this.routing = routing;
InitLabelsInfo();
}
Database Database {
get { return routing.Database; }
}
int[] Layering {
get { return routing.LayerArrays.Y; }
}
BasicGraph<IntEdge> IntGraph {
get { return routing.IntGraph; }
}
LayerArrays LayerArrays {
get { return routing.LayerArrays; }
}
double PaddingForEdges {
get { return settings.LayerSeparation / 8; }
}
void InitLabelsInfo() {
pairArray = new Set<IntPair>(from v in bottomLayer
where v < IntGraph.NodeCount
from edge in IntGraph.OutEdges(v)
where edge.Source != edge.Target
where Layering[edge.Target] == Layering[edge.Source]
select new IntPair(edge.Source, edge.Target)).ToArray();
labelCenters = new double[pairArray.Length];
int i = 0;
foreach (IntPair p in pairArray) {
int leftNode, rightNode;
if (LayerArrays.X[p.First] < LayerArrays.X[p.Second]) {
leftNode = p.First;
rightNode = p.Second;
} else {
leftNode = p.Second;
rightNode = p.First;
}
labelCenters[i++] = (Database.Anchors[leftNode].Right + Database.Anchors[rightNode].Left)/2;
//labelCenters contains ideal position for nodes at the moment
}
InitLabelsToLabelObstacles();
}
void InitLabelsToLabelObstacles() {
labelsToLabelObstacles = new Dictionary<Label, ICurve>();
IEnumerable<Label> labels = from p in pairArray from label in PairLabels(p) select label;
foreach (Label label in labels)
labelsToLabelObstacles[label] = CreatObstaceOnLabel(label);
}
double GetMaxLabelWidth(IntPair intPair) {
IEnumerable<Label> multiEdgeLabels = PairLabels(intPair);
if (multiEdgeLabels.Any())
return multiEdgeLabels.Max(label => label.Width);
return 0;
}
IEnumerable<Label> PairLabels(IntPair intPair) {
return from edge in Database.GetMultiedge(intPair)
let label = edge.Edge.Label
where label != null
select label;
}
/// <summary>
/// Executes the algorithm.
/// </summary>
protected override void RunInternal() {
if (pairArray.Length > 0) {
PositionLabelsOfFlatEdges();
interactiveEdgeRouter = new InteractiveEdgeRouter(GetObstacles(), PaddingForEdges, PaddingForEdges/3, Math.PI/6);
foreach (IntEdge intEdge in IntEdges())
{
this.ProgressStep();
RouteEdge(intEdge);
}
}
}
IEnumerable<ICurve> GetObstacles() {
return (from v in topLayer.Concat(bottomLayer)
where v < routing.OriginalGraph.Nodes.Count
select routing.IntGraph.Nodes[v].BoundaryCurve).Concat(LabelCurves());
}
IEnumerable<ICurve> LabelCurves() {
return from edge in IntEdges()
let label = edge.Edge.Label
where label != null
select CreatObstaceOnLabel(label);
}
static ICurve CreatObstaceOnLabel(Label label) {
var c = new Curve();
double obstacleBottom = label.Center.Y - label.Height/4;
c.AddSegment(new LineSegment(new Point(label.BoundingBox.Left, obstacleBottom),
new Point(label.BoundingBox.Right, obstacleBottom)));
Curve.ContinueWithLineSegment(c, label.BoundingBox.RightTop);
Curve.ContinueWithLineSegment(c, label.BoundingBox.LeftTop);
Curve.CloseCurve(c);
return c;
}
IEnumerable<IntEdge> IntEdges() {
return from pair in pairArray from edge in Database.GetMultiedge(pair) select edge;
}
void RouteEdge(IntEdge edge) {
if (edge.HasLabel)
RouteEdgeWithLabel(edge, edge.Edge.Label);
else
RouteEdgeWithNoLabel(edge);
}
void RouteEdgeWithLabel(IntEdge intEdge, Label label) {
//we allow here for the edge to cross its own label
Node sourceNode = routing.IntGraph.Nodes[intEdge.Source];
Node targetNode = routing.IntGraph.Nodes[intEdge.Target];
var sourcePort = new FloatingPort(sourceNode.BoundaryCurve, sourceNode.Center);
var targetPort = new FloatingPort(targetNode.BoundaryCurve, targetNode.Center);
ICurve labelObstacle = labelsToLabelObstacles[label];
var labelPort = new FloatingPort(labelObstacle, label.Center);
SmoothedPolyline poly0;
interactiveEdgeRouter.RouteSplineFromPortToPortWhenTheWholeGraphIsReady(sourcePort, labelPort, true, out poly0);
SmoothedPolyline poly1;
interactiveEdgeRouter.RouteSplineFromPortToPortWhenTheWholeGraphIsReady(labelPort, targetPort, true, out poly1);
Site site = poly1.HeadSite.Next;
Site lastSite = poly0.LastSite;
lastSite.Next = site;
site.Previous = lastSite;
var eg = intEdge.Edge.EdgeGeometry;
eg.SetSmoothedPolylineAndCurve(poly0);
Arrowheads.TrimSplineAndCalculateArrowheads(eg, intEdge.Edge.Source.BoundaryCurve,
intEdge.Edge.Target.BoundaryCurve, eg.Curve, false,
settings.EdgeRoutingSettings.KeepOriginalSpline);
}
void RouteEdgeWithNoLabel(IntEdge intEdge) {
Node sourceNode = routing.IntGraph.Nodes[intEdge.Source];
Node targetNode = routing.IntGraph.Nodes[intEdge.Target];
var sourcePort = new FloatingPort(sourceNode.BoundaryCurve, sourceNode.Center);
var targetPort = new FloatingPort(targetNode.BoundaryCurve, targetNode.Center);
var eg = intEdge.Edge.EdgeGeometry;
SmoothedPolyline sp;
eg.Curve = interactiveEdgeRouter.RouteSplineFromPortToPortWhenTheWholeGraphIsReady(sourcePort, targetPort, true, out sp);
Arrowheads.TrimSplineAndCalculateArrowheads(eg, intEdge.Edge.Source.BoundaryCurve,
intEdge.Edge.Target.BoundaryCurve, eg.Curve, false,
settings.EdgeRoutingSettings.KeepOriginalSpline);
intEdge.Edge.EdgeGeometry = eg;
}
void PositionLabelsOfFlatEdges() {
if (labelCenters == null || labelCenters.Length == 0)
return;
SortLabelsByX();
CalculateLabelsX();
}
void CalculateLabelsX() {
int i;
ISolverShell solver = ConstrainedOrdering.CreateSolver();
for (i = 0; i < pairArray.Length; i++)
solver.AddVariableWithIdealPosition(i, labelCenters[i], GetLabelWeight(pairArray[i]));
//add non overlapping constraints between to neighbor labels
double prevLabelWidth = GetMaxLabelWidth(pairArray[0]);
for (i = 0; i < pairArray.Length - 1; i++)
solver.AddLeftRightSeparationConstraint(i, i + 1,
(prevLabelWidth +
(prevLabelWidth = GetMaxLabelWidth(pairArray[i + 1])))/2 +
settings.NodeSeparation);
for (i = 0; i < labelCenters.Length; i++) {
double x = labelCenters[i] = solver.GetVariableResolvedPosition(i);
foreach (Label label in PairLabels(pairArray[i]))
label.Center = new Point(x, label.Center.Y);
}
}
double GetLabelWeight(IntPair intPair) {
return Database.GetMultiedge(intPair).Count;
}
void SortLabelsByX() {
Array.Sort(labelCenters, pairArray);
}
}
}
| |
using System;
using System.Collections;
using BigMath;
using NUnit.Framework;
using Raksha.Asn1;
using Raksha.Asn1.CryptoPro;
using Raksha.Asn1.Nist;
using Raksha.Asn1.Sec;
using Raksha.Asn1.TeleTrust;
using Raksha.Asn1.X9;
using Raksha.Crypto;
using Raksha.Crypto.Parameters;
using Raksha.Math;
using Raksha.Pkcs;
using Raksha.Security;
using Raksha.Tests.Utilities;
using Raksha.X509;
namespace Raksha.Tests.Misc
{
[TestFixture]
public class NamedCurveTest
: SimpleTest
{
// private static readonly Hashtable CurveNames = new Hashtable();
// private static readonly Hashtable CurveAliases = new Hashtable();
//
// static NamedCurveTest()
// {
// CurveNames.Add("prime192v1", "prime192v1"); // X9.62
// CurveNames.Add("sect571r1", "sect571r1"); // sec
// CurveNames.Add("secp224r1", "secp224r1");
// CurveNames.Add("B-409", SecNamedCurves.GetName(NistNamedCurves.GetOid("B-409"))); // nist
// CurveNames.Add("P-521", SecNamedCurves.GetName(NistNamedCurves.GetOid("P-521")));
// CurveNames.Add("brainpoolp160r1", "brainpoolp160r1"); // TeleTrusT
//
// CurveAliases.Add("secp192r1", "prime192v1");
// CurveAliases.Add("secp256r1", "prime256v1");
// }
private static ECDomainParameters GetCurveParameters(
string name)
{
ECDomainParameters ecdp = ECGost3410NamedCurves.GetByName(name);
if (ecdp != null)
return ecdp;
X9ECParameters ecP = X962NamedCurves.GetByName(name);
if (ecP == null)
{
ecP = SecNamedCurves.GetByName(name);
if (ecP == null)
{
ecP = NistNamedCurves.GetByName(name);
if (ecP == null)
{
ecP = TeleTrusTNamedCurves.GetByName(name);
if (ecP == null)
throw new Exception("unknown curve name: " + name);
}
}
}
return new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
}
public void doTestCurve(
string name)
{
// ECGenParameterSpec ecSpec = new ECGenParameterSpec(name);
ECDomainParameters ecSpec = GetCurveParameters(name);
IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDH");
// g.initialize(ecSpec, new SecureRandom());
g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));
//
// a side
//
AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();
// KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDHC");
IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDHC");
aKeyAgree.Init(aKeyPair.Private);
//
// b side
//
AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair();
// KeyAgreement bKeyAgree = KeyAgreement.getInstance("ECDHC");
IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement("ECDHC");
bKeyAgree.Init(bKeyPair.Private);
//
// agreement
//
// aKeyAgree.doPhase(bKeyPair.Public, true);
// bKeyAgree.doPhase(aKeyPair.Public, true);
//
// BigInteger k1 = new BigInteger(aKeyAgree.generateSecret());
// BigInteger k2 = new BigInteger(bKeyAgree.generateSecret());
BigInteger k1 = aKeyAgree.CalculateAgreement(bKeyPair.Public);
BigInteger k2 = bKeyAgree.CalculateAgreement(aKeyPair.Public);
if (!k1.Equals(k2))
{
Fail("2-way test failed");
}
//
// public key encoding test
//
// byte[] pubEnc = aKeyPair.Public.getEncoded();
byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();
// KeyFactory keyFac = KeyFactory.getInstance("ECDH");
// X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
// ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc);
// if (!pubKey.getW().Equals(((ECPublicKey)aKeyPair.Public).getW()))
if (!pubKey.Q.Equals(((ECPublicKeyParameters)aKeyPair.Public).Q))
{
Fail("public key encoding (Q test) failed");
}
// TODO Put back in?
// if (!(pubKey.getParams() is ECNamedCurveSpec))
// {
// Fail("public key encoding not named curve");
// }
//
// private key encoding test
//
// byte[] privEnc = aKeyPair.Private.getEncoded();
byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded();
// PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
// ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
ECPrivateKeyParameters privKey = (ECPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc);
// if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS()))
if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D))
{
Fail("private key encoding (S test) failed");
}
// TODO Put back in?
// if (!(privKey.getParams() is ECNamedCurveSpec))
// {
// Fail("private key encoding not named curve");
// }
//
// ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams();
// if (!(privSpec.GetName().Equals(name) || privSpec.GetName().Equals(CurveNames.get(name))))
// {
// Fail("private key encoding wrong named curve. Expected: "
// + CurveNames[name] + " got " + privSpec.GetName());
// }
}
public void doTestECDsa(
string name)
{
// ECGenParameterSpec ecSpec = new ECGenParameterSpec(name);
ECDomainParameters ecSpec = GetCurveParameters(name);
IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
// g.initialize(ecSpec, new SecureRandom());
g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));
ISigner sgr = SignerUtilities.GetSigner("ECDSA");
AsymmetricCipherKeyPair pair = g.GenerateKeyPair();
AsymmetricKeyParameter sKey = pair.Private;
AsymmetricKeyParameter vKey = pair.Public;
sgr.Init(true, sKey);
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
sgr.BlockUpdate(message, 0, message.Length);
byte[] sigBytes = sgr.GenerateSignature();
sgr.Init(false, vKey);
sgr.BlockUpdate(message, 0, message.Length);
if (!sgr.VerifySignature(sigBytes))
{
Fail(name + " verification failed");
}
//
// public key encoding test
//
// byte[] pubEnc = vKey.getEncoded();
byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded();
// KeyFactory keyFac = KeyFactory.getInstance("ECDH");
// X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
// ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc);
// if (!pubKey.getW().Equals(((ECPublicKey)vKey).getW()))
if (!pubKey.Q.Equals(((ECPublicKeyParameters)vKey).Q))
{
Fail("public key encoding (Q test) failed");
}
// TODO Put back in?
// if (!(pubKey.Parameters is ECNamedCurveSpec))
// {
// Fail("public key encoding not named curve");
// }
//
// private key encoding test
//
// byte[] privEnc = sKey.getEncoded();
byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded();
// PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
// ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
ECPrivateKeyParameters privKey = (ECPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc);
// if (!privKey.getS().Equals(((ECPrivateKey)sKey).getS()))
if (!privKey.D.Equals(((ECPrivateKeyParameters)sKey).D))
{
Fail("private key encoding (D test) failed");
}
// TODO Put back in?
// if (!(privKey.Parameters is ECNamedCurveSpec))
// {
// Fail("private key encoding not named curve");
// }
//
// ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams();
// if (!privSpec.GetName().EqualsIgnoreCase(name)
// && !privSpec.GetName().EqualsIgnoreCase((string) CurveAliases[name]))
// {
// Fail("private key encoding wrong named curve. Expected: " + name + " got " + privSpec.GetName());
// }
}
public void doTestECGost(
string name)
{
// ECGenParameterSpec ecSpec = new ECGenParameterSpec(name);
ECDomainParameters ecSpec = GetCurveParameters(name);
IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");
// g.initialize(ecSpec, new SecureRandom());
g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));
ISigner sgr = SignerUtilities.GetSigner("ECGOST3410");
AsymmetricCipherKeyPair pair = g.GenerateKeyPair();
AsymmetricKeyParameter sKey = pair.Private;
AsymmetricKeyParameter vKey = pair.Public;
sgr.Init(true, sKey);
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
sgr.BlockUpdate(message, 0, message.Length);
byte[] sigBytes = sgr.GenerateSignature();
sgr.Init(false, vKey);
sgr.BlockUpdate(message, 0, message.Length);
if (!sgr.VerifySignature(sigBytes))
{
Fail(name + " verification failed");
}
// TODO Get this working?
// //
// // public key encoding test
// //
//// byte[] pubEnc = vKey.getEncoded();
// byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded();
//
//// KeyFactory keyFac = KeyFactory.getInstance("ECGOST3410");
//// X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
//// ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
// ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc);
//
//// if (!pubKey.getW().equals(((ECPublicKey)vKey).getW()))
// if (!pubKey.Q.Equals(((ECPublicKeyParameters)vKey).Q))
// {
// Fail("public key encoding (Q test) failed");
// }
// TODO Put back in?
// if (!(pubKey.Parameters is ECNamedCurveSpec))
// {
// Fail("public key encoding not named curve");
// }
// TODO Get this working?
// //
// // private key encoding test
// //
//// byte[] privEnc = sKey.getEncoded();
// byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded();
//
//// PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//// ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
// ECPrivateKeyParameters privKey = (ECPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc);
//
//// if (!privKey.getS().Equals(((ECPrivateKey)sKey).getS()))
// if (!privKey.D.Equals(((ECPrivateKeyParameters)sKey).D))
// {
// Fail("GOST private key encoding (D test) failed");
// }
// TODO Put back in?
// if (!(privKey.Parameters is ECNamedCurveSpec))
// {
// Fail("GOST private key encoding not named curve");
// }
//
// ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams();
// if (!privSpec.getName().equalsIgnoreCase(name)
// && !privSpec.getName().equalsIgnoreCase((String)CURVE_ALIASES[name]))
// {
// Fail("GOST private key encoding wrong named curve. Expected: " + name + " got " + privSpec.getName());
// }
}
public override string Name
{
get { return "NamedCurve"; }
}
public override void PerformTest()
{
doTestCurve("prime192v1"); // X9.62
doTestCurve("sect571r1"); // sec
doTestCurve("secp224r1");
doTestCurve("B-409"); // nist
doTestCurve("P-521");
doTestCurve("brainpoolp160r1"); // TeleTrusT
foreach (string name in X962NamedCurves.Names)
{
doTestECDsa(name);
}
foreach (string name in SecNamedCurves.Names)
{
doTestECDsa(name);
}
foreach (string name in TeleTrusTNamedCurves.Names)
{
doTestECDsa(name);
}
foreach (string name in ECGost3410NamedCurves.Names)
{
doTestECGost(name);
}
}
public static void Main(
string[] args)
{
RunTest(new NamedCurveTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: class to sort arrays
**
**
===========================================================*/
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
#region ArraySortHelper for single arrays
internal static class IntrospectiveSortUtilities
{
// This is the threshold where Introspective sort switches to Insertion sort.
// Empirically, 16 seems to speed up most cases without slowing down others, at least for integers.
// Large value types may benefit from a smaller number.
internal const int IntrosortSizeThreshold = 16;
internal static int FloorLog2PlusOne(int n)
{
int result = 0;
while (n >= 1)
{
result++;
n = n / 2;
}
return result;
}
internal static void ThrowOrIgnoreBadComparer(object comparer)
{
throw new ArgumentException(SR.Format(SR.Arg_BogusIComparer, comparer));
}
}
internal partial class ArraySortHelper<T>
{
#region IArraySortHelper<T> Members
public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
try
{
if (comparer == null)
{
comparer = Comparer<T>.Default;
}
IntrospectiveSort(keys, index, length, comparer.Compare);
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
public int BinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
try
{
if (comparer == null)
{
comparer = Comparer<T>.Default;
}
return InternalBinarySearch(array, index, length, value, comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
#endregion
internal static void Sort(T[] keys, int index, int length, Comparison<T> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
Debug.Assert(comparer != null, "Check the arguments in the caller!");
// Add a try block here to detect bogus comparisons
try
{
IntrospectiveSort(keys, index, length, comparer);
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
Debug.Assert(array != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
int lo = index;
int hi = index + length - 1;
while (lo <= hi)
{
int i = lo + ((hi - lo) >> 1);
int order = comparer.Compare(array[i], value);
if (order == 0) return i;
if (order < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
private static void SwapIfGreater(T[] keys, Comparison<T> comparer, int a, int b)
{
if (a != b)
{
if (comparer(keys[a], keys[b]) > 0)
{
T key = keys[a];
keys[a] = keys[b];
keys[b] = key;
}
}
}
private static void Swap(T[] a, int i, int j)
{
if (i != j)
{
T t = a[i];
a[i] = a[j];
a[j] = t;
}
}
internal static void IntrospectiveSort(T[] keys, int left, int length, Comparison<T> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(comparer != null);
Debug.Assert(left >= 0);
Debug.Assert(length >= 0);
Debug.Assert(length <= keys.Length);
Debug.Assert(length + left <= keys.Length);
if (length < 2)
return;
IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length), comparer);
}
private static void IntroSort(T[] keys, int lo, int hi, int depthLimit, Comparison<T> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreater(keys, comparer, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreater(keys, comparer, lo, hi - 1);
SwapIfGreater(keys, comparer, lo, hi);
SwapIfGreater(keys, comparer, hi - 1, hi);
return;
}
InsertionSort(keys, lo, hi, comparer);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, lo, hi, comparer);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, lo, hi, comparer);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, p + 1, hi, depthLimit, comparer);
hi = p - 1;
}
}
private static int PickPivotAndPartition(T[] keys, int lo, int hi, Comparison<T> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreater(keys, comparer, lo, middle); // swap the low with the mid point
SwapIfGreater(keys, comparer, lo, hi); // swap the low with the high
SwapIfGreater(keys, comparer, middle, hi); // swap the middle with the high
T pivot = keys[middle];
Swap(keys, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
while (comparer(keys[++left], pivot) < 0) ;
while (comparer(pivot, keys[--right]) < 0) ;
if (left >= right)
break;
Swap(keys, left, right);
}
// Put pivot in the right location.
Swap(keys, left, (hi - 1));
return left;
}
private static void Heapsort(T[] keys, int lo, int hi, Comparison<T> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, i, n, lo, comparer);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, lo, lo + i - 1);
DownHeap(keys, 1, i - 1, lo, comparer);
}
}
private static void DownHeap(T[] keys, int i, int n, int lo, Comparison<T> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(lo < keys.Length);
T d = keys[lo + i - 1];
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && comparer(keys[lo + child - 1], keys[lo + child]) < 0)
{
child++;
}
if (!(comparer(d, keys[lo + child - 1]) < 0))
break;
keys[lo + i - 1] = keys[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
}
private static void InsertionSort(T[] keys, int lo, int hi, Comparison<T> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi >= lo);
Debug.Assert(hi <= keys.Length);
int i, j;
T t;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
while (j >= lo && comparer(t, keys[j]) < 0)
{
keys[j + 1] = keys[j];
j--;
}
keys[j + 1] = t;
}
}
}
internal partial class GenericArraySortHelper<T>
where T : IComparable<T>
{
// Do not add a constructor to this class because ArraySortHelper<T>.CreateSortHelper will not execute it
#region IArraySortHelper<T> Members
public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
try
{
if (comparer == null || comparer == Comparer<T>.Default)
{
IntrospectiveSort(keys, index, length);
}
else
{
ArraySortHelper<T>.IntrospectiveSort(keys, index, length, comparer.Compare);
}
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
public int BinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
Debug.Assert(array != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
try
{
if (comparer == null || comparer == Comparer<T>.Default)
{
return BinarySearch(array, index, length, value);
}
else
{
return ArraySortHelper<T>.InternalBinarySearch(array, index, length, value, comparer);
}
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
#endregion
// This function is called when the user doesn't specify any comparer.
// Since T is constrained here, we can call IComparable<T>.CompareTo here.
// We can avoid boxing for value type and casting for reference types.
private static int BinarySearch(T[] array, int index, int length, T value)
{
int lo = index;
int hi = index + length - 1;
while (lo <= hi)
{
int i = lo + ((hi - lo) >> 1);
int order;
if (array[i] == null)
{
order = (value == null) ? 0 : -1;
}
else
{
order = array[i].CompareTo(value);
}
if (order == 0)
{
return i;
}
if (order < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
private static void SwapIfGreaterWithItems(T[] keys, int a, int b)
{
Debug.Assert(keys != null);
Debug.Assert(0 <= a && a < keys.Length);
Debug.Assert(0 <= b && b < keys.Length);
if (a != b)
{
if (keys[a] != null && keys[a].CompareTo(keys[b]) > 0)
{
T key = keys[a];
keys[a] = keys[b];
keys[b] = key;
}
}
}
private static void Swap(T[] a, int i, int j)
{
if (i != j)
{
T t = a[i];
a[i] = a[j];
a[j] = t;
}
}
internal static void IntrospectiveSort(T[] keys, int left, int length)
{
Debug.Assert(keys != null);
Debug.Assert(left >= 0);
Debug.Assert(length >= 0);
Debug.Assert(length <= keys.Length);
Debug.Assert(length + left <= keys.Length);
if (length < 2)
return;
IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length));
}
private static void IntroSort(T[] keys, int lo, int hi, int depthLimit)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreaterWithItems(keys, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreaterWithItems(keys, lo, hi - 1);
SwapIfGreaterWithItems(keys, lo, hi);
SwapIfGreaterWithItems(keys, hi - 1, hi);
return;
}
InsertionSort(keys, lo, hi);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, lo, hi);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, lo, hi);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, p + 1, hi, depthLimit);
hi = p - 1;
}
}
private static int PickPivotAndPartition(T[] keys, int lo, int hi)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreaterWithItems(keys, lo, middle); // swap the low with the mid point
SwapIfGreaterWithItems(keys, lo, hi); // swap the low with the high
SwapIfGreaterWithItems(keys, middle, hi); // swap the middle with the high
T pivot = keys[middle];
Swap(keys, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
if (pivot == null)
{
while (left < (hi - 1) && keys[++left] == null) ;
while (right > lo && keys[--right] != null) ;
}
else
{
while (pivot.CompareTo(keys[++left]) > 0) ;
while (pivot.CompareTo(keys[--right]) < 0) ;
}
if (left >= right)
break;
Swap(keys, left, right);
}
// Put pivot in the right location.
Swap(keys, left, (hi - 1));
return left;
}
private static void Heapsort(T[] keys, int lo, int hi)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, i, n, lo);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, lo, lo + i - 1);
DownHeap(keys, 1, i - 1, lo);
}
}
private static void DownHeap(T[] keys, int i, int n, int lo)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(lo < keys.Length);
T d = keys[lo + i - 1];
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(keys[lo + child]) < 0))
{
child++;
}
if (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(d) < 0)
break;
keys[lo + i - 1] = keys[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
}
private static void InsertionSort(T[] keys, int lo, int hi)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi >= lo);
Debug.Assert(hi <= keys.Length);
int i, j;
T t;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
while (j >= lo && (t == null || t.CompareTo(keys[j]) < 0))
{
keys[j + 1] = keys[j];
j--;
}
keys[j + 1] = t;
}
}
}
#endregion
#region ArraySortHelper for paired key and value arrays
internal partial class ArraySortHelper<TKey, TValue>
{
public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method
Debug.Assert(values != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
try
{
if (comparer == null || comparer == Comparer<TKey>.Default)
{
comparer = Comparer<TKey>.Default;
}
IntrospectiveSort(keys, values, index, length, comparer);
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, IComparer<TKey> comparer, int a, int b)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(0 <= a && a < keys.Length && a < values.Length);
Debug.Assert(0 <= b && b < keys.Length && b < values.Length);
if (a != b)
{
if (comparer.Compare(keys[a], keys[b]) > 0)
{
TKey key = keys[a];
keys[a] = keys[b];
keys[b] = key;
TValue value = values[a];
values[a] = values[b];
values[b] = value;
}
}
}
private static void Swap(TKey[] keys, TValue[] values, int i, int j)
{
if (i != j)
{
TKey k = keys[i];
keys[i] = keys[j];
keys[j] = k;
TValue v = values[i];
values[i] = values[j];
values[j] = v;
}
}
internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length, IComparer<TKey> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(left >= 0);
Debug.Assert(length >= 0);
Debug.Assert(length <= keys.Length);
Debug.Assert(length + left <= keys.Length);
Debug.Assert(length + left <= values.Length);
if (length < 2)
return;
IntroSort(keys, values, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length), comparer);
}
private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit, IComparer<TKey> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreaterWithItems(keys, values, comparer, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreaterWithItems(keys, values, comparer, lo, hi - 1);
SwapIfGreaterWithItems(keys, values, comparer, lo, hi);
SwapIfGreaterWithItems(keys, values, comparer, hi - 1, hi);
return;
}
InsertionSort(keys, values, lo, hi, comparer);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, values, lo, hi, comparer);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, values, lo, hi, comparer);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, values, p + 1, hi, depthLimit, comparer);
hi = p - 1;
}
}
private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreaterWithItems(keys, values, comparer, lo, middle); // swap the low with the mid point
SwapIfGreaterWithItems(keys, values, comparer, lo, hi); // swap the low with the high
SwapIfGreaterWithItems(keys, values, comparer, middle, hi); // swap the middle with the high
TKey pivot = keys[middle];
Swap(keys, values, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
while (comparer.Compare(keys[++left], pivot) < 0) ;
while (comparer.Compare(pivot, keys[--right]) < 0) ;
if (left >= right)
break;
Swap(keys, values, left, right);
}
// Put pivot in the right location.
Swap(keys, values, left, (hi - 1));
return left;
}
private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, values, i, n, lo, comparer);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, values, lo, lo + i - 1);
DownHeap(keys, values, 1, i - 1, lo, comparer);
}
}
private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo, IComparer<TKey> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(lo < keys.Length);
TKey d = keys[lo + i - 1];
TValue dValue = values[lo + i - 1];
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && comparer.Compare(keys[lo + child - 1], keys[lo + child]) < 0)
{
child++;
}
if (!(comparer.Compare(d, keys[lo + child - 1]) < 0))
break;
keys[lo + i - 1] = keys[lo + child - 1];
values[lo + i - 1] = values[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
values[lo + i - 1] = dValue;
}
private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi >= lo);
Debug.Assert(hi <= keys.Length);
int i, j;
TKey t;
TValue tValue;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
tValue = values[i + 1];
while (j >= lo && comparer.Compare(t, keys[j]) < 0)
{
keys[j + 1] = keys[j];
values[j + 1] = values[j];
j--;
}
keys[j + 1] = t;
values[j + 1] = tValue;
}
}
}
internal partial class GenericArraySortHelper<TKey, TValue>
where TKey : IComparable<TKey>
{
public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
try
{
if (comparer == null || comparer == Comparer<TKey>.Default)
{
IntrospectiveSort(keys, values, index, length);
}
else
{
ArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, index, length, comparer);
}
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, int a, int b)
{
if (a != b)
{
if (keys[a] != null && keys[a].CompareTo(keys[b]) > 0)
{
TKey key = keys[a];
keys[a] = keys[b];
keys[b] = key;
TValue value = values[a];
values[a] = values[b];
values[b] = value;
}
}
}
private static void Swap(TKey[] keys, TValue[] values, int i, int j)
{
if (i != j)
{
TKey k = keys[i];
keys[i] = keys[j];
keys[j] = k;
TValue v = values[i];
values[i] = values[j];
values[j] = v;
}
}
internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(left >= 0);
Debug.Assert(length >= 0);
Debug.Assert(length <= keys.Length);
Debug.Assert(length + left <= keys.Length);
Debug.Assert(length + left <= values.Length);
if (length < 2)
return;
IntroSort(keys, values, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length));
}
private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreaterWithItems(keys, values, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreaterWithItems(keys, values, lo, hi - 1);
SwapIfGreaterWithItems(keys, values, lo, hi);
SwapIfGreaterWithItems(keys, values, hi - 1, hi);
return;
}
InsertionSort(keys, values, lo, hi);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, values, lo, hi);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, values, lo, hi);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, values, p + 1, hi, depthLimit);
hi = p - 1;
}
}
private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreaterWithItems(keys, values, lo, middle); // swap the low with the mid point
SwapIfGreaterWithItems(keys, values, lo, hi); // swap the low with the high
SwapIfGreaterWithItems(keys, values, middle, hi); // swap the middle with the high
TKey pivot = keys[middle];
Swap(keys, values, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
if (pivot == null)
{
while (left < (hi - 1) && keys[++left] == null) ;
while (right > lo && keys[--right] != null) ;
}
else
{
while (pivot.CompareTo(keys[++left]) > 0) ;
while (pivot.CompareTo(keys[--right]) < 0) ;
}
if (left >= right)
break;
Swap(keys, values, left, right);
}
// Put pivot in the right location.
Swap(keys, values, left, (hi - 1));
return left;
}
private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, values, i, n, lo);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, values, lo, lo + i - 1);
DownHeap(keys, values, 1, i - 1, lo);
}
}
private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(lo < keys.Length);
TKey d = keys[lo + i - 1];
TValue dValue = values[lo + i - 1];
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(keys[lo + child]) < 0))
{
child++;
}
if (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(d) < 0)
break;
keys[lo + i - 1] = keys[lo + child - 1];
values[lo + i - 1] = values[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
values[lo + i - 1] = dValue;
}
private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi >= lo);
Debug.Assert(hi <= keys.Length);
int i, j;
TKey t;
TValue tValue;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
tValue = values[i + 1];
while (j >= lo && (t == null || t.CompareTo(keys[j]) < 0))
{
keys[j + 1] = keys[j];
values[j + 1] = values[j];
j--;
}
keys[j + 1] = t;
values[j + 1] = tValue;
}
}
}
#endregion
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;
using System.Web.UI.WebControls;
using Vevo.Domain;
using Vevo.Domain.Products;
using Vevo.Domain.Stores;
using Vevo.WebAppLib;
using Vevo.WebUI;
using Vevo.WebUI.Products;
public partial class AdvancedSearch : Vevo.Deluxe.WebUI.Base.BaseLicenseLanguagePage
{
#region Private
private const string _hide = "[$Hide]";
private const string _show = "[$Show]";
private IList<Category> _tableCategory;
private IList<Department> _tableDepartment;
private string _keywordText = "[$Keyword]";
private bool IsSearched
{
get
{
if (Request.QueryString["IsSearched"] == null)
return false;
else
return Convert.ToBoolean( Request.QueryString["IsSearched"] );
}
}
private string CategoryIDs
{
get
{
if (Request.QueryString["CategoryIDs"] == null)
return String.Empty;
else
return Request.QueryString["CategoryIDs"];
}
}
private string DepartmentIDs
{
get
{
if (Request.QueryString["DepartmentIDs"] == null)
return String.Empty;
else
return Request.QueryString["DepartmentIDs"];
}
}
private string ManufacturerID
{
get
{
if (Request.QueryString["ManufacturerID"] == null)
return String.Empty;
else
return Request.QueryString["ManufacturerID"];
}
}
private string Keyword
{
get
{
if (Request.QueryString["Keyword"] == null)
return String.Empty;
else
return Request.QueryString["Keyword"];
}
}
private string SearchType
{
get
{
if (Request.QueryString["Type"] == null)
return String.Empty;
else
return Request.QueryString["Type"];
}
}
private string Price1
{
get
{
if (Request.QueryString["Price1"] == null)
return String.Empty;
else
return Request.QueryString["Price1"];
}
}
private string Price2
{
get
{
if (Request.QueryString["Price2"] == null)
return String.Empty;
else
return Request.QueryString["Price2"];
}
}
private string ProductSearchType
{
get
{
if (Request.QueryString["SearchType"] == null)
return String.Empty;
else
return Request.QueryString["SearchType"];
}
}
private bool IsNewSearch
{
get
{
if (Request.QueryString["IsNewSearch"] == null)
return false;
else
return Convert.ToBoolean( Request.QueryString["IsNewSearch"] );
}
}
private IList<Vevo.Domain.Contents.ContentMenuItem> _listContentMenuItem;
private IList<Category> TableCategory
{
get
{
return _tableCategory;
}
set
{
_tableCategory = value;
}
}
private IList<Department> TableDepartment
{
get
{
return _tableDepartment;
}
set
{
_tableDepartment = value;
}
}
private int CurrentPage
{
get
{
int result;
string page = Request.QueryString["Page"];
if (String.IsNullOrEmpty( page ) ||
!int.TryParse( page, out result ))
return 1;
else
return result;
}
}
private IList<Vevo.Domain.Contents.ContentMenuItem> ListContentMenuItem
{
get
{
return _listContentMenuItem;
}
set
{
_listContentMenuItem = value;
}
}
private bool IsUseEnhanceAdvancedSearch
{
get
{
string searchMode = DataAccessContext.Configurations.GetValue( "AdvancedSearchMode", new StoreRetriever().GetStore() );
if (searchMode == "Enhance")
{
return true;
}
else
{
return false;
}
}
}
private void RefreshGrid()
{
IList<Category> categoryList = DataAccessContext.CategoryRepository.GetByParentID(
StoreContext.Culture,
DataAccessContext.Configurations.GetValue( "RootCategory", new StoreRetriever().GetStore() ),
"SortOrder",
BoolFilter.ShowTrue );
IList<Department> departmentList = DataAccessContext.DepartmentRepository.GetByParentID(
StoreContext.Culture,
DataAccessContext.Configurations.GetValue( "RootDepartment", new StoreRetriever().GetStore() ),
"SortOrder",
BoolFilter.ShowTrue );
uxCategoryList.DataSource = categoryList;
uxCategoryList.DataBind();
uxDepartmentsList.DataSource = departmentList;
uxDepartmentsList.DataBind();
if (DataAccessContext.ContentMenuRepository.GetOne(
DataAccessContext.Configurations.GetValue( "TopContentMenu" ) ).IsEnabled)
{
uxTopContentMenuItemList.DataSource = DataAccessContext.ContentMenuItemRepository.GetByContentMenuID(
StoreContext.Culture, DataAccessContext.Configurations.GetValue( "TopContentMenu" ),
"SortOrder", BoolFilter.ShowTrue );
uxTopContentMenuItemList.DataBind();
}
if (DataAccessContext.ContentMenuRepository.GetOne(
DataAccessContext.Configurations.GetValue( "LeftContentMenu" ) ).IsEnabled)
{
uxLeftContentMenuItemList.DataSource = DataAccessContext.ContentMenuItemRepository.GetByContentMenuID(
StoreContext.Culture, DataAccessContext.Configurations.GetValue( "LeftContentMenu" ),
"SortOrder", BoolFilter.ShowTrue );
uxLeftContentMenuItemList.DataBind();
}
if (DataAccessContext.ContentMenuRepository.GetOne(
DataAccessContext.Configurations.GetValue( "RightContentMenu" ) ).IsEnabled)
{
uxRightContentMenuItemList.DataSource = DataAccessContext.ContentMenuItemRepository.GetByContentMenuID
( StoreContext.Culture, DataAccessContext.Configurations.GetValue( "RightContentMenu" ),
"SortOrder", BoolFilter.ShowTrue );
uxRightContentMenuItemList.DataBind();
}
if (uxRightContentMenuItemList.Items.Count == 0 && uxLeftContentMenuItemList.Items.Count == 0 && uxTopContentMenuItemList.Items.Count == 0)
uxContentCheckPanel.Visible = false;
}
private string[] GetChildrenCategoryIDs( string id )
{
IList<Category> childList = new List<Category>();
foreach (Category category in TableCategory)
{
if (category.ParentCategoryID == id)
childList.Add( category );
}
string[] categoies = new string[childList.Count];
for (int i = 0; i < categoies.Length; i++)
categoies[i] = childList[i].CategoryID;
return categoies;
}
private string[] GetChildrenDepartmentIDs( string id )
{
IList<Department> childList = new List<Department>();
foreach (Department department in TableDepartment)
{
if (department.ParentDepartmentID == id)
childList.Add( department );
}
string[] departments = new string[childList.Count];
for (int i = 0; i < departments.Length; i++)
departments[i] = childList[i].DepartmentID;
return departments;
}
private string[] GetChildrenContentMenuItemIDs( string id )
{
Vevo.Domain.Contents.ContentMenuItem item = DataAccessContext.ContentMenuItemRepository.GetOne(
StoreContext.Culture, id );
IList<Vevo.Domain.Contents.ContentMenuItem> list = DataAccessContext.ContentMenuItemRepository.GetByContentMenuID(
StoreContext.Culture, item.ReferringMenuID, "SortOrder", BoolFilter.ShowTrue );
string[] contentmenuitems = new string[list.Count];
for (int i = 0; i < contentmenuitems.Length; i++)
contentmenuitems[i] = list[i].ContentMenuItemID;
return contentmenuitems;
}
private void GetLeafOfID( NameValueCollection leafList, string id )
{
string[] children = GetChildrenCategoryIDs( id );
if (children.Length == 0)
{
leafList[id] = id;
}
else
{
foreach (string child in children)
{
GetLeafOfID( leafList, child );
}
}
}
private void GetLeafDepartmentsID( NameValueCollection leafList, string id )
{
string[] children = GetChildrenDepartmentIDs( id );
if (children.Length == 0)
{
leafList[id] = id;
}
else
{
foreach (string child in children)
{
GetLeafDepartmentsID( leafList, child );
}
}
}
private void GetLeafOfContentMenuItemID( NameValueCollection leafList, string id )
{
string[] children = GetChildrenContentMenuItemIDs( id );
if (children.Length == 0)
{
leafList[id] = id;
}
else
{
foreach (string child in children)
{
GetLeafOfContentMenuItemID( leafList, child );
}
}
}
private void GetLeafCategoryIDs( NameValueCollection leafList, string[] categoryIDs )
{
foreach (string id in categoryIDs)
{
GetLeafOfID( leafList, id );
}
}
private void GetLeafDepartmentIDs( NameValueCollection leafList, string[] departmentIDs )
{
foreach (string id in departmentIDs)
{
GetLeafDepartmentsID( leafList, id );
}
}
private void GetLeafContentMenuItemIDs( NameValueCollection leafList, string[] checkedContentMenuItemIDs )
{
foreach (string id in checkedContentMenuItemIDs)
{
GetLeafOfContentMenuItemID( leafList, id );
}
}
private string[] GetCategoryIDCheckInGrid( DataListItem item )
{
CheckBox categoryCheck = (CheckBox) item.FindControl( "uxCategoryCheck" );
Components_CategoryCheckList categoryCheckList =
(Components_CategoryCheckList) item.FindControl( "uxCategoryCheckList" );
HiddenField id = (HiddenField) item.FindControl( "uxCategoryIDHidden" );
string[] checkedCategoryIDs;
if (!categoryCheck.Checked)
{
checkedCategoryIDs = categoryCheckList.CheckedCategoryID();
}
else
{
checkedCategoryIDs = new string[1];
checkedCategoryIDs[0] = id.Value;
}
return checkedCategoryIDs;
}
private string[] GetDepartmentIDCheckInGrid( DataListItem item )
{
CheckBox departmentCheck = (CheckBox) item.FindControl( "uxDepartmentCheck" );
Components_DepartmentCheckList departmentCheckList =
(Components_DepartmentCheckList) item.FindControl( "uxDepartmentCheckList" );
HiddenField id = (HiddenField) item.FindControl( "uxDepartmentIDHidden" );
string[] checkedDepartmentIDs;
if (!departmentCheck.Checked)
{
checkedDepartmentIDs = departmentCheckList.CheckedDepartmentID();
}
else
{
checkedDepartmentIDs = new string[1];
checkedDepartmentIDs[0] = id.Value;
}
return checkedDepartmentIDs;
}
private string[] GetContentIDCheckInGrid( DataListItem item, string checkBoxName, string checklistName, string hiddenfieldName )
{
CheckBox contentMenuItemCheck = (CheckBox) item.FindControl( checkBoxName );
Components_ContentMenuItemCheckList contentMenuItemCheckList =
(Components_ContentMenuItemCheckList) item.FindControl( checklistName );
HiddenField id = (HiddenField) item.FindControl( hiddenfieldName );
string[] checkedMenuItemContentIDs;
if (!contentMenuItemCheck.Checked)
{
checkedMenuItemContentIDs = contentMenuItemCheckList.CheckedContentMenuItemID();
}
else
{
checkedMenuItemContentIDs = new string[1];
checkedMenuItemContentIDs[0] = id.Value;
}
return checkedMenuItemContentIDs;
}
private void PopulateControls()
{
TableCategory = DataAccessContext.CategoryRepository.GetAll( StoreContext.Culture, "CategoryID" );
TableDepartment = DataAccessContext.DepartmentRepository.GetAll( StoreContext.Culture, "DepartmentID" );
ListContentMenuItem = DataAccessContext.ContentMenuItemRepository.GetAll(
StoreContext.Culture, BoolFilter.ShowTrue );
ResultSearch();
}
private void ResultSearch()
{
string categoryIDs = "";
string departmentIDs = "";
string contentMenuItemIDs = "";
string manufacturerID = "";
string keyword = HttpUtility.UrlEncode( uxKeywordText.Text );
if (uxKeywordText.Text == uxStartKeywordTextHidden.Value)
{
keyword = "";
}
if (!IsUseEnhanceAdvancedSearch)
{
NameValueCollection catleafList = new NameValueCollection();
NameValueCollection deptleafList = new NameValueCollection();
NameValueCollection leafContentMenuItemList = new NameValueCollection();
foreach (DataListItem item in uxCategoryList.Items)
{
string[] checkedCategoryIDs = GetCategoryIDCheckInGrid( item );
GetLeafCategoryIDs( catleafList, checkedCategoryIDs );
}
foreach (DataListItem item in uxDepartmentsList.Items)
{
string[] checkedDepartmentIDs = GetDepartmentIDCheckInGrid( item );
GetLeafDepartmentIDs( deptleafList, checkedDepartmentIDs );
}
string[] arCatLeafList = new string[catleafList.Count];
catleafList.CopyTo( arCatLeafList, 0 );
string[] arDeptLeafList = new string[deptleafList.Count];
deptleafList.CopyTo( arDeptLeafList, 0 );
foreach (string leaf in arCatLeafList)
categoryIDs += leaf + "+";
foreach (string leaf in arDeptLeafList)
departmentIDs += leaf + "+";
foreach (DataListItem item in uxTopContentMenuItemList.Items)
{
string[] checkedContentTopMenuItemIDs = GetContentIDCheckInGrid(
item, "uxTopContentMenuItemCheck", "uxTopContentMenuItemCheckList", "uxTopContentMenuItemIDHidden" );
GetLeafContentMenuItemIDs( leafContentMenuItemList, checkedContentTopMenuItemIDs );
}
foreach (DataListItem item in uxLeftContentMenuItemList.Items)
{
string[] checkedContentLeftMenuItemIDs = GetContentIDCheckInGrid(
item, "uxLeftContentMenuItemCheck", "uxLeftContentMenuItemCheckList", "uxLeftContentMenuItemIDHidden" );
GetLeafContentMenuItemIDs( leafContentMenuItemList, checkedContentLeftMenuItemIDs );
}
foreach (DataListItem item in uxRightContentMenuItemList.Items)
{
string[] checkedContentRightMenuItemIDs = GetContentIDCheckInGrid(
item, "uxRightContentMenuItemCheck", "uxRightContentMenuItemCheckList", "uxRightContentMenuItemIDHidden" );
GetLeafContentMenuItemIDs( leafContentMenuItemList, checkedContentRightMenuItemIDs );
}
string[] arLeafContentMenuItemList = new string[leafContentMenuItemList.Count];
leafContentMenuItemList.CopyTo( arLeafContentMenuItemList, 0 );
foreach (string contentMenuItemleaf in arLeafContentMenuItemList)
contentMenuItemIDs += contentMenuItemleaf + "+";
Response.Redirect( "AdvancedSearchResult.aspx?" +
"Type=" + uxSearchDrop.SelectedValue +
"&CategoryIDs=" + categoryIDs +
"&Keyword=" + keyword +
"&Price1=" + uxPrice1Text.Text +
"&Price2=" + uxPrice2Text.Text +
"&ContentMenuItemIDs=" + contentMenuItemIDs +
"&DepartmentIDs=" + departmentIDs +
"&ManufacturerID=" + manufacturerID +
"&SearchType=" + CheckedSearchType() +
"&IsNewSearch=" + IsUseEnhanceAdvancedSearch.ToString() );
}
else
{
categoryIDs = uxCategoryDrop.SelectedValue;
if (uxNewSearchPanel2.Visible)
{
if (DataAccessContext.Configurations.GetBoolValue( "EnableManufacturer" ))
{
manufacturerID = uxManufacturerDrop.SelectedValue;
}
if (DataAccessContext.Configurations.GetBoolValue( "DepartmentListModuleDisplay" ))
{
departmentIDs = uxDepartmentDrop.SelectedValue;
}
}
Response.Redirect( "AdvancedSearch.aspx?" +
"Type=" + uxSearchDrop.SelectedValue +
"&CategoryIDs=" + categoryIDs +
"&Keyword=" + keyword +
"&Price1=" + uxPrice1Text.Text +
"&Price2=" + uxPrice2Text.Text +
"&DepartmentIDs=" + departmentIDs +
"&ManufacturerID=" + manufacturerID +
"&SearchType=" + CheckedSearchType() +
"&IsNewSearch=" + IsUseEnhanceAdvancedSearch.ToString() +
"&IsSearched=true" );
}
}
private void RegisterSubmitButton()
{
WebUtilities.TieButton( this.Page, uxKeywordText, uxSearchImageButton );
}
private void AdvancedSearch_StoreCultureChanged( object sender, CultureEventArgs e )
{
if (!IsUseEnhanceAdvancedSearch)
{
RefreshGrid();
}
else
{
PopulateCategory();
PopulateDepartment();
PopulateManufacturer();
}
}
private void RegisterStoreEvents()
{
GetStorefrontEvents().StoreCultureChanged +=
new StorefrontEvents.CultureEventHandler( AdvancedSearch_StoreCultureChanged );
}
private string GetSearchInListDisplayText( string searchField )
{
switch (searchField)
{
case "ShortDescription":
return "Short Description";
case "LongDescription":
return "Full Description";
case "ImageSecondary":
return "Image Secondary";
case "RelatedProducts":
return "Related Products";
case "ManufacturerPartNumber":
return "Manufacturer Part Number";
case "MetaKeyword":
return "Meta Keyword";
case "MetaDescription":
return "Meta Description";
default:
return searchField;
}
}
private void SetSearchInList()
{
uxSearchTypeCheckList.Items.Clear();
string totalFieldSearch = DataAccessContext.Configurations.GetValueNoThrow( "ProductSearchBy" );
string[] searchFieldList = SplitColumn( totalFieldSearch );
foreach (string searchField in searchFieldList)
{
if (!String.IsNullOrEmpty( searchField ))
{
string displayText = GetSearchInListDisplayText( searchField );
ListItem item = new ListItem( displayText, searchField );
uxSearchTypeCheckList.Items.Add( item );
}
}
uxSearchTypeCheckList.DataBind();
}
private void SelectAllSearchType()
{
foreach (ListItem item in uxSearchTypeCheckList.Items)
{
item.Selected = true;
}
}
private string CheckedSearchType()
{
string searchType = String.Empty;
foreach (ListItem item in uxSearchTypeCheckList.Items)
{
if (item.Selected)
{
if (!String.IsNullOrEmpty( searchType ))
{
searchType += ",";
}
searchType += item.Value;
}
}
return searchType;
}
private string[] SplitColumn( string str )
{
char[] delimiter = new char[] { ',', ':', ';' };
string[] result = str.Split( delimiter );
return result;
}
private void PopulateCategory()
{
uxCategoryDrop.Items.Add( new ListItem( "All Category", "" ) );
IList<Category> categoryList = DataAccessContext.CategoryRepository.GetAllLeafCategory(
StoreContext.Culture, "ParentCategoryID" );
string currentParentID = "";
string tmpFullPath = "";
for (int i = 0; i < categoryList.Count; i++)
{
if (currentParentID != categoryList[i].ParentCategoryID)
{
tmpFullPath = categoryList[i].CreateFullCategoryPathParentOnly();
currentParentID = categoryList[i].ParentCategoryID;
}
uxCategoryDrop.Items.Add(
new ListItem( tmpFullPath + categoryList[i].Name,
categoryList[i].CategoryID ) );
}
}
private void PopulateDepartment()
{
uxDepartmentDrop.Items.Add( new ListItem( "-- Select --", "" ) );
IList<Department> departmentList = DataAccessContext.DepartmentRepository.GetAllLeafDepartment(
StoreContext.Culture, "ParentDepartmentID" );
string currentParentID = "";
string tmpFullPath = "";
for (int i = 0; i < departmentList.Count; i++)
{
if (currentParentID != departmentList[i].ParentDepartmentID)
{
tmpFullPath = departmentList[i].CreateFullDepartmentPathParentOnly();
currentParentID = departmentList[i].ParentDepartmentID;
}
uxDepartmentDrop.Items.Add(
new ListItem( tmpFullPath + departmentList[i].Name, departmentList[i].DepartmentID ) );
}
}
private void PopulateManufacturer()
{
uxManufacturerDrop.Items.Add( new ListItem( "-- Select --", "" ) );
IList<Vevo.Domain.Products.Manufacturer> manufacuterList = DataAccessContext.ManufacturerRepository.GetAll( StoreContext.Culture, BoolFilter.ShowTrue, "Name" );
for (int i = 0; i < manufacuterList.Count; i++)
{
uxManufacturerDrop.Items.Add(
new ListItem( manufacuterList[i].Name, manufacuterList[i].ManufacturerID ) );
}
}
private void RegisterScript()
{
uxKeywordText.Text = _keywordText;
uxKeywordText.Attributes.Add( "onblur", "javascript:if(this.value=='') this.value='" + _keywordText + "';" );
uxKeywordText.Attributes.Add( "onfocus", "javascript:if(this.value=='" + _keywordText + "') this.value='';" );
}
private void InitSearchView()
{
if (IsUseEnhanceAdvancedSearch)
{
uxOldAdvancedSearchDiv.Visible = false;
SetSearchInList();
PopulateCategory();
if (!DataAccessContext.Configurations.GetBoolValue( "EnableManufacturer" ) &&
!DataAccessContext.Configurations.GetBoolValue( "DepartmentListModuleDisplay" ))
{
uxNewSearchPanel2.Visible = false;
}
else
{
if (DataAccessContext.Configurations.GetBoolValue( "DepartmentListModuleDisplay" ))
{
uxDepartmentDiv.Visible = true;
PopulateDepartment();
}
if (DataAccessContext.Configurations.GetBoolValue( "EnableManufacturer" ))
{
uxManufacturerDiv.Visible = true;
if (!uxDepartmentDiv.Visible)
{
uxManufactureLabel.Attributes.Add( "class", "AdvancedSearchDepartmentLabel" );
}
PopulateManufacturer();
}
}
SetDefaultSearchValue();
}
else
{
uxOldAdvancedSearchDiv.Visible = true;
uxNewSearchPanel1.Visible = false;
uxNewSearchPanel2.Visible = false;
uxResetImageButton.Visible = false;
RefreshGrid();
}
}
private void SetDefaultSearchValue()
{
uxKeywordText.Text = String.Empty;
uxSearchDrop.SelectedIndex = 0;
uxCategoryDrop.SelectedIndex = 0;
uxDepartmentDrop.SelectedIndex = 0;
uxManufacturerDrop.SelectedIndex = 0;
SelectAllSearchType();
uxPrice1Text.Text = String.Empty;
uxPrice2Text.Text = String.Empty;
RegisterScript();
}
private void PopulateProductControl()
{
BaseProductListControl productListControl = new BaseProductListControl();
productListControl = LoadControl( String.Format(
"{0}{1}",
SystemConst.LayoutProductListPath,
DataAccessContext.Configurations.GetValue( "DefaultProductListLayout" ) ) ) as BaseProductListControl;
string[] productSearchType = DataAccessContext.Configurations.GetValueList( "ProductSearchBy" );
if (!String.IsNullOrEmpty( ProductSearchType ))
{
productSearchType = SplitColumn( ProductSearchType );
}
productListControl.ID = "uxProductList";
productListControl.DataRetriever = new DataAccessCallbacks.ProductListRetriever( GetSearchResult );
productListControl.IsSearchResult = true;
productListControl.UserDefinedParameters = new object[] {
CategoryIDs,
DepartmentIDs,
ManufacturerID,
Keyword,
Price1,
Price2,
productSearchType,
SearchType,
IsNewSearch};
uxCatalogControlPanel.Controls.Add( productListControl );
}
private IList<Product> GetSearchResult(
Culture culture,
string sortBy,
int startIndex,
int endIndex,
object[] userDefined,
out int howManyItems )
{
if (!String.IsNullOrEmpty( userDefined[0].ToString() )
|| !String.IsNullOrEmpty( userDefined[1].ToString() )
|| !String.IsNullOrEmpty( userDefined[2].ToString() )
|| !String.IsNullOrEmpty( userDefined[3].ToString() )
|| !String.IsNullOrEmpty( userDefined[4].ToString() )
|| !String.IsNullOrEmpty( userDefined[5].ToString() ))
{
if ((bool) userDefined[8])
{
return DataAccessContext.ProductRepository.AdvancedSearch(
culture,
(string) userDefined[0],
(string) userDefined[1],
(string) userDefined[2],
sortBy,
(string) userDefined[3],
(string) userDefined[4],
(string) userDefined[5],
(string[]) userDefined[6],
startIndex,
endIndex,
out howManyItems,
new StoreRetriever().GetCurrentStoreID(),
DataAccessContext.Configurations.GetValue( "RootCategory", new StoreRetriever().GetStore() ),
DataAccessContext.Configurations.GetValue( "RootDepartment", new StoreRetriever().GetStore() ),
(string) userDefined[7]
);
}
else
{
return DataAccessContext.ProductRepository.AdvancedSearch(
culture,
(string) userDefined[0],
sortBy,
(string) userDefined[3],
(string) userDefined[4],
(string) userDefined[5],
(string[]) userDefined[6],
startIndex,
endIndex,
out howManyItems,
new StoreRetriever().GetCurrentStoreID(),
DataAccessContext.Configurations.GetValue( "RootCategory", new StoreRetriever().GetStore() ),
(string) userDefined[7]
);
}
}
else
{
howManyItems = 0;
return null;
}
}
#endregion
#region Protected
protected void Page_Load( object sender, EventArgs e )
{
//check if department is disable
if (!DataAccessContext.Configurations.GetBoolValue( "DepartmentListModuleDisplay", new StoreRetriever().GetStore() )
&& !DataAccessContext.Configurations.GetBoolValue( "DepartmentHeaderMenuDisplay", new StoreRetriever().GetStore() ))
{
uxDepartmentCheckPanel.Visible = false;
}
RegisterSubmitButton();
if (!IsPostBack)
{
InitSearchView();
RegisterScript();
uxStartKeywordTextHidden.Value = _keywordText;
}
RegisterStoreEvents();
if (IsSearched)
{
uxEnhancedSearchResultPanel.Visible = true;
uxDefaultDeptTitleResult.Text = "[$HeadProduct] for \"" + Keyword + "\"";
PopulateProductControl();
}
}
protected void HideAdvancedSearchLinkButton_OnClick( object sender, EventArgs e )
{
if (IsUseEnhanceAdvancedSearch)
{
uxEnhancedSearchPanel.Visible = !uxEnhancedSearchPanel.Visible;
}
if (uxEnhancedSearchPanel.Visible)
{
uxHideAdvancedSearchLinkButton.Text = _hide;
uxHideAdvancedSearchLinkButton.CssClass = "HideAdvancedSearchLinkButton";
}
else
{
uxHideAdvancedSearchLinkButton.Text = _show;
uxHideAdvancedSearchLinkButton.CssClass = "ShowAdvancedSearchLinkButton";
}
}
protected void uxSearchImageButton_Click( object sender, EventArgs e )
{
PopulateControls();
}
protected void uxResetImageButton_Click( object sender, EventArgs e )
{
SetDefaultSearchValue();
}
protected void uxCategoryList_ItemDataBound( object sender, DataListItemEventArgs e )
{
Components_CategoryCheckList catList = (Components_CategoryCheckList) e.Item.FindControl( "uxCategoryCheckList" );
if (catList != null)
catList.refresh();
}
protected void uxDepartmentsList_ItemDataBound( object sender, DataListItemEventArgs e )
{
Components_DepartmentCheckList deptList = (Components_DepartmentCheckList) e.Item.FindControl( "uxDepartmentCheckList" );
if (deptList != null)
deptList.refresh();
}
#endregion
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AutoMoq;
using FizzWare.NBuilder;
using Moq;
using FluentValidation;
using FluentValidation.Results;
using Sample.Core.Models;
using Sample.Core.Services;
using Sample.Core.Validators;
using Sample.Web.ApiControllers;
namespace Sample.Tests.ApiControllers
{
[TestClass]
public class MembersControllerTests
{
#region Helpers/Test Initializers
private AutoMoqer Mocker { get; set; }
private Mock<IMemberService> MockService { get; set; }
private Mock<IValidator<Member>> MockValidator { get; set; }
private MembersController SubjectUnderTest { get; set; }
[TestInitialize]
public void TestInitialize()
{
Mocker = new AutoMoqer();
SubjectUnderTest = Mocker.Create<MembersController>();
SubjectUnderTest.Request = new HttpRequestMessage();
SubjectUnderTest.Configuration = new HttpConfiguration();
MockService = Mocker.GetMock<IMemberService>();
MockValidator = Mocker.GetMock<IValidator<Member>>();
}
#endregion
#region Tests - Get All
[TestMethod]
public void MembersController_Should_GetAll()
{
// arrange
var expected = Builder<Member>.CreateListOfSize(10).Build();
MockService.Setup(x => x.Get()).Returns(expected);
// act
var actual = SubjectUnderTest.GetAll();
// assert
CollectionAssert.AreEqual(expected as ICollection, actual as ICollection);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
#region Tests - Get One
[TestMethod]
public void MembersController_Should_GetOne()
{
// arrange
var expected = Builder<Member>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.Id)).Returns(expected);
// act
var result = SubjectUnderTest.Get(expected.Id);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Member actual = null;
Assert.IsTrue(response.Result.TryGetContentValue<Member>(out actual));
Assert.AreEqual(expected.Id, actual.Id);
Assert.AreEqual(expected.Name, actual.Name);
Assert.AreEqual(expected.CreatedAt, actual.CreatedAt);
Assert.AreEqual(expected.UpdatedAt, actual.UpdatedAt);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void MembersController_Should_GetOne_NotFound()
{
// arrange
var expected = Builder<Member>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.Id)).Returns(null as Member);
// act
var result = SubjectUnderTest.Get(expected.Id);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
#region Tests - Post One
[TestMethod]
public void MembersController_Should_PostOne()
{
// arrange
var expected = Builder<Member>.CreateNew().Build();
MockValidator.Setup(x => x.Validate(expected)).Returns(new ValidationResult(new ValidationFailure[0]));
MockService.Setup(x => x.Insert(expected));
// act
var result = SubjectUnderTest.Post(expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.OK);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void MembersController_Should_PostOne_BadRequest()
{
// arrange
var expected = Builder<Member>.CreateNew().Build();
MockValidator.Setup(x => x.Validate(expected)).Returns(new ValidationResult(new []{ new ValidationFailure("", "") }));
// act
var result = SubjectUnderTest.Post(expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.BadRequest);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
#region Tests - Put One
[TestMethod]
public void MembersController_Should_PutOne()
{
// arrange
var expected = Builder<Member>.CreateNew().Build();
MockValidator.Setup(x => x.Validate(expected)).Returns(new ValidationResult(new ValidationFailure[0]));
MockService.Setup(x => x.Get(expected.Id)).Returns(expected);
MockService.Setup(x => x.Update(expected));
// act
var result = SubjectUnderTest.Put(expected.Id, expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.OK);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void MembersController_Should_PutOne_BadRequest()
{
// arrange
var expected = Builder<Member>.CreateNew().Build();
MockValidator.Setup(x => x.Validate(expected)).Returns(new ValidationResult(new []{ new ValidationFailure("", "") }));
MockService.Setup(x => x.Get(expected.Id)).Returns(expected);
// act
var result = SubjectUnderTest.Put(expected.Id, expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.BadRequest);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void MembersController_Should_PutOne_NotFound()
{
// arrange
var expected = Builder<Member>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.Id)).Returns(null as Member);
// act
var result = SubjectUnderTest.Put(expected.Id, expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
#region Tests - Delete One
[TestMethod]
public void MembersController_Should_DeleteOne()
{
// arrange
var expected = Builder<Member>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.Id)).Returns(expected);
MockService.Setup(x => x.Delete(expected));
// act
var result = SubjectUnderTest.Delete(expected.Id);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.OK);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void MembersController_Should_DeleteOne_NotFound()
{
// arrange
var expected = Builder<Member>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.Id)).Returns(null as Member);
// act
var result = SubjectUnderTest.Delete(expected.Id);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
public class NcCurveAnimation : NcEffectAniBehaviour
{
private class NcComparerCurve : IComparer<NcCurveAnimation.NcInfoCurve>
{
protected static float m_fEqualRange = 0.03f;
protected static float m_fHDiv = 5f;
public int Compare(NcCurveAnimation.NcInfoCurve a, NcCurveAnimation.NcInfoCurve b)
{
float num = a.m_AniCurve.Evaluate(NcCurveAnimation.NcComparerCurve.m_fEqualRange / NcCurveAnimation.NcComparerCurve.m_fHDiv) - b.m_AniCurve.Evaluate(NcCurveAnimation.NcComparerCurve.m_fEqualRange / NcCurveAnimation.NcComparerCurve.m_fHDiv);
if (Mathf.Abs(num) < NcCurveAnimation.NcComparerCurve.m_fEqualRange)
{
num = b.m_AniCurve.Evaluate(1f - NcCurveAnimation.NcComparerCurve.m_fEqualRange / NcCurveAnimation.NcComparerCurve.m_fHDiv) - a.m_AniCurve.Evaluate(1f - NcCurveAnimation.NcComparerCurve.m_fEqualRange / NcCurveAnimation.NcComparerCurve.m_fHDiv);
if (Mathf.Abs(num) < NcCurveAnimation.NcComparerCurve.m_fEqualRange)
{
return 0;
}
}
return (int)(num * 1000f);
}
public static int GetSortGroup(NcCurveAnimation.NcInfoCurve info)
{
float num = info.m_AniCurve.Evaluate(NcCurveAnimation.NcComparerCurve.m_fEqualRange / NcCurveAnimation.NcComparerCurve.m_fHDiv);
if (num < -NcCurveAnimation.NcComparerCurve.m_fEqualRange)
{
return 1;
}
if (NcCurveAnimation.NcComparerCurve.m_fEqualRange < num)
{
return 3;
}
return 2;
}
}
[Serializable]
public class NcInfoCurve
{
public enum APPLY_TYPE
{
NONE,
POSITION,
ROTATION,
SCALE,
COLOR,
TEXTUREUV
}
protected const float m_fOverDraw = 0.2f;
public bool m_bEnabled = true;
public string m_CurveName = string.Empty;
public AnimationCurve m_AniCurve = new AnimationCurve();
public static string[] m_TypeName = new string[]
{
"None",
"Position",
"Rotation",
"Scale",
"Color",
"TextureUV"
};
public NcCurveAnimation.NcInfoCurve.APPLY_TYPE m_ApplyType = NcCurveAnimation.NcInfoCurve.APPLY_TYPE.POSITION;
public bool[] m_bApplyOption;
public bool m_bRecursively;
public float m_fValueScale;
public Vector4 m_ToColor;
public int m_nTag;
public int m_nSortGroup;
public Vector4 m_OriginalValue;
public Vector4 m_BeforeValue;
public Vector4[] m_ChildOriginalColorValues;
public Vector4[] m_ChildBeforeColorValues;
public NcInfoCurve()
{
bool[] expr_2B = new bool[4];
expr_2B[1] = true;
this.m_bApplyOption = expr_2B;
this.m_fValueScale = 1f;
this.m_ToColor = Color.white;
base..ctor();
}
public bool IsEnabled()
{
return this.m_bEnabled;
}
public void SetEnabled(bool bEnable)
{
this.m_bEnabled = bEnable;
}
public string GetCurveName()
{
return this.m_CurveName;
}
public NcCurveAnimation.NcInfoCurve GetClone()
{
NcCurveAnimation.NcInfoCurve ncInfoCurve = new NcCurveAnimation.NcInfoCurve();
ncInfoCurve.m_AniCurve = new AnimationCurve(this.m_AniCurve.keys);
ncInfoCurve.m_AniCurve.postWrapMode = this.m_AniCurve.postWrapMode;
ncInfoCurve.m_AniCurve.preWrapMode = this.m_AniCurve.preWrapMode;
ncInfoCurve.m_bEnabled = this.m_bEnabled;
ncInfoCurve.m_CurveName = this.m_CurveName;
ncInfoCurve.m_ApplyType = this.m_ApplyType;
Array.Copy(this.m_bApplyOption, ncInfoCurve.m_bApplyOption, this.m_bApplyOption.Length);
ncInfoCurve.m_fValueScale = this.m_fValueScale;
ncInfoCurve.m_bRecursively = this.m_bRecursively;
ncInfoCurve.m_ToColor = this.m_ToColor;
ncInfoCurve.m_nTag = this.m_nTag;
ncInfoCurve.m_nSortGroup = this.m_nSortGroup;
return ncInfoCurve;
}
public void CopyTo(NcCurveAnimation.NcInfoCurve target)
{
target.m_AniCurve = new AnimationCurve(this.m_AniCurve.keys);
target.m_AniCurve.postWrapMode = this.m_AniCurve.postWrapMode;
target.m_AniCurve.preWrapMode = this.m_AniCurve.preWrapMode;
target.m_bEnabled = this.m_bEnabled;
target.m_ApplyType = this.m_ApplyType;
Array.Copy(this.m_bApplyOption, target.m_bApplyOption, this.m_bApplyOption.Length);
target.m_fValueScale = this.m_fValueScale;
target.m_bRecursively = this.m_bRecursively;
target.m_ToColor = this.m_ToColor;
target.m_nTag = this.m_nTag;
target.m_nSortGroup = this.m_nSortGroup;
}
public int GetValueCount()
{
switch (this.m_ApplyType)
{
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.POSITION:
return 4;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.ROTATION:
return 4;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.SCALE:
return 3;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.COLOR:
return 4;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.TEXTUREUV:
return 2;
}
return 0;
}
public string GetValueName(int nIndex)
{
string[] array;
switch (this.m_ApplyType)
{
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.POSITION:
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.ROTATION:
array = new string[]
{
"X",
"Y",
"Z",
"World"
};
goto IL_106;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.SCALE:
array = new string[]
{
"X",
"Y",
"Z",
string.Empty
};
goto IL_106;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.COLOR:
array = new string[]
{
"R",
"G",
"B",
"A"
};
goto IL_106;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.TEXTUREUV:
array = new string[]
{
"X",
"Y",
string.Empty,
string.Empty
};
goto IL_106;
}
array = new string[]
{
string.Empty,
string.Empty,
string.Empty,
string.Empty
};
IL_106:
return array[nIndex];
}
public void SetDefaultValueScale()
{
switch (this.m_ApplyType)
{
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.POSITION:
this.m_fValueScale = 1f;
break;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.ROTATION:
this.m_fValueScale = 360f;
break;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.SCALE:
this.m_fValueScale = 1f;
break;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.TEXTUREUV:
this.m_fValueScale = 10f;
break;
}
}
public Rect GetFixedDrawRange()
{
return new Rect(-0.2f, -1.2f, 1.4f, 2.4f);
}
public Rect GetVariableDrawRange()
{
Rect result = default(Rect);
for (int i = 0; i < this.m_AniCurve.keys.Length; i++)
{
result.yMin = Mathf.Min(result.yMin, this.m_AniCurve[i].value);
result.yMax = Mathf.Max(result.yMax, this.m_AniCurve[i].value);
}
int num = 20;
for (int j = 0; j < num; j++)
{
float b = this.m_AniCurve.Evaluate((float)j / (float)num);
result.yMin = Mathf.Min(result.yMin, b);
result.yMax = Mathf.Max(result.yMax, b);
}
result.xMin = 0f;
result.xMax = 1f;
result.xMin -= result.width * 0.2f;
result.xMax += result.width * 0.2f;
result.yMin -= result.height * 0.2f;
result.yMax += result.height * 0.2f;
return result;
}
public Rect GetEditRange()
{
return new Rect(0f, -1f, 1f, 2f);
}
public void NormalizeCurveTime()
{
int i = 0;
while (i < this.m_AniCurve.keys.Length)
{
Keyframe keyframe = this.m_AniCurve[i];
float a = Mathf.Max(0f, keyframe.time);
float num = Mathf.Min(1f, Mathf.Max(a, keyframe.time));
if (num != keyframe.time)
{
Keyframe key = new Keyframe(num, keyframe.value, keyframe.inTangent, keyframe.outTangent);
this.m_AniCurve.RemoveKey(i);
i = 0;
this.m_AniCurve.AddKey(key);
}
else
{
i++;
}
}
}
}
[SerializeField]
public List<NcCurveAnimation.NcInfoCurve> m_CurveInfoList;
public float m_fDelayTime;
private bool m_fDelayTimeComplete;
public float m_fDurationTime = 0.6f;
public bool m_bAutoDestruct = true;
protected float m_fStartTime;
protected float m_fElapsedRate;
protected Transform m_Transform;
private Vector3 m_TransformScale;
private Vector3 m_TransformLocalPosition;
private Quaternion m_TransformLocalRotation;
protected string m_ColorName;
protected Material m_MainMaterial;
protected Color m_MainMaterialOriginColor;
protected string[] m_ChildColorNames;
protected Renderer[] m_ChildRenderers;
protected NcUvAnimation m_NcUvAnimation;
private bool isStarted;
private Renderer thisRenderer;
public override int GetAnimationState()
{
if (!base.enabled || !NcEffectBehaviour.IsActive(base.gameObject))
{
return -1;
}
if (0f < this.m_fDurationTime && (this.m_fStartTime == 0f || !base.IsEndAnimation()))
{
return 1;
}
return 0;
}
public override void ResetAnimation()
{
if (this.isStarted)
{
if (this.m_MainMaterial != null)
{
this.m_MainMaterial.SetColor(this.m_ColorName, this.m_MainMaterialOriginColor);
}
if (this.m_Transform != null)
{
if (this.ContainsCurve(NcCurveAnimation.NcInfoCurve.APPLY_TYPE.SCALE))
{
this.m_Transform.localScale = this.m_TransformScale;
}
this.m_Transform.localPosition = this.m_TransformLocalPosition;
this.m_Transform.localRotation = this.m_TransformLocalRotation;
}
this.m_fDelayTimeComplete = false;
this.m_fStartTime = NcEffectBehaviour.GetEngineTime();
}
if (base.gameObject != null)
{
base.gameObject.SetActive(true);
}
if (this.isStarted)
{
if (this.m_NcUvAnimation != null)
{
this.m_NcUvAnimation.ResetAnimation();
}
base.ResetAnimation();
this.InitAnimation();
if (0f < this.m_fDelayTime && base.renderer)
{
base.renderer.enabled = false;
}
}
}
public float GetRepeatedRate()
{
return this.m_fElapsedRate;
}
private void Awake()
{
this.thisRenderer = base.renderer;
}
private void Start()
{
this.isStarted = true;
this.m_fStartTime = NcEffectBehaviour.GetEngineTime();
this.InitAnimation();
if (0f < this.m_fDelayTime)
{
if (this.thisRenderer)
{
this.thisRenderer.enabled = false;
}
return;
}
base.InitAnimationTimer();
this.UpdateAnimation(0f);
}
private void LateUpdate()
{
if (this.m_fStartTime == 0f)
{
return;
}
if (!this.m_fDelayTimeComplete)
{
if (NcEffectBehaviour.GetEngineTime() < this.m_fStartTime + this.m_fDelayTime)
{
return;
}
this.m_fDelayTimeComplete = true;
base.InitAnimationTimer();
if (this.thisRenderer)
{
this.thisRenderer.enabled = true;
}
}
float time = this.m_Timer.GetTime();
float fElapsedRate = time;
if (this.m_fDurationTime != 0f)
{
fElapsedRate = time / this.m_fDurationTime;
}
this.UpdateAnimation(fElapsedRate);
}
private bool ContainsCurve(NcCurveAnimation.NcInfoCurve.APPLY_TYPE type)
{
int count = this.m_CurveInfoList.Count;
for (int i = 0; i < count; i++)
{
NcCurveAnimation.NcInfoCurve ncInfoCurve = this.m_CurveInfoList[i];
if (ncInfoCurve.m_bEnabled)
{
if (ncInfoCurve.m_ApplyType == type)
{
return true;
}
}
}
return false;
}
private void InitAnimation()
{
this.m_fElapsedRate = 0f;
this.m_Transform = base.transform;
this.m_TransformScale = this.m_Transform.localScale;
this.m_TransformLocalPosition = this.m_Transform.localPosition;
this.m_TransformLocalRotation = this.m_Transform.localRotation;
int count = this.m_CurveInfoList.Count;
for (int i = 0; i < count; i++)
{
NcCurveAnimation.NcInfoCurve ncInfoCurve = this.m_CurveInfoList[i];
if (ncInfoCurve.m_bEnabled)
{
switch (ncInfoCurve.m_ApplyType)
{
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.POSITION:
ncInfoCurve.m_OriginalValue = Vector4.zero;
ncInfoCurve.m_BeforeValue = ncInfoCurve.m_OriginalValue;
break;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.ROTATION:
ncInfoCurve.m_OriginalValue = Vector4.zero;
ncInfoCurve.m_BeforeValue = ncInfoCurve.m_OriginalValue;
break;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.SCALE:
ncInfoCurve.m_OriginalValue = this.m_Transform.localScale;
ncInfoCurve.m_BeforeValue = ncInfoCurve.m_OriginalValue;
break;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.COLOR:
if (ncInfoCurve.m_bRecursively)
{
this.m_ChildRenderers = base.transform.GetComponentsInChildren<Renderer>(true);
this.m_ChildColorNames = new string[this.m_ChildRenderers.Length];
ncInfoCurve.m_ChildOriginalColorValues = new Vector4[this.m_ChildRenderers.Length];
ncInfoCurve.m_ChildBeforeColorValues = new Vector4[this.m_ChildRenderers.Length];
for (int j = 0; j < this.m_ChildRenderers.Length; j++)
{
Renderer renderer = this.m_ChildRenderers[j];
this.m_ChildColorNames[j] = NcCurveAnimation.Ng_GetMaterialColorName(renderer.material);
if (this.m_ChildColorNames[j] != null)
{
ncInfoCurve.m_ChildOriginalColorValues[j] = renderer.material.GetColor(this.m_ChildColorNames[j]);
}
ncInfoCurve.m_ChildBeforeColorValues[j] = Vector4.zero;
}
}
else if (this.thisRenderer != null)
{
this.m_ColorName = NcCurveAnimation.Ng_GetMaterialColorName(this.thisRenderer.sharedMaterial);
if (this.m_ColorName != null)
{
ncInfoCurve.m_OriginalValue = this.thisRenderer.sharedMaterial.GetColor(this.m_ColorName);
}
ncInfoCurve.m_BeforeValue = Vector4.zero;
}
break;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.TEXTUREUV:
if (this.m_NcUvAnimation == null)
{
this.m_NcUvAnimation = base.GetComponent<NcUvAnimation>();
}
if (this.m_NcUvAnimation)
{
ncInfoCurve.m_OriginalValue = new Vector4(this.m_NcUvAnimation.m_fScrollSpeedX, this.m_NcUvAnimation.m_fScrollSpeedY, 0f, 0f);
}
ncInfoCurve.m_BeforeValue = ncInfoCurve.m_OriginalValue;
break;
}
}
}
}
private void UpdateAnimation(float fElapsedRate)
{
this.m_fElapsedRate = fElapsedRate;
int count = this.m_CurveInfoList.Count;
for (int i = 0; i < count; i++)
{
NcCurveAnimation.NcInfoCurve ncInfoCurve = this.m_CurveInfoList[i];
if (ncInfoCurve.m_bEnabled)
{
float num = ncInfoCurve.m_AniCurve.Evaluate(this.m_fElapsedRate);
if (ncInfoCurve.m_ApplyType != NcCurveAnimation.NcInfoCurve.APPLY_TYPE.COLOR)
{
num *= ncInfoCurve.m_fValueScale;
}
switch (ncInfoCurve.m_ApplyType)
{
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.POSITION:
if (ncInfoCurve.m_bApplyOption[3])
{
Vector3 zero = Vector3.zero;
zero.x = this.GetNextValue(ncInfoCurve, 0, num);
zero.y = this.GetNextValue(ncInfoCurve, 1, num);
zero.z = this.GetNextValue(ncInfoCurve, 2, num);
this.m_Transform.position += zero;
}
else
{
Vector3 zero2 = Vector3.zero;
zero2.x = this.GetNextValue(ncInfoCurve, 0, num);
zero2.y = this.GetNextValue(ncInfoCurve, 1, num);
zero2.z = this.GetNextValue(ncInfoCurve, 2, num);
this.m_Transform.localPosition += zero2;
}
break;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.ROTATION:
if (ncInfoCurve.m_bApplyOption[3])
{
this.m_Transform.rotation *= Quaternion.Euler(this.GetNextValue(ncInfoCurve, 0, num), this.GetNextValue(ncInfoCurve, 1, num), this.GetNextValue(ncInfoCurve, 2, num));
}
else
{
Quaternion rhs = Quaternion.Euler(this.GetNextValue(ncInfoCurve, 0, num), this.GetNextValue(ncInfoCurve, 1, num), this.GetNextValue(ncInfoCurve, 2, num));
this.m_Transform.localRotation *= rhs;
}
break;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.SCALE:
{
Vector3 zero3 = Vector3.zero;
zero3.x = this.GetNextScale(ncInfoCurve, 0, num);
zero3.y = this.GetNextScale(ncInfoCurve, 1, num);
zero3.z = this.GetNextScale(ncInfoCurve, 2, num);
this.m_Transform.localScale += zero3;
break;
}
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.COLOR:
if (ncInfoCurve.m_bRecursively)
{
if (this.m_ChildColorNames != null && this.m_ChildColorNames.Length >= 0)
{
for (int j = 0; j < this.m_ChildColorNames.Length; j++)
{
if (this.m_ChildColorNames[j] != null && this.m_ChildRenderers[j] != null)
{
this.SetChildMaterialColor(ncInfoCurve, num, j);
}
}
}
}
else if (this.thisRenderer != null && this.m_ColorName != null)
{
if (this.m_MainMaterial == null)
{
this.m_MainMaterial = this.thisRenderer.material;
this.m_MainMaterialOriginColor = this.m_MainMaterial.GetColor(this.m_ColorName);
}
Color color = ncInfoCurve.m_ToColor - ncInfoCurve.m_OriginalValue;
Color color2 = this.m_MainMaterial.GetColor(this.m_ColorName);
for (int k = 0; k < 4; k++)
{
int index;
int expr_325 = index = k;
float num2 = color2[index];
color2[expr_325] = num2 + this.GetNextValue(ncInfoCurve, k, color[k] * num);
}
this.m_MainMaterial.SetColor(this.m_ColorName, color2);
}
break;
case NcCurveAnimation.NcInfoCurve.APPLY_TYPE.TEXTUREUV:
if (this.m_NcUvAnimation)
{
this.m_NcUvAnimation.m_fScrollSpeedX += this.GetNextValue(ncInfoCurve, 0, num);
this.m_NcUvAnimation.m_fScrollSpeedY += this.GetNextValue(ncInfoCurve, 1, num);
}
break;
}
}
}
if (this.m_fDurationTime != 0f && 1f < this.m_fElapsedRate)
{
if (!base.IsEndAnimation())
{
base.OnEndAnimation();
}
if (this.m_bAutoDestruct)
{
base.gameObject.SetActive(false);
}
}
}
private void SetChildMaterialColor(NcCurveAnimation.NcInfoCurve curveInfo, float fValue, int arrayIndex)
{
Color color = curveInfo.m_ToColor - curveInfo.m_ChildOriginalColorValues[arrayIndex];
Color color2 = this.m_ChildRenderers[arrayIndex].material.GetColor(this.m_ChildColorNames[arrayIndex]);
for (int i = 0; i < 4; i++)
{
int index;
int expr_49 = index = i;
float num = color2[index];
color2[expr_49] = num + this.GetChildNextColorValue(curveInfo, i, color[i] * fValue, arrayIndex);
}
this.m_ChildRenderers[arrayIndex].material.SetColor(this.m_ChildColorNames[arrayIndex], color2);
}
private float GetChildNextColorValue(NcCurveAnimation.NcInfoCurve curveInfo, int nIndex, float fValue, int arrayIndex)
{
if (curveInfo.m_bApplyOption[nIndex])
{
float result = fValue - curveInfo.m_ChildBeforeColorValues[arrayIndex][nIndex];
curveInfo.m_ChildBeforeColorValues[arrayIndex][nIndex] = fValue;
return result;
}
return 0f;
}
private float GetNextValue(NcCurveAnimation.NcInfoCurve curveInfo, int nIndex, float fValue)
{
if (curveInfo.m_bApplyOption[nIndex])
{
float result = fValue - curveInfo.m_BeforeValue[nIndex];
curveInfo.m_BeforeValue[nIndex] = fValue;
return result;
}
return 0f;
}
private float GetNextScale(NcCurveAnimation.NcInfoCurve curveInfo, int nIndex, float fValue)
{
if (curveInfo.m_bApplyOption[nIndex])
{
float num = curveInfo.m_OriginalValue[nIndex] * (1f + fValue);
float result = num - curveInfo.m_BeforeValue[nIndex];
curveInfo.m_BeforeValue[nIndex] = num;
return result;
}
return 0f;
}
public float GetElapsedRate()
{
return this.m_fElapsedRate;
}
public void CopyTo(NcCurveAnimation target, bool bCurveOnly)
{
target.m_CurveInfoList = new List<NcCurveAnimation.NcInfoCurve>();
foreach (NcCurveAnimation.NcInfoCurve current in this.m_CurveInfoList)
{
target.m_CurveInfoList.Add(current.GetClone());
}
if (!bCurveOnly)
{
target.m_fDelayTime = this.m_fDelayTime;
target.m_fDurationTime = this.m_fDurationTime;
}
}
public void AppendTo(NcCurveAnimation target, bool bCurveOnly)
{
if (target.m_CurveInfoList == null)
{
target.m_CurveInfoList = new List<NcCurveAnimation.NcInfoCurve>();
}
foreach (NcCurveAnimation.NcInfoCurve current in this.m_CurveInfoList)
{
target.m_CurveInfoList.Add(current.GetClone());
}
if (!bCurveOnly)
{
target.m_fDelayTime = this.m_fDelayTime;
target.m_fDurationTime = this.m_fDurationTime;
}
}
public NcCurveAnimation.NcInfoCurve GetCurveInfo(int nIndex)
{
if (this.m_CurveInfoList == null || nIndex < 0 || this.m_CurveInfoList.Count <= nIndex)
{
return null;
}
return this.m_CurveInfoList[nIndex];
}
public NcCurveAnimation.NcInfoCurve GetCurveInfo(string curveName)
{
if (this.m_CurveInfoList == null)
{
return null;
}
foreach (NcCurveAnimation.NcInfoCurve current in this.m_CurveInfoList)
{
if (current.m_CurveName == curveName)
{
return current;
}
}
return null;
}
public NcCurveAnimation.NcInfoCurve SetCurveInfo(int nIndex, NcCurveAnimation.NcInfoCurve newInfo)
{
if (this.m_CurveInfoList == null || nIndex < 0 || this.m_CurveInfoList.Count <= nIndex)
{
return null;
}
NcCurveAnimation.NcInfoCurve result = this.m_CurveInfoList[nIndex];
this.m_CurveInfoList[nIndex] = newInfo;
return result;
}
public int AddCurveInfo()
{
NcCurveAnimation.NcInfoCurve ncInfoCurve = new NcCurveAnimation.NcInfoCurve();
ncInfoCurve.m_AniCurve = AnimationCurve.EaseInOut(0f, 0f, 1f, 0f);
ncInfoCurve.m_AniCurve.AddKey(0.5f, 0.5f);
if (this.m_CurveInfoList == null)
{
this.m_CurveInfoList = new List<NcCurveAnimation.NcInfoCurve>();
}
this.m_CurveInfoList.Add(ncInfoCurve);
return this.m_CurveInfoList.Count - 1;
}
public int AddCurveInfo(NcCurveAnimation.NcInfoCurve addCurveInfo)
{
if (this.m_CurveInfoList == null)
{
this.m_CurveInfoList = new List<NcCurveAnimation.NcInfoCurve>();
}
this.m_CurveInfoList.Add(addCurveInfo.GetClone());
return this.m_CurveInfoList.Count - 1;
}
public void DeleteCurveInfo(int nIndex)
{
if (this.m_CurveInfoList == null || nIndex < 0 || this.m_CurveInfoList.Count <= nIndex)
{
return;
}
this.m_CurveInfoList.Remove(this.m_CurveInfoList[nIndex]);
}
public void ClearAllCurveInfo()
{
if (this.m_CurveInfoList == null)
{
return;
}
this.m_CurveInfoList.Clear();
}
public int GetCurveInfoCount()
{
if (this.m_CurveInfoList == null)
{
return 0;
}
return this.m_CurveInfoList.Count;
}
public void SortCurveInfo()
{
if (this.m_CurveInfoList == null)
{
return;
}
this.m_CurveInfoList.Sort(new NcCurveAnimation.NcComparerCurve());
foreach (NcCurveAnimation.NcInfoCurve current in this.m_CurveInfoList)
{
current.m_nSortGroup = NcCurveAnimation.NcComparerCurve.GetSortGroup(current);
}
}
public bool CheckInvalidOption()
{
bool result = false;
for (int i = 0; i < this.m_CurveInfoList.Count; i++)
{
if (this.CheckInvalidOption(i))
{
result = true;
}
}
return result;
}
public bool CheckInvalidOption(int nSrcIndex)
{
NcCurveAnimation.NcInfoCurve curveInfo = this.GetCurveInfo(nSrcIndex);
return curveInfo != null && (curveInfo.m_ApplyType != NcCurveAnimation.NcInfoCurve.APPLY_TYPE.COLOR && curveInfo.m_ApplyType != NcCurveAnimation.NcInfoCurve.APPLY_TYPE.SCALE && curveInfo.m_ApplyType != NcCurveAnimation.NcInfoCurve.APPLY_TYPE.TEXTUREUV) && false;
}
public override void OnUpdateEffectSpeed(float fSpeedRate, bool bRuntime)
{
this.m_fDelayTime /= fSpeedRate;
this.m_fDurationTime /= fSpeedRate;
}
public static string Ng_GetMaterialColorName(Material mat)
{
string[] array = new string[]
{
"_Color",
"_TintColor",
"_EmisColor"
};
if (mat != null)
{
string[] array2 = array;
for (int i = 0; i < array2.Length; i++)
{
string text = array2[i];
if (mat.HasProperty(text))
{
return text;
}
}
}
return null;
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.DDF
{
using System;
using System.IO;
using System.Collections;
using NPOI.Util;
using System.Collections.Generic;
/// <summary>
/// The base abstract record from which all escher records are defined. Subclasses will need
/// to define methods for serialization/deserialization and for determining the record size.
/// @author Glen Stampoultzis
/// </summary>
abstract internal class EscherRecord : ICloneable
{
private short options;
private short recordId;
/// <summary>
/// Initializes a new instance of the <see cref="EscherRecord"/> class.
/// </summary>
public EscherRecord()
{
}
/// <summary>
/// Delegates to FillFields(byte[], int, EscherRecordFactory)
/// </summary>
/// <param name="data">The data.</param>
/// <param name="f">The f.</param>
/// <returns></returns>
public int FillFields(byte[] data, EscherRecordFactory f)
{
return FillFields(data, 0, f);
}
/// <summary>
/// The contract of this method is to deSerialize an escher record including
/// it's children.
/// </summary>
/// <param name="data">The byte array containing the Serialized escher
/// records.</param>
/// <param name="offset">The offset into the byte array.</param>
/// <param name="recordFactory">A factory for creating new escher records.</param>
/// <returns>The number of bytes written.</returns>
public abstract int FillFields(byte[] data, int offset, EscherRecordFactory recordFactory);
/// <summary>
/// Reads the 8 byte header information and populates the
/// <c>options</c>
/// and
/// <c>recordId</c>
/// records.
/// </summary>
/// <param name="data">the byte array to Read from</param>
/// <param name="offset">the offset to start Reading from</param>
/// <returns>the number of bytes remaining in this record. This</returns>
protected int ReadHeader(byte[] data, int offset)
{
EscherRecordHeader header = EscherRecordHeader.ReadHeader(data, offset);
options = header.Options;
recordId = header.RecordId;
return header.RemainingBytes;
}
/// <summary>
/// Determine whether this is a container record by inspecting the option
/// field.
/// </summary>
/// <value>
/// <c>true</c> if this instance is container record; otherwise, <c>false</c>.
/// </value>
public bool IsContainerRecord
{
get { return (options & (short)0x000f) == (short)0x000f; }
}
/// <summary>
/// Gets or sets the options field for this record. All records have one
/// </summary>
/// <value>The options.</value>
public virtual short Options
{
get { return options; }
set { this.options = value; }
}
/// <summary>
/// Serializes to a new byte array. This is done by delegating to
/// Serialize(int, byte[]);
/// </summary>
/// <returns>the Serialized record.</returns>
public byte[] Serialize()
{
byte[] retval = new byte[RecordSize];
int length=Serialize(0, retval);
return retval;
}
/// <summary>
/// Serializes to an existing byte array without serialization listener.
/// This is done by delegating to Serialize(int, byte[], EscherSerializationListener).
/// </summary>
/// <param name="offset">the offset within the data byte array.</param>
/// <param name="data">the data array to Serialize to.</param>
/// <returns>The number of bytes written.</returns>
public int Serialize(int offset, byte[] data)
{
return Serialize(offset, data, new NullEscherSerializationListener());
}
/// <summary>
/// Serializes the record to an existing byte array.
/// </summary>
/// <param name="offset">the offset within the byte array.</param>
/// <param name="data">the offset within the byte array</param>
/// <param name="listener">a listener for begin and end serialization events. This.
/// is useful because the serialization is
/// hierarchical/recursive and sometimes you need to be able
/// break into that.
/// </param>
/// <returns></returns>
public abstract int Serialize(int offset, byte[] data, EscherSerializationListener listener);
/// <summary>
/// Subclasses should effeciently return the number of bytes required to
/// Serialize the record.
/// </summary>
/// <value>number of bytes</value>
abstract public int RecordSize { get; }
/// <summary>
/// Return the current record id.
/// </summary>
/// <value>The 16 bit record id.</value>
public virtual short RecordId
{
get { return recordId; }
set { this.recordId = value; }
}
/// <summary>
/// Gets or sets the child records.
/// </summary>
/// <value>Returns the children of this record. By default this will
/// be an empty list. EscherCotainerRecord is the only record that may contain children.</value>
public virtual List<EscherRecord> ChildRecords
{
get { return new List<EscherRecord>(); }
set { throw new ArgumentException("This record does not support child records."); }
}
/// <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 object Clone()
{
throw new Exception("The class " + this.GetType().Name + " needs to define a clone method");
}
/// <summary>
/// Returns the indexed child record.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
public EscherRecord GetChild(int index)
{
return (EscherRecord)ChildRecords[index];
}
/// <summary>
/// The display methods allows escher variables to print the record names
/// according to their hierarchy.
/// </summary>
/// <param name="indent">The current indent level.</param>
public virtual void Display(int indent)
{
for (int i = 0; i < indent * 4; i++)
{
Console.Write(' ');
}
Console.WriteLine(RecordName);
}
/// <summary>
/// Gets the name of the record.
/// </summary>
/// <value>The name of the record.</value>
public abstract String RecordName { get; }
/// <summary>
/// Returns the instance part of the option record.
/// </summary>
/// <returns>The instance part of the record</returns>
public short GetInstance()
{
return (short)(options >> 4);
}
/// <summary>
/// This class Reads the standard escher header.
/// </summary>
internal class EscherRecordHeader
{
private short options;
private short recordId;
private int remainingBytes;
private EscherRecordHeader()
{
}
/// <summary>
/// Reads the header.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="offset">The off set.</param>
/// <returns></returns>
public static EscherRecordHeader ReadHeader(byte[] data, int offset)
{
EscherRecordHeader header = new EscherRecordHeader();
header.options = LittleEndian.GetShort(data, offset);
header.recordId = LittleEndian.GetShort(data, offset + 2);
header.remainingBytes = LittleEndian.GetInt(data, offset + 4);
return header;
}
/// <summary>
/// Gets the options.
/// </summary>
/// <value>The options.</value>
public short Options
{
get { return options; }
}
/// <summary>
/// Gets the record id.
/// </summary>
/// <value>The record id.</value>
public virtual short RecordId
{
get { return recordId; }
}
/// <summary>
/// Gets the remaining bytes.
/// </summary>
/// <value>The remaining bytes.</value>
public int RemainingBytes
{
get { return remainingBytes; }
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
return "EscherRecordHeader{" +
"options=" + options +
", recordId=" + recordId +
", remainingBytes=" + remainingBytes +
"}";
}
}
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace HostMe.Sdk.Model
{
/// <summary>
/// RestaurantConfiguration
/// </summary>
[DataContract]
public partial class RestaurantConfiguration : IEquatable<RestaurantConfiguration>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="RestaurantConfiguration" /> class.
/// </summary>
/// <param name="Name">Name.</param>
/// <param name="TimeZone">TimeZone.</param>
/// <param name="Address">Address.</param>
/// <param name="Password">Password.</param>
/// <param name="Created">Created.</param>
/// <param name="Settings">Settings.</param>
/// <param name="WaitingSettings">WaitingSettings.</param>
/// <param name="LoyaltySettings">LoyaltySettings.</param>
/// <param name="ReservationSettings">ReservationSettings.</param>
/// <param name="TableStates">TableStates.</param>
/// <param name="PaymentSettings">PaymentSettings.</param>
public RestaurantConfiguration(string Name = null, string TimeZone = null, string Address = null, string Password = null, DateTimeOffset? Created = null, RestaurantSettings Settings = null, WaitingSettings WaitingSettings = null, LoyaltySettings LoyaltySettings = null, ReservationSettings ReservationSettings = null, List<TableState> TableStates = null, PaymentSettings PaymentSettings = null)
{
this.Name = Name;
this.TimeZone = TimeZone;
this.Address = Address;
this.Password = Password;
this.Created = Created;
this.Settings = Settings;
this.WaitingSettings = WaitingSettings;
this.LoyaltySettings = LoyaltySettings;
this.ReservationSettings = ReservationSettings;
this.TableStates = TableStates;
this.PaymentSettings = PaymentSettings;
}
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=true)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets TimeZone
/// </summary>
[DataMember(Name="timeZone", EmitDefaultValue=true)]
public string TimeZone { get; set; }
/// <summary>
/// Gets or Sets Address
/// </summary>
[DataMember(Name="address", EmitDefaultValue=true)]
public string Address { get; set; }
/// <summary>
/// Gets or Sets Password
/// </summary>
[DataMember(Name="password", EmitDefaultValue=true)]
public string Password { get; set; }
/// <summary>
/// Gets or Sets Created
/// </summary>
[DataMember(Name="created", EmitDefaultValue=true)]
public DateTimeOffset? Created { get; set; }
/// <summary>
/// Gets or Sets Settings
/// </summary>
[DataMember(Name="settings", EmitDefaultValue=true)]
public RestaurantSettings Settings { get; set; }
/// <summary>
/// Gets or Sets WaitingSettings
/// </summary>
[DataMember(Name="waitingSettings", EmitDefaultValue=true)]
public WaitingSettings WaitingSettings { get; set; }
/// <summary>
/// Gets or Sets LoyaltySettings
/// </summary>
[DataMember(Name="loyaltySettings", EmitDefaultValue=true)]
public LoyaltySettings LoyaltySettings { get; set; }
/// <summary>
/// Gets or Sets ReservationSettings
/// </summary>
[DataMember(Name="reservationSettings", EmitDefaultValue=true)]
public ReservationSettings ReservationSettings { get; set; }
/// <summary>
/// Gets or Sets TableStates
/// </summary>
[DataMember(Name="tableStates", EmitDefaultValue=true)]
public List<TableState> TableStates { get; set; }
/// <summary>
/// Gets or Sets PaymentSettings
/// </summary>
[DataMember(Name="paymentSettings", EmitDefaultValue=true)]
public PaymentSettings PaymentSettings { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class RestaurantConfiguration {\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" TimeZone: ").Append(TimeZone).Append("\n");
sb.Append(" Address: ").Append(Address).Append("\n");
sb.Append(" Password: ").Append(Password).Append("\n");
sb.Append(" Created: ").Append(Created).Append("\n");
sb.Append(" Settings: ").Append(Settings).Append("\n");
sb.Append(" WaitingSettings: ").Append(WaitingSettings).Append("\n");
sb.Append(" LoyaltySettings: ").Append(LoyaltySettings).Append("\n");
sb.Append(" ReservationSettings: ").Append(ReservationSettings).Append("\n");
sb.Append(" TableStates: ").Append(TableStates).Append("\n");
sb.Append(" PaymentSettings: ").Append(PaymentSettings).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as RestaurantConfiguration);
}
/// <summary>
/// Returns true if RestaurantConfiguration instances are equal
/// </summary>
/// <param name="other">Instance of RestaurantConfiguration to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RestaurantConfiguration other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.TimeZone == other.TimeZone ||
this.TimeZone != null &&
this.TimeZone.Equals(other.TimeZone)
) &&
(
this.Address == other.Address ||
this.Address != null &&
this.Address.Equals(other.Address)
) &&
(
this.Password == other.Password ||
this.Password != null &&
this.Password.Equals(other.Password)
) &&
(
this.Created == other.Created ||
this.Created != null &&
this.Created.Equals(other.Created)
) &&
(
this.Settings == other.Settings ||
this.Settings != null &&
this.Settings.Equals(other.Settings)
) &&
(
this.WaitingSettings == other.WaitingSettings ||
this.WaitingSettings != null &&
this.WaitingSettings.Equals(other.WaitingSettings)
) &&
(
this.LoyaltySettings == other.LoyaltySettings ||
this.LoyaltySettings != null &&
this.LoyaltySettings.Equals(other.LoyaltySettings)
) &&
(
this.ReservationSettings == other.ReservationSettings ||
this.ReservationSettings != null &&
this.ReservationSettings.Equals(other.ReservationSettings)
) &&
(
this.TableStates == other.TableStates ||
this.TableStates != null &&
this.TableStates.SequenceEqual(other.TableStates)
) &&
(
this.PaymentSettings == other.PaymentSettings ||
this.PaymentSettings != null &&
this.PaymentSettings.Equals(other.PaymentSettings)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.TimeZone != null)
hash = hash * 59 + this.TimeZone.GetHashCode();
if (this.Address != null)
hash = hash * 59 + this.Address.GetHashCode();
if (this.Password != null)
hash = hash * 59 + this.Password.GetHashCode();
if (this.Created != null)
hash = hash * 59 + this.Created.GetHashCode();
if (this.Settings != null)
hash = hash * 59 + this.Settings.GetHashCode();
if (this.WaitingSettings != null)
hash = hash * 59 + this.WaitingSettings.GetHashCode();
if (this.LoyaltySettings != null)
hash = hash * 59 + this.LoyaltySettings.GetHashCode();
if (this.ReservationSettings != null)
hash = hash * 59 + this.ReservationSettings.GetHashCode();
if (this.TableStates != null)
hash = hash * 59 + this.TableStates.GetHashCode();
if (this.PaymentSettings != null)
hash = hash * 59 + this.PaymentSettings.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ElementAtQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// ElementAt just retrieves an element at a specific index. There is some cross-partition
/// coordination to force partitions to stop looking once a partition has found the
/// sought-after element.
/// </summary>
/// <typeparam name="TSource"></typeparam>
internal sealed class ElementAtQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource>
{
private readonly int _index; // The index that we're looking for.
private readonly bool _prematureMerge = false; // Whether to prematurely merge the input of this operator.
private readonly bool _limitsParallelism = false; // Whether this operator limits parallelism
//---------------------------------------------------------------------------------------
// Constructs a new instance of the contains search operator.
//
// Arguments:
// child - the child tree to enumerate.
// index - index we are searching for.
//
internal ElementAtQueryOperator(IEnumerable<TSource> child, int index)
: base(child)
{
Debug.Assert(child != null, "child data source cannot be null");
Debug.Assert(index >= 0, "index can't be less than 0");
_index = index;
OrdinalIndexState childIndexState = Child.OrdinalIndexState;
if (ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct))
{
_prematureMerge = true;
_limitsParallelism = childIndexState != OrdinalIndexState.Shuffled;
}
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<TSource> Open(
QuerySettings settings, bool preferStriping)
{
// We just open the child operator.
QueryResults<TSource> childQueryResults = Child.Open(settings, false);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings)
{
// If the child OOP index is not correct, reindex.
int partitionCount = inputStream.PartitionCount;
PartitionedStream<TSource, int> intKeyStream;
if (_prematureMerge)
{
intKeyStream = ExecuteAndCollectResults(inputStream, partitionCount, Child.OutputOrdered, preferStriping, settings).GetPartitionedStream();
Debug.Assert(intKeyStream.OrdinalIndexState == OrdinalIndexState.Indexable);
}
else
{
intKeyStream = (PartitionedStream<TSource, int>)(object)inputStream;
}
// Create a shared cancellation variable and then return a possibly wrapped new enumerator.
Shared<bool> resultFoundFlag = new Shared<bool>(false);
PartitionedStream<TSource, int> outputStream = new PartitionedStream<TSource, int>(
partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Correct);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new ElementAtQueryOperatorEnumerator(intKeyStream[i], _index, resultFoundFlag, settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
[ExcludeFromCodeCoverage]
internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token)
{
Debug.Fail("This method should never be called as fallback to sequential is handled in Aggregate().");
throw new NotSupportedException();
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return _limitsParallelism; }
}
/// <summary>
/// Executes the query, either sequentially or in parallel, depending on the query execution mode and
/// whether a premature merge was inserted by this ElementAt operator.
/// </summary>
/// <param name="result">result</param>
/// <param name="withDefaultValue">withDefaultValue</param>
/// <returns>whether an element with this index exists</returns>
internal bool Aggregate([MaybeNullWhen(false)] out TSource result, bool withDefaultValue)
{
// If we were to insert a premature merge before this ElementAt, and we are executing in conservative mode, run the whole query
// sequentially.
if (LimitsParallelism && SpecifiedQuerySettings.WithDefaults().ExecutionMode!.Value != ParallelExecutionMode.ForceParallelism)
{
CancellationState cancelState = SpecifiedQuerySettings.CancellationState;
if (withDefaultValue)
{
IEnumerable<TSource> childAsSequential = Child.AsSequentialQuery(cancelState.ExternalCancellationToken);
IEnumerable<TSource> childWithCancelChecks = CancellableEnumerable.Wrap(childAsSequential, cancelState.ExternalCancellationToken);
result = ExceptionAggregator.WrapEnumerable(childWithCancelChecks, cancelState).ElementAtOrDefault(_index)!;
}
else
{
IEnumerable<TSource> childAsSequential = Child.AsSequentialQuery(cancelState.ExternalCancellationToken);
IEnumerable<TSource> childWithCancelChecks = CancellableEnumerable.Wrap(childAsSequential, cancelState.ExternalCancellationToken);
result = ExceptionAggregator.WrapEnumerable(childWithCancelChecks, cancelState).ElementAt(_index);
}
return true;
}
using (IEnumerator<TSource> e = GetEnumerator(ParallelMergeOptions.FullyBuffered))
{
if (e.MoveNext())
{
TSource current = e.Current;
Debug.Assert(!e.MoveNext(), "expected enumerator to be empty");
result = current;
return true;
}
}
result = default(TSource)!;
return false;
}
//---------------------------------------------------------------------------------------
// This enumerator performs the search for the element at the specified index.
//
private class ElementAtQueryOperatorEnumerator : QueryOperatorEnumerator<TSource, int>
{
private readonly QueryOperatorEnumerator<TSource, int> _source; // The source data.
private readonly int _index; // The index of the element to seek.
private readonly Shared<bool> _resultFoundFlag; // Whether to cancel the operation.
private readonly CancellationToken _cancellationToken;
//---------------------------------------------------------------------------------------
// Instantiates a new any/all search operator.
//
internal ElementAtQueryOperatorEnumerator(QueryOperatorEnumerator<TSource, int> source,
int index, Shared<bool> resultFoundFlag,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
Debug.Assert(index >= 0);
Debug.Assert(resultFoundFlag != null);
_source = source;
_index = index;
_resultFoundFlag = resultFoundFlag;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Enumerates the entire input until the element with the specified is found or another
// partition has signaled that it found the element.
//
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TSource currentElement, ref int currentKey)
{
// Just walk the enumerator until we've found the element.
int i = 0;
while (_source.MoveNext(ref currentElement!, ref currentKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
if (_resultFoundFlag.Value)
{
// Another partition found the element.
break;
}
if (currentKey == _index)
{
// We have found the element. Cancel other searches and return true.
_resultFoundFlag.Value = true;
return true;
}
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_source != null);
_source.Dispose();
}
}
}
}
| |
// 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.Linq.Expressions.Tests
{
public static class BinaryShiftTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckByteShiftTest(bool useInterpreter)
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyByteShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableByteShiftTest(bool useInterpreter)
{
byte?[] array = { 0, 1, byte.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableByteShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckSByteShiftTest(bool useInterpreter)
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifySByteShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableSByteShiftTest(bool useInterpreter)
{
sbyte?[] array = { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableSByteShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortShiftTest(bool useInterpreter)
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyUShortShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUShortShiftTest(bool useInterpreter)
{
ushort?[] array = { 0, 1, ushort.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableUShortShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortShiftTest(bool useInterpreter)
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyShortShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableShortShiftTest(bool useInterpreter)
{
short?[] array = { 0, 1, -1, short.MinValue, short.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableShortShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntShiftTest(bool useInterpreter)
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyUIntShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUIntShiftTest(bool useInterpreter)
{
uint?[] array = { 0, 1, uint.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableUIntShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntShiftTest(bool useInterpreter)
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyIntShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableIntShiftTest(bool useInterpreter)
{
int?[] array = { 0, 1, -1, int.MinValue, int.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableIntShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongShiftTest(bool useInterpreter)
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyULongShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableULongShiftTest(bool useInterpreter)
{
ulong?[] array = { 0, 1, ulong.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableULongShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongShiftTest(bool useInterpreter)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyLongShift(array[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableLongShiftTest(bool useInterpreter)
{
long?[] array = { 0, 1, -1, long.MinValue, long.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableLongShift(array[i], useInterpreter);
}
}
#endregion
#region Test verifiers
private static int[] s_shifts = new[] { int.MinValue, -1, 0, 1, 2, 31, 32, 63, 64, int.MaxValue };
private static void VerifyByteShift(byte a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyByteShift(a, b, true, useInterpreter);
VerifyByteShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyByteShift(byte a, int b, bool left, bool useInterpreter)
{
Expression<Func<byte>> e =
Expression.Lambda<Func<byte>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(int)))
);
Func<byte> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((byte)(left ? a << b : a >> b)), f());
Expression<Func<byte?>> en =
Expression.Lambda<Func<byte?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(int?)))
);
Func<byte?> fn = en.Compile(useInterpreter);
Assert.Equal(unchecked((byte)(left ? a << b : a >> b)), fn());
}
private static void VerifyNullableByteShift(byte? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableByteShift(a, b, true, useInterpreter);
VerifyNullableByteShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableByteShift(byte? a, int b, bool left, bool useInterpreter)
{
Expression<Func<byte?>> e =
Expression.Lambda<Func<byte?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(int)))
);
Func<byte?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((byte?)(left ? a << b : a >> b)), f());
e =
Expression.Lambda<Func<byte?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(unchecked((byte?)(left ? a << b : a >> b)), f());
}
private static void VerifySByteShift(sbyte a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifySByteShift(a, b, true, useInterpreter);
VerifySByteShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifySByteShift(sbyte a, int b, bool left, bool useInterpreter)
{
Expression<Func<sbyte>> e =
Expression.Lambda<Func<sbyte>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(int)))
);
Func<sbyte> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((sbyte)(left ? a << b : a >> b)), f());
Expression<Func<sbyte?>> en =
Expression.Lambda<Func<sbyte?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(int?)))
);
Func<sbyte?> fn = en.Compile(useInterpreter);
Assert.Equal(unchecked((sbyte)(left ? a << b : a >> b)), fn());
}
private static void VerifyNullableSByteShift(sbyte? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableSByteShift(a, b, true, useInterpreter);
VerifyNullableSByteShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableSByteShift(sbyte? a, int b, bool left, bool useInterpreter)
{
Expression<Func<sbyte?>> e =
Expression.Lambda<Func<sbyte?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(int)))
);
Func<sbyte?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((sbyte?)(left ? a << b : a >> b)), f());
e =
Expression.Lambda<Func<sbyte?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(unchecked((sbyte?)(left ? a << b : a >> b)), f());
}
private static void VerifyUShortShift(ushort a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyUShortShift(a, b, true, useInterpreter);
VerifyUShortShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyUShortShift(ushort a, int b, bool left, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(int)))
);
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ushort)(left ? a << b : a >> b)), f());
Expression<Func<ushort?>> en =
Expression.Lambda<Func<ushort?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(int?)))
);
Func<ushort?> fn = en.Compile(useInterpreter);
Assert.Equal(unchecked((ushort)(left ? a << b : a >> b)), fn());
}
private static void VerifyNullableUShortShift(ushort? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableUShortShift(a, b, true, useInterpreter);
VerifyNullableUShortShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableUShortShift(ushort? a, int b, bool left, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(int)))
);
Func<ushort?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ushort?)(left ? a << b : a >> b)), f());
e =
Expression.Lambda<Func<ushort?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ushort?)(left ? a << b : a >> b)), f());
}
private static void VerifyShortShift(short a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyShortShift(a, b, true, useInterpreter);
VerifyShortShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyShortShift(short a, int b, bool left, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(int)))
);
Func<short> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((short)(left ? a << b : a >> b)), f());
Expression<Func<short?>> en =
Expression.Lambda<Func<short?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(int?)))
);
Func<short?> fn = en.Compile(useInterpreter);
Assert.Equal(unchecked((short)(left ? a << b : a >> b)), fn());
}
private static void VerifyNullableShortShift(short? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableShortShift(a, b, true, useInterpreter);
VerifyNullableShortShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableShortShift(short? a, int b, bool left, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(int)))
);
Func<short?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((short?)(left ? a << b : a >> b)), f());
e =
Expression.Lambda<Func<short?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(unchecked((short?)(left ? a << b : a >> b)), f());
}
private static void VerifyUIntShift(uint a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyUIntShift(a, b, true, useInterpreter);
VerifyUIntShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyUIntShift(uint a, int b, bool left, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(int)))
);
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
Expression<Func<uint?>> en =
Expression.Lambda<Func<uint?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(int?)))
);
Func<uint?> fn = en.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, fn());
}
private static void VerifyNullableUIntShift(uint? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableUIntShift(a, b, true, useInterpreter);
VerifyNullableUIntShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableUIntShift(uint? a, int b, bool left, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(int)))
);
Func<uint?> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
e =
Expression.Lambda<Func<uint?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
}
private static void VerifyIntShift(int a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyIntShift(a, b, true, useInterpreter);
VerifyIntShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyIntShift(int a, int b, bool left, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int)))
);
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
Expression<Func<int?>> en =
Expression.Lambda<Func<int?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int?)))
);
Func<int?> fn = en.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, fn());
}
private static void VerifyNullableIntShift(int? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableIntShift(a, b, true, useInterpreter);
VerifyNullableIntShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableIntShift(int? a, int b, bool left, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int)))
);
Func<int?> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
e =
Expression.Lambda<Func<int?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
}
private static void VerifyULongShift(ulong a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyULongShift(a, b, true, useInterpreter);
VerifyULongShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyULongShift(ulong a, int b, bool left, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(int)))
);
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
Expression<Func<ulong?>> en =
Expression.Lambda<Func<ulong?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(int?)))
);
Func<ulong?> fn = en.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, fn());
}
private static void VerifyNullableULongShift(ulong? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableULongShift(a, b, true, useInterpreter);
VerifyNullableULongShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableULongShift(ulong? a, int b, bool left, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(int)))
);
Func<ulong?> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
e =
Expression.Lambda<Func<ulong?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
}
private static void VerifyLongShift(long a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyLongShift(a, b, true, useInterpreter);
VerifyLongShift(a, b, false, useInterpreter);
}
VerifyNullShift(a, true, useInterpreter);
VerifyNullShift(a, false, useInterpreter);
}
private static void VerifyLongShift(long a, int b, bool left, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(int)))
);
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
Expression<Func<long?>> en =
Expression.Lambda<Func<long?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(int?)))
);
Func<long?> fn = en.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, fn());
}
private static void VerifyNullableLongShift(long? a, bool useInterpreter)
{
foreach (var b in s_shifts)
{
VerifyNullableLongShift(a, b, true, useInterpreter);
VerifyNullableLongShift(a, b, false, useInterpreter);
}
VerifyNullableNullShift(a, true, useInterpreter);
VerifyNullableNullShift(a, false, useInterpreter);
}
private static void VerifyNullableLongShift(long? a, int b, bool left, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(int)))
:
Expression.RightShift(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(int)))
);
Func<long?> f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
e =
Expression.Lambda<Func<long?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(int?)))
);
f = e.Compile(useInterpreter);
Assert.Equal(left ? a << b : a >> b, f());
}
private static void VerifyNullShift<T>(T a, bool left, bool useInterpreter) where T : struct
{
Expression<Func<T?>> e =
Expression.Lambda<Func<T?>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(T)),
Expression.Default(typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(T)),
Expression.Default(typeof(int?)))
);
Func<T?> f = e.Compile(useInterpreter);
Assert.Null(f());
}
private static void VerifyNullableNullShift<T>(T a, bool left, bool useInterpreter)
{
Expression<Func<T>> e =
Expression.Lambda<Func<T>>(
left
?
Expression.LeftShift(
Expression.Constant(a, typeof(T)),
Expression.Default(typeof(int?)))
:
Expression.RightShift(
Expression.Constant(a, typeof(T)),
Expression.Default(typeof(int?)))
);
Func<T> f = e.Compile(useInterpreter);
Assert.Null(f());
}
#endregion
[Fact]
public static void CannotReduceLeft()
{
Expression exp = Expression.LeftShift(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void CannotReduceRight()
{
Expression exp = Expression.RightShift(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void LeftThrowsOnLeftNull()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.LeftShift(null, Expression.Constant("")));
}
[Fact]
public static void LeftThrowsOnRightNull()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.LeftShift(Expression.Constant(""), null));
}
[Fact]
public static void RightThrowsOnLeftNull()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.RightShift(null, Expression.Constant("")));
}
[Fact]
public static void RightThrowsOnRightNull()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.RightShift(Expression.Constant(""), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void LeftThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("left", () => Expression.LeftShift(value, Expression.Constant(1)));
}
[Fact]
public static void LeftThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("right", () => Expression.LeftShift(Expression.Constant(1), value));
}
[Fact]
public static void RightThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("left", () => Expression.RightShift(value, Expression.Constant(1)));
}
[Fact]
public static void RightThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("right", () => Expression.RightShift(Expression.Constant(1), value));
}
[Fact]
public static void ToStringTest()
{
BinaryExpression e1 = Expression.LeftShift(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a << b)", e1.ToString());
BinaryExpression e2 = Expression.RightShift(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a >> b)", e2.ToString());
}
[Theory, InlineData(typeof(E)), InlineData(typeof(El)), InlineData(typeof(string))]
public static void IncorrectLHSTypes(Type type)
{
DefaultExpression lhs = Expression.Default(type);
ConstantExpression rhs = Expression.Constant(0);
Assert.Throws<InvalidOperationException>(() => Expression.LeftShift(lhs, rhs));
Assert.Throws<InvalidOperationException>(() => Expression.RightShift(lhs, rhs));
}
[Theory, InlineData(typeof(E)), InlineData(typeof(El)), InlineData(typeof(string)), InlineData(typeof(long)),
InlineData(typeof(short)), InlineData(typeof(uint))]
public static void IncorrectRHSTypes(Type type)
{
ConstantExpression lhs = Expression.Constant(0);
DefaultExpression rhs = Expression.Default(type);
Assert.Throws<InvalidOperationException>(() => Expression.LeftShift(lhs, rhs));
Assert.Throws<InvalidOperationException>(() => Expression.RightShift(lhs, rhs));
}
}
}
| |
/*******************************************************************************
// Copyright (C) 2000-2006 Microsoft Corporation. All rights reserved.
* ****************************************************************************/
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Web;
using System.Collections.Specialized;
using System.Threading;
using System.Web.Services;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using System.Security.Permissions;
using System.Security.Principal;
using System.Reflection;
#endregion
namespace System.Workflow.Activities
{
/// <summary>
/// Abstract WorkflowWebService Base class for all the Workflow's Web Service.
/// </summary>
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public abstract class WorkflowWebService : WebService
{
Type workflowType;
/// <summary>
/// Protected Constructor for the Workflow Web Service.
/// </summary>
/// <param name="workflowType"></param>
protected WorkflowWebService(Type workflowType)
{
this.workflowType = workflowType;
}
protected Object[] Invoke(Type interfaceType, String methodName, bool isActivation, Object[] parameters)
{
Guid workflowInstanceId = GetWorkflowInstanceId(ref isActivation);
WorkflowInstance wfInstance;
EventQueueName key = new EventQueueName(interfaceType, methodName);
MethodInfo mInfo = interfaceType.GetMethod(methodName);
bool responseRequired = (mInfo.ReturnType != typeof(void));
if (!responseRequired)
{
foreach (ParameterInfo parameter in mInfo.GetParameters())
{
if (parameter.ParameterType.IsByRef || parameter.IsOut)
{
responseRequired = true;
break;
}
}
}
MethodMessage methodMessage = PrepareMessage(interfaceType, methodName, parameters, responseRequired);
EventHandler<WorkflowTerminatedEventArgs> workflowTerminationHandler = null;
EventHandler<WorkflowCompletedEventArgs> workflowCompletedHandler = null;
try
{
if (isActivation)
{
wfInstance = WorkflowRuntime.CreateWorkflow(this.workflowType, null, workflowInstanceId);
SafeEnqueueItem(wfInstance, key, methodMessage);
wfInstance.Start();
}
else
{
wfInstance = WorkflowRuntime.GetWorkflow(workflowInstanceId);
SafeEnqueueItem(wfInstance, key, methodMessage);
}
bool workflowTerminated = false;
//Handler for workflow termination in b/w outstanding req-response.
workflowTerminationHandler = delegate(Object sender, WorkflowTerminatedEventArgs e)
{
if (e.WorkflowInstance.InstanceId.Equals(workflowInstanceId))
{
methodMessage.SendException(e.Exception);
workflowTerminated = true;
}
};
workflowCompletedHandler = delegate(Object sender, WorkflowCompletedEventArgs e)
{
if (e.WorkflowInstance.InstanceId.Equals(workflowInstanceId))
{
methodMessage.SendException(new ApplicationException(SR.GetString(System.Globalization.CultureInfo.CurrentCulture, SR.Error_WorkflowCompleted)));
}
};
WorkflowRuntime.WorkflowTerminated += workflowTerminationHandler;
WorkflowRuntime.WorkflowCompleted += workflowCompletedHandler;
ManualWorkflowSchedulerService scheduler = WorkflowRuntime.GetService<ManualWorkflowSchedulerService>();
if (scheduler != null)
{
scheduler.RunWorkflow(wfInstance.InstanceId);
}
if (!responseRequired)
{
// no ret, out or ref
return new Object[] { };
}
IMethodResponseMessage response = methodMessage.WaitForResponseMessage();
if (response.Exception != null)
{
if (!workflowTerminated)
throw response.Exception;
else
throw new ApplicationException(SR.GetString(System.Globalization.CultureInfo.CurrentCulture, SR.Error_WorkflowTerminated), response.Exception);
}
if (response.OutArgs != null)
return ((ArrayList)response.OutArgs).ToArray();
else
return new Object[] { };
}
finally
{
if (workflowTerminationHandler != null)
WorkflowRuntime.WorkflowTerminated -= workflowTerminationHandler;
if (workflowCompletedHandler != null)
WorkflowRuntime.WorkflowCompleted -= workflowCompletedHandler;
}
}
protected WorkflowRuntime WorkflowRuntime
{
get
{
if (HttpContext.Current != null)
return WorkflowWebService.CurrentWorkflowRuntime;
return null;
}
}
#region Static Helpers
private static Guid GetWorkflowInstanceId(ref bool isActivation)
{
Guid workflowInstanceId = Guid.Empty;
Object instanceId = HttpContext.Current.Items["__WorkflowInstanceId__"];
if (instanceId == null && !isActivation)
throw new InvalidOperationException(SR.GetString(SR.Error_NoInstanceInSession));
if (instanceId != null)
{
workflowInstanceId = (Guid)instanceId;
Object isActivationContext = HttpContext.Current.Items["__IsActivationContext__"];
if (isActivationContext != null)
isActivation = (bool)isActivationContext;
else
isActivation = false;
}
else if (isActivation)
{
workflowInstanceId = Guid.NewGuid();
HttpContext.Current.Items["__WorkflowInstanceId__"] = workflowInstanceId;
}
return workflowInstanceId;
}
private static MethodMessage PrepareMessage(Type interfaceType, String operation, object[] parameters, bool responseRequired)
{
// construct IMethodMessage object
String securityIdentifier = null;
IIdentity identity = System.Threading.Thread.CurrentPrincipal.Identity;
WindowsIdentity windowsIdentity = identity as WindowsIdentity;
if (windowsIdentity != null && windowsIdentity.User != null)
securityIdentifier = windowsIdentity.User.Translate(typeof(NTAccount)).ToString();
else if (identity != null)
securityIdentifier = identity.Name;
MethodMessage msg = new MethodMessage(interfaceType, operation, parameters, securityIdentifier, responseRequired);
return msg;
}
//Back - off logic for conflicting workflow load across workflow runtime boundaries.
static void SafeEnqueueItem(WorkflowInstance instance, EventQueueName key, MethodMessage message)
{
while (true) //When Execution times out ASP.NET going to forcefully plung this request.
{
try
{
instance.EnqueueItem(key, message, null, null);
return;
}
catch (WorkflowOwnershipException)
{
WorkflowActivityTrace.Activity.TraceEvent(TraceEventType.Warning, 0, String.Format(System.Globalization.CultureInfo.InvariantCulture, "Workflow Web Host Encountered Workflow Instance Ownership conflict for instanceid {0}.", instance.InstanceId));
//Back-off for 1/2 sec. Should we make this configurable?
System.Threading.Thread.Sleep(500);
continue;
}
}
}
#endregion
#region Singleton WorkflowRuntime Accessor
internal const string ConfigSectionName = "WorkflowRuntime";
// Double-checked locking pattern requires volatile for read/write synchronization
static volatile WorkflowRuntime wRuntime;
static Object wRuntimeSync = new Object();
internal static WorkflowRuntime CurrentWorkflowRuntime
{
get
{
if (wRuntime == null)
{
lock (wRuntimeSync)
{
if (wRuntime == null)
{
WorkflowRuntime workflowRuntimeTemp = new WorkflowRuntime(ConfigSectionName);
try
{
workflowRuntimeTemp.StartRuntime();
}
catch
{
workflowRuntimeTemp.Dispose();
throw;
}
wRuntime = workflowRuntimeTemp;
}
}
}
return wRuntime;
}
}
#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.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal abstract partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax> : IIntroduceVariableService
where TService : AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
where TExpressionSyntax : SyntaxNode
where TTypeSyntax : TExpressionSyntax
where TTypeDeclarationSyntax : SyntaxNode
where TQueryExpressionSyntax : TExpressionSyntax
{
protected abstract bool IsInNonFirstQueryClause(TExpressionSyntax expression);
protected abstract bool IsInFieldInitializer(TExpressionSyntax expression);
protected abstract bool IsInParameterInitializer(TExpressionSyntax expression);
protected abstract bool IsInConstructorInitializer(TExpressionSyntax expression);
protected abstract bool IsInAttributeArgumentInitializer(TExpressionSyntax expression);
protected abstract bool IsInExpressionBodiedMember(TExpressionSyntax expression);
protected abstract IEnumerable<SyntaxNode> GetContainingExecutableBlocks(TExpressionSyntax expression);
protected abstract IList<bool> GetInsertionIndices(TTypeDeclarationSyntax destination, CancellationToken cancellationToken);
protected abstract bool CanIntroduceVariableFor(TExpressionSyntax expression);
protected abstract bool CanReplace(TExpressionSyntax expression);
protected abstract Task<Document> IntroduceQueryLocalAsync(SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, CancellationToken cancellationToken);
protected abstract Task<Document> IntroduceLocalAsync(SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, bool isConstant, CancellationToken cancellationToken);
protected abstract Task<Tuple<Document, SyntaxNode, int>> IntroduceFieldAsync(SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, bool isConstant, CancellationToken cancellationToken);
protected virtual bool BlockOverlapsHiddenPosition(SyntaxNode block, CancellationToken cancellationToken)
{
return block.OverlapsHiddenPosition(cancellationToken);
}
public async Task<IIntroduceVariableResult> IntroduceVariableAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_IntroduceVariable, cancellationToken))
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var state = State.Generate((TService)this, semanticDocument, textSpan, cancellationToken);
if (state == null)
{
return IntroduceVariableResult.Failure;
}
var actions = await CreateActionsAsync(state, cancellationToken).ConfigureAwait(false);
if (actions.Count == 0)
{
return IntroduceVariableResult.Failure;
}
return new IntroduceVariableResult(new CodeRefactoring(null, actions));
}
}
private async Task<List<CodeAction>> CreateActionsAsync(State state, CancellationToken cancellationToken)
{
var actions = new List<CodeAction>();
if (state.InQueryContext)
{
actions.Add(CreateAction(state, allOccurrences: false, isConstant: false, isLocal: false, isQueryLocal: true));
actions.Add(CreateAction(state, allOccurrences: true, isConstant: false, isLocal: false, isQueryLocal: true));
}
else if (state.InParameterContext)
{
actions.Add(CreateAction(state, allOccurrences: false, isConstant: true, isLocal: false, isQueryLocal: false));
actions.Add(CreateAction(state, allOccurrences: true, isConstant: true, isLocal: false, isQueryLocal: false));
}
else if (state.InFieldContext)
{
actions.Add(CreateAction(state, allOccurrences: false, isConstant: state.IsConstant, isLocal: false, isQueryLocal: false));
actions.Add(CreateAction(state, allOccurrences: true, isConstant: state.IsConstant, isLocal: false, isQueryLocal: false));
}
else if (state.InConstructorInitializerContext)
{
actions.Add(CreateAction(state, allOccurrences: false, isConstant: state.IsConstant, isLocal: false, isQueryLocal: false));
actions.Add(CreateAction(state, allOccurrences: true, isConstant: state.IsConstant, isLocal: false, isQueryLocal: false));
}
else if (state.InAttributeContext)
{
actions.Add(CreateAction(state, allOccurrences: false, isConstant: true, isLocal: false, isQueryLocal: false));
actions.Add(CreateAction(state, allOccurrences: true, isConstant: true, isLocal: false, isQueryLocal: false));
}
else if (state.InBlockContext)
{
await CreateConstantFieldActionsAsync(state, actions, cancellationToken).ConfigureAwait(false);
var blocks = this.GetContainingExecutableBlocks(state.Expression);
var block = blocks.FirstOrDefault();
if (!BlockOverlapsHiddenPosition(block, cancellationToken))
{
actions.Add(CreateAction(state, allOccurrences: false, isConstant: state.IsConstant, isLocal: true, isQueryLocal: false));
if (blocks.All(b => !BlockOverlapsHiddenPosition(b, cancellationToken)))
{
actions.Add(CreateAction(state, allOccurrences: true, isConstant: state.IsConstant, isLocal: true, isQueryLocal: false));
}
}
}
else if (state.InExpressionBodiedMemberContext)
{
await CreateConstantFieldActionsAsync(state, actions, cancellationToken).ConfigureAwait(false);
actions.Add(CreateAction(state, allOccurrences: false, isConstant: state.IsConstant, isLocal: true, isQueryLocal: false));
actions.Add(CreateAction(state, allOccurrences: true, isConstant: state.IsConstant, isLocal: true, isQueryLocal: false));
}
return actions;
}
private async Task CreateConstantFieldActionsAsync(State state, List<CodeAction> actions, CancellationToken cancellationToken)
{
if (state.IsConstant &&
!state.GetSemanticMap(cancellationToken).AllReferencedSymbols.OfType<ILocalSymbol>().Any() &&
!state.GetSemanticMap(cancellationToken).AllReferencedSymbols.OfType<IParameterSymbol>().Any())
{
// If something is a constant, and it doesn't access any other locals constants,
// then we prefer to offer to generate a constant field instead of a constant
// local.
var action1 = CreateAction(state, allOccurrences: false, isConstant: true, isLocal: false, isQueryLocal: false);
if (await CanGenerateIntoContainerAsync(state, action1, cancellationToken).ConfigureAwait(false))
{
actions.Add(action1);
}
var action2 = CreateAction(state, allOccurrences: true, isConstant: true, isLocal: false, isQueryLocal: false);
if (await CanGenerateIntoContainerAsync(state, action2, cancellationToken).ConfigureAwait(false))
{
actions.Add(action2);
}
}
}
private async Task<bool> CanGenerateIntoContainerAsync(State state, CodeAction action, CancellationToken cancellationToken)
{
var result = await this.IntroduceFieldAsync(
state.Document, state.Expression,
allOccurrences: false, isConstant: state.IsConstant, cancellationToken: cancellationToken).ConfigureAwait(false);
SyntaxNode destination = result.Item2;
int insertionIndex = result.Item3;
if (!destination.OverlapsHiddenPosition(cancellationToken))
{
return true;
}
if (destination is TTypeDeclarationSyntax)
{
var insertionIndices = this.GetInsertionIndices((TTypeDeclarationSyntax)destination, cancellationToken);
if (insertionIndices != null &&
insertionIndices.Count > insertionIndex &&
insertionIndices[insertionIndex])
{
return true;
}
}
return false;
}
private CodeAction CreateAction(State state, bool allOccurrences, bool isConstant, bool isLocal, bool isQueryLocal)
{
if (allOccurrences)
{
return new IntroduceVariableAllOccurrenceCodeAction((TService)this, state.Document, state.Expression, allOccurrences, isConstant, isLocal, isQueryLocal);
}
return new IntroduceVariableCodeAction((TService)this, state.Document, state.Expression, allOccurrences, isConstant, isLocal, isQueryLocal);
}
protected static SyntaxToken GenerateUniqueFieldName(
SemanticDocument document,
TExpressionSyntax expression,
bool isConstant,
CancellationToken cancellationToken)
{
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var semanticFacts = document.Project.LanguageServices.GetService<ISemanticFactsService>();
var semanticModel = document.SemanticModel;
var baseName = semanticFacts.GenerateNameForExpression(semanticModel, expression, isConstant);
// A field can't conflict with any existing member names.
var declaringType = semanticModel.GetEnclosingNamedType(expression.SpanStart, cancellationToken);
var reservedNames = declaringType.GetMembers().Select(m => m.Name);
return syntaxFacts.ToIdentifierToken(
NameGenerator.EnsureUniqueness(baseName, reservedNames, syntaxFacts.IsCaseSensitive));
}
protected static SyntaxToken GenerateUniqueLocalName(
SemanticDocument document,
TExpressionSyntax expression,
bool isConstant,
CancellationToken cancellationToken)
{
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var semanticFacts = document.Project.LanguageServices.GetService<ISemanticFactsService>();
var semanticModel = document.SemanticModel;
var baseName = semanticFacts.GenerateNameForExpression(semanticModel, expression, capitalize: isConstant);
var reservedNames = semanticModel.LookupSymbols(expression.SpanStart).Select(s => s.Name);
return syntaxFacts.ToIdentifierToken(
NameGenerator.EnsureUniqueness(baseName, reservedNames, syntaxFacts.IsCaseSensitive));
}
protected ISet<TExpressionSyntax> FindMatches(
SemanticDocument originalDocument,
TExpressionSyntax expressionInOriginal,
SemanticDocument currentDocument,
SyntaxNode withinNodeInCurrent,
bool allOccurrences,
CancellationToken cancellationToken)
{
var syntaxFacts = currentDocument.Project.LanguageServices.GetService<ISyntaxFactsService>();
var originalSemanticModel = originalDocument.SemanticModel;
var currentSemanticModel = currentDocument.SemanticModel;
var result = new HashSet<TExpressionSyntax>();
var matches = from nodeInCurrent in withinNodeInCurrent.DescendantNodesAndSelf().OfType<TExpressionSyntax>()
where NodeMatchesExpression(originalSemanticModel, currentSemanticModel, syntaxFacts, expressionInOriginal, nodeInCurrent, allOccurrences, cancellationToken)
select nodeInCurrent;
result.AddRange(matches.OfType<TExpressionSyntax>());
return result;
}
private bool NodeMatchesExpression(
SemanticModel originalSemanticModel,
SemanticModel currentSemanticModel,
ISyntaxFactsService syntaxFacts,
TExpressionSyntax expressionInOriginal,
TExpressionSyntax nodeInCurrent,
bool allOccurrences,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (nodeInCurrent == expressionInOriginal)
{
return true;
}
else
{
if (allOccurrences &&
this.CanReplace(nodeInCurrent))
{
return SemanticEquivalence.AreSemanticallyEquivalent(
originalSemanticModel, currentSemanticModel, expressionInOriginal, nodeInCurrent);
}
}
return false;
}
protected TNode Rewrite<TNode>(
SemanticDocument originalDocument,
TExpressionSyntax expressionInOriginal,
TExpressionSyntax variableName,
SemanticDocument currentDocument,
TNode withinNodeInCurrent,
bool allOccurrences,
CancellationToken cancellationToken)
where TNode : SyntaxNode
{
var syntaxFacts = originalDocument.Project.LanguageServices.GetService<ISyntaxFactsService>();
var matches = FindMatches(originalDocument, expressionInOriginal, currentDocument, withinNodeInCurrent, allOccurrences, cancellationToken);
// Parenthesize the variable, and go and replace anything we find with it.
// NOTE: we do not want elastic trivia as we want to just replace the existing code
// as is, while preserving the trivia there. We do not want to update it.
var replacement = syntaxFacts.Parenthesize(variableName, includeElasticTrivia: false)
.WithAdditionalAnnotations(Formatter.Annotation);
return RewriteCore(withinNodeInCurrent, replacement, matches);
}
protected abstract TNode RewriteCore<TNode>(
TNode node,
SyntaxNode replacementNode,
ISet<TExpressionSyntax> matches)
where TNode : SyntaxNode;
protected static ITypeSymbol GetTypeSymbol(
SemanticDocument document,
TExpressionSyntax expression,
CancellationToken cancellationToken,
bool objectAsDefault = true)
{
var semanticModel = document.SemanticModel;
var typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken);
if (typeInfo.Type != null)
{
return typeInfo.Type;
}
if (typeInfo.ConvertedType != null)
{
return typeInfo.ConvertedType;
}
if (objectAsDefault)
{
return semanticModel.Compilation.GetSpecialType(SpecialType.System_Object);
}
return null;
}
protected static IEnumerable<IParameterSymbol> GetAnonymousMethodParameters(
SemanticDocument document, TExpressionSyntax expression, CancellationToken cancellationToken)
{
var semanticModel = document.SemanticModel;
var semanticMap = semanticModel.GetSemanticMap(expression, cancellationToken);
var anonymousMethodParameters = semanticMap.AllReferencedSymbols
.OfType<IParameterSymbol>()
.Where(p => p.ContainingSymbol.IsAnonymousFunction());
return anonymousMethodParameters;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields", Scope = "type", Target = "System.ComponentModel.EventDescriptorCollection")]
namespace System.ComponentModel
{
/// <summary>
/// <para>
/// Represents a collection of events.
/// </para>
/// </summary>
public class EventDescriptorCollection : ICollection, IList
{
private EventDescriptor[] _events;
private string[] _namedSort;
private readonly IComparer _comparer;
private bool _eventsOwned;
private bool _needSort = false;
private int _eventCount;
private readonly bool _readOnly = false;
/// <summary>
/// An empty AttributeCollection that can used instead of creating a new one with no items.
/// </summary>
public static readonly EventDescriptorCollection Empty = new EventDescriptorCollection(null, true);
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.EventDescriptorCollection'/> class.
/// </para>
/// </summary>
public EventDescriptorCollection(EventDescriptor[] events)
{
_events = events;
if (events == null)
{
_events = new EventDescriptor[0];
_eventCount = 0;
}
else
{
_eventCount = _events.Length;
}
_eventsOwned = true;
}
/// <summary>
/// Initializes a new instance of an event descriptor collection, and allows you to mark the
/// collection as read-only so it cannot be modified.
/// </summary>
public EventDescriptorCollection(EventDescriptor[] events, bool readOnly) : this(events)
{
_readOnly = readOnly;
}
private EventDescriptorCollection(EventDescriptor[] events, int eventCount, string[] namedSort, IComparer comparer)
{
_eventsOwned = false;
if (namedSort != null)
{
_namedSort = (string[])namedSort.Clone();
}
_comparer = comparer;
_events = events;
_eventCount = eventCount;
_needSort = true;
}
/// <summary>
/// <para>
/// Gets the number
/// of event descriptors in the collection.
/// </para>
/// </summary>
public int Count
{
get
{
return _eventCount;
}
}
/// <summary>
/// <para>Gets the event with the specified index
/// number.</para>
/// </summary>
public virtual EventDescriptor this[int index]
{
get
{
if (index >= _eventCount)
{
throw new IndexOutOfRangeException();
}
EnsureEventsOwned();
return _events[index];
}
}
/// <summary>
/// <para>
/// Gets the event with the specified name.
/// </para>
/// </summary>
public virtual EventDescriptor this[string name]
{
get
{
return Find(name, false);
}
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public int Add(EventDescriptor value)
{
if (_readOnly)
{
throw new NotSupportedException();
}
EnsureSize(_eventCount + 1);
_events[_eventCount++] = value;
return _eventCount - 1;
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public void Clear()
{
if (_readOnly)
{
throw new NotSupportedException();
}
_eventCount = 0;
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public bool Contains(EventDescriptor value)
{
return IndexOf(value) >= 0;
}
/// <internalonly/>
void ICollection.CopyTo(Array array, int index)
{
EnsureEventsOwned();
Array.Copy(_events, 0, array, index, Count);
}
private void EnsureEventsOwned()
{
if (!_eventsOwned)
{
_eventsOwned = true;
if (_events != null)
{
EventDescriptor[] newEvents = new EventDescriptor[Count];
Array.Copy(_events, 0, newEvents, 0, Count);
_events = newEvents;
}
}
if (_needSort)
{
_needSort = false;
InternalSort(_namedSort);
}
}
private void EnsureSize(int sizeNeeded)
{
if (sizeNeeded <= _events.Length)
{
return;
}
if (_events == null || _events.Length == 0)
{
_eventCount = 0;
_events = new EventDescriptor[sizeNeeded];
return;
}
EnsureEventsOwned();
int newSize = Math.Max(sizeNeeded, _events.Length * 2);
EventDescriptor[] newEvents = new EventDescriptor[newSize];
Array.Copy(_events, 0, newEvents, 0, _eventCount);
_events = newEvents;
}
/// <summary>
/// <para>
/// Gets the description of the event with the specified
/// name
/// in the collection.
/// </para>
/// </summary>
public virtual EventDescriptor Find(string name, bool ignoreCase)
{
EventDescriptor p = null;
if (ignoreCase)
{
for (int i = 0; i < Count; i++)
{
if (String.Equals(_events[i].Name, name, StringComparison.OrdinalIgnoreCase))
{
p = _events[i];
break;
}
}
}
else
{
for (int i = 0; i < Count; i++)
{
if (String.Equals(_events[i].Name, name, StringComparison.Ordinal))
{
p = _events[i];
break;
}
}
}
return p;
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public int IndexOf(EventDescriptor value)
{
return Array.IndexOf(_events, value, 0, _eventCount);
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public void Insert(int index, EventDescriptor value)
{
if (_readOnly)
{
throw new NotSupportedException();
}
EnsureSize(_eventCount + 1);
if (index < _eventCount)
{
Array.Copy(_events, index, _events, index + 1, _eventCount - index);
}
_events[index] = value;
_eventCount++;
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public void Remove(EventDescriptor value)
{
if (_readOnly)
{
throw new NotSupportedException();
}
int index = IndexOf(value);
if (index != -1)
{
RemoveAt(index);
}
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public void RemoveAt(int index)
{
if (_readOnly)
{
throw new NotSupportedException();
}
if (index < _eventCount - 1)
{
Array.Copy(_events, index + 1, _events, index, _eventCount - index - 1);
}
_events[_eventCount - 1] = null;
_eventCount--;
}
/// <summary>
/// <para>
/// Gets an enumerator for this <see cref='System.ComponentModel.EventDescriptorCollection'/>.
/// </para>
/// </summary>
public IEnumerator GetEnumerator()
{
// we can only return an enumerator on the events we actually have...
if (_events.Length == _eventCount)
{
return _events.GetEnumerator();
}
else
{
return new ArraySubsetEnumerator(_events, _eventCount);
}
}
/// <summary>
/// <para>
/// Sorts the members of this EventDescriptorCollection, using the default sort for this collection,
/// which is usually alphabetical.
/// </para>
/// </summary>
public virtual EventDescriptorCollection Sort()
{
return new EventDescriptorCollection(_events, _eventCount, _namedSort, _comparer);
}
/// <summary>
/// <para>
/// Sorts the members of this EventDescriptorCollection. Any specified NamedSort arguments will
/// be applied first, followed by sort using the specified IComparer.
/// </para>
/// </summary>
public virtual EventDescriptorCollection Sort(string[] names)
{
return new EventDescriptorCollection(_events, _eventCount, names, _comparer);
}
/// <summary>
/// <para>
/// Sorts the members of this EventDescriptorCollection. Any specified NamedSort arguments will
/// be applied first, followed by sort using the specified IComparer.
/// </para>
/// </summary>
public virtual EventDescriptorCollection Sort(string[] names, IComparer comparer)
{
return new EventDescriptorCollection(_events, _eventCount, names, comparer);
}
/// <summary>
/// <para>
/// Sorts the members of this EventDescriptorCollection, using the specified IComparer to compare,
/// the EventDescriptors contained in the collection.
/// </para>
/// </summary>
public virtual EventDescriptorCollection Sort(IComparer comparer)
{
return new EventDescriptorCollection(_events, _eventCount, _namedSort, comparer);
}
/// <summary>
/// <para>
/// Sorts the members of this EventDescriptorCollection. Any specified NamedSort arguments will
/// be applied first, followed by sort using the specified IComparer.
/// </para>
/// </summary>
protected void InternalSort(string[] names)
{
if (_events == null || _events.Length == 0)
{
return;
}
this.InternalSort(_comparer);
if (names != null && names.Length > 0)
{
ArrayList eventArrayList = new ArrayList(_events);
int foundCount = 0;
int eventCount = _events.Length;
for (int i = 0; i < names.Length; i++)
{
for (int j = 0; j < eventCount; j++)
{
EventDescriptor currentEvent = (EventDescriptor)eventArrayList[j];
// Found a matching event. Here, we add it to our array. We also
// mark it as null in our array list so we don't add it twice later.
//
if (currentEvent != null && currentEvent.Name.Equals(names[i]))
{
_events[foundCount++] = currentEvent;
eventArrayList[j] = null;
break;
}
}
}
// At this point we have filled in the first "foundCount" number of propeties, one for each
// name in our name array. If a name didn't match, then it is ignored. Next, we must fill
// in the rest of the properties. We now have a sparse array containing the remainder, so
// it's easy.
//
for (int i = 0; i < eventCount; i++)
{
if (eventArrayList[i] != null)
{
_events[foundCount++] = (EventDescriptor)eventArrayList[i];
}
}
Debug.Assert(foundCount == eventCount, "We did not completely fill our event array");
}
}
/// <summary>
/// <para>
/// Sorts the members of this EventDescriptorCollection using the specified IComparer.
/// </para>
/// </summary>
protected void InternalSort(IComparer sorter)
{
if (sorter == null)
{
TypeDescriptor.SortDescriptorArray(this);
}
else
{
Array.Sort(_events, sorter);
}
}
/// <internalonly/>
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
/// <internalonly/>
object ICollection.SyncRoot
{
get
{
return null;
}
}
/// <internalonly/>
object IList.this[int index]
{
get
{
return this[index];
}
set
{
if (_readOnly)
{
throw new NotSupportedException();
}
if (index >= _eventCount)
{
throw new IndexOutOfRangeException();
}
EnsureEventsOwned();
_events[index] = (EventDescriptor)value;
}
}
/// <internalonly/>
int IList.Add(object value)
{
return Add((EventDescriptor)value);
}
/// <internalonly/>
bool IList.Contains(object value)
{
return Contains((EventDescriptor)value);
}
/// <internalonly/>
int IList.IndexOf(object value)
{
return IndexOf((EventDescriptor)value);
}
/// <internalonly/>
void IList.Insert(int index, object value)
{
Insert(index, (EventDescriptor)value);
}
/// <internalonly/>
void IList.Remove(object value)
{
Remove((EventDescriptor)value);
}
/// <internalonly/>
bool IList.IsReadOnly
{
get
{
return _readOnly;
}
}
/// <internalonly/>
bool IList.IsFixedSize
{
get
{
return _readOnly;
}
}
private class ArraySubsetEnumerator : IEnumerator
{
private readonly Array _array;
private readonly int _total;
private int _current;
public ArraySubsetEnumerator(Array array, int count)
{
Debug.Assert(count == 0 || array != null, "if array is null, count should be 0");
Debug.Assert(array == null || count <= array.Length, "Trying to enumerate more than the array contains");
_array = array;
_total = count;
_current = -1;
}
public bool MoveNext()
{
if (_current < _total - 1)
{
_current++;
return true;
}
else
{
return false;
}
}
public void Reset()
{
_current = -1;
}
public object Current
{
get
{
if (_current == -1)
{
throw new InvalidOperationException();
}
else
{
return _array.GetValue(_current);
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.SolutionCrawler
{
public class WorkCoordinatorTests
{
private const string SolutionCrawler = "SolutionCrawler";
[Fact]
public void RegisterService()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var registrationService = new WorkCoordinatorRegistrationService(
SpecializedCollections.EmptyEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>(),
AggregateAsynchronousOperationListener.EmptyListeners);
// register and unregister workspace to the service
registrationService.Register(workspace);
registrationService.Unregister(workspace);
}
}
[Fact, WorkItem(747226)]
public void SolutionAdded_Simple()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solutionId = SolutionId.CreateNewId();
var projectId = ProjectId.CreateNewId();
var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[]
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1")
})
});
var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void SolutionAdded_Complex()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solution));
Assert.Equal(10, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Solution_Remove()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var worker = ExecuteOperation(workspace, w => w.OnSolutionRemoved());
Assert.Equal(10, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Solution_Clear()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var worker = ExecuteOperation(workspace, w => w.ClearSolution());
Assert.Equal(10, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Solution_Reload()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var worker = ExecuteOperation(workspace, w => w.OnSolutionReloaded(solution));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Solution_Change()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solutionInfo = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solutionInfo);
WaitWaiter(workspace.ExportProvider);
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.First().DocumentIds[0];
solution = solution.RemoveDocument(documentId);
var changedSolution = solution.AddProject("P3", "P3", LanguageNames.CSharp).AddDocument("D1", "").Project.Solution;
var worker = ExecuteOperation(workspace, w => w.ChangeSolution(changedSolution));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Project_Add()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var projectId = ProjectId.CreateNewId();
var projectInfo = ProjectInfo.Create(
projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
documents: new List<DocumentInfo>
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2")
});
var worker = ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo));
Assert.Equal(2, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Project_Remove()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var projectid = workspace.CurrentSolution.ProjectIds[0];
var worker = ExecuteOperation(workspace, w => w.OnProjectRemoved(projectid));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Project_Change()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solutionInfo = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solutionInfo);
WaitWaiter(workspace.ExportProvider);
var project = workspace.CurrentSolution.Projects.First();
var documentId = project.DocumentIds[0];
var solution = workspace.CurrentSolution.RemoveDocument(documentId);
var worker = ExecuteOperation(workspace, w => w.ChangeProject(project.Id, solution));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(1, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Project_Reload()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var project = solution.Projects[0];
var worker = ExecuteOperation(workspace, w => w.OnProjectReloaded(project));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Document_Add()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var project = solution.Projects[0];
var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6");
var worker = ExecuteOperation(workspace, w => w.OnDocumentAdded(info));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(6, worker.DocumentIds.Count);
}
}
[Fact]
public void Document_Remove()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var worker = ExecuteOperation(workspace, w => w.OnDocumentRemoved(id));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(4, worker.DocumentIds.Count);
Assert.Equal(1, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Document_Reload()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = solution.Projects[0].Documents[0];
var worker = ExecuteOperation(workspace, w => w.OnDocumentReloaded(id));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Document_Reanalyze()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var info = solution.Projects[0].Documents[0];
var worker = new Analyzer();
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler);
var service = new WorkCoordinatorRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
// don't rely on background parser to have tree. explicitly do it here.
TouchEverything(workspace.CurrentSolution);
service.Reanalyze(workspace, worker, projectIds: null, documentIds: SpecializedCollections.SingletonEnumerable<DocumentId>(info.Id));
TouchEverything(workspace.CurrentSolution);
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(1, worker.DocumentIds.Count);
}
}
[WorkItem(670335)]
public void Document_Change()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var worker = ExecuteOperation(workspace, w => w.ChangeDocument(id, SourceText.From("//")));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Document_AdditionalFileChange()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var project = solution.Projects[0];
var ncfile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6");
var worker = ExecuteOperation(workspace, w => w.OnAdditionalDocumentAdded(ncfile));
Assert.Equal(5, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.DocumentIds.Count);
worker = ExecuteOperation(workspace, w => w.ChangeAdditionalDocument(ncfile.Id, SourceText.From("//")));
Assert.Equal(5, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.DocumentIds.Count);
worker = ExecuteOperation(workspace, w => w.OnAdditionalDocumentRemoved(ncfile.Id));
Assert.Equal(5, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.DocumentIds.Count);
}
}
[WorkItem(670335)]
public void Document_Cancellation()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var analyzer = new Analyzer(waitForCancellation: true);
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
var service = new WorkCoordinatorRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
workspace.ChangeDocument(id, SourceText.From("//"));
analyzer.RunningEvent.Wait();
workspace.ChangeDocument(id, SourceText.From("// "));
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(5, analyzer.DocumentIds.Count);
}
}
[WorkItem(670335)]
public void Document_Cancellation_MultipleTimes()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var analyzer = new Analyzer(waitForCancellation: true);
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
var service = new WorkCoordinatorRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
workspace.ChangeDocument(id, SourceText.From("//"));
analyzer.RunningEvent.Wait();
analyzer.RunningEvent.Reset();
workspace.ChangeDocument(id, SourceText.From("// "));
analyzer.RunningEvent.Wait();
workspace.ChangeDocument(id, SourceText.From("// "));
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(5, analyzer.DocumentIds.Count);
}
}
[WorkItem(670335)]
public void Document_InvocationReasons()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var analyzer = new Analyzer(blockedRun: true);
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
var service = new WorkCoordinatorRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
// first invocation will block worker
workspace.ChangeDocument(id, SourceText.From("//"));
analyzer.RunningEvent.Wait();
var openReady = new ManualResetEventSlim(initialState: false);
var closeReady = new ManualResetEventSlim(initialState: false);
workspace.DocumentOpened += (o, e) => openReady.Set();
workspace.DocumentClosed += (o, e) => closeReady.Set();
// cause several different request to queue up
workspace.ChangeDocument(id, SourceText.From("// "));
workspace.OpenDocument(id);
workspace.CloseDocument(id);
openReady.Set();
closeReady.Set();
analyzer.BlockEvent.Set();
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(5, analyzer.DocumentIds.Count);
}
}
[Fact]
public void Document_TopLevelType_Whitespace()
{
var code = @"class C { $$ }";
var textToInsert = " ";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevelType_Character()
{
var code = @"class C { $$ }";
var textToInsert = "int";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevelType_NewLine()
{
var code = @"class C { $$ }";
var textToInsert = "\r\n";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevelType_NewLine2()
{
var code = @"class C { $$";
var textToInsert = "\r\n";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_EmptyFile()
{
var code = @"$$";
var textToInsert = "class";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevel1()
{
var code = @"class C
{
public void Test($$";
var textToInsert = "int";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevel2()
{
var code = @"class C
{
public void Test(int $$";
var textToInsert = " ";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevel3()
{
var code = @"class C
{
public void Test(int i,$$";
var textToInsert = "\r\n";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_InteriorNode1()
{
var code = @"class C
{
public void Test()
{$$";
var textToInsert = "\r\n";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_InteriorNode2()
{
var code = @"class C
{
public void Test()
{
$$
}";
var textToInsert = "int";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_InteriorNode_Field()
{
var code = @"class C
{
int i = $$
}";
var textToInsert = "1";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_InteriorNode_Field1()
{
var code = @"class C
{
int i = 1 + $$
}";
var textToInsert = "1";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_InteriorNode_Accessor()
{
var code = @"class C
{
public int A
{
get
{
$$
}
}
}";
var textToInsert = "return";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_TopLevelWhitespace()
{
var code = @"class C
{
/// $$
public int A()
{
}
}";
var textToInsert = "return";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevelWhitespace2()
{
var code = @"/// $$
class C
{
public int A()
{
}
}";
var textToInsert = "return";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_InteriorNode_Malformed()
{
var code = @"class C
{
public void Test()
{
$$";
var textToInsert = "int";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void VBPropertyTest()
{
var markup = @"Class C
Default Public Property G(x As Integer) As Integer
Get
$$
End Get
Set(value As Integer)
End Set
End Property
End Class";
int position;
string code;
MarkupTestFile.GetPosition(markup, out code, out position);
var root = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseCompilationUnit(code);
var property = root.FindToken(position).Parent.FirstAncestorOrSelf<Microsoft.CodeAnalysis.VisualBasic.Syntax.PropertyBlockSyntax>();
var memberId = (new Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxFactsService()).GetMethodLevelMemberId(root, property);
Assert.Equal(0, memberId);
}
[Fact, WorkItem(739943)]
public void SemanticChange_Propagation()
{
var solution = GetInitialSolutionInfoWithP2P();
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = solution.Projects[0].Id;
var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6");
var worker = ExecuteOperation(workspace, w => w.OnDocumentAdded(info));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(4, worker.DocumentIds.Count);
#if false
Assert.True(1 == worker.SyntaxDocumentIds.Count,
string.Format("Expected 1 SyntaxDocumentIds, Got {0}\n\n{1}", worker.SyntaxDocumentIds.Count, GetListenerTrace(workspace.ExportProvider)));
Assert.True(4 == worker.DocumentIds.Count,
string.Format("Expected 4 DocumentIds, Got {0}\n\n{1}", worker.DocumentIds.Count, GetListenerTrace(workspace.ExportProvider)));
#endif
}
}
private void InsertText(string code, string text, bool expectDocumentAnalysis, string language = LanguageNames.CSharp)
{
using (var workspace = TestWorkspaceFactory.CreateWorkspaceFromLines(
SolutionCrawler, language, compilationOptions: null, parseOptions: null, content: new string[] { code }))
{
var analyzer = new Analyzer();
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
var service = new WorkCoordinatorRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
var testDocument = workspace.Documents.First();
var insertPosition = testDocument.CursorPosition;
var textBuffer = testDocument.GetTextBuffer();
using (var edit = textBuffer.CreateEdit())
{
edit.Insert(insertPosition.Value, text);
edit.Apply();
}
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(expectDocumentAnalysis ? 1 : 0, analyzer.DocumentIds.Count);
}
}
private Analyzer ExecuteOperation(TestWorkspace workspace, Action<TestWorkspace> operation)
{
var worker = new Analyzer();
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler);
var service = new WorkCoordinatorRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
// don't rely on background parser to have tree. explicitly do it here.
TouchEverything(workspace.CurrentSolution);
operation(workspace);
TouchEverything(workspace.CurrentSolution);
Wait(service, workspace);
service.Unregister(workspace);
return worker;
}
private void TouchEverything(Solution solution)
{
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
document.GetTextAsync().PumpingWait();
document.GetSyntaxRootAsync().PumpingWait();
document.GetSemanticModelAsync().PumpingWait();
}
}
}
private void Wait(WorkCoordinatorRegistrationService service, TestWorkspace workspace)
{
WaitWaiter(workspace.ExportProvider);
service.WaitUntilCompletion_ForTestingPurposesOnly(workspace);
}
private void WaitWaiter(ExportProvider provider)
{
var workspasceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter;
workspasceWaiter.CreateWaitTask().PumpingWait();
var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter;
solutionCrawlerWaiter.CreateWaitTask().PumpingWait();
}
private static SolutionInfo GetInitialSolutionInfoWithP2P()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var projectId3 = ProjectId.CreateNewId();
var projectId4 = ProjectId.CreateNewId();
var projectId5 = ProjectId.CreateNewId();
var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1") }),
ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2") },
projectReferences: new[] { new ProjectReference(projectId1) }),
ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId3), "D3") },
projectReferences: new[] { new ProjectReference(projectId2) }),
ProjectInfo.Create(projectId4, VersionStamp.Create(), "P4", "P4", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId4), "D4") }),
ProjectInfo.Create(projectId5, VersionStamp.Create(), "P5", "P5", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId5), "D5") },
projectReferences: new[] { new ProjectReference(projectId4) }),
});
return solution;
}
private static SolutionInfo GetInitialSolutionInfo(TestWorkspace workspace)
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
return SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[]
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D2"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D3"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D4"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D5")
}),
ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
documents: new[]
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D1"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D3"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D4"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D5")
})
});
}
private IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> GetListeners(ExportProvider provider)
{
return provider.GetExports<IAsynchronousOperationListener, FeatureMetadata>();
}
[Export(typeof(IAsynchronousOperationListener))]
[Export(typeof(IAsynchronousOperationWaiter))]
[Feature(FeatureAttribute.SolutionCrawler)]
private class SolutionCrawlerWaiter : AsynchronousOperationListener { }
[Export(typeof(IAsynchronousOperationListener))]
[Export(typeof(IAsynchronousOperationWaiter))]
[Feature(FeatureAttribute.Workspace)]
private class WorkspaceWaiter : AsynchronousOperationListener { }
private class AnalyzerProvider : IIncrementalAnalyzerProvider
{
private readonly Analyzer _analyzer;
public AnalyzerProvider(Analyzer analyzer)
{
_analyzer = analyzer;
}
public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace)
{
return _analyzer;
}
}
internal class Metadata : IncrementalAnalyzerProviderMetadata
{
public Metadata(params string[] workspaceKinds)
: base(new Dictionary<string, object> { { "WorkspaceKinds", workspaceKinds }, { "HighPriorityForActiveFile", false } })
{
}
public static readonly Metadata Crawler = new Metadata(SolutionCrawler);
}
private class Analyzer : IIncrementalAnalyzer
{
private readonly bool _waitForCancellation;
private readonly bool _blockedRun;
public readonly ManualResetEventSlim BlockEvent;
public readonly ManualResetEventSlim RunningEvent;
public readonly HashSet<DocumentId> SyntaxDocumentIds = new HashSet<DocumentId>();
public readonly HashSet<DocumentId> DocumentIds = new HashSet<DocumentId>();
public readonly HashSet<ProjectId> ProjectIds = new HashSet<ProjectId>();
public readonly HashSet<DocumentId> InvalidateDocumentIds = new HashSet<DocumentId>();
public readonly HashSet<ProjectId> InvalidateProjectIds = new HashSet<ProjectId>();
public Analyzer(bool waitForCancellation = false, bool blockedRun = false)
{
_waitForCancellation = waitForCancellation;
_blockedRun = blockedRun;
this.BlockEvent = new ManualResetEventSlim(initialState: false);
this.RunningEvent = new ManualResetEventSlim(initialState: false);
}
public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
{
this.ProjectIds.Add(project.Id);
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
{
if (bodyOpt == null)
{
this.DocumentIds.Add(document.Id);
}
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
this.SyntaxDocumentIds.Add(document.Id);
Process(document.Id, cancellationToken);
return SpecializedTasks.EmptyTask;
}
public void RemoveDocument(DocumentId documentId)
{
InvalidateDocumentIds.Add(documentId);
}
public void RemoveProject(ProjectId projectId)
{
InvalidateProjectIds.Add(projectId);
}
private void Process(DocumentId documentId, CancellationToken cancellationToken)
{
if (_blockedRun && !RunningEvent.IsSet)
{
this.RunningEvent.Set();
// Wait until unblocked
this.BlockEvent.Wait();
}
if (_waitForCancellation && !RunningEvent.IsSet)
{
this.RunningEvent.Set();
cancellationToken.WaitHandle.WaitOne();
cancellationToken.ThrowIfCancellationRequested();
}
}
#region unused
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e)
{
return false;
}
#endregion
}
#if false
private string GetListenerTrace(ExportProvider provider)
{
var sb = new StringBuilder();
var workspasceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as TestAsynchronousOperationListener;
sb.AppendLine("workspace");
sb.AppendLine(workspasceWaiter.Trace());
var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as TestAsynchronousOperationListener;
sb.AppendLine("solutionCrawler");
sb.AppendLine(solutionCrawlerWaiter.Trace());
return sb.ToString();
}
internal abstract partial class TestAsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter
{
private readonly object gate = new object();
private readonly HashSet<TaskCompletionSource<bool>> pendingTasks = new HashSet<TaskCompletionSource<bool>>();
private readonly StringBuilder sb = new StringBuilder();
private int counter;
public TestAsynchronousOperationListener()
{
}
public IAsyncToken BeginAsyncOperation(string name, object tag = null)
{
lock (gate)
{
return new AsyncToken(this, name);
}
}
private void Increment(string name)
{
lock (gate)
{
sb.AppendLine("i -> " + name + ":" + counter++);
}
}
private void Decrement(string name)
{
lock (gate)
{
counter--;
if (counter == 0)
{
foreach (var task in pendingTasks)
{
task.SetResult(true);
}
pendingTasks.Clear();
}
sb.AppendLine("d -> " + name + ":" + counter);
}
}
public virtual Task CreateWaitTask()
{
lock (gate)
{
var source = new TaskCompletionSource<bool>();
if (counter == 0)
{
// There is nothing to wait for, so we are immediately done
source.SetResult(true);
}
else
{
pendingTasks.Add(source);
}
return source.Task;
}
}
public bool TrackActiveTokens { get; set; }
public bool HasPendingWork
{
get
{
return counter != 0;
}
}
private class AsyncToken : IAsyncToken
{
private readonly TestAsynchronousOperationListener listener;
private readonly string name;
private bool disposed;
public AsyncToken(TestAsynchronousOperationListener listener, string name)
{
this.listener = listener;
this.name = name;
listener.Increment(name);
}
public void Dispose()
{
lock (listener.gate)
{
if (disposed)
{
throw new InvalidOperationException("Double disposing of an async token");
}
disposed = true;
listener.Decrement(this.name);
}
}
}
public string Trace()
{
return sb.ToString();
}
}
#endif
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="HtmlTableRow.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.HtmlControls {
using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Security.Permissions;
/// <devdoc>
/// <para>
/// The <see langword='HtmlTableRow'/>
/// class defines the properties, methods, and events for the HtmlTableRow control.
/// This class allows programmatic access on the server to individual HTML
/// <tr> elements enclosed within an <see cref='System.Web.UI.HtmlControls.HtmlTable'/> control.
/// </para>
/// </devdoc>
[
ParseChildren(true, "Cells")
]
public class HtmlTableRow : HtmlContainerControl {
HtmlTableCellCollection cells;
public HtmlTableRow() : base("tr") {
}
/// <devdoc>
/// <para>
/// Gets or sets the horizontal alignment of the cells contained in an
/// <see langword='HtmlTableRow'/> control.
/// </para>
/// </devdoc>
[
WebCategory("Layout"),
DefaultValue(""),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string Align {
get {
string s = Attributes["align"];
return((s != null) ? s : String.Empty);
}
set {
Attributes["align"] = MapStringAttributeToString(value);
}
}
/*
* Collection of child TableCells.
*/
/// <devdoc>
/// <para>
/// Gets or sets the group of table cells contained within an
/// <see langword='HtmlTableRow'/> control.
/// </para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
]
public virtual HtmlTableCellCollection Cells {
get {
if (cells == null)
cells = new HtmlTableCellCollection(this);
return cells;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the background color of an <see langword='HtmlTableRow'/>
/// control.
/// </para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(""),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string BgColor {
get {
string s = Attributes["bgcolor"];
return((s != null) ? s : String.Empty);
}
set {
Attributes["bgcolor"] = MapStringAttributeToString(value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the border color of an <see langword='HtmlTableRow'/> control.
/// </para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(""),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string BorderColor {
get {
string s = Attributes["bordercolor"];
return((s != null) ? s : String.Empty);
}
set {
Attributes["bordercolor"] = MapStringAttributeToString(value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the height of an <see langword='HtmlTableRow'/> control.
/// </para>
/// </devdoc>
[
WebCategory("Layout"),
DefaultValue(""),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string Height {
get {
string s = Attributes["height"];
return((s != null) ? s : String.Empty);
}
set {
Attributes["height"] = MapStringAttributeToString(value);
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override string InnerHtml {
get {
throw new NotSupportedException(SR.GetString(SR.InnerHtml_not_supported, this.GetType().Name));
}
set {
throw new NotSupportedException(SR.GetString(SR.InnerHtml_not_supported, this.GetType().Name));
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override string InnerText {
get {
throw new NotSupportedException(SR.GetString(SR.InnerText_not_supported, this.GetType().Name));
}
set {
throw new NotSupportedException(SR.GetString(SR.InnerText_not_supported, this.GetType().Name));
}
}
/// <devdoc>
/// <para>
/// Gets or sets the vertical alignment of of the cells contained in an
/// <see langword='HtmlTableRow'/> control.
/// </para>
/// </devdoc>
[
WebCategory("Layout"),
DefaultValue(""),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string VAlign {
get {
string s = Attributes["valign"];
return((s != null) ? s : String.Empty);
}
set {
Attributes["valign"] = MapStringAttributeToString(value);
}
}
/// <internalonly/>
/// <devdoc>
/// </devdoc>
protected internal override void RenderChildren(HtmlTextWriter writer) {
writer.WriteLine();
writer.Indent++;
base.RenderChildren(writer);
writer.Indent--;
}
/// <internalonly/>
/// <devdoc>
/// </devdoc>
protected override void RenderEndTag(HtmlTextWriter writer) {
base.RenderEndTag(writer);
writer.WriteLine();
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override ControlCollection CreateControlCollection() {
return new HtmlTableCellControlCollection(this);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected class HtmlTableCellControlCollection : ControlCollection {
internal HtmlTableCellControlCollection (Control owner) : base(owner) {
}
/// <devdoc>
/// <para>Adds the specified <see cref='System.Web.UI.Control'/> object to the collection. The new control is added
/// to the end of the array.</para>
/// </devdoc>
public override void Add(Control child) {
if (child is HtmlTableCell)
base.Add(child);
else
throw new ArgumentException(SR.GetString(SR.Cannot_Have_Children_Of_Type, "HtmlTableRow", child.GetType().Name.ToString(CultureInfo.InvariantCulture))); // throw an exception here
}
/// <devdoc>
/// <para>Adds the specified <see cref='System.Web.UI.Control'/> object to the collection. The new control is added
/// to the array at the specified index location.</para>
/// </devdoc>
public override void AddAt(int index, Control child) {
if (child is HtmlTableCell)
base.AddAt(index, child);
else
throw new ArgumentException(SR.GetString(SR.Cannot_Have_Children_Of_Type, "HtmlTableRow", child.GetType().Name.ToString(CultureInfo.InvariantCulture))); // throw an exception here
}
}
}
}
| |
using Entitas;
using NSpec;
class describe_Context : nspec {
void when_created() {
IContext<TestEntity> ctx = null;
before = () => {
ctx = new MyTestContext();
};
it["increments creationIndex"] = () => {
ctx.CreateEntity().creationIndex.should_be(0);
ctx.CreateEntity().creationIndex.should_be(1);
};
it["starts with given creationIndex"] = () => {
new MyTestContext(CID.TotalComponents, 42, null).CreateEntity().creationIndex.should_be(42);
};
it["has no entities when no entities were created"] = () => {
ctx.GetEntities().should_be_empty();
};
it["gets total entity count"] = () => {
ctx.count.should_be(0);
};
it["creates entity"] = () => {
var e = ctx.CreateEntity();
e.should_not_be_null();
e.GetType().should_be(typeof(TestEntity));
e.totalComponents.should_be(ctx.totalComponents);
e.isEnabled.should_be_true();
};
it["has default ContextInfo"] = () => {
ctx.contextInfo.name.should_be("Unnamed Context");
ctx.contextInfo.componentNames.Length.should_be(CID.TotalComponents);
for (int i = 0; i < ctx.contextInfo.componentNames.Length; i++) {
ctx.contextInfo.componentNames[i].should_be("Index " + i);
}
};
it["creates component pools"] = () => {
ctx.componentPools.should_not_be_null();
ctx.componentPools.Length.should_be(CID.TotalComponents);
};
it["creates entity with component pools"] = () => {
var e = ctx.CreateEntity();
e.componentPools.should_be_same(ctx.componentPools);
};
it["can ToString"] = () => {
ctx.ToString().should_be("Unnamed Context");
};
context["when ContextInfo set"] = () => {
ContextInfo contextInfo = null;
before = () => {
var componentNames = new [] { "Health", "Position", "View" };
var componentTypes = new [] { typeof(ComponentA), typeof(ComponentB), typeof(ComponentC) };
contextInfo = new ContextInfo("My Context", componentNames, componentTypes);
ctx = new MyTestContext(componentNames.Length, 0, contextInfo);
};
it["has custom ContextInfo"] = () => {
ctx.contextInfo.should_be_same(contextInfo);
};
it["creates entity with same ContextInfo"] = () => {
ctx.CreateEntity().contextInfo.should_be_same(contextInfo);
};
it["throws when componentNames is not same length as totalComponents"] = expect<ContextInfoException>(() => {
new MyTestContext(contextInfo.componentNames.Length + 1, 0, contextInfo);
});
};
context["when entity created"] = () => {
TestEntity e = null;
before = () => {
e = ctx.CreateEntity();
e.AddComponentA();
};
it["gets total entity count"] = () => {
ctx.count.should_be(1);
};
it["has entities that were created with CreateEntity()"] = () => {
ctx.HasEntity(e).should_be_true();
};
it["doesn't have entities that were not created with CreateEntity()"] = () => {
ctx.HasEntity(this.CreateEntity()).should_be_false();
};
it["returns all created entities"] = () => {
var e2 = ctx.CreateEntity();
var entities = ctx.GetEntities();
entities.Length.should_be(2);
entities.should_contain(e);
entities.should_contain(e2);
};
it["destroys entity and removes it"] = () => {
e.Destroy();
ctx.HasEntity(e).should_be_false();
ctx.count.should_be(0);
ctx.GetEntities().should_be_empty();
};
it["destroys an entity and removes all its components"] = () => {
e.Destroy();
e.GetComponents().should_be_empty();
};
it["removes OnDestroyEntity handler"] = () => {
var didDestroy = 0;
ctx.OnEntityWillBeDestroyed += delegate {
didDestroy += 1;
};
e.Destroy();
ctx.CreateEntity().Destroy();
didDestroy.should_be(2);
};
it["destroys all entities"] = () => {
ctx.CreateEntity();
ctx.DestroyAllEntities();
ctx.HasEntity(e).should_be_false();
ctx.count.should_be(0);
ctx.GetEntities().should_be_empty();
e.GetComponents().should_be_empty();
};
it["ensures same deterministic order when getting entities after destroying all entities"] = () => {
// This is a Unity specific problem. Run Unity Test Tools with in the Entitas.Unity project
const int numEntities = 10;
for (int i = 0; i < numEntities; i++) {
ctx.CreateEntity();
}
var order1 = new int[numEntities];
var entities1 = ctx.GetEntities();
for (int i = 0; i < numEntities; i++) {
order1[i] = entities1[i].creationIndex;
}
ctx.DestroyAllEntities();
ctx.ResetCreationIndex();
for (int i = 0; i < numEntities; i++) {
ctx.CreateEntity();
}
var order2 = new int[numEntities];
var entities2 = ctx.GetEntities();
for (int i = 0; i < numEntities; i++) {
order2[i] = entities2[i].creationIndex;
}
for (int i = 0; i < numEntities; i++) {
var index1 = order1[i];
var index2 = order2[i];
index1.should_be(index2);
}
};
it["throws when destroying all entities and there are still entities retained"] = expect<ContextStillHasRetainedEntitiesException>(() => {
ctx.CreateEntity().Retain(new object());
ctx.DestroyAllEntities();
});
};
context["internal caching"] = () => {
it["caches entities"] = () => {
var entities = ctx.GetEntities();
ctx.GetEntities().should_be_same(entities);
};
it["updates entities cache when creating an entity"] = () => {
var entities = ctx.GetEntities();
ctx.CreateEntity();
ctx.GetEntities().should_not_be_same(entities);
};
it["updates entities cache when destroying an entity"] = () => {
var e = ctx.CreateEntity();
var entities = ctx.GetEntities();
e.Destroy();
ctx.GetEntities().should_not_be_same(entities);
};
};
context["events"] = () => {
var didDispatch = 0;
before = () => {
didDispatch = 0;
};
it["dispatches OnEntityCreated when creating a new entity"] = () => {
IEntity eventEntity = null;
ctx.OnEntityCreated += (c, entity) => {
didDispatch += 1;
eventEntity = entity;
c.should_be_same(ctx);
};
var e = ctx.CreateEntity();
didDispatch.should_be(1);
eventEntity.should_be_same(e);
};
it["dispatches OnEntityWillBeDestroyed when destroying an entity"] = () => {
var e = ctx.CreateEntity();
e.AddComponentA();
ctx.OnEntityWillBeDestroyed += (c, entity) => {
didDispatch += 1;
c.should_be_same(ctx);
entity.should_be_same(e);
entity.HasComponentA().should_be_true();
entity.isEnabled.should_be_true();
((IContext<TestEntity>)c).GetEntities().Length.should_be(0);
};
ctx.GetEntities();
e.Destroy();
didDispatch.should_be(1);
};
it["dispatches OnEntityDestroyed when destroying an entity"] = () => {
var e = ctx.CreateEntity();
ctx.OnEntityDestroyed += (p, entity) => {
didDispatch += 1;
p.should_be_same(ctx);
entity.should_be_same(e);
entity.HasComponentA().should_be_false();
entity.isEnabled.should_be_false();
};
e.Destroy();
didDispatch.should_be(1);
};
it["entity is released after OnEntityDestroyed"] = () => {
var e = ctx.CreateEntity();
ctx.OnEntityDestroyed += (p, entity) => {
didDispatch += 1;
entity.retainCount.should_be(1);
var newEntity = ctx.CreateEntity();
newEntity.should_not_be_null();
newEntity.should_not_be_same(entity);
};
e.Destroy();
var reusedEntity = ctx.CreateEntity();
reusedEntity.should_be_same(e);
didDispatch.should_be(1);
};
it["throws if entity is released before it is destroyed"] = expect<EntityIsNotDestroyedException>(() => {
var e = ctx.CreateEntity();
e.Release(ctx);
});
it["dispatches OnGroupCreated when creating a new group"] = () => {
IGroup eventGroup = null;
ctx.OnGroupCreated += (p, g) => {
didDispatch += 1;
p.should_be_same(ctx);
eventGroup = g;
};
var group = ctx.GetGroup(Matcher<TestEntity>.AllOf(0));
didDispatch.should_be(1);
eventGroup.should_be_same(group);
};
it["doesn't dispatch OnGroupCreated when group alredy exists"] = () => {
ctx.GetGroup(Matcher<TestEntity>.AllOf(0));
ctx.OnGroupCreated += delegate { this.Fail(); };
ctx.GetGroup(Matcher<TestEntity>.AllOf(0));
};
it["removes all external delegates when destroying an entity"] = () => {
var e = ctx.CreateEntity();
e.OnComponentAdded += delegate { this.Fail(); };
e.OnComponentRemoved += delegate { this.Fail(); };
e.OnComponentReplaced += delegate { this.Fail(); };
e.Destroy();
var e2 = ctx.CreateEntity();
e2.should_be_same(e);
e2.AddComponentA();
e2.ReplaceComponentA(Component.A);
e2.RemoveComponentA();
};
it["will not remove external delegates for OnEntityReleased"] = () => {
var e = ctx.CreateEntity();
var didRelease = 0;
e.OnEntityReleased += entity => didRelease += 1;
e.Destroy();
didRelease.should_be(1);
};
it["removes all external delegates from OnEntityReleased when after being dispatched"] = () => {
var e = ctx.CreateEntity();
var didRelease = 0;
e.OnEntityReleased += entity => didRelease += 1;
e.Destroy();
e.Retain(this);
e.Release(this);
didRelease.should_be(1);
};
it["removes all external delegates from OnEntityReleased after being dispatched (when delayed release)"] = () => {
var e = ctx.CreateEntity();
var didRelease = 0;
e.OnEntityReleased += entity => didRelease += 1;
e.Retain(this);
e.Destroy();
didRelease.should_be(0);
e.Release(this);
didRelease.should_be(1);
e.Retain(this);
e.Release(this);
didRelease.should_be(1);
};
};
context["entity pool"] = () => {
it["gets entity from object pool"] = () => {
var e = ctx.CreateEntity();
e.should_not_be_null();
e.GetType().should_be(typeof(TestEntity));
};
it["destroys entity when pushing back to object pool"] = () => {
var e = ctx.CreateEntity();
e.AddComponentA();
e.Destroy();
e.HasComponent(CID.ComponentA).should_be_false();
};
it["returns pushed entity"] = () => {
var e = ctx.CreateEntity();
e.AddComponentA();
e.Destroy();
var entity = ctx.CreateEntity();
entity.HasComponent(CID.ComponentA).should_be_false();
entity.should_be_same(e);
};
it["only returns released entities"] = () => {
var e1 = ctx.CreateEntity();
e1.Retain(this);
e1.Destroy();
var e2 = ctx.CreateEntity();
e2.should_not_be_same(e1);
e1.Release(this);
var e3 = ctx.CreateEntity();
e3.should_be_same(e1);
};
it["returns new entity"] = () => {
var e1 = ctx.CreateEntity();
e1.AddComponentA();
e1.Destroy();
ctx.CreateEntity();
var e2 = ctx.CreateEntity();
e2.HasComponent(CID.ComponentA).should_be_false();
e2.should_not_be_same(e1);
};
it["sets up entity from pool"] = () => {
var e = ctx.CreateEntity();
var creationIndex = e.creationIndex;
e.Destroy();
var g = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentA));
e = ctx.CreateEntity();
e.creationIndex.should_be(creationIndex + 1);
e.isEnabled.should_be_true();
e.AddComponentA();
g.GetEntities().should_contain(e);
};
context["when entity gets destroyed"] = () => {
TestEntity e = null;
before = () => {
e = ctx.CreateEntity();
e.AddComponentA();
e.Destroy();
};
it["throws when adding component"] = expect<EntityIsNotEnabledException>(() => e.AddComponentA());
it["throws when removing component"] = expect<EntityIsNotEnabledException>(() => e.RemoveComponentA());
it["throws when replacing component"] = expect<EntityIsNotEnabledException>(() => e.ReplaceComponentA(new ComponentA()));
it["throws when replacing component with null"] = expect<EntityIsNotEnabledException>(() => e.ReplaceComponentA(null));
it["throws when attempting to destroy again"] = expect<EntityIsNotEnabledException>(() => e.Destroy());
};
};
context["groups"] = () => {
it["gets empty group for matcher when no entities were created"] = () => {
var g = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentA));
g.should_not_be_null();
g.GetEntities().should_be_empty();
};
context["when entities created"] = () => {
TestEntity eAB1 = null;
TestEntity eAB2 = null;
TestEntity eA = null;
IMatcher<TestEntity> matcherAB = Matcher<TestEntity>.AllOf(new [] {
CID.ComponentA,
CID.ComponentB
});
before = () => {
eAB1 = ctx.CreateEntity();
eAB1.AddComponentA();
eAB1.AddComponentB();
eAB2 = ctx.CreateEntity();
eAB2.AddComponentA();
eAB2.AddComponentB();
eA = ctx.CreateEntity();
eA.AddComponentA();
};
it["gets group with matching entities"] = () => {
var g = ctx.GetGroup(matcherAB).GetEntities();
g.Length.should_be(2);
g.should_contain(eAB1);
g.should_contain(eAB2);
};
it["gets cached group"] = () => {
ctx.GetGroup(matcherAB).should_be_same(ctx.GetGroup(matcherAB));
};
it["cached group contains newly created matching entity"] = () => {
var g = ctx.GetGroup(matcherAB);
eA.AddComponentB();
g.GetEntities().should_contain(eA);
};
it["cached group doesn't contain entity which are not matching anymore"] = () => {
var g = ctx.GetGroup(matcherAB);
eAB1.RemoveComponentA();
g.GetEntities().should_not_contain(eAB1);
};
it["removes destroyed entity"] = () => {
var g = ctx.GetGroup(matcherAB);
eAB1.Destroy();
g.GetEntities().should_not_contain(eAB1);
};
it["group dispatches OnEntityRemoved and OnEntityAdded when replacing components"] = () => {
var g = ctx.GetGroup(matcherAB);
var didDispatchRemoved = 0;
var didDispatchAdded = 0;
var componentA = new ComponentA();
g.OnEntityRemoved += (group, entity, index, component) => {
group.should_be_same(g);
entity.should_be_same(eAB1);
index.should_be(CID.ComponentA);
component.should_be_same(Component.A);
didDispatchRemoved++;
};
g.OnEntityAdded += (group, entity, index, component) => {
group.should_be_same(g);
entity.should_be_same(eAB1);
index.should_be(CID.ComponentA);
component.should_be_same(componentA);
didDispatchAdded++;
};
eAB1.ReplaceComponentA(componentA);
didDispatchRemoved.should_be(1);
didDispatchAdded.should_be(1);
};
it["group dispatches OnEntityUpdated with previous and current component when replacing a component"] = () => {
var updated = 0;
var prevComp = eA.GetComponent(CID.ComponentA);
var newComp = new ComponentA();
var g = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentA));
g.OnEntityUpdated += (group, entity, index, previousComponent, newComponent) => {
updated += 1;
group.should_be_same(g);
entity.should_be_same(eA);
index.should_be(CID.ComponentA);
previousComponent.should_be_same(prevComp);
newComponent.should_be_same(newComp);
};
eA.ReplaceComponent(CID.ComponentA, newComp);
updated.should_be(1);
};
it["group with matcher NoneOf doesn't dispatch OnEntityAdded when destroying entity"] = () => {
var e = ctx.CreateEntity()
.AddComponentA()
.AddComponentB();
var matcher = Matcher<TestEntity>.AllOf(CID.ComponentB).NoneOf(CID.ComponentA);
var g = ctx.GetGroup(matcher);
g.OnEntityAdded += delegate { this.Fail(); };
e.Destroy();
};
context["event timing"] = () => {
before = () => {
ctx = new MyTestContext();
};
it["dispatches group.OnEntityAdded events after all groups are updated"] = () => {
var groupA = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentA, CID.ComponentB));
var groupB = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentB));
groupA.OnEntityAdded += delegate {
groupB.count.should_be(1);
};
var entity = ctx.CreateEntity();
entity.AddComponentA();
entity.AddComponentB();
};
it["dispatches group.OnEntityRemoved events after all groups are updated"] = () => {
ctx = new MyTestContext();
var groupB = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentB));
var groupAB = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentA, CID.ComponentB));
groupB.OnEntityRemoved += delegate {
groupAB.count.should_be(0);
};
var entity = ctx.CreateEntity();
entity.AddComponentA();
entity.AddComponentB();
entity.RemoveComponentB();
};
};
};
};
context["EntityIndex"] = () => {
it["throws when EntityIndex for key doesn't exist"] = expect<ContextEntityIndexDoesNotExistException>(() => {
ctx.GetEntityIndex("unknown");
});
it["adds and EntityIndex"] = () => {
const int componentIndex = 1;
var entityIndex = new PrimaryEntityIndex<TestEntity, string>("TestIndex", ctx.GetGroup(Matcher<TestEntity>.AllOf(componentIndex)), (arg1, arg2) => string.Empty);
ctx.AddEntityIndex(entityIndex);
ctx.GetEntityIndex(entityIndex.name).should_be_same(entityIndex);
};
it["throws when adding an EntityIndex with same name"] = expect<ContextEntityIndexDoesAlreadyExistException>(() => {
const int componentIndex = 1;
var entityIndex = new PrimaryEntityIndex<TestEntity, string>("TestIndex", ctx.GetGroup(Matcher<TestEntity>.AllOf(componentIndex)), (arg1, arg2) => string.Empty);
ctx.AddEntityIndex(entityIndex);
ctx.AddEntityIndex(entityIndex);
});
};
context["reset"] = () => {
context["context"] = () => {
it["resets creation index"] = () => {
ctx.CreateEntity();
ctx.ResetCreationIndex();
ctx.CreateEntity().creationIndex.should_be(0);
};
context["removes all event handlers"] = () => {
it["removes OnEntityCreated"] = () => {
ctx.OnEntityCreated += delegate { this.Fail(); };
ctx.RemoveAllEventHandlers();
ctx.CreateEntity();
};
it["removes OnEntityWillBeDestroyed"] = () => {
ctx.OnEntityWillBeDestroyed += delegate { this.Fail(); };
ctx.RemoveAllEventHandlers();
ctx.CreateEntity().Destroy();
};
it["removes OnEntityDestroyed"] = () => {
ctx.OnEntityDestroyed += delegate { this.Fail(); };
ctx.RemoveAllEventHandlers();
ctx.CreateEntity().Destroy();
};
it["removes OnGroupCreated"] = () => {
ctx.OnGroupCreated += delegate { this.Fail(); };
ctx.RemoveAllEventHandlers();
ctx.GetGroup(Matcher<TestEntity>.AllOf(0));
};
};
};
context["component pools"] = () => {
before = () => {
var entity = ctx.CreateEntity();
entity.AddComponentA();
entity.AddComponentB();
entity.RemoveComponentA();
entity.RemoveComponentB();
};
it["clears all component pools"] = () => {
ctx.componentPools[CID.ComponentA].Count.should_be(1);
ctx.componentPools[CID.ComponentB].Count.should_be(1);
ctx.ClearComponentPools();
ctx.componentPools[CID.ComponentA].Count.should_be(0);
ctx.componentPools[CID.ComponentB].Count.should_be(0);
};
it["clears a specific component pool"] = () => {
ctx.ClearComponentPool(CID.ComponentB);
ctx.componentPools[CID.ComponentA].Count.should_be(1);
ctx.componentPools[CID.ComponentB].Count.should_be(0);
};
it["only clears existing component pool"] = () => {
ctx.ClearComponentPool(CID.ComponentC);
};
};
};
context["EntitasCache"] = () => {
it["pops new list from list pool"] = () => {
var groupA = ctx.GetGroup(Matcher<TestEntity>.AllOf(CID.ComponentA));
var groupAB = ctx.GetGroup(Matcher<TestEntity>.AnyOf(CID.ComponentA, CID.ComponentB));
var groupABC = ctx.GetGroup(Matcher<TestEntity>.AnyOf(CID.ComponentA, CID.ComponentB, CID.ComponentC));
var didExecute = 0;
groupA.OnEntityAdded += (g, entity, index, component) => {
didExecute += 1;
entity.RemoveComponentA();
};
groupAB.OnEntityAdded += (g, entity, index, component) => {
didExecute += 1;
};
groupABC.OnEntityAdded += (g, entity, index, component) => {
didExecute += 1;
};
ctx.CreateEntity().AddComponentA();
didExecute.should_be(3);
};
};
}
}
| |
//---------------------------------------------------------------------------
//
// File: HtmlXamlConverter.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Prototype for Html - Xaml conversion
//
//---------------------------------------------------------------------------
namespace MarkupConverter
{
using System;
using System.Xml;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows; // DependencyProperty
using System.Windows.Documents; // TextElement
internal static class HtmlCssParser
{
// .................................................................
//
// Processing CSS Attributes
//
// .................................................................
internal static void GetElementPropertiesFromCssAttributes(XmlElement htmlElement, string elementName, CssStylesheet stylesheet, Hashtable localProperties, List<XmlElement> sourceContext)
{
string styleFromStylesheet = stylesheet.GetStyle(elementName, sourceContext);
string styleInline = HtmlToXamlConverter.GetAttribute(htmlElement, "style");
// Combine styles from stylesheet and from inline attribute.
// The order is important - the latter styles will override the former.
string style = styleFromStylesheet != null ? styleFromStylesheet : null;
if (styleInline != null)
{
style = style == null ? styleInline : (style + ";" + styleInline);
}
// Apply local style to current formatting properties
if (style != null)
{
string[] styleValues = style.Split(';');
for (int i = 0; i < styleValues.Length; i++)
{
string[] styleNameValue;
styleNameValue = styleValues[i].Split(':');
if (styleNameValue.Length == 2)
{
string styleName = styleNameValue[0].Trim().ToLower();
string styleValue = HtmlToXamlConverter.UnQuote(styleNameValue[1].Trim()).ToLower();
int nextIndex = 0;
switch (styleName)
{
case "font":
ParseCssFont(styleValue, localProperties);
break;
case "font-family":
ParseCssFontFamily(styleValue, ref nextIndex, localProperties);
break;
case "font-size":
ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true);
break;
case "font-style":
ParseCssFontStyle(styleValue, ref nextIndex, localProperties);
break;
case "font-weight":
ParseCssFontWeight(styleValue, ref nextIndex, localProperties);
break;
case "font-variant":
ParseCssFontVariant(styleValue, ref nextIndex, localProperties);
break;
case "line-height":
ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true);
break;
case "word-spacing":
// Implement word-spacing conversion
break;
case "letter-spacing":
// Implement letter-spacing conversion
break;
case "color":
ParseCssColor(styleValue, ref nextIndex, localProperties, "color");
break;
case "text-decoration":
ParseCssTextDecoration(styleValue, ref nextIndex, localProperties);
break;
case "text-transform":
ParseCssTextTransform(styleValue, ref nextIndex, localProperties);
break;
case "background-color":
ParseCssColor(styleValue, ref nextIndex, localProperties, "background-color");
break;
case "background":
// TODO: need to parse composite background property
ParseCssBackground(styleValue, ref nextIndex, localProperties);
break;
case "text-align":
ParseCssTextAlign(styleValue, ref nextIndex, localProperties);
break;
case "vertical-align":
ParseCssVerticalAlign(styleValue, ref nextIndex, localProperties);
break;
case "text-indent":
ParseCssSize(styleValue, ref nextIndex, localProperties, "text-indent", /*mustBeNonNegative:*/false);
break;
case "width":
case "height":
ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true);
break;
case "margin": // top/right/bottom/left
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName);
break;
case "margin-top":
case "margin-right":
case "margin-bottom":
case "margin-left":
ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true);
break;
case "padding":
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName);
break;
case "padding-top":
case "padding-right":
case "padding-bottom":
case "padding-left":
ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true);
break;
case "border":
ParseCssBorder(styleValue, ref nextIndex, localProperties);
break;
case "border-style":
case "border-width":
case "border-color":
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName);
break;
case "border-top":
case "border-right":
case "border-left":
case "border-bottom":
// Parse css border style
break;
// NOTE: css names for elementary border styles have side indications in the middle (top/bottom/left/right)
// In our internal notation we intentionally put them at the end - to unify processing in ParseCssRectangleProperty method
case "border-top-style":
case "border-right-style":
case "border-left-style":
case "border-bottom-style":
case "border-top-color":
case "border-right-color":
case "border-left-color":
case "border-bottom-color":
case "border-top-width":
case "border-right-width":
case "border-left-width":
case "border-bottom-width":
// Parse css border style
break;
case "display":
// Implement display style conversion
break;
case "float":
ParseCssFloat(styleValue, ref nextIndex, localProperties);
break;
case "clear":
ParseCssClear(styleValue, ref nextIndex, localProperties);
break;
default:
break;
}
}
}
}
}
// .................................................................
//
// Parsing CSS - Lexical Helpers
//
// .................................................................
// Skips whitespaces in style values
private static void ParseWhiteSpace(string styleValue, ref int nextIndex)
{
while (nextIndex < styleValue.Length && Char.IsWhiteSpace(styleValue[nextIndex]))
{
nextIndex++;
}
}
// Checks if the following character matches to a given word and advances nextIndex
// by the word's length in case of success.
// Otherwise leaves nextIndex in place (except for possible whitespaces).
// Returns true or false depending on success or failure of matching.
private static bool ParseWord(string word, string styleValue, ref int nextIndex)
{
ParseWhiteSpace(styleValue, ref nextIndex);
for (int i = 0; i < word.Length; i++)
{
if (!(nextIndex + i < styleValue.Length && word[i] == styleValue[nextIndex + i]))
{
return false;
}
}
if (nextIndex + word.Length < styleValue.Length && Char.IsLetterOrDigit(styleValue[nextIndex + word.Length]))
{
return false;
}
nextIndex += word.Length;
return true;
}
// CHecks whether the following character sequence matches to one of the given words,
// and advances the nextIndex to matched word length.
// Returns null in case if there is no match or the word matched.
private static string ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex)
{
for (int i = 0; i < words.Length; i++)
{
if (ParseWord(words[i], styleValue, ref nextIndex))
{
return words[i];
}
}
return null;
}
private static void ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex, Hashtable localProperties, string attributeName)
{
string attributeValue = ParseWordEnumeration(words, styleValue, ref nextIndex);
if (attributeValue != null)
{
localProperties[attributeName] = attributeValue;
}
}
private static string ParseCssSize(string styleValue, ref int nextIndex, bool mustBeNonNegative)
{
ParseWhiteSpace(styleValue, ref nextIndex);
int startIndex = nextIndex;
// Parse optional munis sign
if (nextIndex < styleValue.Length && styleValue[nextIndex] == '-')
{
nextIndex++;
}
if (nextIndex < styleValue.Length && Char.IsDigit(styleValue[nextIndex]))
{
while (nextIndex < styleValue.Length && (Char.IsDigit(styleValue[nextIndex]) || styleValue[nextIndex] == '.'))
{
nextIndex++;
}
string number = styleValue.Substring(startIndex, nextIndex - startIndex);
string unit = ParseWordEnumeration(_fontSizeUnits, styleValue, ref nextIndex);
if (unit == null)
{
unit = "px"; // Assuming pixels by default
}
if (mustBeNonNegative && styleValue[startIndex] == '-')
{
return "0";
}
else
{
return number + unit;
}
}
return null;
}
private static void ParseCssSize(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName, bool mustBeNonNegative)
{
string length = ParseCssSize(styleValue, ref nextIndex, mustBeNonNegative);
if (length != null)
{
localValues[propertyName] = length;
}
}
private static readonly string[] _colors = new string[]
{
"aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond",
"blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral",
"cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray",
"darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred",
"darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink",
"deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro",
"ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "honeydew", "hotpink", "indianred",
"indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
"lightcyan", "lightgoldenrodyellow", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen",
"lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
"maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue",
"mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
"navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod",
"palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
"purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell",
"sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal",
"thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen",
};
private static readonly string[] _systemColors = new string[]
{
"activeborder", "activecaption", "appworkspace", "background", "buttonface", "buttonhighlight", "buttonshadow",
"buttontext", "captiontext", "graytext", "highlight", "highlighttext", "inactiveborder", "inactivecaption",
"inactivecaptiontext", "infobackground", "infotext", "menu", "menutext", "scrollbar", "threeddarkshadow",
"threedface", "threedhighlight", "threedlightshadow", "threedshadow", "window", "windowframe", "windowtext",
};
private static string ParseCssColor(string styleValue, ref int nextIndex)
{
// Implement color parsing
// rgb(100%,53.5%,10%)
// rgb(255,91,26)
// #FF5B1A
// black | silver | gray | ... | aqua
// transparent - for background-color
ParseWhiteSpace(styleValue, ref nextIndex);
string color = null;
if (nextIndex < styleValue.Length)
{
int startIndex = nextIndex;
char character = styleValue[nextIndex];
if (character == '#')
{
nextIndex++;
while (nextIndex < styleValue.Length)
{
character = Char.ToUpper(styleValue[nextIndex]);
if (!('0' <= character && character <= '9' || 'A' <= character && character <= 'F'))
{
break;
}
nextIndex++;
}
if (nextIndex > startIndex + 1)
{
color = styleValue.Substring(startIndex, nextIndex - startIndex);
}
}
else if (styleValue.Substring(nextIndex, 3).ToLower() == "rbg")
{
// Implement real rgb() color parsing
while (nextIndex < styleValue.Length && styleValue[nextIndex] != ')')
{
nextIndex++;
}
if (nextIndex < styleValue.Length)
{
nextIndex++; // to skip ')'
}
color = "gray"; // return bogus color
}
else if (Char.IsLetter(character))
{
color = ParseWordEnumeration(_colors, styleValue, ref nextIndex);
if (color == null)
{
color = ParseWordEnumeration(_systemColors, styleValue, ref nextIndex);
if (color != null)
{
// Implement smarter system color converions into real colors
color = "black";
}
}
}
}
return color;
}
private static void ParseCssColor(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName)
{
string color = ParseCssColor(styleValue, ref nextIndex);
if (color != null)
{
localValues[propertyName] = color;
}
}
// .................................................................
//
// Pasring CSS font Property
//
// .................................................................
// CSS has five font properties: font-family, font-style, font-variant, font-weight, font-size.
// An aggregated "font" property lets you specify in one action all the five in combination
// with additional line-height property.
//
// font-family: [<family-name>,]* [<family-name> | <generic-family>]
// generic-family: serif | sans-serif | monospace | cursive | fantasy
// The list of families sets priorities to choose fonts;
// Quotes not allowed around generic-family names
// font-style: normal | italic | oblique
// font-variant: normal | small-caps
// font-weight: normal | bold | bolder | lighter | 100 ... 900 |
// Default is "normal", normal==400
// font-size: <absolute-size> | <relative-size> | <length> | <percentage>
// absolute-size: xx-small | x-small | small | medium | large | x-large | xx-large
// relative-size: larger | smaller
// length: <point> | <pica> | <ex> | <em> | <points> | <millimeters> | <centimeters> | <inches>
// Default: medium
// font: [ <font-style> || <font-variant> || <font-weight ]? <font-size> [ / <line-height> ]? <font-family>
private static readonly string[] _fontGenericFamilies = new string[] { "serif", "sans-serif", "monospace", "cursive", "fantasy" };
private static readonly string[] _fontStyles = new string[] { "normal", "italic", "oblique" };
private static readonly string[] _fontVariants = new string[] { "normal", "small-caps" };
private static readonly string[] _fontWeights = new string[] { "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900" };
private static readonly string[] _fontAbsoluteSizes = new string[] { "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large" };
private static readonly string[] _fontRelativeSizes = new string[] { "larger", "smaller" };
private static readonly string[] _fontSizeUnits = new string[] { "px", "mm", "cm", "in", "pt", "pc", "em", "ex", "%" };
// Parses CSS string fontStyle representing a value for css font attribute
private static void ParseCssFont(string styleValue, Hashtable localProperties)
{
int nextIndex = 0;
ParseCssFontStyle(styleValue, ref nextIndex, localProperties);
ParseCssFontVariant(styleValue, ref nextIndex, localProperties);
ParseCssFontWeight(styleValue, ref nextIndex, localProperties);
ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true);
ParseWhiteSpace(styleValue, ref nextIndex);
if (nextIndex < styleValue.Length && styleValue[nextIndex] == '/')
{
nextIndex++;
ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true);
}
ParseCssFontFamily(styleValue, ref nextIndex, localProperties);
}
private static void ParseCssFontStyle(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_fontStyles, styleValue, ref nextIndex, localProperties, "font-style");
}
private static void ParseCssFontVariant(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_fontVariants, styleValue, ref nextIndex, localProperties, "font-variant");
}
private static void ParseCssFontWeight(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_fontWeights, styleValue, ref nextIndex, localProperties, "font-weight");
}
private static void ParseCssFontFamily(string styleValue, ref int nextIndex, Hashtable localProperties)
{
string fontFamilyList = null;
while (nextIndex < styleValue.Length)
{
// Try generic-family
string fontFamily = ParseWordEnumeration(_fontGenericFamilies, styleValue, ref nextIndex);
if (fontFamily == null)
{
// Try quoted font family name
if (nextIndex < styleValue.Length && (styleValue[nextIndex] == '"' || styleValue[nextIndex] == '\''))
{
char quote = styleValue[nextIndex];
nextIndex++;
int startIndex = nextIndex;
while (nextIndex < styleValue.Length && styleValue[nextIndex] != quote)
{
nextIndex++;
}
fontFamily = '"' + styleValue.Substring(startIndex, nextIndex - startIndex) + '"';
}
if (fontFamily == null)
{
// Try unquoted font family name
int startIndex = nextIndex;
while (nextIndex < styleValue.Length && styleValue[nextIndex] != ',' && styleValue[nextIndex] != ';')
{
nextIndex++;
}
if (nextIndex > startIndex)
{
fontFamily = styleValue.Substring(startIndex, nextIndex - startIndex).Trim();
if (fontFamily.Length == 0)
{
fontFamily = null;
}
}
}
}
ParseWhiteSpace(styleValue, ref nextIndex);
if (nextIndex < styleValue.Length && styleValue[nextIndex] == ',')
{
nextIndex++;
}
if (fontFamily != null)
{
// css font-family can contein a list of names. We only consider the first name from the list. Need a decision what to do with remaining names
// fontFamilyList = (fontFamilyList == null) ? fontFamily : fontFamilyList + "," + fontFamily;
if (fontFamilyList == null && fontFamily.Length > 0)
{
if (fontFamily[0] == '"' || fontFamily[0] == '\'')
{
// Unquote the font family name
fontFamily = fontFamily.Substring(1, fontFamily.Length - 2);
}
else
{
// Convert generic css family name
}
fontFamilyList = fontFamily;
}
}
else
{
break;
}
}
if (fontFamilyList != null)
{
localProperties["font-family"] = fontFamilyList;
}
}
// .................................................................
//
// Pasring CSS list-style Property
//
// .................................................................
// list-style: [ <list-style-type> || <list-style-position> || <list-style-image> ]
private static readonly string[] _listStyleTypes = new string[] { "disc", "circle", "square", "decimal", "lower-roman", "upper-roman", "lower-alpha", "upper-alpha", "none" };
private static readonly string[] _listStylePositions = new string[] { "inside", "outside" };
private static void ParseCssListStyle(string styleValue, Hashtable localProperties)
{
int nextIndex = 0;
while (nextIndex < styleValue.Length)
{
string listStyleType = ParseCssListStyleType(styleValue, ref nextIndex);
if (listStyleType != null)
{
localProperties["list-style-type"] = listStyleType;
}
else
{
string listStylePosition = ParseCssListStylePosition(styleValue, ref nextIndex);
if (listStylePosition != null)
{
localProperties["list-style-position"] = listStylePosition;
}
else
{
string listStyleImage = ParseCssListStyleImage(styleValue, ref nextIndex);
if (listStyleImage != null)
{
localProperties["list-style-image"] = listStyleImage;
}
else
{
// TODO: Process unrecognized list style value
break;
}
}
}
}
}
private static string ParseCssListStyleType(string styleValue, ref int nextIndex)
{
return ParseWordEnumeration(_listStyleTypes, styleValue, ref nextIndex);
}
private static string ParseCssListStylePosition(string styleValue, ref int nextIndex)
{
return ParseWordEnumeration(_listStylePositions, styleValue, ref nextIndex);
}
private static string ParseCssListStyleImage(string styleValue, ref int nextIndex)
{
// TODO: Implement URL parsing for images
return null;
}
// .................................................................
//
// Pasring CSS text-decorations Property
//
// .................................................................
private static readonly string[] _textDecorations = new string[] { "none", "underline", "overline", "line-through", "blink" };
private static void ParseCssTextDecoration(string styleValue, ref int nextIndex, Hashtable localProperties)
{
// Set default text-decorations:none;
for (int i = 1; i < _textDecorations.Length; i++)
{
localProperties["text-decoration-" + _textDecorations[i]] = "false";
}
// Parse list of decorations values
while (nextIndex < styleValue.Length)
{
string decoration = ParseWordEnumeration(_textDecorations, styleValue, ref nextIndex);
if (decoration == null || decoration == "none")
{
break;
}
localProperties["text-decoration-" + decoration] = "true";
}
}
// .................................................................
//
// Pasring CSS text-transform Property
//
// .................................................................
private static readonly string[] _textTransforms = new string[] { "none", "capitalize", "uppercase", "lowercase" };
private static void ParseCssTextTransform(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_textTransforms, styleValue, ref nextIndex, localProperties, "text-transform");
}
// .................................................................
//
// Pasring CSS text-align Property
//
// .................................................................
private static readonly string[] _textAligns = new string[] { "left", "right", "center", "justify" };
private static void ParseCssTextAlign(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_textAligns, styleValue, ref nextIndex, localProperties, "text-align");
}
// .................................................................
//
// Pasring CSS vertical-align Property
//
// .................................................................
private static readonly string[] _verticalAligns = new string[] { "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom" };
private static void ParseCssVerticalAlign(string styleValue, ref int nextIndex, Hashtable localProperties)
{
// Parse percentage value for vertical-align style
ParseWordEnumeration(_verticalAligns, styleValue, ref nextIndex, localProperties, "vertical-align");
}
// .................................................................
//
// Pasring CSS float Property
//
// .................................................................
private static readonly string[] _floats = new string[] { "left", "right", "none" };
private static void ParseCssFloat(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_floats, styleValue, ref nextIndex, localProperties, "float");
}
// .................................................................
//
// Pasring CSS clear Property
//
// .................................................................
private static readonly string[] _clears = new string[] { "none", "left", "right", "both" };
private static void ParseCssClear(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_clears, styleValue, ref nextIndex, localProperties, "clear");
}
// .................................................................
//
// Pasring CSS margin and padding Properties
//
// .................................................................
// Generic method for parsing any of four-values properties, such as margin, padding, border-width, border-style, border-color
private static bool ParseCssRectangleProperty(string styleValue, ref int nextIndex, Hashtable localProperties, string propertyName)
{
// CSS Spec:
// If only one value is set, then the value applies to all four sides;
// If two or three values are set, then missinng value(s) are taken fromm the opposite side(s).
// The order they are applied is: top/right/bottom/left
Debug.Assert(propertyName == "margin" || propertyName == "padding" || propertyName == "border-width" || propertyName == "border-style" || propertyName == "border-color");
string value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true);
if (value != null)
{
localProperties[propertyName + "-top"] = value;
localProperties[propertyName + "-bottom"] = value;
localProperties[propertyName + "-right"] = value;
localProperties[propertyName + "-left"] = value;
value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true);
if (value != null)
{
localProperties[propertyName + "-right"] = value;
localProperties[propertyName + "-left"] = value;
value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true);
if (value != null)
{
localProperties[propertyName + "-bottom"] = value;
value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true);
if (value != null)
{
localProperties[propertyName + "-left"] = value;
}
}
}
return true;
}
return false;
}
// .................................................................
//
// Pasring CSS border Properties
//
// .................................................................
// border: [ <border-width> || <border-style> || <border-color> ]
private static void ParseCssBorder(string styleValue, ref int nextIndex, Hashtable localProperties)
{
while (
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-width") ||
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-style") ||
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-color"))
{
}
}
// .................................................................
//
// Pasring CSS border-style Propertie
//
// .................................................................
private static readonly string[] _borderStyles = new string[] { "none", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset" };
private static string ParseCssBorderStyle(string styleValue, ref int nextIndex)
{
return ParseWordEnumeration(_borderStyles, styleValue, ref nextIndex);
}
// .................................................................
//
// What are these definitions doing here:
//
// .................................................................
private static string[] _blocks = new string[] { "block", "inline", "list-item", "none" };
// .................................................................
//
// Pasring CSS Background Properties
//
// .................................................................
private static void ParseCssBackground(string styleValue, ref int nextIndex, Hashtable localValues)
{
// Implement parsing background attribute
}
}
internal class CssStylesheet
{
// Constructor
public CssStylesheet(XmlElement htmlElement)
{
if (htmlElement != null)
{
this.DiscoverStyleDefinitions(htmlElement);
}
}
// Recursively traverses an html tree, discovers STYLE elements and creates a style definition table
// for further cascading style application
public void DiscoverStyleDefinitions(XmlElement htmlElement)
{
if (htmlElement.LocalName.ToLower() == "link")
{
return;
// Add LINK elements processing for included stylesheets
// <LINK href="http://sc.msn.com/global/css/ptnr/orange.css" type=text/css \r\nrel=stylesheet>
}
if (htmlElement.LocalName.ToLower() != "style")
{
// This is not a STYLE element. Recurse into it
for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
{
if (htmlChildNode is XmlElement)
{
this.DiscoverStyleDefinitions((XmlElement)htmlChildNode);
}
}
return;
}
// Add style definitions from this style.
// Collect all text from this style definition
StringBuilder stylesheetBuffer = new StringBuilder();
for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
{
if (htmlChildNode is XmlText || htmlChildNode is XmlComment)
{
stylesheetBuffer.Append(RemoveComments(htmlChildNode.Value));
}
}
// CssStylesheet has the following syntactical structure:
// @import declaration;
// selector { definition }
// where "selector" is one of: ".classname", "tagname"
// It can contain comments in the following form: /*...*/
int nextCharacterIndex = 0;
while (nextCharacterIndex < stylesheetBuffer.Length)
{
// Extract selector
int selectorStart = nextCharacterIndex;
while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '{')
{
// Skip declaration directive starting from @
if (stylesheetBuffer[nextCharacterIndex] == '@')
{
while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != ';')
{
nextCharacterIndex++;
}
selectorStart = nextCharacterIndex + 1;
}
nextCharacterIndex++;
}
if (nextCharacterIndex < stylesheetBuffer.Length)
{
// Extract definition
int definitionStart = nextCharacterIndex;
while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '}')
{
nextCharacterIndex++;
}
// Define a style
if (nextCharacterIndex - definitionStart > 2)
{
this.AddStyleDefinition(
stylesheetBuffer.ToString(selectorStart, definitionStart - selectorStart),
stylesheetBuffer.ToString(definitionStart + 1, nextCharacterIndex - definitionStart - 2));
}
// Skip closing brace
if (nextCharacterIndex < stylesheetBuffer.Length)
{
Debug.Assert(stylesheetBuffer[nextCharacterIndex] == '}');
nextCharacterIndex++;
}
}
}
}
// Returns a string with all c-style comments replaced by spaces
private string RemoveComments(string text)
{
int commentStart = text.IndexOf("/*");
if (commentStart < 0)
{
return text;
}
int commentEnd = text.IndexOf("*/", commentStart + 2);
if (commentEnd < 0)
{
return text.Substring(0, commentStart);
}
return text.Substring(0, commentStart) + " " + RemoveComments(text.Substring(commentEnd + 2));
}
public void AddStyleDefinition(string selector, string definition)
{
// Notrmalize parameter values
selector = selector.Trim().ToLower();
definition = definition.Trim().ToLower();
if (selector.Length == 0 || definition.Length == 0)
{
return;
}
if (_styleDefinitions == null)
{
_styleDefinitions = new List<StyleDefinition>();
}
string[] simpleSelectors = selector.Split(',');
for (int i = 0; i < simpleSelectors.Length; i++)
{
string simpleSelector = simpleSelectors[i].Trim();
if (simpleSelector.Length > 0)
{
_styleDefinitions.Add(new StyleDefinition(simpleSelector, definition));
}
}
}
public string GetStyle(string elementName, List<XmlElement> sourceContext)
{
Debug.Assert(sourceContext.Count > 0);
Debug.Assert(elementName == sourceContext[sourceContext.Count - 1].LocalName);
// Add id processing for style selectors
if (_styleDefinitions != null)
{
for (int i = _styleDefinitions.Count - 1; i >= 0; i--)
{
string selector = _styleDefinitions[i].Selector;
string[] selectorLevels = selector.Split(' ');
int indexInSelector = selectorLevels.Length - 1;
int indexInContext = sourceContext.Count - 1;
string selectorLevel = selectorLevels[indexInSelector].Trim();
if (MatchSelectorLevel(selectorLevel, sourceContext[sourceContext.Count - 1]))
{
return _styleDefinitions[i].Definition;
}
}
}
return null;
}
private bool MatchSelectorLevel(string selectorLevel, XmlElement xmlElement)
{
if (selectorLevel.Length == 0)
{
return false;
}
int indexOfDot = selectorLevel.IndexOf('.');
int indexOfPound = selectorLevel.IndexOf('#');
string selectorClass = null;
string selectorId = null;
string selectorTag = null;
if (indexOfDot >= 0)
{
if (indexOfDot > 0)
{
selectorTag = selectorLevel.Substring(0, indexOfDot);
}
selectorClass = selectorLevel.Substring(indexOfDot + 1);
}
else if (indexOfPound >= 0)
{
if (indexOfPound > 0)
{
selectorTag = selectorLevel.Substring(0, indexOfPound);
}
selectorId = selectorLevel.Substring(indexOfPound + 1);
}
else
{
selectorTag = selectorLevel;
}
if (selectorTag != null && selectorTag != xmlElement.LocalName)
{
return false;
}
if (selectorId != null && HtmlToXamlConverter.GetAttribute(xmlElement, "id") != selectorId)
{
return false;
}
if (selectorClass != null && HtmlToXamlConverter.GetAttribute(xmlElement, "class") != selectorClass)
{
return false;
}
return true;
}
private class StyleDefinition
{
public StyleDefinition(string selector, string definition)
{
this.Selector = selector;
this.Definition = definition;
}
public string Selector;
public string Definition;
}
private List<StyleDefinition> _styleDefinitions;
}
}
| |
//
// SubExpressionType.cs.cs
//
// This file was generated by XMLSPY 2004 Enterprise Edition.
//
// YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE
// OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION.
//
// Refer to the XMLSPY Documentation for further details.
// http://www.altova.com/xmlspy
//
using System;
using System.Collections;
using System.Xml;
using Altova.Types;
namespace XMLRules
{
public class SubExpressionType : Altova.Node
{
#region Forward constructors
public SubExpressionType() : base() { SetCollectionParents(); }
public SubExpressionType(XmlDocument doc) : base(doc) { SetCollectionParents(); }
public SubExpressionType(XmlNode node) : base(node) { SetCollectionParents(); }
public SubExpressionType(Altova.Node node) : base(node) { SetCollectionParents(); }
#endregion // Forward constructors
public override void AdjustPrefix()
{
int nCount;
nCount = DomChildCount(NodeType.Element, "", "LHSArithmeticExpression");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "LHSArithmeticExpression", i);
InternalAdjustPrefix(DOMNode, true);
new ArithmeticExpression(DOMNode).AdjustPrefix();
}
nCount = DomChildCount(NodeType.Element, "", "ArithmeticOperator");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "ArithmeticOperator", i);
InternalAdjustPrefix(DOMNode, true);
new ArithemticOperator(DOMNode).AdjustPrefix();
}
nCount = DomChildCount(NodeType.Element, "", "RHSArithmeticExpression");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "RHSArithmeticExpression", i);
InternalAdjustPrefix(DOMNode, true);
new ArithmeticExpression(DOMNode).AdjustPrefix();
}
}
#region LHSArithmeticExpression accessor methods
public int GetLHSArithmeticExpressionMinCount()
{
return 1;
}
public int LHSArithmeticExpressionMinCount
{
get
{
return 1;
}
}
public int GetLHSArithmeticExpressionMaxCount()
{
return 1;
}
public int LHSArithmeticExpressionMaxCount
{
get
{
return 1;
}
}
public int GetLHSArithmeticExpressionCount()
{
return DomChildCount(NodeType.Element, "", "LHSArithmeticExpression");
}
public int LHSArithmeticExpressionCount
{
get
{
return DomChildCount(NodeType.Element, "", "LHSArithmeticExpression");
}
}
public bool HasLHSArithmeticExpression()
{
return HasDomChild(NodeType.Element, "", "LHSArithmeticExpression");
}
public ArithmeticExpression GetLHSArithmeticExpressionAt(int index)
{
return new ArithmeticExpression(GetDomChildAt(NodeType.Element, "", "LHSArithmeticExpression", index));
}
public ArithmeticExpression GetLHSArithmeticExpression()
{
return GetLHSArithmeticExpressionAt(0);
}
public ArithmeticExpression LHSArithmeticExpression
{
get
{
return GetLHSArithmeticExpressionAt(0);
}
}
public void RemoveLHSArithmeticExpressionAt(int index)
{
RemoveDomChildAt(NodeType.Element, "", "LHSArithmeticExpression", index);
}
public void RemoveLHSArithmeticExpression()
{
while (HasLHSArithmeticExpression())
RemoveLHSArithmeticExpressionAt(0);
}
public void AddLHSArithmeticExpression(ArithmeticExpression newValue)
{
AppendDomElement("", "LHSArithmeticExpression", newValue);
}
public void InsertLHSArithmeticExpressionAt(ArithmeticExpression newValue, int index)
{
InsertDomElementAt("", "LHSArithmeticExpression", index, newValue);
}
public void ReplaceLHSArithmeticExpressionAt(ArithmeticExpression newValue, int index)
{
ReplaceDomElementAt("", "LHSArithmeticExpression", index, newValue);
}
#endregion // LHSArithmeticExpression accessor methods
#region LHSArithmeticExpression collection
public LHSArithmeticExpressionCollection MyLHSArithmeticExpressions = new LHSArithmeticExpressionCollection( );
public class LHSArithmeticExpressionCollection: IEnumerable
{
SubExpressionType parent;
public SubExpressionType Parent
{
set
{
parent = value;
}
}
public LHSArithmeticExpressionEnumerator GetEnumerator()
{
return new LHSArithmeticExpressionEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class LHSArithmeticExpressionEnumerator: IEnumerator
{
int nIndex;
SubExpressionType parent;
public LHSArithmeticExpressionEnumerator(SubExpressionType par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.LHSArithmeticExpressionCount );
}
public ArithmeticExpression Current
{
get
{
return(parent.GetLHSArithmeticExpressionAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // LHSArithmeticExpression collection
#region ArithmeticOperator accessor methods
public int GetArithmeticOperatorMinCount()
{
return 1;
}
public int ArithmeticOperatorMinCount
{
get
{
return 1;
}
}
public int GetArithmeticOperatorMaxCount()
{
return 1;
}
public int ArithmeticOperatorMaxCount
{
get
{
return 1;
}
}
public int GetArithmeticOperatorCount()
{
return DomChildCount(NodeType.Element, "", "ArithmeticOperator");
}
public int ArithmeticOperatorCount
{
get
{
return DomChildCount(NodeType.Element, "", "ArithmeticOperator");
}
}
public bool HasArithmeticOperator()
{
return HasDomChild(NodeType.Element, "", "ArithmeticOperator");
}
public ArithemticOperator GetArithmeticOperatorAt(int index)
{
return new ArithemticOperator(GetDomChildAt(NodeType.Element, "", "ArithmeticOperator", index));
}
public ArithemticOperator GetArithmeticOperator()
{
return GetArithmeticOperatorAt(0);
}
public ArithemticOperator ArithmeticOperator
{
get
{
return GetArithmeticOperatorAt(0);
}
}
public void RemoveArithmeticOperatorAt(int index)
{
RemoveDomChildAt(NodeType.Element, "", "ArithmeticOperator", index);
}
public void RemoveArithmeticOperator()
{
while (HasArithmeticOperator())
RemoveArithmeticOperatorAt(0);
}
public void AddArithmeticOperator(ArithemticOperator newValue)
{
AppendDomElement("", "ArithmeticOperator", newValue);
}
public void InsertArithmeticOperatorAt(ArithemticOperator newValue, int index)
{
InsertDomElementAt("", "ArithmeticOperator", index, newValue);
}
public void ReplaceArithmeticOperatorAt(ArithemticOperator newValue, int index)
{
ReplaceDomElementAt("", "ArithmeticOperator", index, newValue);
}
#endregion // ArithmeticOperator accessor methods
#region ArithmeticOperator collection
public ArithmeticOperatorCollection MyArithmeticOperators = new ArithmeticOperatorCollection( );
public class ArithmeticOperatorCollection: IEnumerable
{
SubExpressionType parent;
public SubExpressionType Parent
{
set
{
parent = value;
}
}
public ArithmeticOperatorEnumerator GetEnumerator()
{
return new ArithmeticOperatorEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class ArithmeticOperatorEnumerator: IEnumerator
{
int nIndex;
SubExpressionType parent;
public ArithmeticOperatorEnumerator(SubExpressionType par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.ArithmeticOperatorCount );
}
public ArithemticOperator Current
{
get
{
return(parent.GetArithmeticOperatorAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // ArithmeticOperator collection
#region RHSArithmeticExpression accessor methods
public int GetRHSArithmeticExpressionMinCount()
{
return 1;
}
public int RHSArithmeticExpressionMinCount
{
get
{
return 1;
}
}
public int GetRHSArithmeticExpressionMaxCount()
{
return 1;
}
public int RHSArithmeticExpressionMaxCount
{
get
{
return 1;
}
}
public int GetRHSArithmeticExpressionCount()
{
return DomChildCount(NodeType.Element, "", "RHSArithmeticExpression");
}
public int RHSArithmeticExpressionCount
{
get
{
return DomChildCount(NodeType.Element, "", "RHSArithmeticExpression");
}
}
public bool HasRHSArithmeticExpression()
{
return HasDomChild(NodeType.Element, "", "RHSArithmeticExpression");
}
public ArithmeticExpression GetRHSArithmeticExpressionAt(int index)
{
return new ArithmeticExpression(GetDomChildAt(NodeType.Element, "", "RHSArithmeticExpression", index));
}
public ArithmeticExpression GetRHSArithmeticExpression()
{
return GetRHSArithmeticExpressionAt(0);
}
public ArithmeticExpression RHSArithmeticExpression
{
get
{
return GetRHSArithmeticExpressionAt(0);
}
}
public void RemoveRHSArithmeticExpressionAt(int index)
{
RemoveDomChildAt(NodeType.Element, "", "RHSArithmeticExpression", index);
}
public void RemoveRHSArithmeticExpression()
{
while (HasRHSArithmeticExpression())
RemoveRHSArithmeticExpressionAt(0);
}
public void AddRHSArithmeticExpression(ArithmeticExpression newValue)
{
AppendDomElement("", "RHSArithmeticExpression", newValue);
}
public void InsertRHSArithmeticExpressionAt(ArithmeticExpression newValue, int index)
{
InsertDomElementAt("", "RHSArithmeticExpression", index, newValue);
}
public void ReplaceRHSArithmeticExpressionAt(ArithmeticExpression newValue, int index)
{
ReplaceDomElementAt("", "RHSArithmeticExpression", index, newValue);
}
#endregion // RHSArithmeticExpression accessor methods
#region RHSArithmeticExpression collection
public RHSArithmeticExpressionCollection MyRHSArithmeticExpressions = new RHSArithmeticExpressionCollection( );
public class RHSArithmeticExpressionCollection: IEnumerable
{
SubExpressionType parent;
public SubExpressionType Parent
{
set
{
parent = value;
}
}
public RHSArithmeticExpressionEnumerator GetEnumerator()
{
return new RHSArithmeticExpressionEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class RHSArithmeticExpressionEnumerator: IEnumerator
{
int nIndex;
SubExpressionType parent;
public RHSArithmeticExpressionEnumerator(SubExpressionType par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.RHSArithmeticExpressionCount );
}
public ArithmeticExpression Current
{
get
{
return(parent.GetRHSArithmeticExpressionAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // RHSArithmeticExpression collection
private void SetCollectionParents()
{
MyLHSArithmeticExpressions.Parent = this;
MyArithmeticOperators.Parent = this;
MyRHSArithmeticExpressions.Parent = this;
}
}
}
| |
namespace System.Workflow.Activities
{
#region Imports
using System;
using System.Text;
using System.Reflection;
using System.Collections;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Drawing;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.Runtime.DebugEngine;
using System.Workflow.Activities.Common;
#endregion
[SRDescription(SR.ParallelActivityDescription)]
[ToolboxItem(typeof(ParallelToolboxItem))]
[ToolboxBitmap(typeof(ParallelActivity), "Resources.Parallel.png")]
[Designer(typeof(ParallelDesigner), typeof(IDesigner))]
[ActivityValidator(typeof(ParallelValidator))]
[SRCategory(SR.Standard)]
[WorkflowDebuggerSteppingAttribute(WorkflowDebuggerSteppingOption.Concurrent)]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class ParallelActivity : CompositeActivity, IActivityEventListener<ActivityExecutionStatusChangedEventArgs>
{
#region Constructors
public ParallelActivity()
{
}
public ParallelActivity(string name)
: base(name)
{
}
#endregion
#region Protected Methods
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
//Tomark that execute method is called for this activity.
this.IsExecuting = true;
for (int i = 0; i < this.EnabledActivities.Count; ++i)
{
Activity childActivity = this.EnabledActivities[i];
childActivity.RegisterForStatusChange(Activity.ClosedEvent, this);
executionContext.ExecuteActivity(childActivity);
}
return (this.EnabledActivities.Count == 0) ? ActivityExecutionStatus.Closed : ActivityExecutionStatus.Executing;
}
protected override ActivityExecutionStatus Cancel(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
bool canCloseNow = true;
for (int i = 0; i < this.EnabledActivities.Count; ++i)
{
Activity childActivity = this.EnabledActivities[i];
if (childActivity.ExecutionStatus == ActivityExecutionStatus.Executing)
{
executionContext.CancelActivity(childActivity);
canCloseNow = false;
}
else if (childActivity.ExecutionStatus == ActivityExecutionStatus.Canceling || childActivity.ExecutionStatus == ActivityExecutionStatus.Faulting)
{
canCloseNow = false;
}
}
return canCloseNow ? ActivityExecutionStatus.Closed : ActivityExecutionStatus.Canceling;
}
protected override void OnClosed(IServiceProvider provider)
{
base.RemoveProperty(ParallelActivity.IsExecutingProperty);
}
protected override void OnActivityChangeAdd(ActivityExecutionContext executionContext, Activity addedActivity)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
if (addedActivity == null)
throw new ArgumentNullException("addedActivity");
ParallelActivity parallel = executionContext.Activity as ParallelActivity;
if (parallel.ExecutionStatus == ActivityExecutionStatus.Executing && parallel.IsExecuting)
{
addedActivity.RegisterForStatusChange(Activity.ClosedEvent, this);
executionContext.ExecuteActivity(addedActivity);
}
}
protected override void OnActivityChangeRemove(ActivityExecutionContext rootExecutionContext, Activity removedActivity)
{
}
protected override void OnWorkflowChangesCompleted(ActivityExecutionContext executionContext)
{
base.OnWorkflowChangesCompleted(executionContext);
if (this.IsExecuting)
{
bool canCloseNow = true;
for (int i = 0; i < this.EnabledActivities.Count; ++i)
{
Activity childActivity = this.EnabledActivities[i];
if (childActivity.ExecutionStatus != ActivityExecutionStatus.Closed)
{
canCloseNow = false;
break;
}
}
if (canCloseNow)
executionContext.CloseActivity();
}
}
#endregion
#region IActivityEventListener<ActivityExecutionStatusChangedEventArgs> Members
void IActivityEventListener<ActivityExecutionStatusChangedEventArgs>.OnEvent(object sender, ActivityExecutionStatusChangedEventArgs e)
{
if (sender == null)
throw new ArgumentNullException("sender");
if (e == null)
throw new ArgumentNullException("e");
ActivityExecutionContext context = sender as ActivityExecutionContext;
if (context == null)
throw new ArgumentException(SR.Error_SenderMustBeActivityExecutionContext, "sender");
ParallelActivity parallel = context.Activity as ParallelActivity;
e.Activity.UnregisterForStatusChange(Activity.ClosedEvent, this);
bool canCloseNow = true;
for (int i = 0; i < parallel.EnabledActivities.Count; ++i)
{
Activity childActivity = parallel.EnabledActivities[i];
if (!(childActivity.ExecutionStatus == ActivityExecutionStatus.Initialized || childActivity.ExecutionStatus == ActivityExecutionStatus.Closed))
{
canCloseNow = false;
break;
}
}
if (canCloseNow)
context.CloseActivity();
}
#endregion
#region Runtime Specific Data
//Runtime Properties
static DependencyProperty IsExecutingProperty = DependencyProperty.Register("IsExecuting", typeof(bool), typeof(ParallelActivity), new PropertyMetadata(false));
private bool IsExecuting
{
get
{
return (bool)base.GetValue(IsExecutingProperty);
}
set
{
base.SetValue(IsExecutingProperty, value);
}
}
#endregion
}
#region Validator
internal sealed class ParallelValidator : CompositeActivityValidator
{
public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
{
ValidationErrorCollection validationErrors = base.Validate(manager, obj);
ParallelActivity parallel = obj as ParallelActivity;
if (parallel == null)
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(ParallelActivity).FullName), "obj");
// Validate number of children
if (parallel.EnabledActivities.Count < 2)
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_ParallelLessThanTwoChildren), ErrorNumbers.Error_ParallelLessThanTwoChildren));
bool notAllSequence = false;
foreach (Activity activity in parallel.EnabledActivities)
{
if (activity.GetType() != typeof(SequenceActivity))
{
notAllSequence = true;
}
}
// Validate that all child activities are sequence activities.
if (notAllSequence)
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_ParallelNotAllSequence), ErrorNumbers.Error_ParallelNotAllSequence));
return validationErrors;
}
}
#endregion
}
| |
using System.Collections.Generic;
using System.Linq;
using Chutzpah.FrameworkDefinitions;
using Chutzpah.Models;
using Chutzpah.Utility;
using Chutzpah.Wrappers;
using Moq;
using Xunit;
namespace Chutzpah.Facts
{
public class TestHarnessBuilderFacts
{
private const string TestTempateContents = @"
<!DOCTYPE html><html><head>
@@TestFrameworkDependencies@@
@@ReferencedCSSFiles@@
@@TestHtmlTemplateFiles@@
@@ReferencedJSFiles@@
@@TestJSFile@@
@@CustomReplacement1@@
@@CustomReplacement2@@
</head>
<body><div id=""qunit-fixture""></div></body></html>
";
private static string TestContextBuilder_GetScriptStatement(string path)
{
return new Script(new ReferencedFile { Path = path }).ToString();
}
private static string TestContextBuilder_GetStyleStatement(string path)
{
return new ExternalStylesheet(new ReferencedFile { Path = path }).ToString();
}
private class TestableTestHarnessBuilder : Testable<TestHarnessBuilder>
{
public TestableTestHarnessBuilder()
{
var frameworkMock = Mock<IFrameworkDefinition>();
frameworkMock.Setup(x => x.FileUsesFramework(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<PathType>())).Returns(true);
frameworkMock.Setup(x => x.FrameworkKey).Returns("qunit");
frameworkMock.Setup(x => x.GetTestRunner(It.IsAny<ChutzpahTestSettingsFile>())).Returns("qunitRunner.js");
frameworkMock.Setup(x => x.GetTestHarness(It.IsAny<ChutzpahTestSettingsFile>())).Returns("qunit.html");
frameworkMock.Setup(x => x.GetFileDependencies(It.IsAny<ChutzpahTestSettingsFile>())).Returns(new[] { "qunit.js", "qunit.css" });
Mock<IFileProbe>().Setup(x => x.FindFilePath(It.IsAny<string>())).Returns<string>(x => x);
Mock<IFileProbe>().Setup(x => x.GetPathInfo(It.IsAny<string>())).Returns<string>(x => new PathInfo { FullPath = x, Type = PathType.JavaScript });
Mock<IFileSystemWrapper>().Setup(x => x.GetTemporaryFolder(It.IsAny<string>())).Returns(@"C:\temp\");
Mock<IFileSystemWrapper>().Setup(x => x.GetText(It.IsAny<string>())).Returns(string.Empty);
Mock<IFileSystemWrapper>().Setup(x => x.GetRandomFileName()).Returns("unique");
Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
Mock<IHasher>().Setup(x => x.Hash(It.IsAny<string>())).Returns("hash");
Mock<IFileProbe>()
.Setup(x => x.GetPathInfo(@"TestFiles\qunit.html"))
.Returns(new PathInfo { Type = PathType.JavaScript, FullPath = @"path\qunit.html" });
Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\qunit.html"))
.Returns(TestTempateContents);
}
public TestContext GetContext()
{
var context = new TestContext
{
InputTestFiles = new []{ @"C:\folder\test.js"},
TestHarnessDirectory = @"C:\folder",
FrameworkDefinition = Mock<IFrameworkDefinition>().Object,
TestFileSettings = new ChutzpahTestSettingsFile().InheritFromDefault()
};
context.TestFileSettings.SettingsFileDirectory = "settingsPath";
return context;
}
}
[Fact]
public void Will_save_generated_test_html()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
creator.Mock<IFileSystemWrapper>().Verify(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()));
Assert.Equal(@"C:\folder\_Chutzpah.hash.test.html", context.TestHarnessPath);
Assert.Equal(@"C:\folder\test.js", context.InputTestFiles.FirstOrDefault());
}
[Fact]
public void Will_use_custom_template_path()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
string text = null;
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\qunit.js", IsTestFrameworkFile = true});
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\qunit.css", IsTestFrameworkFile = true });
context.TestFileSettings.CustomTestHarnessPath = @"folder\customHarness.html";
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(@"settingsPath\folder\customHarness.html"))
.Returns(@"path\customHarness.html");
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\customHarness.html"))
.Returns(TestTempateContents);
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
string scriptStatement = TestContextBuilder_GetScriptStatement(@"path\qunit.js");
string cssStatement = TestContextBuilder_GetStyleStatement(@"path\qunit.css");
Assert.Contains(scriptStatement, text);
Assert.Contains(cssStatement, text);
Assert.DoesNotContain("@@TestFrameworkDependencies@@", text);
}
[Fact]
public void Will_replace_test_dependency_placeholder_in_test_harness_html()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\qunit.js", IsTestFrameworkFile = true });
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\qunit.css", IsTestFrameworkFile = true });
string text = null;
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
string scriptStatement = TestContextBuilder_GetScriptStatement(@"path\qunit.js");
string cssStatement = TestContextBuilder_GetStyleStatement(@"path\qunit.css");
Assert.Contains(scriptStatement, text);
Assert.Contains(cssStatement, text);
Assert.DoesNotContain("@@TestFrameworkDependencies@@", text);
}
[Fact]
public void Will_put_test_html_file_at_end_of_references_in_html_template()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\file.html" });
string text = null;
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\file.html"))
.Returns("<h1>This is the included HTML</h1>");
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
Assert.Contains("<h1>This is the included HTML</h1>", text);
}
[Fact]
public void Will_put_test_js_file_at_end_of_references_in_html_template_with_test_file()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\test.js", IsFileUnderTest = true });
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\lib.js" });
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\common.js" });
string text = null;
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
string scriptStatement1 = TestContextBuilder_GetScriptStatement(@"path\lib.js");
string scriptStatement2 = TestContextBuilder_GetScriptStatement(@"path\common.js");
string scriptStatement3 = TestContextBuilder_GetScriptStatement(@"path\test.js");
var pos1 = text.IndexOf(scriptStatement1);
var pos2 = text.IndexOf(scriptStatement2);
var pos3 = text.IndexOf(scriptStatement3);
Assert.True(pos1 < pos2);
Assert.True(pos2 < pos3);
Assert.Equal(1, context.ReferencedFiles.Count(x => x.IsFileUnderTest));
}
[Fact]
public void Will_replace_referenced_js_file_place_holder_in_html_template_with_referenced_js_files_from_js_test_file()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\lib.js" });
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\common.js" });
string text = null;
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
string scriptStatement1 = TestContextBuilder_GetScriptStatement(@"path\lib.js");
string scriptStatement2 = TestContextBuilder_GetScriptStatement(@"path\common.js");
Assert.Contains(scriptStatement1, text);
Assert.Contains(scriptStatement2, text);
Assert.DoesNotContain("@@ReferencedJSFiles@@", text);
}
[Fact]
public void Will_replace_referenced_css_file_place_holder_in_html_template_with_referenced_css_files_from_js_test_file()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\style.css" });
string text = null;
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
string styleStatement = TestContextBuilder_GetStyleStatement(@"path\style.css");
Assert.Contains(styleStatement, text);
Assert.DoesNotContain("@@ReferencedCSSFiles@@", text);
}
[Fact]
public void Will_replace_custom_framework_placeholders_with_contents_from_framwork_definition()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
string text = null;
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.Mock<IFrameworkDefinition>()
.Setup(x => x.GetFrameworkReplacements(It.IsAny<ChutzpahTestSettingsFile>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(new Dictionary<string, string>
{
{"CustomReference1", "CustomReplacement1"},
{"CustomReference2", "CustomReplacement2"}
});
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
Assert.DoesNotContain("@@CustomReference1@@", text);
Assert.DoesNotContain("@@CustomReference2@@", text);
Assert.Contains("CustomReplacement1", text);
Assert.Contains("CustomReplacement2", text);
}
}
}
| |
/*
* 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.
*/
// ReSharper disable UnassignedField.Global
// ReSharper disable CollectionNeverUpdated.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace Apache.Ignite.Core.Tests.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using NUnit.Framework;
/// <summary>
/// Binary builder self test.
/// </summary>
public class BinaryBuilderSelfTest
{
/** Undefined type: Empty. */
private const string TypeEmpty = "EmptyUndefined";
/** Grid. */
private Ignite _grid;
/** Marshaller. */
private Marshaller _marsh;
/// <summary>
/// Set up routine.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
TestUtils.KillProcesses();
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = GetTypeConfigurations(),
IdMapper = new IdMapper(),
NameMapper = new NameMapper(GetNameMapper()),
CompactFooter = GetCompactFooter(),
}
};
_grid = (Ignite) Ignition.Start(cfg);
_marsh = _grid.Marshaller;
}
/// <summary>
/// Gets the type configurations.
/// </summary>
protected virtual ICollection<BinaryTypeConfiguration> GetTypeConfigurations()
{
return new[]
{
new BinaryTypeConfiguration(typeof(Empty)),
new BinaryTypeConfiguration(typeof(Primitives)),
new BinaryTypeConfiguration(typeof(PrimitiveArrays)),
new BinaryTypeConfiguration(typeof(StringDateGuidEnum)),
new BinaryTypeConfiguration(typeof(WithRaw)),
new BinaryTypeConfiguration(typeof(MetaOverwrite)),
new BinaryTypeConfiguration(typeof(NestedOuter)),
new BinaryTypeConfiguration(typeof(NestedInner)),
new BinaryTypeConfiguration(typeof(MigrationOuter)),
new BinaryTypeConfiguration(typeof(MigrationInner)),
new BinaryTypeConfiguration(typeof(InversionOuter)),
new BinaryTypeConfiguration(typeof(InversionInner)),
new BinaryTypeConfiguration(typeof(CompositeOuter)),
new BinaryTypeConfiguration(typeof(CompositeInner)),
new BinaryTypeConfiguration(typeof(CompositeArray)),
new BinaryTypeConfiguration(typeof(CompositeContainer)),
new BinaryTypeConfiguration(typeof(ToBinary)),
new BinaryTypeConfiguration(typeof(Remove)),
new BinaryTypeConfiguration(typeof(RemoveInner)),
new BinaryTypeConfiguration(typeof(BuilderInBuilderOuter)),
new BinaryTypeConfiguration(typeof(BuilderInBuilderInner)),
new BinaryTypeConfiguration(typeof(BuilderCollection)),
new BinaryTypeConfiguration(typeof(BuilderCollectionItem)),
new BinaryTypeConfiguration(typeof(DecimalHolder)),
new BinaryTypeConfiguration(TypeEmpty),
new BinaryTypeConfiguration(typeof(TestEnumRegistered)),
new BinaryTypeConfiguration(typeof(NameMapperTestType))
};
}
/// <summary>
/// Gets the compact footer setting.
/// </summary>
protected virtual bool GetCompactFooter()
{
return true;
}
/// <summary>
/// Gets the name mapper.
/// </summary>
protected virtual IBinaryNameMapper GetNameMapper()
{
return BinaryBasicNameMapper.FullNameInstance;
}
/// <summary>
/// Gets the name of the type.
/// </summary>
private string GetTypeName(Type type)
{
return GetNameMapper().GetTypeName(type.AssemblyQualifiedName);
}
/// <summary>
/// Tear down routine.
/// </summary>
[TestFixtureTearDown]
public void TearDown()
{
Ignition.StopAll(true);
_grid = null;
}
/// <summary>
/// Ensure that binary engine is able to work with type names, which are not configured.
/// </summary>
[Test]
public void TestNonConfigured()
{
string typeName1 = "Type1";
string typeName2 = "Type2";
string field1 = "field1";
string field2 = "field2";
// 1. Ensure that builder works fine.
IBinaryObject binObj1 = _grid.GetBinary().GetBuilder(typeName1).SetField(field1, 1).Build();
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 2. Ensure that object can be unmarshalled without deserialization.
byte[] data = ((BinaryObject) binObj1).Data;
binObj1 = _grid.Marshaller.Unmarshal<IBinaryObject>(data, BinaryMode.ForceBinary);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 3. Ensure that we can nest one anonymous object inside another
IBinaryObject binObj2 =
_grid.GetBinary().GetBuilder(typeName2).SetField(field2, binObj1).Build();
Assert.AreEqual(typeName2, binObj2.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj2.GetBinaryType().Fields.Count);
Assert.AreEqual(field2, binObj2.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, binObj2.GetBinaryType().GetFieldTypeName(field2));
binObj1 = binObj2.GetField<IBinaryObject>(field2);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 4. Ensure that we can unmarshal object with other nested object.
data = ((BinaryObject) binObj2).Data;
binObj2 = _grid.Marshaller.Unmarshal<IBinaryObject>(data, BinaryMode.ForceBinary);
Assert.AreEqual(typeName2, binObj2.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj2.GetBinaryType().Fields.Count);
Assert.AreEqual(field2, binObj2.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, binObj2.GetBinaryType().GetFieldTypeName(field2));
binObj1 = binObj2.GetField<IBinaryObject>(field2);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
}
/// <summary>
/// Test "ToBinary()" method.
/// </summary>
[Test]
public void TestToBinary()
{
DateTime date = DateTime.Now.ToUniversalTime();
Guid guid = Guid.NewGuid();
IBinary api = _grid.GetBinary();
// 1. Primitives.
Assert.AreEqual(1, api.ToBinary<byte>((byte)1));
Assert.AreEqual(1, api.ToBinary<short>((short)1));
Assert.AreEqual(1, api.ToBinary<int>(1));
Assert.AreEqual(1, api.ToBinary<long>((long)1));
Assert.AreEqual((float)1, api.ToBinary<float>((float)1));
Assert.AreEqual((double)1, api.ToBinary<double>((double)1));
Assert.AreEqual(true, api.ToBinary<bool>(true));
Assert.AreEqual('a', api.ToBinary<char>('a'));
// 2. Special types.
Assert.AreEqual("a", api.ToBinary<string>("a"));
Assert.AreEqual(date, api.ToBinary<IBinaryObject>(date).Deserialize<DateTime>());
Assert.AreEqual(guid, api.ToBinary<Guid>(guid));
Assert.AreEqual(TestEnumRegistered.One, api.ToBinary<IBinaryObject>(TestEnumRegistered.One)
.Deserialize<TestEnumRegistered>());
// 3. Arrays.
Assert.AreEqual(new byte[] { 1 }, api.ToBinary<byte[]>(new byte[] { 1 }));
Assert.AreEqual(new short[] { 1 }, api.ToBinary<short[]>(new short[] { 1 }));
Assert.AreEqual(new[] { 1 }, api.ToBinary<int[]>(new[] { 1 }));
Assert.AreEqual(new long[] { 1 }, api.ToBinary<long[]>(new long[] { 1 }));
Assert.AreEqual(new float[] { 1 }, api.ToBinary<float[]>(new float[] { 1 }));
Assert.AreEqual(new double[] { 1 }, api.ToBinary<double[]>(new double[] { 1 }));
Assert.AreEqual(new[] { true }, api.ToBinary<bool[]>(new[] { true }));
Assert.AreEqual(new[] { 'a' }, api.ToBinary<char[]>(new[] { 'a' }));
Assert.AreEqual(new[] { "a" }, api.ToBinary<string[]>(new[] { "a" }));
Assert.AreEqual(new[] {date}, api.ToBinary<IBinaryObject[]>(new[] {date})
.Select(x => x.Deserialize<DateTime>()));
Assert.AreEqual(new[] { guid }, api.ToBinary<Guid[]>(new[] { guid }));
Assert.AreEqual(new[] { TestEnumRegistered.One},
api.ToBinary<IBinaryObject[]>(new[] { TestEnumRegistered.One})
.Select(x => x.Deserialize<TestEnumRegistered>()).ToArray());
// 4. Objects.
IBinaryObject binObj = api.ToBinary<IBinaryObject>(new ToBinary(1));
Assert.AreEqual(GetTypeName(typeof(ToBinary)), binObj.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj.GetBinaryType().Fields.Count);
Assert.AreEqual("Val", binObj.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj.GetBinaryType().GetFieldTypeName("Val"));
Assert.AreEqual(1, binObj.GetField<int>("val"));
Assert.AreEqual(1, binObj.Deserialize<ToBinary>().Val);
// 5. Object array.
var binObjArr = api.ToBinary<object[]>(new object[] {new ToBinary(1)})
.OfType<IBinaryObject>().ToArray();
Assert.AreEqual(1, binObjArr.Length);
Assert.AreEqual(1, binObjArr[0].GetField<int>("Val"));
Assert.AreEqual(1, binObjArr[0].Deserialize<ToBinary>().Val);
}
/// <summary>
/// Test builder field remove logic.
/// </summary>
[Test]
public void TestRemove()
{
// Create empty object.
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Remove)).Build();
Assert.IsNull(binObj.GetField<object>("val"));
Assert.IsNull(binObj.Deserialize<Remove>().Val);
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(Remove)), meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
// Populate it with field.
IBinaryObjectBuilder builder = binObj.ToBuilder();
Assert.IsNull(builder.GetField<object>("val"));
object val = 1;
builder.SetField("val", val);
Assert.AreEqual(val, builder.GetField<object>("val"));
binObj = builder.Build();
Assert.AreEqual(val, binObj.GetField<object>("val"));
Assert.AreEqual(val, binObj.Deserialize<Remove>().Val);
meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(Remove)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("val", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("val"));
// Perform field remove.
builder = binObj.ToBuilder();
Assert.AreEqual(val, builder.GetField<object>("val"));
builder.RemoveField("val");
Assert.IsNull(builder.GetField<object>("val"));
builder.SetField("val", val);
Assert.AreEqual(val, builder.GetField<object>("val"));
builder.RemoveField("val");
Assert.IsNull(builder.GetField<object>("val"));
binObj = builder.Build();
Assert.IsNull(binObj.GetField<object>("val"));
Assert.IsNull(binObj.Deserialize<Remove>().Val);
// Test correct removal of field being referenced by handle somewhere else.
RemoveInner inner = new RemoveInner(2);
binObj = _grid.GetBinary().GetBuilder(typeof(Remove))
.SetField("val", inner)
.SetField("val2", inner)
.Build();
binObj = binObj.ToBuilder().RemoveField("val").Build();
Remove obj = binObj.Deserialize<Remove>();
Assert.IsNull(obj.Val);
Assert.AreEqual(2, obj.Val2.Val);
}
/// <summary>
/// Test builder-in-builder scenario.
/// </summary>
[Test]
public void TestBuilderInBuilder()
{
// Test different builders assembly.
IBinaryObjectBuilder builderOuter = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderOuter));
IBinaryObjectBuilder builderInner = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderInner));
builderOuter.SetField<object>("inner", builderInner);
builderInner.SetField<object>("outer", builderOuter);
IBinaryObject outerbinObj = builderOuter.Build();
IBinaryType meta = outerbinObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(BuilderInBuilderOuter)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("inner", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner"));
IBinaryObject innerbinObj = outerbinObj.GetField<IBinaryObject>("inner");
meta = innerbinObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(BuilderInBuilderInner)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("outer", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("outer"));
BuilderInBuilderOuter outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer, outer.Inner.Outer);
// Test same builders assembly.
innerbinObj = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderInner)).Build();
outerbinObj = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderOuter))
.SetField("inner", innerbinObj)
.SetField("inner2", innerbinObj)
.Build();
meta = outerbinObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(BuilderInBuilderOuter)), meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.IsTrue(meta.Fields.Contains("inner"));
Assert.IsTrue(meta.Fields.Contains("inner2"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner2"));
outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer.Inner, outer.Inner2);
builderOuter = _grid.GetBinary().GetBuilder(outerbinObj);
IBinaryObjectBuilder builderInner2 = builderOuter.GetField<IBinaryObjectBuilder>("inner2");
builderInner2.SetField("outer", builderOuter);
outerbinObj = builderOuter.Build();
outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer, outer.Inner.Outer);
Assert.AreSame(outer.Inner, outer.Inner2);
}
/// <summary>
/// Test for decimals building.
/// </summary>
[Test]
public void TestDecimals()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(DecimalHolder))
.SetField("val", decimal.One)
.SetField("valArr", new decimal?[] { decimal.MinusOne })
.Build();
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(DecimalHolder)), meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.IsTrue(meta.Fields.Contains("val"));
Assert.IsTrue(meta.Fields.Contains("valArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameDecimal, meta.GetFieldTypeName("val"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDecimal, meta.GetFieldTypeName("valArr"));
Assert.AreEqual(decimal.One, binObj.GetField<decimal>("val"));
Assert.AreEqual(new decimal?[] { decimal.MinusOne }, binObj.GetField<decimal?[]>("valArr"));
DecimalHolder obj = binObj.Deserialize<DecimalHolder>();
Assert.AreEqual(decimal.One, obj.Val);
Assert.AreEqual(new decimal?[] { decimal.MinusOne }, obj.ValArr);
}
/// <summary>
/// Test for an object returning collection of builders.
/// </summary>
[Test]
public void TestBuilderCollection()
{
// Test collection with single element.
IBinaryObjectBuilder builderCol = _grid.GetBinary().GetBuilder(typeof(BuilderCollection));
IBinaryObjectBuilder builderItem =
_grid.GetBinary().GetBuilder(typeof(BuilderCollectionItem)).SetField("val", 1);
builderCol.SetCollectionField("col", new ArrayList { builderItem });
IBinaryObject binCol = builderCol.Build();
IBinaryType meta = binCol.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(BuilderCollection)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("col", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameCollection, meta.GetFieldTypeName("col"));
var binColItems = binCol.GetField<ArrayList>("col");
Assert.AreEqual(1, binColItems.Count);
var binItem = (IBinaryObject) binColItems[0];
meta = binItem.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(BuilderCollectionItem)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("val", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, meta.GetFieldTypeName("val"));
BuilderCollection col = binCol.Deserialize<BuilderCollection>();
Assert.IsNotNull(col.Col);
Assert.AreEqual(1, col.Col.Count);
Assert.AreEqual(1, ((BuilderCollectionItem) col.Col[0]).Val);
// Add more binary objects to collection.
builderCol = _grid.GetBinary().GetBuilder(binCol);
IList builderColItems = builderCol.GetField<IList>("col");
Assert.AreEqual(1, builderColItems.Count);
BinaryObjectBuilder builderColItem = (BinaryObjectBuilder) builderColItems[0];
builderColItem.SetField("val", 2); // Change nested value.
builderColItems.Add(builderColItem); // Add the same object to check handles.
builderColItems.Add(builderItem); // Add item from another builder.
builderColItems.Add(binItem); // Add item in binary form.
binCol = builderCol.Build();
col = binCol.Deserialize<BuilderCollection>();
Assert.AreEqual(4, col.Col.Count);
var item0 = (BuilderCollectionItem) col.Col[0];
var item1 = (BuilderCollectionItem) col.Col[1];
var item2 = (BuilderCollectionItem) col.Col[2];
var item3 = (BuilderCollectionItem) col.Col[3];
Assert.AreEqual(2, item0.Val);
Assert.AreSame(item0, item1);
Assert.AreNotSame(item0, item2);
Assert.AreNotSame(item0, item3);
Assert.AreEqual(1, item2.Val);
Assert.AreEqual(1, item3.Val);
Assert.AreNotSame(item2, item3);
// Test handle update inside collection.
builderCol = _grid.GetBinary().GetBuilder(binCol);
builderColItems = builderCol.GetField<IList>("col");
((BinaryObjectBuilder) builderColItems[1]).SetField("val", 3);
binCol = builderCol.Build();
col = binCol.Deserialize<BuilderCollection>();
item0 = (BuilderCollectionItem) col.Col[0];
item1 = (BuilderCollectionItem) col.Col[1];
Assert.AreEqual(3, item0.Val);
Assert.AreSame(item0, item1);
}
/// <summary>
/// Test build of an empty object.
/// </summary>
[Test]
public void TestEmptyDefined()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Empty)).Build();
Assert.IsNotNull(binObj);
Assert.AreEqual(1, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.IsNotNull(meta);
Assert.AreEqual(GetTypeName(typeof(Empty)), meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
Empty obj = binObj.Deserialize<Empty>();
Assert.IsNotNull(obj);
}
/// <summary>
/// Test build of an empty undefined object.
/// </summary>
[Test]
public void TestEmptyUndefined()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(TypeEmpty).Build();
Assert.IsNotNull(binObj);
Assert.AreEqual(1, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.IsNotNull(meta);
Assert.AreEqual(TypeEmpty, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
}
/// <summary>
/// Test object rebuild with no changes.
/// </summary>
[Test]
public void TestEmptyRebuild()
{
var binObj = (BinaryObject) _grid.GetBinary().GetBuilder(typeof(Empty)).Build();
BinaryObject newbinObj = (BinaryObject) _grid.GetBinary().GetBuilder(binObj).Build();
Assert.AreEqual(binObj.Data, newbinObj.Data);
}
/// <summary>
/// Tests equality and formatting members.
/// </summary>
[Test]
public void TestEquality()
{
var bin = _grid.GetBinary();
var obj1 = bin.GetBuilder("myType").SetStringField("str", "foo").SetIntField("int", 1).Build();
var obj2 = bin.GetBuilder("myType").SetStringField("str", "foo").SetIntField("int", 1).Build();
Assert.AreEqual(obj1, obj2);
Assert.AreEqual(-88648479, obj1.GetHashCode());
Assert.AreEqual(obj1.GetHashCode(), obj2.GetHashCode());
Assert.AreEqual("myType [, int=1, str=foo]", Regex.Replace(obj1.ToString(), "idHash=\\d+", ""));
}
/// <summary>
/// Test primitive fields setting.
/// </summary>
[Test]
public void TestPrimitiveFields()
{
// Generic SetField method.
var binObj = _grid.GetBinary().GetBuilder(typeof(Primitives))
.SetField<byte>("fByte", 1)
.SetField("fBool", true)
.SetField<short>("fShort", 2)
.SetField("fChar", 'a')
.SetField("fInt", 3)
.SetField<long>("fLong", 4)
.SetField<float>("fFloat", 5)
.SetField<double>("fDouble", 6)
.SetField("fDecimal", 7.7m)
.Build();
CheckPrimitiveFields1(binObj);
// Rebuild unchanged.
binObj = binObj.ToBuilder().Build();
CheckPrimitiveFields1(binObj);
// Specific setter methods.
var binObj2 = _grid.GetBinary().GetBuilder(typeof(Primitives))
.SetByteField("fByte", 1)
.SetBooleanField("fBool", true)
.SetShortField("fShort", 2)
.SetCharField("fChar", 'a')
.SetIntField("fInt", 3)
.SetLongField("fLong", 4)
.SetFloatField("fFloat", 5)
.SetDoubleField("fDouble", 6)
.SetDecimalField("fDecimal", 7.7m)
.Build();
CheckPrimitiveFields1(binObj2);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
// Overwrite with generic methods.
binObj = binObj.ToBuilder()
.SetField<byte>("fByte", 7)
.SetField("fBool", false)
.SetField<short>("fShort", 8)
.SetField("fChar", 'b')
.SetField("fInt", 9)
.SetField<long>("fLong", 10)
.SetField<float>("fFloat", 11)
.SetField<double>("fDouble", 12)
.SetField("fDecimal", 13.13m)
.Build();
CheckPrimitiveFields2(binObj);
// Overwrite with specific methods.
binObj2 = binObj.ToBuilder()
.SetByteField("fByte", 7)
.SetBooleanField("fBool", false)
.SetShortField("fShort", 8)
.SetCharField("fChar", 'b')
.SetIntField("fInt", 9)
.SetLongField("fLong", 10)
.SetFloatField("fFloat", 11)
.SetDoubleField("fDouble", 12)
.SetDecimalField("fDecimal", 13.13m)
.Build();
CheckPrimitiveFields2(binObj);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
}
/// <summary>
/// Checks the primitive fields values.
/// </summary>
private void CheckPrimitiveFields1(IBinaryObject binObj)
{
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(Primitives)), meta.TypeName);
Assert.AreEqual(9, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameByte, meta.GetFieldTypeName("fByte"));
Assert.AreEqual(BinaryTypeNames.TypeNameBool, meta.GetFieldTypeName("fBool"));
Assert.AreEqual(BinaryTypeNames.TypeNameShort, meta.GetFieldTypeName("fShort"));
Assert.AreEqual(BinaryTypeNames.TypeNameChar, meta.GetFieldTypeName("fChar"));
Assert.AreEqual(BinaryTypeNames.TypeNameInt, meta.GetFieldTypeName("fInt"));
Assert.AreEqual(BinaryTypeNames.TypeNameLong, meta.GetFieldTypeName("fLong"));
Assert.AreEqual(BinaryTypeNames.TypeNameFloat, meta.GetFieldTypeName("fFloat"));
Assert.AreEqual(BinaryTypeNames.TypeNameDouble, meta.GetFieldTypeName("fDouble"));
Assert.AreEqual(BinaryTypeNames.TypeNameDecimal, meta.GetFieldTypeName("fDecimal"));
Assert.AreEqual(1, binObj.GetField<byte>("fByte"));
Assert.AreEqual(true, binObj.GetField<bool>("fBool"));
Assert.AreEqual(2, binObj.GetField<short>("fShort"));
Assert.AreEqual('a', binObj.GetField<char>("fChar"));
Assert.AreEqual(3, binObj.GetField<int>("fInt"));
Assert.AreEqual(4, binObj.GetField<long>("fLong"));
Assert.AreEqual(5, binObj.GetField<float>("fFloat"));
Assert.AreEqual(6, binObj.GetField<double>("fDouble"));
Assert.AreEqual(7.7m, binObj.GetField<decimal>("fDecimal"));
Primitives obj = binObj.Deserialize<Primitives>();
Assert.AreEqual(1, obj.FByte);
Assert.AreEqual(true, obj.FBool);
Assert.AreEqual(2, obj.FShort);
Assert.AreEqual('a', obj.FChar);
Assert.AreEqual(3, obj.FInt);
Assert.AreEqual(4, obj.FLong);
Assert.AreEqual(5, obj.FFloat);
Assert.AreEqual(6, obj.FDouble);
Assert.AreEqual(7.7m, obj.FDecimal);
}
/// <summary>
/// Checks the primitive fields values.
/// </summary>
private static void CheckPrimitiveFields2(IBinaryObject binObj)
{
Assert.AreEqual(7, binObj.GetField<byte>("fByte"));
Assert.AreEqual(false, binObj.GetField<bool>("fBool"));
Assert.AreEqual(8, binObj.GetField<short>("fShort"));
Assert.AreEqual('b', binObj.GetField<char>("fChar"));
Assert.AreEqual(9, binObj.GetField<int>("fInt"));
Assert.AreEqual(10, binObj.GetField<long>("fLong"));
Assert.AreEqual(11, binObj.GetField<float>("fFloat"));
Assert.AreEqual(12, binObj.GetField<double>("fDouble"));
Assert.AreEqual(13.13m, binObj.GetField<decimal>("fDecimal"));
var obj = binObj.Deserialize<Primitives>();
Assert.AreEqual(7, obj.FByte);
Assert.AreEqual(false, obj.FBool);
Assert.AreEqual(8, obj.FShort);
Assert.AreEqual('b', obj.FChar);
Assert.AreEqual(9, obj.FInt);
Assert.AreEqual(10, obj.FLong);
Assert.AreEqual(11, obj.FFloat);
Assert.AreEqual(12, obj.FDouble);
Assert.AreEqual(13.13m, obj.FDecimal);
}
/// <summary>
/// Test primitive array fields setting.
/// </summary>
[Test]
public void TestPrimitiveArrayFields()
{
// Generic SetField method.
var binObj = _grid.GetBinary().GetBuilder(typeof(PrimitiveArrays))
.SetField("fByte", new byte[] { 1 })
.SetField("fBool", new[] { true })
.SetField("fShort", new short[] { 2 })
.SetField("fChar", new[] { 'a' })
.SetField("fInt", new[] { 3 })
.SetField("fLong", new long[] { 4 })
.SetField("fFloat", new float[] { 5 })
.SetField("fDouble", new double[] { 6 })
.SetField("fDecimal", new decimal?[] { 7.7m })
.Build();
CheckPrimitiveArrayFields1(binObj);
// Rebuild unchanged.
binObj = binObj.ToBuilder().Build();
CheckPrimitiveArrayFields1(binObj);
// Specific setters.
var binObj2 = _grid.GetBinary().GetBuilder(typeof(PrimitiveArrays))
.SetByteArrayField("fByte", new byte[] {1})
.SetBooleanArrayField("fBool", new[] {true})
.SetShortArrayField("fShort", new short[] {2})
.SetCharArrayField("fChar", new[] {'a'})
.SetIntArrayField("fInt", new[] {3})
.SetLongArrayField("fLong", new long[] {4})
.SetFloatArrayField("fFloat", new float[] {5})
.SetDoubleArrayField("fDouble", new double[] {6})
.SetDecimalArrayField("fDecimal", new decimal?[] {7.7m})
.Build();
CheckPrimitiveArrayFields1(binObj2);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
// Overwrite with generic setter.
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("fByte", new byte[] { 7 })
.SetField("fBool", new[] { false })
.SetField("fShort", new short[] { 8 })
.SetField("fChar", new[] { 'b' })
.SetField("fInt", new[] { 9 })
.SetField("fLong", new long[] { 10 })
.SetField("fFloat", new float[] { 11 })
.SetField("fDouble", new double[] { 12 })
.SetField("fDecimal", new decimal?[] { 13.13m })
.Build();
CheckPrimitiveArrayFields2(binObj);
// Overwrite with specific setters.
binObj2 = _grid.GetBinary().GetBuilder(binObj)
.SetByteArrayField("fByte", new byte[] { 7 })
.SetBooleanArrayField("fBool", new[] { false })
.SetShortArrayField("fShort", new short[] { 8 })
.SetCharArrayField("fChar", new[] { 'b' })
.SetIntArrayField("fInt", new[] { 9 })
.SetLongArrayField("fLong", new long[] { 10 })
.SetFloatArrayField("fFloat", new float[] { 11 })
.SetDoubleArrayField("fDouble", new double[] { 12 })
.SetDecimalArrayField("fDecimal", new decimal?[] { 13.13m })
.Build();
CheckPrimitiveArrayFields2(binObj);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
}
/// <summary>
/// Checks the primitive array fields.
/// </summary>
private void CheckPrimitiveArrayFields1(IBinaryObject binObj)
{
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(PrimitiveArrays)), meta.TypeName);
Assert.AreEqual(9, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayByte, meta.GetFieldTypeName("fByte"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayBool, meta.GetFieldTypeName("fBool"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayShort, meta.GetFieldTypeName("fShort"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayChar, meta.GetFieldTypeName("fChar"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayInt, meta.GetFieldTypeName("fInt"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayLong, meta.GetFieldTypeName("fLong"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayFloat, meta.GetFieldTypeName("fFloat"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDouble, meta.GetFieldTypeName("fDouble"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDecimal, meta.GetFieldTypeName("fDecimal"));
Assert.AreEqual(new byte[] { 1 }, binObj.GetField<byte[]>("fByte"));
Assert.AreEqual(new[] { true }, binObj.GetField<bool[]>("fBool"));
Assert.AreEqual(new short[] { 2 }, binObj.GetField<short[]>("fShort"));
Assert.AreEqual(new[] { 'a' }, binObj.GetField<char[]>("fChar"));
Assert.AreEqual(new[] { 3 }, binObj.GetField<int[]>("fInt"));
Assert.AreEqual(new long[] { 4 }, binObj.GetField<long[]>("fLong"));
Assert.AreEqual(new float[] { 5 }, binObj.GetField<float[]>("fFloat"));
Assert.AreEqual(new double[] { 6 }, binObj.GetField<double[]>("fDouble"));
Assert.AreEqual(new decimal?[] { 7.7m }, binObj.GetField<decimal?[]>("fDecimal"));
PrimitiveArrays obj = binObj.Deserialize<PrimitiveArrays>();
Assert.AreEqual(new byte[] { 1 }, obj.FByte);
Assert.AreEqual(new[] { true }, obj.FBool);
Assert.AreEqual(new short[] { 2 }, obj.FShort);
Assert.AreEqual(new[] { 'a' }, obj.FChar);
Assert.AreEqual(new[] { 3 }, obj.FInt);
Assert.AreEqual(new long[] { 4 }, obj.FLong);
Assert.AreEqual(new float[] { 5 }, obj.FFloat);
Assert.AreEqual(new double[] { 6 }, obj.FDouble);
Assert.AreEqual(new decimal?[] { 7.7m }, obj.FDecimal);
}
/// <summary>
/// Checks the primitive array fields.
/// </summary>
private static void CheckPrimitiveArrayFields2(IBinaryObject binObj)
{
Assert.AreEqual(new byte[] { 7 }, binObj.GetField<byte[]>("fByte"));
Assert.AreEqual(new[] { false }, binObj.GetField<bool[]>("fBool"));
Assert.AreEqual(new short[] { 8 }, binObj.GetField<short[]>("fShort"));
Assert.AreEqual(new[] { 'b' }, binObj.GetField<char[]>("fChar"));
Assert.AreEqual(new[] { 9 }, binObj.GetField<int[]>("fInt"));
Assert.AreEqual(new long[] { 10 }, binObj.GetField<long[]>("fLong"));
Assert.AreEqual(new float[] { 11 }, binObj.GetField<float[]>("fFloat"));
Assert.AreEqual(new double[] { 12 }, binObj.GetField<double[]>("fDouble"));
Assert.AreEqual(new decimal?[] { 13.13m }, binObj.GetField<decimal?[]>("fDecimal"));
var obj = binObj.Deserialize<PrimitiveArrays>();
Assert.AreEqual(new byte[] { 7 }, obj.FByte);
Assert.AreEqual(new[] { false }, obj.FBool);
Assert.AreEqual(new short[] { 8 }, obj.FShort);
Assert.AreEqual(new[] { 'b' }, obj.FChar);
Assert.AreEqual(new[] { 9 }, obj.FInt);
Assert.AreEqual(new long[] { 10 }, obj.FLong);
Assert.AreEqual(new float[] { 11 }, obj.FFloat);
Assert.AreEqual(new double[] { 12 }, obj.FDouble);
Assert.AreEqual(new decimal?[] { 13.13m }, obj.FDecimal);
}
/// <summary>
/// Test non-primitive fields and their array counterparts.
/// </summary>
[Test]
public void TestStringDateGuidEnum()
{
DateTime? nDate = DateTime.Now.ToUniversalTime();
Guid? nGuid = Guid.NewGuid();
// Generic setters.
var binObj = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetField("fStr", "str")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetField("fNGuid", nGuid)
.SetField("fEnum", TestEnum.One)
.SetStringArrayField("fStrArr", new[] { "str" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetEnumArrayField("fEnumArr", new[] { TestEnum.One })
.Build();
CheckStringDateGuidEnum1(binObj, nDate, nGuid);
// Rebuild with no changes.
binObj = binObj.ToBuilder().Build();
CheckStringDateGuidEnum1(binObj, nDate, nGuid);
// Specific setters.
var binObj2 = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetStringField("fStr", "str")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetGuidField("fNGuid", nGuid)
.SetEnumField("fEnum", TestEnum.One)
.SetStringArrayField("fStrArr", new[] { "str" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetEnumArrayField("fEnumArr", new[] { TestEnum.One })
.Build();
CheckStringDateGuidEnum1(binObj2, nDate, nGuid);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
// Overwrite.
nDate = DateTime.Now.ToUniversalTime();
nGuid = Guid.NewGuid();
binObj = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetField("fStr", "str2")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetField("fNGuid", nGuid)
.SetField("fEnum", TestEnum.Two)
.SetField("fStrArr", new[] { "str2" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetField("fGuidArr", new[] { nGuid })
.SetField("fEnumArr", new[] { TestEnum.Two })
.Build();
CheckStringDateGuidEnum2(binObj, nDate, nGuid);
// Overwrite with specific setters
binObj2 = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetStringField("fStr", "str2")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetGuidField("fNGuid", nGuid)
.SetEnumField("fEnum", TestEnum.Two)
.SetStringArrayField("fStrArr", new[] { "str2" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetEnumArrayField("fEnumArr", new[] { TestEnum.Two })
.Build();
CheckStringDateGuidEnum2(binObj2, nDate, nGuid);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
}
/// <summary>
/// Checks the string date guid enum values.
/// </summary>
private void CheckStringDateGuidEnum1(IBinaryObject binObj, DateTime? nDate, Guid? nGuid)
{
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(StringDateGuidEnum)), meta.TypeName);
Assert.AreEqual(10, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameString, meta.GetFieldTypeName("fStr"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("fNDate"));
Assert.AreEqual(BinaryTypeNames.TypeNameTimestamp, meta.GetFieldTypeName("fNTimestamp"));
Assert.AreEqual(BinaryTypeNames.TypeNameGuid, meta.GetFieldTypeName("fNGuid"));
Assert.AreEqual(BinaryTypeNames.TypeNameEnum, meta.GetFieldTypeName("fEnum"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayString, meta.GetFieldTypeName("fStrArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("fDateArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayTimestamp, meta.GetFieldTypeName("fTimestampArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayGuid, meta.GetFieldTypeName("fGuidArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayEnum, meta.GetFieldTypeName("fEnumArr"));
Assert.AreEqual("str", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<IBinaryObject>("fNDate").Deserialize<DateTime?>());
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, binObj.GetField<IBinaryObject>("fEnum").Deserialize<TestEnum>());
Assert.AreEqual(new[] {"str"}, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<IBinaryObject[]>("fDateArr")
.Select(x => x.Deserialize<DateTime?>()));
Assert.AreEqual(new[] {nDate}, binObj.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] {nGuid}, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One},
binObj.GetField<IBinaryObject[]>("fEnumArr").Select(x => x.Deserialize<TestEnum>()));
StringDateGuidEnum obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nDate, obj.FnTimestamp);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.One, obj.FEnum);
Assert.AreEqual(new[] {"str"}, obj.FStrArr);
Assert.AreEqual(new[] {nDate}, obj.FDateArr);
Assert.AreEqual(new[] {nGuid}, obj.FGuidArr);
Assert.AreEqual(new[] {TestEnum.One}, obj.FEnumArr);
// Check builder field caching.
var builder = _grid.GetBinary().GetBuilder(binObj);
Assert.AreEqual("str", builder.GetField<string>("fStr"));
Assert.AreEqual(nDate, builder.GetField<IBinaryObjectBuilder>("fNDate").Build().Deserialize<DateTime?>());
Assert.AreEqual(nDate, builder.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, builder.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, builder.GetField<IBinaryObject>("fEnum").Deserialize<TestEnum>());
Assert.AreEqual(new[] {"str"}, builder.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, builder.GetField<IBinaryObjectBuilder[]>("fDateArr")
.Select(x => x.Build().Deserialize<DateTime?>()));
Assert.AreEqual(new[] {nDate}, builder.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] {nGuid}, builder.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One},
builder.GetField<IBinaryObject[]>("fEnumArr").Select(x => x.Deserialize<TestEnum>()));
// Check reassemble.
binObj = builder.Build();
Assert.AreEqual("str", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<IBinaryObject>("fNDate").Deserialize<DateTime?>());
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, binObj.GetField<IBinaryObject>("fEnum").Deserialize<TestEnum>());
Assert.AreEqual(new[] {"str"}, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<IBinaryObject[]>("fDateArr")
.Select(x => x.Deserialize<DateTime?>()));
Assert.AreEqual(new[] {nDate}, binObj.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] {nGuid}, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] { TestEnum.One },
binObj.GetField<IBinaryObject[]>("fEnumArr").Select(x => x.Deserialize<TestEnum>()));
obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nDate, obj.FnTimestamp);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.One, obj.FEnum);
Assert.AreEqual(new[] {"str"}, obj.FStrArr);
Assert.AreEqual(new[] {nDate}, obj.FDateArr);
Assert.AreEqual(new[] {nGuid}, obj.FGuidArr);
Assert.AreEqual(new[] {TestEnum.One}, obj.FEnumArr);
}
/// <summary>
/// Checks the string date guid enum values.
/// </summary>
private static void CheckStringDateGuidEnum2(IBinaryObject binObj, DateTime? nDate, Guid? nGuid)
{
Assert.AreEqual("str2", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<IBinaryObject>("fNDate").Deserialize<DateTime?>());
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.Two, binObj.GetField<IBinaryObject>("fEnum").Deserialize<TestEnum>());
Assert.AreEqual(new[] { "str2" }, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<IBinaryObject[]>("fDateArr")
.Select(x => x.Deserialize<DateTime?>()));
Assert.AreEqual(new[] { nDate }, binObj.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] { nGuid }, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.Two},
binObj.GetField<IBinaryObject[]>("fEnumArr").Select(x => x.Deserialize<TestEnum>()));
var obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str2", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nDate, obj.FnTimestamp);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.Two, obj.FEnum);
Assert.AreEqual(new[] { "str2" }, obj.FStrArr);
Assert.AreEqual(new[] { nDate }, obj.FDateArr);
Assert.AreEqual(new[] { nGuid }, obj.FGuidArr);
Assert.AreEqual(new[] { TestEnum.Two }, obj.FEnumArr);
}
[Test]
public void TestEnumMeta()
{
var bin = _grid.GetBinary();
// Put to cache to populate metas
var binEnum = bin.ToBinary<IBinaryObject>(TestEnumRegistered.One);
Assert.AreEqual(_marsh.GetDescriptor(typeof (TestEnumRegistered)).TypeId, binEnum.GetBinaryType().TypeId);
Assert.AreEqual(0, binEnum.EnumValue);
var meta = binEnum.GetBinaryType();
Assert.IsTrue(meta.IsEnum);
Assert.AreEqual(GetTypeName(typeof (TestEnumRegistered)), meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
}
/// <summary>
/// Test arrays.
/// </summary>
[Test]
public void TestCompositeArray()
{
// 1. Test simple array.
object[] inArr = { new CompositeInner(1) };
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray))
.SetField("inArr", inArr).Build();
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(CompositeArray)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("inArr"));
var binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(1, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
CompositeArray arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(1, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner) arr.InArr[0]).Val);
// 2. Test addition to array.
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("inArr", new[] { binInArr[0], null }).Build();
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.IsNull(binInArr[1]);
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner) arr.InArr[0]).Val);
Assert.IsNull(arr.InArr[1]);
binInArr[1] = _grid.GetBinary().GetBuilder(typeof(CompositeInner)).SetField("val", 2).Build();
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("inArr", binInArr.OfType<object>().ToArray()).Build();
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.AreEqual(2, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(2, ((CompositeInner)arr.InArr[1]).Val);
// 3. Test top-level handle inversion.
CompositeInner inner = new CompositeInner(1);
inArr = new object[] { inner, inner };
binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray))
.SetField("inArr", inArr).Build();
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.AreEqual(1, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[1]).Val);
binInArr[0] = _grid.GetBinary().GetBuilder(typeof(CompositeInner)).SetField("val", 2).Build();
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("inArr", binInArr.ToArray<object>()).Build();
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(2, binInArr[0].GetField<int>("val"));
Assert.AreEqual(1, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(2, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[1]).Val);
// 4. Test nested object handle inversion.
CompositeOuter[] outArr = { new CompositeOuter(inner), new CompositeOuter(inner) };
binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray))
.SetField("outArr", outArr.ToArray<object>()).Build();
meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(CompositeArray)), meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("inArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("outArr"));
var binOutArr = binObj.GetField<IBinaryObject[]>("outArr").ToArray();
Assert.AreEqual(2, binOutArr.Length);
Assert.AreEqual(1, binOutArr[0].GetField<IBinaryObject>("inner").GetField<int>("val"));
Assert.AreEqual(1, binOutArr[1].GetField<IBinaryObject>("inner").GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.InArr);
Assert.AreEqual(2, arr.OutArr.Length);
Assert.AreEqual(1, ((CompositeOuter) arr.OutArr[0]).Inner.Val);
Assert.AreEqual(1, ((CompositeOuter) arr.OutArr[0]).Inner.Val);
binOutArr[0] = _grid.GetBinary().GetBuilder(typeof(CompositeOuter))
.SetField("inner", new CompositeInner(2)).Build();
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("outArr", binOutArr.ToArray<object>()).Build();
binInArr = binObj.GetField<IBinaryObject[]>("outArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(2, binOutArr[0].GetField<IBinaryObject>("inner").GetField<int>("val"));
Assert.AreEqual(1, binOutArr[1].GetField<IBinaryObject>("inner").GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.InArr);
Assert.AreEqual(2, arr.OutArr.Length);
Assert.AreEqual(2, ((CompositeOuter)arr.OutArr[0]).Inner.Val);
Assert.AreEqual(1, ((CompositeOuter)arr.OutArr[1]).Inner.Val);
}
/// <summary>
/// Test container types other than array.
/// </summary>
[Test]
public void TestCompositeContainer()
{
ArrayList col = new ArrayList();
IDictionary dict = new Hashtable();
col.Add(new CompositeInner(1));
dict[3] = new CompositeInner(3);
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(CompositeContainer))
.SetCollectionField("col", col)
.SetDictionaryField("dict", dict).Build();
// 1. Check meta.
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(CompositeContainer)), meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameCollection, meta.GetFieldTypeName("col"));
Assert.AreEqual(BinaryTypeNames.TypeNameMap, meta.GetFieldTypeName("dict"));
// 2. Check in binary form.
Assert.AreEqual(1, binObj.GetField<ICollection>("col").Count);
Assert.AreEqual(1, binObj.GetField<ICollection>("col").OfType<IBinaryObject>().First()
.GetField<int>("val"));
Assert.AreEqual(1, binObj.GetField<IDictionary>("dict").Count);
Assert.AreEqual(3, ((IBinaryObject) binObj.GetField<IDictionary>("dict")[3]).GetField<int>("val"));
// 3. Check in deserialized form.
CompositeContainer obj = binObj.Deserialize<CompositeContainer>();
Assert.AreEqual(1, obj.Col.Count);
Assert.AreEqual(1, obj.Col.OfType<CompositeInner>().First().Val);
Assert.AreEqual(1, obj.Dict.Count);
Assert.AreEqual(3, ((CompositeInner) obj.Dict[3]).Val);
}
/// <summary>
/// Ensure that raw data is not lost during build.
/// </summary>
[Test]
public void TestRawData()
{
var raw = new WithRaw
{
A = 1,
B = 2
};
var binObj = _marsh.Unmarshal<IBinaryObject>(_marsh.Marshal(raw), BinaryMode.ForceBinary);
raw = binObj.Deserialize<WithRaw>();
Assert.AreEqual(1, raw.A);
Assert.AreEqual(2, raw.B);
IBinaryObject newbinObj = _grid.GetBinary().GetBuilder(binObj).SetField("a", 3).Build();
raw = newbinObj.Deserialize<WithRaw>();
Assert.AreEqual(3, raw.A);
Assert.AreEqual(2, raw.B);
}
/// <summary>
/// Test nested objects.
/// </summary>
[Test]
public void TestNested()
{
// 1. Create from scratch.
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(NestedOuter));
NestedInner inner1 = new NestedInner {Val = 1};
builder.SetField("inner1", inner1);
IBinaryObject outerbinObj = builder.Build();
IBinaryType meta = outerbinObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(NestedOuter)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner1"));
IBinaryObject innerbinObj1 = outerbinObj.GetField<IBinaryObject>("inner1");
IBinaryType innerMeta = innerbinObj1.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(NestedInner)), innerMeta.TypeName);
Assert.AreEqual(1, innerMeta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameInt, innerMeta.GetFieldTypeName("Val"));
inner1 = innerbinObj1.Deserialize<NestedInner>();
Assert.AreEqual(1, inner1.Val);
NestedOuter outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(outer.Inner1.Val, 1);
Assert.IsNull(outer.Inner2);
// 2. Add another field over existing binary object.
builder = _grid.GetBinary().GetBuilder(outerbinObj);
NestedInner inner2 = new NestedInner {Val = 2};
builder.SetField("inner2", inner2);
outerbinObj = builder.Build();
outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(1, outer.Inner1.Val);
Assert.AreEqual(2, outer.Inner2.Val);
// 3. Try setting inner object in binary form.
innerbinObj1 = _grid.GetBinary().GetBuilder(innerbinObj1).SetField("val", 3).Build();
inner1 = innerbinObj1.Deserialize<NestedInner>();
Assert.AreEqual(3, inner1.Val);
outerbinObj = _grid.GetBinary().GetBuilder(outerbinObj).SetField<object>("inner1", innerbinObj1).Build();
outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(3, outer.Inner1.Val);
Assert.AreEqual(2, outer.Inner2.Val);
}
/// <summary>
/// Test handle migration.
/// </summary>
[Test]
public void TestHandleMigration()
{
// 1. Simple comparison of results.
MigrationInner inner = new MigrationInner {Val = 1};
MigrationOuter outer = new MigrationOuter
{
Inner1 = inner,
Inner2 = inner
};
byte[] outerBytes = _marsh.Marshal(outer);
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(MigrationOuter));
builder.SetField<object>("inner1", inner);
builder.SetField<object>("inner2", inner);
BinaryObject portOuter = (BinaryObject) builder.Build();
byte[] portOuterBytes = new byte[outerBytes.Length];
Buffer.BlockCopy(portOuter.Data, 0, portOuterBytes, 0, portOuterBytes.Length);
Assert.AreEqual(outerBytes, portOuterBytes);
// 2. Change the first inner object so that the handle must migrate.
MigrationInner inner1 = new MigrationInner {Val = 2};
IBinaryObject portOuterMigrated =
_grid.GetBinary().GetBuilder(portOuter).SetField<object>("inner1", inner1).Build();
MigrationOuter outerMigrated = portOuterMigrated.Deserialize<MigrationOuter>();
Assert.AreEqual(2, outerMigrated.Inner1.Val);
Assert.AreEqual(1, outerMigrated.Inner2.Val);
// 3. Change the first value using serialized form.
IBinaryObject inner1Port =
_grid.GetBinary().GetBuilder(typeof(MigrationInner)).SetField("val", 2).Build();
portOuterMigrated =
_grid.GetBinary().GetBuilder(portOuter).SetField<object>("inner1", inner1Port).Build();
outerMigrated = portOuterMigrated.Deserialize<MigrationOuter>();
Assert.AreEqual(2, outerMigrated.Inner1.Val);
Assert.AreEqual(1, outerMigrated.Inner2.Val);
}
/// <summary>
/// Test handle inversion.
/// </summary>
[Test]
public void TestHandleInversion()
{
InversionInner inner = new InversionInner();
InversionOuter outer = new InversionOuter();
inner.Outer = outer;
outer.Inner = inner;
byte[] rawOuter = _marsh.Marshal(outer);
IBinaryObject portOuter = _marsh.Unmarshal<IBinaryObject>(rawOuter, BinaryMode.ForceBinary);
IBinaryObject portInner = portOuter.GetField<IBinaryObject>("inner");
// 1. Ensure that inner object can be deserialized after build.
IBinaryObject portInnerNew = _grid.GetBinary().GetBuilder(portInner).Build();
InversionInner innerNew = portInnerNew.Deserialize<InversionInner>();
Assert.AreSame(innerNew, innerNew.Outer.Inner);
// 2. Ensure that binary object with external dependencies could be added to builder.
IBinaryObject portOuterNew =
_grid.GetBinary().GetBuilder(typeof(InversionOuter)).SetField<object>("inner", portInner).Build();
InversionOuter outerNew = portOuterNew.Deserialize<InversionOuter>();
Assert.AreNotSame(outerNew, outerNew.Inner.Outer);
Assert.AreSame(outerNew.Inner, outerNew.Inner.Outer.Inner);
}
/// <summary>
/// Test build multiple objects.
/// </summary>
[Test]
public void TestBuildMultiple()
{
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(Primitives));
builder.SetField<byte>("fByte", 1).SetField("fBool", true);
IBinaryObject po1 = builder.Build();
IBinaryObject po2 = builder.Build();
Assert.AreEqual(1, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(1, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
builder.SetField<byte>("fByte", 2);
IBinaryObject po3 = builder.Build();
Assert.AreEqual(1, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(1, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
Assert.AreEqual(2, po3.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
builder = _grid.GetBinary().GetBuilder(po1);
builder.SetField<byte>("fByte", 10);
po1 = builder.Build();
po2 = builder.Build();
builder.SetField<byte>("fByte", 20);
po3 = builder.Build();
Assert.AreEqual(10, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(10, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
Assert.AreEqual(20, po3.GetField<byte>("fByte"));
Assert.AreEqual(true, po3.GetField<bool>("fBool"));
}
/// <summary>
/// Tests type id method.
/// </summary>
[Test]
public void TestTypeId()
{
Assert.Throws<ArgumentException>(() => _grid.GetBinary().GetTypeId(null));
Assert.AreEqual(IdMapper.TestTypeId, _grid.GetBinary().GetTypeId(IdMapper.TestTypeName));
Assert.AreEqual(BinaryUtils.GetStringHashCode("someTypeName"), _grid.GetBinary().GetTypeId("someTypeName"));
}
/// <summary>
/// Tests type name mapper.
/// </summary>
[Test]
public void TestTypeName()
{
var bytes = _marsh.Marshal(new NameMapperTestType {NameMapperTestField = 17});
var bin = _marsh.Unmarshal<IBinaryObject>(bytes, BinaryMode.ForceBinary);
var binType = bin.GetBinaryType();
Assert.AreEqual(BinaryUtils.GetStringHashCode(NameMapper.TestTypeName + "_"), binType.TypeId);
Assert.AreEqual(17, bin.GetField<int>(NameMapper.TestFieldName));
}
/// <summary>
/// Tests metadata methods.
/// </summary>
[Test]
public void TestMetadata()
{
// Populate metadata
var binary = _grid.GetBinary();
binary.ToBinary<IBinaryObject>(new DecimalHolder());
var typeName = GetTypeName(typeof(DecimalHolder));
// All meta
var allMetas = binary.GetBinaryTypes();
var decimalMeta = allMetas.Single(x => x.TypeName == typeName);
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type
decimalMeta = binary.GetBinaryType(typeof (DecimalHolder));
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type id
decimalMeta = binary.GetBinaryType(binary.GetTypeId(typeName));
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type name
decimalMeta = binary.GetBinaryType(typeName);
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
}
/// <summary>
/// Tests the enum builder.
/// </summary>
[Test]
public void TestBuildEnum()
{
var binary = _grid.GetBinary();
int val = (int)TestEnumRegistered.Two;
var typeName = GetTypeName(typeof(TestEnumRegistered));
var typeId = BinaryUtils.GetStringHashCode(typeName);
var binEnums = new[]
{
binary.BuildEnum(typeof (TestEnumRegistered), val),
binary.BuildEnum(typeName, val)
};
foreach (var binEnum in binEnums)
{
Assert.IsTrue(binEnum.GetBinaryType().IsEnum);
Assert.AreEqual(val, binEnum.EnumValue);
Assert.AreEqual(string.Format("{0} [typeId={1}, enumValue={2}, enumValueName={3}]",
typeName, typeId, val, (TestEnumRegistered) val), binEnum.ToString());
Assert.AreEqual((TestEnumRegistered)val, binEnum.Deserialize<TestEnumRegistered>());
}
Assert.AreEqual(binEnums[0], binEnums[1]);
Assert.AreEqual(binEnums[0].GetHashCode(), binEnums[1].GetHashCode());
Assert.IsFalse(binEnums[0].Equals(null));
Assert.IsFalse(binEnums[0].Equals(new object()));
Assert.IsTrue(binEnums[0].Equals(binEnums[1]));
var ex = Assert.Throws<NotSupportedException>(() => binEnums[1].ToBuilder());
Assert.AreEqual("Builder cannot be created for enum.", ex.Message);
}
/// <summary>
/// Tests the compact footer setting.
/// </summary>
[Test]
public void TestCompactFooterSetting()
{
Assert.AreEqual(GetCompactFooter(), _marsh.CompactFooter);
}
/// <summary>
/// Tests the binary mode on remote node.
/// </summary>
[Test]
public void TestRemoteBinaryMode()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = "grid2",
BinaryConfiguration = new BinaryConfiguration
{
CompactFooter = GetCompactFooter()
}
};
using (var grid2 = Ignition.Start(cfg))
{
var cache1 = _grid.GetOrCreateCache<int, Primitives>("cache");
var cache2 = grid2.GetCache<int, object>("cache").WithKeepBinary<int, IBinaryObject>();
// Exchange data
cache1[1] = new Primitives {FByte = 3};
var obj = cache2[1];
// Rebuild with no changes.
cache2[2] = obj.ToBuilder().Build();
Assert.AreEqual(3, cache1[2].FByte);
// Rebuild with read
Assert.AreEqual(3, obj.GetField<byte>("FByte"));
cache2[3] = obj.ToBuilder().Build();
Assert.AreEqual(3, cache1[3].FByte);
// Modify and rebuild
cache2[4] = obj.ToBuilder().SetField("FShort", (short) 15).Build();
Assert.AreEqual(15, cache1[4].FShort);
// New binary type without a class
cache2[5] = grid2.GetBinary().GetBuilder("myNewType").SetField("foo", "bar").Build();
var cache1Bin = cache1.WithKeepBinary<int, IBinaryObject>();
var newObj = cache1Bin[5];
Assert.AreEqual("bar", newObj.GetField<string>("foo"));
cache1Bin[6] = newObj.ToBuilder().SetField("foo2", 3).Build();
Assert.AreEqual(3, cache2[6].GetField<int>("foo2"));
}
}
/// <summary>
/// Tests that fields are sorted by name in serialized form.
/// </summary>
[Test]
public void TestFieldSorting()
{
var obj1 = (BinaryObject)_grid.GetBinary().GetBuilder("sortTest")
.SetByteField("c", 3).SetByteField("b", 1).SetByteField("a", 2).Build();
var obj2 = (BinaryObject)_grid.GetBinary().GetBuilder("sortTest")
.SetByteField("b", 1).SetByteField("a", 2).SetByteField("c", 3).Build();
Assert.AreEqual(obj1, obj2);
Assert.AreEqual(obj1.GetHashCode(), obj2.GetHashCode());
Assert.AreEqual("sortTest [, a=2, b=1, c=3]", Regex.Replace(obj1.ToString(), "idHash=\\d+", ""));
// Skip header, take 3 fields (type code + value).
var bytes1 = obj1.Data.Skip(24).Take(6).ToArray();
var bytes2 = obj2.Data.Skip(24).Take(6).ToArray();
Assert.AreEqual(bytes1, bytes2);
Assert.AreEqual(new[] {1, 2, 1, 1, 1, 3}, bytes1);
}
}
/// <summary>
/// Empty binary class.
/// </summary>
public class Empty
{
// No-op.
}
/// <summary>
/// binary with primitive fields.
/// </summary>
public class Primitives
{
public byte FByte;
public bool FBool;
public short FShort;
public char FChar;
public int FInt;
public long FLong;
public float FFloat;
public double FDouble;
public decimal FDecimal;
}
/// <summary>
/// binary with primitive array fields.
/// </summary>
public class PrimitiveArrays
{
public byte[] FByte;
public bool[] FBool;
public short[] FShort;
public char[] FChar;
public int[] FInt;
public long[] FLong;
public float[] FFloat;
public double[] FDouble;
public decimal?[] FDecimal;
}
/// <summary>
/// binary having strings, dates, Guids and enums.
/// </summary>
public class StringDateGuidEnum
{
public string FStr;
public DateTime? FnDate;
public DateTime? FnTimestamp;
public Guid? FnGuid;
public TestEnum FEnum;
public string[] FStrArr;
public DateTime?[] FDateArr;
public Guid?[] FGuidArr;
public TestEnum[] FEnumArr;
}
/// <summary>
/// Enumeration.
/// </summary>
public enum TestEnum
{
One, Two
}
/// <summary>
/// Registered enumeration.
/// </summary>
public enum TestEnumRegistered
{
One, Two
}
/// <summary>
/// binary with raw data.
/// </summary>
public class WithRaw : IBinarizable
{
public int A;
public int B;
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
writer.WriteInt("a", A);
writer.GetRawWriter().WriteInt(B);
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
A = reader.ReadInt("a");
B = reader.GetRawReader().ReadInt();
}
}
/// <summary>
/// Empty class for metadata overwrite test.
/// </summary>
public class MetaOverwrite
{
// No-op.
}
/// <summary>
/// Nested outer object.
/// </summary>
public class NestedOuter
{
public NestedInner Inner1;
public NestedInner Inner2;
}
/// <summary>
/// Nested inner object.
/// </summary>
public class NestedInner
{
public int Val;
}
/// <summary>
/// Outer object for handle migration test.
/// </summary>
public class MigrationOuter
{
public MigrationInner Inner1;
public MigrationInner Inner2;
}
/// <summary>
/// Inner object for handle migration test.
/// </summary>
public class MigrationInner
{
public int Val;
}
/// <summary>
/// Outer object for handle inversion test.
/// </summary>
public class InversionOuter
{
public InversionInner Inner;
}
/// <summary>
/// Inner object for handle inversion test.
/// </summary>
public class InversionInner
{
public InversionOuter Outer;
}
/// <summary>
/// Object for composite array tests.
/// </summary>
public class CompositeArray
{
public object[] InArr;
public object[] OutArr;
}
/// <summary>
/// Object for composite collection/dictionary tests.
/// </summary>
public class CompositeContainer
{
public ICollection Col;
public IDictionary Dict;
}
/// <summary>
/// OUter object for composite structures test.
/// </summary>
public class CompositeOuter
{
public CompositeInner Inner;
public CompositeOuter()
{
// No-op.
}
public CompositeOuter(CompositeInner inner)
{
Inner = inner;
}
}
/// <summary>
/// Inner object for composite structures test.
/// </summary>
public class CompositeInner
{
public int Val;
public CompositeInner()
{
// No-op.
}
public CompositeInner(int val)
{
Val = val;
}
}
/// <summary>
/// Type to test "ToBinary()" logic.
/// </summary>
public class ToBinary
{
public int Val;
public ToBinary(int val)
{
Val = val;
}
}
/// <summary>
/// Type to test removal.
/// </summary>
public class Remove
{
public object Val;
public RemoveInner Val2;
}
/// <summary>
/// Inner type to test removal.
/// </summary>
public class RemoveInner
{
/** */
public int Val;
/// <summary>
///
/// </summary>
/// <param name="val"></param>
public RemoveInner(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
public class BuilderInBuilderOuter
{
/** */
public BuilderInBuilderInner Inner;
/** */
public BuilderInBuilderInner Inner2;
}
/// <summary>
///
/// </summary>
public class BuilderInBuilderInner
{
/** */
public BuilderInBuilderOuter Outer;
}
/// <summary>
///
/// </summary>
public class BuilderCollection
{
/** */
public readonly ArrayList Col;
/// <summary>
///
/// </summary>
/// <param name="col"></param>
public BuilderCollection(ArrayList col)
{
Col = col;
}
}
/// <summary>
///
/// </summary>
public class BuilderCollectionItem
{
/** */
public int Val;
/// <summary>
///
/// </summary>
/// <param name="val"></param>
public BuilderCollectionItem(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
public class DecimalHolder
{
/** */
public decimal Val;
/** */
public decimal?[] ValArr;
}
/// <summary>
/// Test id mapper.
/// </summary>
public class IdMapper : IBinaryIdMapper
{
/** */
public const string TestTypeName = "IdMapperTestType";
/** */
public const int TestTypeId = -65537;
/** <inheritdoc /> */
public int GetTypeId(string typeName)
{
return typeName == TestTypeName ? TestTypeId : 0;
}
/** <inheritdoc /> */
public int GetFieldId(int typeId, string fieldName)
{
return 0;
}
}
/// <summary>
/// Test name mapper.
/// </summary>
public class NameMapper : IBinaryNameMapper
{
/** */
private readonly IBinaryNameMapper _baseMapper;
/** */
public const string TestTypeName = "NameMapperTestType";
/** */
public const string TestFieldName = "NameMapperTestField";
/// <summary>
/// Initializes a new instance of the <see cref="NameMapper" /> class.
/// </summary>
/// <param name="baseMapper">The base mapper.</param>
public NameMapper(IBinaryNameMapper baseMapper)
{
_baseMapper = baseMapper;
}
/** <inheritdoc /> */
public string GetTypeName(string name)
{
if (name == typeof(NameMapperTestType).AssemblyQualifiedName)
return TestTypeName + "_";
return _baseMapper.GetTypeName(name);
}
/** <inheritdoc /> */
public string GetFieldName(string name)
{
if (name == TestFieldName)
return name + "_";
return name;
}
}
/// <summary>
/// Name mapper test type.
/// </summary>
public class NameMapperTestType
{
/** */
public int NameMapperTestField { get; set; }
}
}
| |
// Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
namespace DBus
{
using Authentication;
//using System.Runtime.InteropServices;
//[StructLayout (LayoutKind.Sequential)]
unsafe struct UUID
{
private int a, b, c, d;
const int ByteLength = 16;
public static readonly UUID Zero = new UUID ();
public static bool operator == (UUID a, UUID b)
{
if (a.a == b.a && a.b == b.b && a.c == b.c && a.d == b.d)
return true;
else
return false;
}
public static bool operator != (UUID a, UUID b)
{
return !(a == b);
}
public override bool Equals (object o)
{
if (o == null)
return false;
if (!(o is UUID))
return false;
return this == (UUID)o;
}
public override int GetHashCode ()
{
return a ^ b ^ c ^ d;
}
public override string ToString ()
{
StringBuilder sb = new StringBuilder (ByteLength * 2);
fixed (int* p = &a) {
byte* bp = (byte*)p;
for (int i = 0 ; i != ByteLength ; i++)
sb.Append (bp[i].ToString ("x2", CultureInfo.InvariantCulture));
}
return sb.ToString ();
}
public static UUID Parse (string hex)
{
if (hex.Length != ByteLength * 2)
throw new Exception ("Cannot parse UUID/GUID of invalid length");
UUID id = new UUID ();
byte* result = (byte*)&id.a;
int n = 0, i = 0;
while (n < ByteLength) {
result[n] = (byte)(Sasl.FromHexChar (hex[i++]) << 4);
result[n++] += Sasl.FromHexChar (hex[i++]);
}
return id;
}
static Random rand = new Random ();
static byte[] buf = new byte[12];
public static UUID Generate (DateTime timestamp)
{
UUID id = new UUID ();
lock (buf) {
rand.NextBytes (buf);
fixed (byte* bp = &buf[0]) {
int* p = (int*)bp;
id.a = p[0];
id.b = p[1];
id.c = p[2];
}
}
//id.d is assigned to by Timestamp
id.Timestamp = timestamp;
return id;
}
public static UUID Generate ()
{
return Generate (DateTime.Now);
}
public uint UnixTimestamp
{
get {
uint unixTime;
fixed (int* ip = &d) {
if (BitConverter.IsLittleEndian) {
byte* p = (byte*)ip;
byte* bp = (byte*)&unixTime;
bp[0] = p[3];
bp[1] = p[2];
bp[2] = p[1];
bp[3] = p[0];
} else {
unixTime = *(uint*)ip;
}
}
return unixTime;
} set {
uint unixTime = value;
fixed (int* ip = &d) {
if (BitConverter.IsLittleEndian) {
byte* p = (byte*)&unixTime;
byte* bp = (byte*)ip;
bp[0] = p[3];
bp[1] = p[2];
bp[2] = p[1];
bp[3] = p[0];
} else {
*(uint*)ip = unixTime;
}
}
}
}
public DateTime Timestamp
{
get {
return Sasl.UnixToDateTime (UnixTimestamp);
} set {
UnixTimestamp = (uint)Sasl.DateTimeToUnix (value);
}
}
}
}
namespace DBus.Authentication
{
enum ClientState
{
WaitingForData,
WaitingForOK,
WaitingForReject,
}
enum ServerState
{
WaitingForAuth,
WaitingForData,
WaitingForBegin,
}
class AuthCommand
{
/*
public AuthCommand (string value)
{
//this.Value = value;
this.Value = value.Trim ();
}
*/
public AuthCommand (string value)
{
//this.Value = value;
this.Value = value.Trim ();
Args.AddRange (Value.Split (' '));
}
readonly List<string> Args = new List<string> ();
public string this[int index]
{
get {
if (index >= Args.Count)
return String.Empty;
return Args[index];
}
}
/*
public AuthCommand (string value, params string[] args)
{
if (args.Length == 0)
this.Value = value;
else
this.Value = value + " " + String.Join (" ", args);
}
*/
public readonly string Value;
}
class SaslPeer : IEnumerable<AuthCommand>
{
//public Connection conn;
public SaslPeer Peer;
public Stream stream = null;
public bool UseConsole = false;
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
internal bool isFinalRead = false;
public virtual IEnumerator<AuthCommand> GetEnumerator ()
{
// Read the mandatory null credentials byte
/*
if (!UseConsole)
if (conn.Transport.Stream.ReadByte () != 0)
yield break;
*/
TextReader sr;
sr = UseConsole ? Console.In : new StreamReader (stream, Encoding.ASCII);
while (true) {
string ln;
bool isEnd = false;
if (!UseConsole && isFinalRead) {
StringBuilder sb = new StringBuilder ();
while (true) {
//MemoryStream ms = new MemoryStream ();
// TODO: Use char instead? Check for -1?
int a = stream.ReadByte ();
if (a == -1) {
isEnd = true;
break;
}
if (a == '\r') {
int b = stream.ReadByte ();
if (b != '\n')
throw new Exception ();
break;
}
sb.Append ((char)a);
}
ln = sb.ToString ();
//isFinalRead = false;
} else {
ln = sr.ReadLine ();
}
//if (isEnd && ln == string.Empty)
// yield break;
if (ln == null)
yield break;
if (ln != String.Empty)
yield return new AuthCommand (ln);
if (isEnd)
yield break;
}
}
public bool Authenticate ()
{
return Run (this);
}
public bool AuthenticateSelf ()
{
//IEnumerator<AuthCommand> a = Peer.GetEnumerator ();
IEnumerator<AuthCommand> b = GetEnumerator ();
//bool ret = b.MoveNext ();
while (b.MoveNext ()) {
if (b.Current.Value == "BEGIN")
return true;
}
return false;
}
public virtual bool Run (IEnumerable<AuthCommand> commands)
{
TextWriter sw;
sw = UseConsole ? Console.Out : new StreamWriter (stream, Encoding.ASCII);
if (!UseConsole)
sw.NewLine = "\r\n";
foreach (AuthCommand command in commands) {
if (command == null) {
// Disconnect here?
return false;
}
sw.WriteLine (command.Value);
sw.Flush ();
}
return true;
}
}
class SaslClient : SaslPeer
{
public string Identity = String.Empty;
public bool TransportSupportsUnixFD = false;
public bool UnixFDSupported = false;
//static Regex rejectedRegex = new Regex (@"^REJECTED(\s+(\w+))*$");
// This enables simple support for multiple AUTH schemes
enum AuthMech
{
External,
Anonymous,
None,
}
public override IEnumerator<AuthCommand> GetEnumerator ()
{
IEnumerator<AuthCommand> replies = Peer.GetEnumerator ();
AuthMech currMech = AuthMech.External;
while (true) {
Peer.isFinalRead = false;
if (currMech == AuthMech.External) {
string str = Identity;
byte[] bs = Encoding.ASCII.GetBytes (str);
string initialData = Sasl.ToHex (bs);
yield return new AuthCommand ("AUTH EXTERNAL " + initialData);
currMech = AuthMech.Anonymous;
} else if (currMech == AuthMech.Anonymous) {
yield return new AuthCommand ("AUTH ANONYMOUS");
currMech = AuthMech.None;
} else {
throw new Exception ("Authentication failure");
}
Peer.isFinalRead = true;
AuthCommand reply;
if (!replies.MoveNext ())
yield break;
reply = replies.Current;
if (reply[0] == "REJECTED") {
continue;
}
/*
Match m = rejectedRegex.Match (reply.Value);
if (m.Success) {
string[] mechanisms = m.Groups[1].Value.Split (' ');
//yield return new AuthCommand ("CANCEL");
continue;
}
*/
if (reply[0] != "OK") {
yield return new AuthCommand ("ERROR");
continue;
}
if (reply[1] == String.Empty)
ActualId = UUID.Zero;
else
ActualId = UUID.Parse (reply[1]);
if (TransportSupportsUnixFD) {
yield return new AuthCommand ("NEGOTIATE_UNIX_FD");
if (!replies.MoveNext ())
yield break;
reply = replies.Current;
UnixFDSupported = reply[0] == "AGREE_UNIX_FD";
}
yield return new AuthCommand ("BEGIN");
yield break;
}
}
public UUID ActualId = UUID.Zero;
}
class SaslServer : SaslPeer
{
//public int MaxFailures = 10;
public UUID Guid = UUID.Zero;
public long uid = 0;
static Regex authRegex = new Regex (@"^AUTH\s+(\w+)(?:\s+(.*))?$");
static string[] supportedMechanisms = {"EXTERNAL"};
public override IEnumerator<AuthCommand> GetEnumerator ()
{
IEnumerator<AuthCommand> replies = Peer.GetEnumerator ();
while (true) {
Peer.isFinalRead = false;
AuthCommand reply;
if (!replies.MoveNext ()) {
yield return null;
yield break;
//continue;
}
reply = replies.Current;
Match m = authRegex.Match (reply.Value);
if (!m.Success) {
yield return new AuthCommand ("ERROR");
continue;
}
string mechanism = m.Groups[1].Value;
string initialResponse = m.Groups[2].Value;
if (mechanism == "EXTERNAL") {
try {
byte[] bs = Sasl.FromHex (initialResponse);
string authStr = Encoding.ASCII.GetString (bs);
uid = UInt32.Parse (authStr);
} catch {
uid = 0;
}
//return RunExternal (Run (), initialResponse);
} else {
yield return new AuthCommand ("REJECTED " + String.Join (" ", supportedMechanisms));
continue;
}
if (Guid == UUID.Zero)
yield return new AuthCommand ("OK");
else
yield return new AuthCommand ("OK " + Guid.ToString ());
Peer.isFinalRead = true;
if (!replies.MoveNext ()) {
/*
yield break;
continue;
*/
yield return null;
yield break;
}
reply = replies.Current;
if (reply.Value != "BEGIN") {
yield return new AuthCommand ("ERROR");
continue;
}
yield break;
}
}
}
static class Sasl
{
//From Mono.Unix.Native.NativeConvert
//should these methods use long or (u)int?
public static DateTime UnixToDateTime (long time)
{
DateTime LocalUnixEpoch = new DateTime (1970, 1, 1);
TimeSpan LocalUtcOffset = TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.UtcNow);
return LocalUnixEpoch.AddSeconds ((double) time + LocalUtcOffset.TotalSeconds);
}
public static long DateTimeToUnix (DateTime time)
{
DateTime LocalUnixEpoch = new DateTime (1970, 1, 1);
TimeSpan LocalUtcOffset = TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.UtcNow);
TimeSpan unixTime = time.Subtract (LocalUnixEpoch) - LocalUtcOffset;
return (long) unixTime.TotalSeconds;
}
//From Mono.Security.Cryptography
//Modified to output lowercase hex
static public string ToHex (byte[] input)
{
if (input == null)
return null;
StringBuilder sb = new StringBuilder (input.Length * 2);
foreach (byte b in input) {
sb.Append (b.ToString ("x2", CultureInfo.InvariantCulture));
}
return sb.ToString ();
}
//From Mono.Security.Cryptography
static public byte FromHexChar (char c)
{
if ((c >= 'a') && (c <= 'f'))
return (byte) (c - 'a' + 10);
if ((c >= 'A') && (c <= 'F'))
return (byte) (c - 'A' + 10);
if ((c >= '0') && (c <= '9'))
return (byte) (c - '0');
throw new ArgumentException ("Invalid hex char");
}
//From Mono.Security.Cryptography
static public byte[] FromHex (string hex)
{
if (hex == null)
return null;
if ((hex.Length & 0x1) == 0x1)
throw new ArgumentException ("Length must be a multiple of 2");
byte[] result = new byte [hex.Length >> 1];
int n = 0;
int i = 0;
while (n < result.Length) {
result [n] = (byte) (FromHexChar (hex [i++]) << 4);
result [n++] += FromHexChar (hex [i++]);
}
return result;
}
}
}
| |
/*
* ListView.cs - Implementation of the
* "System.Windows.Forms.ListView" class.
*
* Copyright (C) 2003 Neil Cawse.
*
* 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.Windows.Forms
{
using System;
using System.Drawing;
using System.Collections;
public class ListView : Control
{
private ItemActivation activation;
private ListViewAlignment alignStyle;
private BorderStyle borderStyle;
private ColumnHeaderStyle headerStyle;
private SortOrder sorting;
private View viewStyle;
private bool allowColumnReorder;
private bool autoArrange;
private bool checkBoxes;
private bool fullRowSelect;
private bool gridLines;
private bool hideSelection;
private bool labelEdit;
private bool labelWrap;
private bool multiSelect;
private bool scrollable;
private bool hoverSelection;
private ListViewItemCollection items;
private ColumnHeaderCollection columns;
private CheckedIndexCollection checkedIndices;
private CheckedListViewItemCollection checkedItems;
private SelectedListViewItemCollection selectedItems;
internal ColumnHeader[] columnHeaders;
internal ArrayList listItems;
private SelectedIndexCollection selectedIndices;
private IComparer listViewItemSorter;
private ImageList largeImageList;
private ImageList smallImageList;
private ImageList stateImageList;
private int updating;
private bool inLabelEdit;
public event LabelEditEventHandler AfterLabelEdit;
public event LabelEditEventHandler BeforeLabelEdit;
public event ColumnClickEventHandler ColumnClick;
public event EventHandler ItemActivate;
public event ItemCheckEventHandler ItemCheck;
public event ItemDragEventHandler ItemDrag;
public ListView()
{
items = new ListViewItemCollection(this);
columns = new ColumnHeaderCollection(this);
listItems = new ArrayList();
autoArrange = true;
hideSelection = true;
labelWrap = true;
multiSelect = true;
scrollable = true;
activation = ItemActivation.Standard;
alignStyle = ListViewAlignment.Top;
borderStyle = BorderStyle.Fixed3D;
headerStyle = ColumnHeaderStyle.Clickable;
sorting = SortOrder.None;
viewStyle = View.LargeIcon;
}
[TODO]
public ItemActivation Activation
{
get
{
return activation;
}
set
{
if (activation != value)
{
activation = value;
}
}
}
[TODO]
public ListViewAlignment Alignment
{
get
{
return alignStyle;
}
set
{
if (alignStyle != value)
{
alignStyle = value;
}
}
}
[TODO]
public bool AllowColumnReorder
{
get
{
return allowColumnReorder;
}
set
{
if (allowColumnReorder != value)
{
allowColumnReorder = value;
}
}
}
[TODO]
public bool AutoArrange
{
get
{
return autoArrange;
}
set
{
if (value != autoArrange)
{
autoArrange = value;
}
}
}
[TODO]
public override Color BackColor
{
get
{
return base.BackColor;
}
set
{
base.BackColor = value;
}
}
public override Image BackgroundImage
{
get
{
return base.BackgroundImage;
}
set
{
base.BackgroundImage = value;
}
}
internal void BeginEdit(ListViewItem item)
{
}
[TODO]
public BorderStyle BorderStyle
{
get
{
return borderStyle;
}
set
{
if (borderStyle != value)
{
borderStyle = value;
}
}
}
[TODO]
public bool CheckBoxes
{
get
{
return checkBoxes;
}
set
{
if (checkBoxes != value)
{
checkBoxes = value;
}
}
}
public CheckedIndexCollection CheckedIndices
{
get
{
if (checkedIndices == null)
{
checkedIndices = new CheckedIndexCollection(this);
}
return checkedIndices;
}
}
public CheckedListViewItemCollection CheckedItems
{
get
{
if (checkedItems == null)
{
checkedItems = new CheckedListViewItemCollection(this);
}
return checkedItems;
}
}
public ColumnHeaderCollection Columns
{
get
{
return columns;
}
}
protected override CreateParams CreateParams
{
get
{
return base.CreateParams;
}
}
[TODO]
public ListViewItem FocusedItem
{
get
{
return null;
}
}
[TODO]
internal ListViewItem FocusedItemInternal
{
set
{
}
}
protected override Size DefaultSize
{
get
{
return new Size(121, 97);
}
}
[TODO]
public override Color ForeColor
{
get
{
return base.ForeColor;
}
set
{
base.ForeColor = value;
}
}
[TODO]
public bool FullRowSelect
{
get
{
return fullRowSelect;
}
set
{
if (fullRowSelect != value)
{
fullRowSelect = value;
}
}
}
[TODO]
public ColumnHeaderStyle HeaderStyle
{
get
{
return headerStyle;
}
set
{
if (headerStyle != value)
{
headerStyle = value;
}
}
}
[TODO]
public bool GridLines
{
get
{
return gridLines;
}
set
{
if (gridLines != value)
{
gridLines = value;
}
}
}
[TODO]
public bool HideSelection
{
get
{
return hideSelection;
}
set
{
if (value != hideSelection)
{
hideSelection = value;
}
}
}
[TODO]
public bool HoverSelection
{
get
{
return hoverSelection;
}
set
{
if (hoverSelection != value)
{
hoverSelection = value;
}
}
}
[TODO]
public bool LabelEdit
{
get
{
return labelEdit;
}
set
{
if (value != labelEdit)
{
labelEdit = value;
}
}
}
[TODO]
public bool LabelWrap
{
get
{
return labelWrap;
}
set
{
if (value != labelWrap)
{
labelWrap = value;
}
}
}
[TODO]
public ImageList LargeImageList
{
get
{
return largeImageList;
}
set
{
if (value != largeImageList)
{
if (largeImageList != null)
{
largeImageList.Dispose();
}
largeImageList = value;
}
}
}
public ListViewItemCollection Items
{
get
{
return items;
}
}
public IComparer ListViewItemSorter
{
get
{
return listViewItemSorter;
}
set
{
if (listViewItemSorter != value)
{
listViewItemSorter = value;
Sort();
}
}
}
[TODO]
public bool MultiSelect
{
get
{
return multiSelect;
}
set
{
if (value != multiSelect)
{
multiSelect = value;
}
}
}
[TODO]
public bool Scrollable
{
get
{
return scrollable;
}
set
{
if (value != scrollable)
{
scrollable = value;
}
}
}
public SelectedIndexCollection SelectedIndices
{
get
{
if (selectedIndices == null)
{
selectedIndices = new SelectedIndexCollection(this);
}
return selectedIndices;
}
}
public SelectedListViewItemCollection SelectedItems
{
get
{
if (selectedItems == null)
{
selectedItems = new SelectedListViewItemCollection(this);
}
return selectedItems;
}
}
[TODO]
public ImageList SmallImageList
{
get
{
return smallImageList;
}
set
{
if (value != smallImageList)
{
if (smallImageList != null)
{
smallImageList.Dispose();
}
smallImageList = value;
}
}
}
[TODO]
public SortOrder Sorting
{
get
{
return sorting;
}
set
{
if (sorting != value)
{
sorting = value;
}
}
}
[TODO]
public ImageList StateImageList
{
get
{
return null;
}
set
{
if (stateImageList == value)
{
return;
}
if (stateImageList != null)
{
stateImageList.Dispose();
}
stateImageList = value;
}
}
[TODO]
public override string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
}
}
[TODO]
public ListViewItem TopItem
{
get
{
return null;
}
}
[TODO]
public View View
{
get
{
return viewStyle;
}
set
{
if (viewStyle != value)
{
viewStyle = value;
}
}
}
protected override void OnEnabledChanged(EventArgs e)
{
base.OnEnabledChanged(e);
}
[TODO]
public void ArrangeIcons(ListViewAlignment value)
{
if (viewStyle == View.Details)
{
return;
}
if (sorting != SortOrder.None)
{
Sort();
}
}
public void ArrangeIcons()
{
ArrangeIcons(ListViewAlignment.Default);
}
public void BeginUpdate()
{
updating++;
}
public void Clear()
{
Items.Clear();
Columns.Clear();
}
protected override void CreateHandle()
{
base.CreateHandle();
}
protected override void Dispose(bool disposing)
{
if (columnHeaders != null)
{
// More efficient to remove from the back.
for (int i = columnHeaders.Length - 1; i >= 0; i--)
{
columnHeaders[i].Dispose();
}
columnHeaders = null;
}
base.Dispose(disposing);
}
public void EndUpdate()
{
if (--updating <= 0)
{
Invalidate();
}
}
[TODO]
public void EnsureVisible(int index)
{
}
[TODO]
public ListViewItem GetItemAt(int x, int y)
{
return null;
}
public Rectangle GetItemRect(int index)
{
return GetItemRect(index, ItemBoundsPortion.Entire);
}
[TODO]
public Rectangle GetItemRect(int index, ItemBoundsPortion portion)
{
return Rectangle.Empty;
}
protected override bool IsInputKey(Keys keyData)
{
if ((keyData & Keys.Alt) != 0)
{
return false;
}
Keys key = keyData & Keys.KeyCode;
if (key == Keys.Prior || key == Keys.Next || key == Keys.Home || key == Keys.End || base.IsInputKey(keyData))
{
return true;
}
if (inLabelEdit)
{
if (key == Keys.Return || key == Keys.Escape)
{
return true;
}
}
return false;
}
protected virtual void OnAfterLabelEdit(LabelEditEventArgs e)
{
if (AfterLabelEdit != null)
{
AfterLabelEdit(this, e);
}
}
protected virtual void OnBeforeLabelEdit(LabelEditEventArgs e)
{
if (BeforeLabelEdit != null)
{
BeforeLabelEdit(this, e);
}
}
protected virtual void OnColumnClick(ColumnClickEventArgs e)
{
if (ColumnClick != null)
{
ColumnClick(this, e);
}
}
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
Invalidate();
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
}
protected override void OnHandleDestroyed(EventArgs e)
{
base.OnHandleDestroyed(e);
}
protected virtual void OnItemActivate(EventArgs e)
{
if (ItemActivate != null)
{
ItemActivate(this, e);
}
}
protected virtual void OnItemCheck(ItemCheckEventArgs ice)
{
if (ItemCheck != null)
{
ItemCheck(this, ice);
}
}
protected virtual void OnItemDrag(ItemDragEventArgs e)
{
if (ItemDrag != null)
{
ItemDrag(this, e);
}
}
protected virtual void OnSelectedIndexChanged(EventArgs e)
{
EventHandler handler = GetHandler(EventId.SelectedIndexChanged) as EventHandler;
if(handler != null)
{
handler(this, e);
}
}
protected override void OnSystemColorsChanged(EventArgs e)
{
base.OnSystemColorsChanged(e);
}
protected void RealizeProperties()
{
// Not required in this implementation.
}
[TODO]
public void Sort()
{
}
public override string ToString()
{
String s = base.ToString();
if (listItems != null)
{
s += ", Count: " + listItems.Count;
if (listItems.Count > 0)
{
String s1 = ", Items[0]: " + listItems[0];
if (s1.Length > 50)
{
s1 = s1.Substring(0, 50);
}
s += s1;
}
}
return s;
}
protected void UpdateExtendedStyles()
{
}
#if !CONFIG_COMPACT_FORMS
protected override void WndProc(ref Message m)
{
}
#endif
public event EventHandler SelectedIndexChanged
{
add
{
AddHandler(EventId.SelectedIndexChanged, value);
}
remove
{
RemoveHandler(EventId.SelectedIndexChanged, value);
}
}
public class CheckedIndexCollection: IList
{
private ListView owner;
public virtual int Count
{
get
{
if (!owner.CheckBoxes)
{
return 0;
}
int count = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
if ((owner.listItems[i] as ListViewItem).Checked)
{
count++;
}
}
return count;
}
}
public int this[int index]
{
get
{
int pos = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
if ((owner.listItems[i] as ListViewItem).Checked)
{
if (pos == index)
{
return pos;
}
pos++;
}
}
throw new ArgumentOutOfRangeException();
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
throw new NotSupportedException();
}
}
public virtual bool IsReadOnly
{
get
{
return true;
}
}
public CheckedIndexCollection(ListView owner)
{
this.owner = owner;
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
bool IList.IsFixedSize
{
get
{
return true;
}
}
public bool Contains(int checkedIndex)
{
return (owner.listItems[checkedIndex] as ListViewItem).Checked;
}
bool IList.Contains(object checkedIndex)
{
if (checkedIndex is int)
{
return Contains((int)checkedIndex);
}
else
{
return false;
}
}
public int IndexOf(int checkedIndex)
{
int pos = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
ListViewItem item = owner.listItems[i] as ListViewItem;
if (item.Checked)
{
if (i == checkedIndex)
{
return pos;
}
pos++;
}
}
return -1;
}
int IList.IndexOf(object checkedIndex)
{
if (checkedIndex is Int32)
{
return IndexOf((int)checkedIndex);
}
else
{
return -1;
}
}
int IList.Add(object value)
{
throw new NotSupportedException();
}
void IList.Clear()
{
throw new NotSupportedException();
}
void IList.Insert(int index, object value)
{
throw new NotSupportedException();
}
void IList.Remove(object value)
{
throw new NotSupportedException();
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException();
}
void ICollection.CopyTo(Array dest, int index)
{
for (int i = 0; i < owner.listItems.Count; i++)
{
if ((owner.listItems[i] as ListViewItem).Checked)
{
dest.SetValue(i, index++);
}
}
}
public virtual IEnumerator GetEnumerator()
{
return GenerateCheckedIndexes().GetEnumerator();
}
private int[] GenerateCheckedIndexes()
{
int[] indexes =new int[Count];
int pos = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
if ((owner.listItems[i] as ListViewItem).Checked)
{
indexes[pos++] = i;
}
}
return indexes;
}
}
public class CheckedListViewItemCollection: IList
{
private ListView owner;
public virtual int Count
{
get
{
return owner.CheckedIndices.Count;
}
}
private ListViewItem[] GenerateCheckedItems()
{
ListViewItem[] indexes =new ListViewItem[owner.CheckedIndices.Count];
int pos = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
ListViewItem item = owner.listItems[i] as ListViewItem;
if (item.Checked)
{
indexes[pos++] = item;
}
}
return indexes;
}
public ListViewItem this[int index]
{
get
{
int pos = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
ListViewItem item = owner.listItems[i] as ListViewItem;
if (item.Checked)
{
if (pos == index)
{
return item;
}
pos++;
}
}
return null;
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
throw new NotSupportedException();
}
}
public virtual bool IsReadOnly
{
get
{
return true;
}
}
public CheckedListViewItemCollection(ListView owner)
{
this.owner = owner;
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
bool IList.IsFixedSize
{
get
{
return true;
}
}
public bool Contains(ListViewItem item)
{
if (item != null && item.ListView == owner && item.Checked)
{
return true;
}
else
{
return false;
}
}
bool IList.Contains(object item)
{
if (item is ListViewItem)
{
return Contains(item as ListViewItem);
}
else
{
return false;
}
}
public int IndexOf(ListViewItem item)
{
int pos = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
ListViewItem itemArray = owner.listItems[i] as ListViewItem;
if (item.Checked)
{
if (item == itemArray)
{
return pos;
}
pos++;
}
}
return -1;
}
int IList.IndexOf(object item)
{
ListViewItem listViewItem = item as ListViewItem;
if (listViewItem != null)
{
return IndexOf(listViewItem);
}
else
{
return -1;
}
}
void IList.Clear()
{
throw new NotSupportedException();
}
int IList.Add(object value)
{
throw new NotSupportedException();
}
void IList.Insert(int index, object value)
{
throw new NotSupportedException();
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException();
}
void IList.Remove(object value)
{
throw new NotSupportedException();
}
public virtual void CopyTo(Array dest, int index)
{
for (int i = 0; i < owner.listItems.Count; i++)
{
ListViewItem item = owner.listItems[i] as ListViewItem;
if (item.Checked)
{
dest.SetValue(item, index++);
}
}
}
public virtual IEnumerator GetEnumerator()
{
return GenerateCheckedItems().GetEnumerator();
}
}
public class SelectedIndexCollection: IList
{
private ListView owner;
public virtual int Count
{
get
{
int pos = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
ListViewItem listViewItem = owner.listItems[i] as ListViewItem;
if (listViewItem.Selected)
{
pos++;
}
}
return pos;
}
}
public int this[int index]
{
get
{
int pos = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
ListViewItem listViewItem = owner.listItems[i] as ListViewItem;
if (listViewItem.Selected)
{
if (pos == index)
{
return i;
}
pos++;
}
}
throw new ArgumentOutOfRangeException();
}
}
public virtual bool IsReadOnly
{
get
{
return true;
}
}
public SelectedIndexCollection(ListView owner)
{
this.owner = owner;
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
throw new NotSupportedException();
}
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
bool IList.IsFixedSize
{
get
{
return true;
}
}
public bool Contains(int selectedIndex)
{
return owner.Items[selectedIndex].Selected;
}
bool IList.Contains(object selectedIndex)
{
if (selectedIndex is Int32)
{
return Contains((int)selectedIndex);
}
else
{
return false;
}
}
public int IndexOf(int selectedIndex)
{
int pos = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
ListViewItem listViewItem = owner.listItems[i] as ListViewItem;
if (listViewItem.Selected)
{
if (selectedIndex == i)
{
return pos;
}
pos++;
}
}
return -1;
}
int IList.IndexOf(object selectedIndex)
{
if (selectedIndex is Int32)
{
return IndexOf((int)selectedIndex);
}
else
{
return -1;
}
}
int IList.Add(object value)
{
throw new NotSupportedException();
}
void IList.Clear()
{
throw new NotSupportedException();
}
void IList.Insert(int index, object value)
{
throw new NotSupportedException();
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException();
}
void IList.Remove(object value)
{
throw new NotSupportedException();
}
public virtual void CopyTo(Array dest, int index)
{
for (int i = 0; i < owner.listItems.Count; i++)
{
if ((owner.listItems[i] as ListViewItem).Selected)
{
dest.SetValue(i, index++);
}
}
}
public virtual IEnumerator GetEnumerator()
{
return GenerateSelectedIndexArray().GetEnumerator();
}
private int[] GenerateSelectedIndexArray()
{
int[] selectedIndexes = new int[Count];
int pos = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
if ((owner.listItems[i] as ListViewItem).Selected)
{
selectedIndexes[pos++] = i;
}
}
return selectedIndexes;
}
}
public class SelectedListViewItemCollection: IList
{
private ListView owner;
public virtual int Count
{
get
{
return owner.selectedIndices.Count;
}
}
public ListViewItem this[int index]
{
get
{
int pos = 0;
for (int i = 0;i < owner.listItems.Count; i++)
{
ListViewItem listViewItem = owner.listItems[i] as ListViewItem;
if (listViewItem.Selected)
{
if (index == pos)
{
return listViewItem;
}
pos++;
}
}
throw new ArgumentOutOfRangeException();
}
}
public virtual bool IsReadOnly
{
get
{
return true;
}
}
public SelectedListViewItemCollection(ListView owner)
{
this.owner = owner;
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
throw new NotSupportedException();
}
}
bool IList.IsFixedSize
{
get
{
return true;
}
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
int IList.Add(object value)
{
throw new NotSupportedException();
}
void IList.Insert(int index, object value)
{
throw new NotSupportedException();
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException();
}
void IList.Remove(object value)
{
throw new NotSupportedException();
}
public virtual void Clear()
{
for (int i = 0; i < owner.listItems.Count; i++)
{
ListViewItem listViewItem = owner.listItems[i] as ListViewItem;
if (listViewItem.Selected)
{
listViewItem.Selected = false;
}
}
}
public bool Contains(ListViewItem item)
{
return IndexOf(item) != -1;
}
bool IList.Contains(object item)
{
ListViewItem listViewItem = item as ListViewItem;
if (listViewItem != null)
{
return Contains(item as ListViewItem);
}
else
{
return false;
}
}
public virtual void CopyTo(Array dest, int index)
{
for (int i = 0; i < owner.listItems.Count; i++)
{
ListViewItem listViewItem = owner.listItems[i] as ListViewItem;
if (listViewItem.Selected)
{
dest.SetValue(listViewItem, index++);
}
}
}
public int IndexOf(ListViewItem item)
{
int pos = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
ListViewItem arrayItem = owner.listItems[i] as ListViewItem;
if (arrayItem.Selected)
{
if (arrayItem == item)
{
return pos;
}
pos++;
}
}
return -1;
}
public virtual IEnumerator GetEnumerator()
{
return GenerateSelectedItemArray().GetEnumerator();
}
private ListViewItem[] GenerateSelectedItemArray()
{
ListViewItem[] selectedItems = new ListViewItem[Count];
int pos = 0;
for (int i = 0; i < owner.listItems.Count; i++)
{
ListViewItem item = owner.listItems[i] as ListViewItem;
if (item.Selected)
{
selectedItems[pos++] = item;
}
}
return selectedItems;
}
int IList.IndexOf(object item)
{
ListViewItem listViewItem = item as ListViewItem;
if (listViewItem != null)
{
return IndexOf(listViewItem);
}
return -1;
}
}
public class ListViewItemCollection: IList
{
private ListView owner;
public virtual int Count
{
get
{
return owner.listItems.Count;
}
}
public virtual bool IsReadOnly
{
get
{
return false;
}
}
[TODO]
public virtual ListViewItem this[int displayIndex]
{
get
{
return owner.listItems[displayIndex] as ListViewItem;
}
set
{
owner.listItems[displayIndex] = value;
}
}
public ListViewItemCollection(ListView owner)
{
this.owner = owner;
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
bool ICollection.IsSynchronized
{
get
{
return true;
}
}
bool IList.IsFixedSize
{
get
{
return false;
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
if (value is ListViewItem)
{
this[index] = value as ListViewItem;
}
else if (value != null)
{
this[index] = new ListViewItem(value.ToString());
}
}
}
public virtual ListViewItem Add(string text)
{
return Add(text, -1);
}
int IList.Add(object item)
{
if (item is ListViewItem)
{
return IndexOf(Add(item as ListViewItem));
}
if (item != null)
{
return IndexOf(Add(item.ToString()));
}
return -1;
}
public virtual ListViewItem Add(string text, int imageIndex)
{
ListViewItem listViewItem = new ListViewItem(text, imageIndex);
Add(listViewItem);
return listViewItem;
}
[TODO]
public virtual ListViewItem Add(ListViewItem value)
{
owner.listItems.Add(value);
owner.Sort();
return value;
}
[TODO]
public void AddRange(ListViewItem[] values)
{
owner.listItems.AddRange(values);
owner.Sort();
}
[TODO]
public virtual void Clear()
{
if (owner.listItems.Count > 0)
{
owner.listItems.Clear();
}
}
public bool Contains(ListViewItem item)
{
return IndexOf(item) != -1;
}
bool IList.Contains(object item)
{
if (item is ListViewItem)
{
return Contains(item as ListViewItem);
}
else
{
return false;
}
}
public virtual void CopyTo(Array dest, int index)
{
for (int i = 0; i < owner.listItems.Count; i++)
{
dest.SetValue(owner.listItems[i], index++);
}
}
public virtual IEnumerator GetEnumerator()
{
ListViewItem[] listViewItems = new ListViewItem[owner.listItems.Count];
CopyTo(listViewItems, 0);
return listViewItems.GetEnumerator();
}
public int IndexOf(ListViewItem item)
{
for (int i = 0; i < Count; i++)
{
if (this[i] == item)
{
return i;
}
}
return -1;
}
int IList.IndexOf(object item)
{
ListViewItem listViewItem = item as ListViewItem;
if (item != null)
{
return IndexOf(listViewItem);
}
else
{
return -1;
}
}
void IList.Insert(int index, object item)
{
ListViewItem listViewItem = item as ListViewItem;
if (listViewItem != null)
{
Insert(index, listViewItem);
}
else if (item != null)
{
Insert(index, item.ToString());
}
}
[TODO]
public virtual void RemoveAt(int index)
{
owner.listItems.RemoveAt(index);
}
[TODO]
public virtual void Remove(ListViewItem item)
{
Remove(item);
}
void IList.Remove(object item)
{
if (item == null || !(item is ListViewItem))
{
return;
}
Remove(item as ListViewItem);
}
[TODO]
public ListViewItem Insert(int index, ListViewItem item)
{
owner.listItems.Insert(index, item);
return item;
}
public ListViewItem Insert(int index, string text)
{
return Insert(index, new ListViewItem(text));
}
public ListViewItem Insert(int index, string text, int imageIndex)
{
return Insert(index, new ListViewItem(text, imageIndex));
}
}
public class ColumnHeaderCollection: IList
{
private ListView owner;
public virtual ColumnHeader this[int index]
{
get
{
return owner.columnHeaders[index];
}
}
public virtual int Count
{
get
{
if (owner.columnHeaders != null)
{
return owner.columnHeaders.Length;
}
else
{
return 0;
}
}
}
public virtual bool IsReadOnly
{
get
{
return true;
}
}
public ColumnHeaderCollection(ListView owner)
{
this.owner = owner;
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
throw new NotSupportedException();
}
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
bool ICollection.IsSynchronized
{
get
{
return true;
}
}
bool IList.IsFixedSize
{
get
{
return false;
}
}
public virtual ColumnHeader Add(string str, int width, HorizontalAlignment textAlign)
{
ColumnHeader columnHeader = new ColumnHeader();
columnHeader.text = str;
columnHeader.width = width;
columnHeader.textAlign = textAlign;
Add(columnHeader);
return columnHeader;
}
[TODO]
public virtual int Add(ColumnHeader value)
{
return Count;
}
public virtual void AddRange(ColumnHeader[] values)
{
for (int i = 0; i < values.Length; i++)
Add(values[i]);
}
int IList.Add(object value)
{
return Add(value as ColumnHeader);
}
[TODO]
public virtual void Clear()
{
if (owner.columnHeaders != null)
{
owner.columnHeaders = null;
}
}
void ICollection.CopyTo(Array dest, int index)
{
Array.Copy(owner.columnHeaders, 0, dest, index, owner.columnHeaders.Length);
}
public int IndexOf(ColumnHeader value)
{
for (int i = 0; i < owner.columnHeaders.Length; i++)
{
if (this[i] == value)
{
return i;
}
}
return -1;
}
int IList.IndexOf(object value)
{
ColumnHeader columnHeader = value as ColumnHeader;
if (columnHeader != null)
{
return IndexOf(columnHeader);
}
else
{
return -1;
}
}
public bool Contains(ColumnHeader value)
{
return IndexOf(value) != -1;
}
bool IList.Contains(object value)
{
ColumnHeader columnHeader = value as ColumnHeader;
if (columnHeader != null)
{
return Contains(columnHeader);
}
else
{
return false;
}
}
public virtual void Remove(ColumnHeader column)
{
int pos = IndexOf(column);
if (pos != -1)
{
RemoveAt(pos);
}
}
void IList.Remove(object value)
{
if (value is ColumnHeader)
{
Remove(value as ColumnHeader);
}
}
public virtual void RemoveAt(int index)
{
owner.columnHeaders[index].listView = null;
int newLen = owner.columnHeaders.Length - 1;
if (newLen == 0)
{
owner.columnHeaders = null;
return;
}
ColumnHeader[] columnHeaders = new ColumnHeader[newLen];
Array.Copy(owner.columnHeaders, 0, columnHeaders, 0, index);
if (index < newLen)
{
Array.Copy(owner.columnHeaders, index + 1, columnHeaders, index, newLen - index);
}
owner.columnHeaders = columnHeaders;
}
public virtual IEnumerator GetEnumerator()
{
if (owner.columnHeaders != null)
{
return owner.columnHeaders.GetEnumerator();
}
else
{
return new ColumnHeader[0].GetEnumerator();
}
}
public void Insert(int index, ColumnHeader value)
{
value.listView = owner;
int oldLen = 0;
if (owner.columnHeaders == null)
{
owner.columnHeaders = new ColumnHeader[1];
}
else
{
oldLen = owner.columnHeaders.Length;
ColumnHeader[] newColumnHeaders = new ColumnHeader[oldLen + 1];
Array.Copy(owner.columnHeaders, newColumnHeaders, oldLen);
owner.columnHeaders = newColumnHeaders;
}
Array.Copy(owner.columnHeaders, index, owner.columnHeaders, index + 1, oldLen - index);
owner.columnHeaders[index] = value;
//TODO
}
void IList.Insert(int index, object value)
{
ColumnHeader columnHeader = value as ColumnHeader;
if (columnHeader != null)
{
Insert(index, columnHeader);
}
}
public void Insert(int index, string str, int width, HorizontalAlignment textAlign)
{
ColumnHeader columnHeader = new ColumnHeader();
columnHeader.text = str;
columnHeader.width = width;
columnHeader.textAlign = textAlign;
Insert(index, columnHeader);
}
}
}
}
| |
// This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
// http://dead-code.org/redir.php?target=wme
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DeadCode.WME.Global;
using DeadCode.WME.Global.Actions;
using System.IO;
using DeadCode.WME.Global.Utils;
namespace DeadCode.WME.WindowEdit
{
public partial class FrmMain : ActionForm, IActionProvider
{
private const string AppName = "WindowEdit";
// settings
public Size GridSize = new Size(5, 5);
public Color SelectionColor = Color.Red;
public Color BoxColor = Color.FromArgb(100, 0, 0, 255);
//////////////////////////////////////////////////////////////////////////
public FrmMain()
{
InitializeComponent();
AppMgr = new ApplicationMgr("WindowEdit");
// load available actions
ActionManager.LoadActions(typeof(FrmMain));
ActionManager.LoadActions(typeof(WindowDoc));
// setup image list
ImageList Img = new ImageList();
Img.TransparentColor = Color.Magenta;
Img.ColorDepth = ColorDepth.Depth32Bit;
Img.Images.Add("window", new Bitmap(typeof(FrmMain), "Graphics.Icons.window.png"));
Img.Images.Add("button", new Bitmap(typeof(FrmMain), "Graphics.Icons.button.png"));
Img.Images.Add("editor", new Bitmap(typeof(FrmMain), "Graphics.Icons.editor.png"));
Img.Images.Add("static", new Bitmap(typeof(FrmMain), "Graphics.Icons.static.png"));
Img.Images.Add("entity", new Bitmap(typeof(FrmMain), "Graphics.Icons.entity.png"));
Img.Images.Add("box", new Bitmap(typeof(FrmMain), "Graphics.Icons.box.png"));
TreeLayout.ImageList = Img;
}
//////////////////////////////////////////////////////////////////////////
private void OnLoad(object sender, EventArgs e)
{
this.MinimumSize = this.Size;
AppMgr.Settings.LoadFromXmlFile();
LoadLayout(AppMgr.Settings);
LoadSettings(AppMgr.Settings);
// build menus and toolbars
ActionStripItem MainMenuDef = DefineMainMenu();
ActContext.StripBuilder.AddToolStrip(MainMenuDef, MainMenu.Items, true);
ActionStripItem MainToolbarDef = DefineMainToolbar();
ActContext.StripBuilder.AddToolStrip(MainToolbarDef, MainToolbar.Items, false);
ActContext.ActivateObject(ActiveObjectSlot.Application, this);
ActContext.StripBuilder.SetManagedToolStripsState();
// handle command-line
if (Environment.GetCommandLineArgs().Length > 1)
OpenFile(Environment.GetCommandLineArgs()[1]);
}
//////////////////////////////////////////////////////////////////////////
private void OnFormClosed(object sender, FormClosedEventArgs e)
{
SaveLayout(AppMgr.Settings);
SaveSettings(AppMgr.Settings);
AppMgr.Settings.SaveToXmlFile();
}
//////////////////////////////////////////////////////////////////////////
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
if(CurrentDoc!=null)
{
e.Cancel = !CurrentDoc.CloseDocument();
}
}
//////////////////////////////////////////////////////////////////////////
public void SaveSettings(SettingsNode RootNode)
{
SettingsNode Section = RootNode.GetNode("General", true, true);
if (Section == null) return;
Section.Clear();
Section.SetValue("SelectionColor", SelectionColor);
Section.SetValue("BoxColor", BoxColor);
Section.SetValue("BackgroundColor", WindowCanvas.BackColor);
Section.SetValue("GridWidth", GridSize.Width);
Section.SetValue("GridHeight", GridSize.Height);
SettingsNode RecentList = new SettingsNode("RecentFiles");
foreach (string RecentFile in _RecentFiles)
{
RecentList.Children.Add(new SettingsNode("RecentFile", RecentFile));
}
Section.Children.Add(RecentList);
}
//////////////////////////////////////////////////////////////////////////
public void LoadSettings(SettingsNode RootNode)
{
SettingsNode Section = RootNode.GetNode("General", true);
if (Section == null) return;
SelectionColor = Section.GetColor("SelectionColor", SelectionColor);
BoxColor = Section.GetColor("BoxColor", BoxColor);
WindowCanvas.BackColor = Section.GetColor("BackgroundColor", WindowCanvas.BackColor);
GridSize = new Size(Section.GetInt("GridWidth", GridSize.Width), Section.GetInt("GridHeight", GridSize.Height));
_RecentFiles.Clear();
SettingsNode RecentList = Section.GetNode("RecentFiles");
if (RecentList != null)
{
foreach (SettingsNode Node in RecentList.Children)
{
string RecentFile = Node.GetString();
if(File.Exists(RecentFile)) _RecentFiles.Add(RecentFile);
}
}
}
//////////////////////////////////////////////////////////////////////////
public ActionStripItem DefineMainMenu()
{
ActionStripItem Root = new ActionStripItem();
ActionStripItem FileMenu = Root.AddSub("FileMenu", "File");
FileMenu.AddItem("File.New");
FileMenu.AddItem("File.Open");
FileMenu.AddItem("File.Save");
FileMenu.AddItem("File.SaveAs");
FileMenu.AddItem();
FileMenu.AddItem("File.RecentFiles");
FileMenu.AddItem();
FileMenu.AddItem("File.AppClose");
ActionStripItem EditMenu = Root.AddSub("EditMenu", "Edit");
EditMenu.AddItem("Edit.Undo");
EditMenu.AddItem("Edit.Redo");
EditMenu.AddItem();
EditMenu.AddItem("Edit.Cut");
EditMenu.AddItem("Edit.Copy");
EditMenu.AddItem("Edit.Paste");
EditMenu.AddItem("Document.DeleteItem");
ActionStripItem ControlMenu = Root.AddSub("ControlMenu", "Controls");
ControlMenu.AddItem("Document.AddNone");
ControlMenu.AddItem();
ControlMenu.AddItem("Document.AddButton");
ControlMenu.AddItem("Document.AddStatic");
ControlMenu.AddItem("Document.AddEditor");
ControlMenu.AddItem("Document.AddEntity");
ControlMenu.AddItem();
ControlMenu.AddItem("Document.AddWindow");
ActionStripItem ToolsMenu = Root.AddSub("ToolsMenu", "Tools");
ToolsMenu.AddItem("Tools.Options");
ActionStripItem HelpMenu = Root.AddSub("HelpMenu", "Help");
HelpMenu.AddItem("Help.Contents");
HelpMenu.AddItem();
HelpMenu.AddItem("Help.About");
return Root;
}
//////////////////////////////////////////////////////////////////////////
public ActionStripItem DefineMainToolbar()
{
ActionStripItem Root = new ActionStripItem();
Root.AddItem("File.New");
Root.AddItem("File.Open");
Root.AddItem("File.Save");
Root.AddItem();
Root.AddItem("Edit.Undo");
Root.AddItem("Edit.Redo");
Root.AddItem();
Root.AddItem("Edit.Cut");
Root.AddItem("Edit.Copy");
Root.AddItem("Edit.Paste");
Root.AddItem("Document.DeleteItem");
Root.AddItem();
Root.AddItem("Document.AddNone");
Root.AddItem();
Root.AddItem("Document.AddButton");
Root.AddItem("Document.AddStatic");
Root.AddItem("Document.AddEditor");
Root.AddItem("Document.AddEntity");
Root.AddItem();
Root.AddItem("Document.AddWindow");
Root.AddItem();
Root.AddItem();
Root.AddItem("Document.Refresh");
return Root;
}
private WindowDoc _CurrentDoc = null;
//////////////////////////////////////////////////////////////////////////
public WindowDoc CurrentDoc
{
get
{
return _CurrentDoc;
}
set
{
_CurrentDoc = value;
ActContext.ActivateObject(ActiveObjectSlot.Document, _CurrentDoc);
}
}
//////////////////////////////////////////////////////////////////////////
private void OnDocumentCaptionChanged(object sender, EventArgs e)
{
this.Text = ((Document)sender).GetDocumentCaption(AppName);
}
//////////////////////////////////////////////////////////////////////////
private void OnDocumentFileNameChanged(object sender, EventArgs e)
{
AddRecentFile(((Document)sender).FileName);
}
List<string> _RecentFiles = new List<string>();
//////////////////////////////////////////////////////////////////////////
public void RunRecentFile(string FileName)
{
OpenFile(FileName);
}
//////////////////////////////////////////////////////////////////////////
private void AddRecentFile(string FileName)
{
if (FileName == null || FileName == string.Empty) return;
foreach(string RecentFile in _RecentFiles)
{
if (string.Compare(FileName, RecentFile, true) == 0)
{
_RecentFiles.Remove(RecentFile);
break;
}
}
_RecentFiles.Insert(0, FileName);
while(_RecentFiles.Count > 8)
{
_RecentFiles.RemoveAt(_RecentFiles.Count - 1);
}
ActContext.StripBuilder.RefreshManagedToolStrips();
}
#region Actions
//////////////////////////////////////////////////////////////////////////
[ActionProp("File.AppClose",
Caption = "Exit",
Type = ActionType.Button,
ShortcutKeys = Keys.Alt|Keys.F4)
]
public void File_AppClose(ActionParam Param)
{
switch (Param.Type)
{
case ActionParam.QueryType.Invoke:
this.Close();
break;
}
}
//////////////////////////////////////////////////////////////////////////
[ActionProp("File.New",
Caption = "New",
IconName = "Graphics.Icons.new.png",
Type = ActionType.Button,
ShortcutKeys = Keys.Control | Keys.N)
]
public void File_New(ActionParam Param)
{
switch (Param.Type)
{
case ActionParam.QueryType.Invoke:
if(CurrentDoc != null)
{
if (CurrentDoc.CloseDocument())
{
CurrentDoc.CaptionChanged -= new EventHandler(OnDocumentCaptionChanged);
CurrentDoc.FileNameChanged -= new EventHandler(OnDocumentFileNameChanged);
CurrentDoc.Dispose();
}
else
return;
}
PropItem.SelectedObject = null;
WindowDoc NewDoc = new WindowDoc(this);
NewDoc.CaptionChanged += new EventHandler(OnDocumentCaptionChanged);
NewDoc.FileNameChanged += new EventHandler(OnDocumentFileNameChanged);
if (NewDoc.NewDocument(WindowCanvas))
{
CurrentDoc = NewDoc;
CurrentDoc.PropGrid = PropItem;
CurrentDoc.LayoutTree = TreeLayout;
}
else CurrentDoc = null;
break;
}
}
//////////////////////////////////////////////////////////////////////////
[ActionProp("File.Open",
Caption = "Open",
IconName = "Graphics.Icons.open.png",
Type = ActionType.Button,
ShortcutKeys = Keys.Control | Keys.O)
]
public void File_Open(ActionParam Param)
{
switch (Param.Type)
{
case ActionParam.QueryType.Invoke:
OpenFile();
break;
}
}
//////////////////////////////////////////////////////////////////////////
private void OpenFile()
{
OpenFile(null);
}
//////////////////////////////////////////////////////////////////////////
private void OpenFile(string Filename)
{
if (CurrentDoc != null)
{
if (CurrentDoc.CloseDocument())
{
CurrentDoc.CaptionChanged -= new EventHandler(OnDocumentCaptionChanged);
CurrentDoc.FileNameChanged -= new EventHandler(OnDocumentFileNameChanged);
CurrentDoc.Dispose();
}
else
return;
}
HourGlass.Enabled = true;
WindowDoc NewDoc = new WindowDoc(this);
NewDoc.CaptionChanged += new EventHandler(OnDocumentCaptionChanged);
NewDoc.FileNameChanged += new EventHandler(OnDocumentFileNameChanged);
Document.DocumentOpenResult Res = NewDoc.OpenDocument(WindowCanvas, Filename);
if (Res == Document.DocumentOpenResult.Ok)
{
CurrentDoc = NewDoc;
CurrentDoc.PropGrid = PropItem;
CurrentDoc.LayoutTree = TreeLayout;
AddRecentFile(CurrentDoc.FileName);
}
else
{
CurrentDoc = null;
if(Res == Document.DocumentOpenResult.Error)
MessageBox.Show("Error opening file. See WindowEdit.log for details.", Form.ActiveForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Text = AppName;
}
HourGlass.Enabled = false;
}
//////////////////////////////////////////////////////////////////////////
[ActionProp("File.RecentFiles",
Caption = "Recent files",
Type = ActionType.Custom)
]
public void File_RecentFiles(ActionParam Param)
{
switch (Param.Type)
{
case ActionParam.QueryType.CustomBuild:
if(Param.Items != null)
{
if (_RecentFiles.Count > 0)
{
int Count = 0;
foreach (string RecentFile in _RecentFiles)
{
if (!File.Exists(RecentFile)) continue;
Count++;
string FileToLoad = RecentFile;
ToolStripMenuItem NewItem = new ToolStripMenuItem("&" + Count.ToString() + " " + WmeUtils.ShortenPathname(RecentFile, 50));
NewItem.Click += delegate(object sender, EventArgs e)
{
RunRecentFile(FileToLoad);
};
Param.Items.Add(NewItem);
}
}
Param.Processed = true;
}
break;
}
}
//////////////////////////////////////////////////////////////////////////
[ActionProp("Tools.Options",
Caption = "Options...",
Type = ActionType.Button)
]
public void Tools_Options(ActionParam Param)
{
switch (Param.Type)
{
case ActionParam.QueryType.Invoke:
SettingsForm dlg = new SettingsForm();
dlg.GridSize = GridSize;
dlg.SelectionColor = SelectionColor;
dlg.BoxColor = BoxColor;
dlg.BackgroundColor = WindowCanvas.BackColor;
if(dlg.ShowDialog() == DialogResult.OK)
{
GridSize = dlg.GridSize;
SelectionColor = dlg.SelectionColor;
BoxColor = dlg.BoxColor;
WindowCanvas.BackColor = dlg.BackgroundColor;
}
break;
}
}
//////////////////////////////////////////////////////////////////////////
[ActionProp("Help.Contents",
Caption = "Documentation",
IconName = "Graphics.Icons.help.png",
ShortcutKeys = Keys.F1,
Type = ActionType.Button)
]
public void Help_Contents(ActionParam Param)
{
switch (Param.Type)
{
case ActionParam.QueryType.Invoke:
string ChmPath = WmeUtils.ToolsPath + "wme.chm";
Help.ShowHelp(this, ChmPath);
break;
}
}
//////////////////////////////////////////////////////////////////////////
[ActionProp("Help.About",
Caption = "About...",
Type = ActionType.Button)
]
public void Help_About(ActionParam Param)
{
switch (Param.Type)
{
case ActionParam.QueryType.Invoke:
FrmAbout dlg = new FrmAbout();
dlg.ShowDialog();
break;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.WebSockets.Client.Tests
{
public class ConnectTest : ClientWebSocketTestBase
{
public ConnectTest(ITestOutputHelper output) : base(output) { }
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(UnavailableWebSocketServers))]
public async Task ConnectAsync_NotWebSocketServer_ThrowsWebSocketExceptionWithMessage(Uri server, string exceptionMessage)
{
using (var cws = new ClientWebSocket())
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() =>
cws.ConnectAsync(server, cts.Token));
Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode);
Assert.Equal(WebSocketState.Closed, cws.State);
// .NET Framework and UAP implmentations have different exception message from .NET Core.
if (!PlatformDetection.IsFullFramework && !PlatformDetection.IsUap)
{
Assert.Equal(exceptionMessage, ex.Message);
}
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task EchoBinaryMessage_Success(Uri server)
{
await WebSocketHelper.TestEcho(server, WebSocketMessageType.Binary, TimeOutMilliseconds, _output);
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task EchoTextMessage_Success(Uri server)
{
await WebSocketHelper.TestEcho(server, WebSocketMessageType.Text, TimeOutMilliseconds, _output);
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoHeadersServers))]
public async Task ConnectAsync_AddCustomHeaders_Success(Uri server)
{
using (var cws = new ClientWebSocket())
{
cws.Options.SetRequestHeader("X-CustomHeader1", "Value1");
cws.Options.SetRequestHeader("X-CustomHeader2", "Value2");
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
Task taskConnect = cws.ConnectAsync(server, cts.Token);
Assert.True(
(cws.State == WebSocketState.None) ||
(cws.State == WebSocketState.Connecting) ||
(cws.State == WebSocketState.Open),
"State immediately after ConnectAsync incorrect: " + cws.State);
await taskConnect;
}
Assert.Equal(WebSocketState.Open, cws.State);
byte[] buffer = new byte[65536];
WebSocketReceiveResult recvResult;
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
recvResult = await ReceiveEntireMessageAsync(cws, new ArraySegment<byte>(buffer), cts.Token);
}
Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType);
string headers = WebSocketData.GetTextFromBuffer(new ArraySegment<byte>(buffer, 0, recvResult.Count));
Assert.True(headers.Contains("X-CustomHeader1:Value1"));
Assert.True(headers.Contains("X-CustomHeader2:Value2"));
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
}
[ActiveIssue(18784, TargetFrameworkMonikers.NetFramework)]
[OuterLoop]
[ConditionalTheory(nameof(WebSocketsSupported))]
public async Task ConnectAsync_AddHostHeader_Success()
{
Uri server = System.Net.Test.Common.Configuration.WebSockets.RemoteEchoServer;
// Send via the physical address such as "corefx-net.cloudapp.net"
// Set the Host header to logical address like "subdomain.corefx-net.cloudapp.net"
// Verify the scenario works and the remote server received "Host: subdomain.corefx-net.cloudapp.net"
string logicalHost = "subdomain." + server.Host;
using (var cws = new ClientWebSocket())
{
// Set the Host header to the logical address
cws.Options.SetRequestHeader("Host", logicalHost);
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
// Connect using the physical address
Task taskConnect = cws.ConnectAsync(server, cts.Token);
Assert.True(
(cws.State == WebSocketState.None) ||
(cws.State == WebSocketState.Connecting) ||
(cws.State == WebSocketState.Open),
"State immediately after ConnectAsync incorrect: " + cws.State);
await taskConnect;
}
Assert.Equal(WebSocketState.Open, cws.State);
byte[] buffer = new byte[65536];
WebSocketReceiveResult recvResult;
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
recvResult = await ReceiveEntireMessageAsync(cws, new ArraySegment<byte>(buffer), cts.Token);
}
Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType);
string headers = WebSocketData.GetTextFromBuffer(new ArraySegment<byte>(buffer, 0, recvResult.Count));
Assert.Contains($"Host:{logicalHost}", headers, StringComparison.Ordinal);
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoHeadersServers))]
public async Task ConnectAsync_CookieHeaders_Success(Uri server)
{
using (var cws = new ClientWebSocket())
{
Assert.Null(cws.Options.Cookies);
cws.Options.Cookies = new CookieContainer();
Cookie cookie1 = new Cookie("Cookies", "Are Yummy");
Cookie cookie2 = new Cookie("Especially", "Chocolate Chip");
Cookie secureCookie = new Cookie("Occasionally", "Raisin");
secureCookie.Secure = true;
cws.Options.Cookies.Add(server, cookie1);
cws.Options.Cookies.Add(server, cookie2);
cws.Options.Cookies.Add(server, secureCookie);
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
Task taskConnect = cws.ConnectAsync(server, cts.Token);
Assert.True(
cws.State == WebSocketState.None ||
cws.State == WebSocketState.Connecting ||
cws.State == WebSocketState.Open,
"State immediately after ConnectAsync incorrect: " + cws.State);
await taskConnect;
}
Assert.Equal(WebSocketState.Open, cws.State);
byte[] buffer = new byte[65536];
WebSocketReceiveResult recvResult;
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
recvResult = await ReceiveEntireMessageAsync(cws, new ArraySegment<byte>(buffer), cts.Token);
}
Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType);
string headers = WebSocketData.GetTextFromBuffer(new ArraySegment<byte>(buffer, 0, recvResult.Count));
Assert.True(headers.Contains("Cookies=Are Yummy"));
Assert.True(headers.Contains("Especially=Chocolate Chip"));
Assert.Equal(server.Scheme == "wss", headers.Contains("Occasionally=Raisin"));
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task ConnectAsync_PassNoSubProtocol_ServerRequires_ThrowsWebSocketExceptionWithMessage(Uri server)
{
const string AcceptedProtocol = "CustomProtocol";
using (var cws = new ClientWebSocket())
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var ub = new UriBuilder(server);
ub.Query = "subprotocol=" + AcceptedProtocol;
WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() =>
cws.ConnectAsync(ub.Uri, cts.Token));
Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode);
Assert.Equal(WebSocketState.Closed, cws.State);
Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task ConnectAsync_PassMultipleSubProtocols_ServerRequires_ConnectionUsesAgreedSubProtocol(Uri server)
{
const string AcceptedProtocol = "AcceptedProtocol";
const string OtherProtocol = "OtherProtocol";
using (var cws = new ClientWebSocket())
{
cws.Options.AddSubProtocol(AcceptedProtocol);
cws.Options.AddSubProtocol(OtherProtocol);
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var ub = new UriBuilder(server);
ub.Query = "subprotocol=" + AcceptedProtocol;
await cws.ConnectAsync(ub.Uri, cts.Token);
Assert.Equal(WebSocketState.Open, cws.State);
Assert.Equal(AcceptedProtocol, cws.SubProtocol);
}
}
}
}
| |
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Interop;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System.Windows.Forms;
using SaveFileDialog = System.Windows.Forms.SaveFileDialog;
using DialogResult = System.Windows.Forms.DialogResult;
#endregion // Namespaces
namespace RvtVa3c
{
[Transaction( TransactionMode.Manual )]
public class Command : IExternalCommand
{
/// <summary>
/// Custom assembly resolver to find our support
/// DLL without being forced to place our entire
/// application in a subfolder of the Revit.exe
/// directory.
/// </summary>
System.Reflection.Assembly
CurrentDomain_AssemblyResolve(
object sender,
ResolveEventArgs args )
{
if( args.Name.Contains( "Newtonsoft" ) )
{
string filename = Path.GetDirectoryName(
System.Reflection.Assembly
.GetExecutingAssembly().Location );
filename = Path.Combine( filename,
"Newtonsoft.Json.dll" );
if( File.Exists( filename ) )
{
return System.Reflection.Assembly
.LoadFrom( filename );
}
}
return null;
}
/// <summary>
/// Export a given 3D view to JSON using
/// our custom exporter context.
/// </summary>
public void ExportView3D(
View3D view3d,
string filename )
{
AppDomain.CurrentDomain.AssemblyResolve
+= CurrentDomain_AssemblyResolve;
Document doc = view3d.Document;
Va3cExportContext context
= new Va3cExportContext( doc, filename );
CustomExporter exporter = new CustomExporter(
doc, context );
// Note: Excluding faces just suppresses the
// OnFaceBegin calls, not the actual processing
// of face tessellation. Meshes of the faces
// will still be received by the context.
//
//exporter.IncludeFaces = false; // removed in Revit 2017
exporter.ShouldStopOnError = false;
exporter.Export( view3d );
}
#region UI to Filter Parameters
public static ParameterFilter _filter;
public static TabControl _tabControl;
public static Dictionary<string, List<string>> _parameterDictionary;
public static Dictionary<string, List<string>> _toExportDictionary;
/// <summary>
/// Function to filter the parameters of the objects in the scene
/// </summary>
/// <param name="doc">Revit Document</param>
/// <param name="includeType">Include Type Parameters in the filter dialog</param>
public void filterElementParameters(
Document doc,
bool includeType )
{
_parameterDictionary = new Dictionary<string, List<string>>();
_toExportDictionary = new Dictionary<string, List<string>>();
FilteredElementCollector collector
= new FilteredElementCollector( doc,
doc.ActiveView.Id );
// Create a dictionary with all the properties for each category.
foreach( var fi in collector )
{
if( null == fi.Category )
{
continue;
}
string category = fi.Category.Name;
if( category != "Title Blocks"
&& category != "Generic Annotations"
&& category != "Detail Items"
&& category != "Cameras" )
{
IList<Parameter> parameters = fi.GetOrderedParameters();
List<string> parameterNames = new List<string>();
foreach( Parameter p in parameters )
{
string pName = p.Definition.Name;
string tempVal = "";
if( StorageType.String == p.StorageType )
{
tempVal = p.AsString();
}
else
{
tempVal = p.AsValueString();
}
if( !string.IsNullOrEmpty( tempVal ) )
{
if( _parameterDictionary.ContainsKey( category ) )
{
if( !_parameterDictionary[category].Contains( pName ) )
{
_parameterDictionary[category].Add( pName );
}
}
else
{
parameterNames.Add( pName );
}
}
}
if( parameterNames.Count > 0 )
{
_parameterDictionary.Add( category, parameterNames );
}
if( includeType )
{
ElementId idType = fi.GetTypeId();
if( ElementId.InvalidElementId != idType )
{
Element typ = doc.GetElement( idType );
parameters = typ.GetOrderedParameters();
List<string> parameterTypes = new List<string>();
foreach( Parameter p in parameters )
{
string pName = "Type " + p.Definition.Name;
string tempVal = "";
if( !_parameterDictionary[category].Contains( pName ) )
{
if( StorageType.String == p.StorageType )
{
tempVal = p.AsString();
}
else
{
tempVal = p.AsValueString();
}
if( !string.IsNullOrEmpty( tempVal ) )
{
if( _parameterDictionary.ContainsKey( category ) )
{
if( !_parameterDictionary[category].Contains( pName ) )
{
_parameterDictionary[category].Add( pName );
}
}
else
{
parameterTypes.Add( pName );
}
}
}
}
if( parameterTypes.Count > 0 )
{
_parameterDictionary[category].AddRange( parameterTypes );
}
}
}
}
}
// Create filter UI.
_filter = new ParameterFilter();
_tabControl = new TabControl();
_tabControl.Size = new System.Drawing.Size( 600, 375 );
_tabControl.Location = new System.Drawing.Point( 0, 55 );
_tabControl.Anchor = ( (System.Windows.Forms.AnchorStyles) ( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom )
| System.Windows.Forms.AnchorStyles.Left )
| System.Windows.Forms.AnchorStyles.Right ) ) );
int j = 8;
// Populate the parameters as a checkbox in each tab
foreach( string c in _parameterDictionary.Keys )
{
//Create a checklist
CheckedListBox checkList = new CheckedListBox();
//set the properties of the checklist
checkList.Anchor = ( (System.Windows.Forms.AnchorStyles) ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right ) ) );
checkList.FormattingEnabled = true;
checkList.HorizontalScrollbar = true;
checkList.Items.AddRange( _parameterDictionary[c].ToArray() );
checkList.MultiColumn = true;
checkList.Size = new System.Drawing.Size( 560, 360 );
checkList.ColumnWidth = 200;
checkList.CheckOnClick = true;
checkList.TabIndex = j;
j++;
for( int i = 0; i <= ( checkList.Items.Count - 1 ); i++ )
{
checkList.SetItemCheckState( i, CheckState.Checked );
}
//add a tab
TabPage tab = new TabPage( c );
tab.Name = c;
//attach the checklist to the tab
tab.Controls.Add( checkList );
// attach the tab to the tab control
_tabControl.TabPages.Add( tab );
}
// Attach the tab control to the filter form
_filter.Controls.Add( _tabControl );
// Display filter ui
_filter.ShowDialog();
// Loop thru each tab and get the parameters to export
foreach( TabPage tab in _tabControl.TabPages )
{
List<string> parametersToExport = new List<string>();
foreach( var checkedP in ( (CheckedListBox) tab.Controls[0] ).CheckedItems )
{
parametersToExport.Add( checkedP.ToString() );
}
_toExportDictionary.Add( tab.Name, parametersToExport );
}
}
#endregion // UI to Filter Parameters
#region SelectFile
/// <summary>
/// Store the last user selected output folder
/// in the current editing session.
/// </summary>
static string _output_folder_path = null;
/// <summary>
/// Return true is user selects and confirms
/// output file name and folder.
/// </summary>
static bool SelectFile(
ref string folder_path,
ref string filename )
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Select JSON Output File";
dlg.Filter = "JSON files|*.js";
if( null != folder_path
&& 0 < folder_path.Length )
{
dlg.InitialDirectory = folder_path;
}
dlg.FileName = filename;
bool rc = DialogResult.OK == dlg.ShowDialog();
if( rc )
{
filename = Path.Combine( dlg.InitialDirectory,
dlg.FileName );
folder_path = Path.GetDirectoryName(
filename );
}
return rc;
}
#endregion // SelectFile
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements )
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Autodesk.Revit.ApplicationServices.Application app
= uiapp.Application;
Document doc = uidoc.Document;
// Check that we are in a 3D view.
View3D view = doc.ActiveView as View3D;
if( null == view )
{
Util.ErrorMsg(
"You must be in a 3D view to export." );
return Result.Failed;
}
// Prompt for output filename selection.
string filename = doc.PathName;
if( 0 == filename.Length )
{
filename = doc.Title;
}
if( null == _output_folder_path )
{
// Sometimes the command fails if the file is
// detached from central and not saved locally
try
{
_output_folder_path = Path.GetDirectoryName(
filename );
}
catch
{
TaskDialog.Show( "Folder not found",
"Please save the file and run the command again." );
return Result.Failed;
}
}
filename = Path.GetFileName( filename ) + ".js";
if( !SelectFile( ref _output_folder_path,
ref filename ) )
{
return Result.Cancelled;
}
filename = Path.Combine( _output_folder_path,
filename );
// Ask user whether to interactively choose
// which parameters to export or just export
// them all.
TaskDialog td = new TaskDialog( "Ask user to filter parameters" );
td.Title = "Filter parameters";
td.CommonButtons = TaskDialogCommonButtons.No | TaskDialogCommonButtons.Yes;
td.MainInstruction = "Do you want to filter the parameters of the objects to be exported?";
td.MainContent = "Click Yes and you will be able to select parameters for each category in the next window";
td.AllowCancellation = true;
td.VerificationText = "Check this to include type properties";
if( TaskDialogResult.Yes == td.Show() )
{
filterElementParameters( doc, td.WasVerificationChecked() );
if( ParameterFilter.status == "cancelled" )
{
ParameterFilter.status = "";
return Result.Cancelled;
}
}
// Save file.
ExportView3D( doc.ActiveView as View3D,
filename );
return Result.Succeeded;
}
}
}
| |
// 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 ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.noaccessibility004.noaccessibility004
{
// <Title>Call methods that have different accessibility</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class Foo
{
protected internal int this[int x]
{
set
{
Test.Status = 0;
}
}
}
public class Test
{
public static int Status = -1;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
dynamic d = 3;
f[d] = -1;
return Status;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier
{
using System;
using System.Globalization;
using System.Reflection;
using System.Resources;
public enum ErrorElementId
{
None,
SK_METHOD, // method
SK_CLASS, // type
SK_NAMESPACE, // namespace
SK_FIELD, // field
SK_PROPERTY, // property
SK_UNKNOWN, // element
SK_VARIABLE, // variable
SK_EVENT, // event
SK_TYVAR, // type parameter
SK_ALIAS, // using alias
ERRORSYM, // <error>
NULL, // <null>
GlobalNamespace, // <global namespace>
MethodGroup, // method group
AnonMethod, // anonymous method
Lambda, // lambda expression
AnonymousType, // anonymous type
}
public enum ErrorMessageId
{
None,
BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'
IntDivByZero, // Division by constant zero
BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}'
BadIndexCount, // Wrong number of indices inside []; expected '{0}'
BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}'
NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}'
NoExplicitConv, // Cannot convert type '{0}' to '{1}'
ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}'
AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'
AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}'
ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type
WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}'
NoSuchMember, // '{0}' does not contain a definition for '{1}'
ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}'
AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}'
BadAccess, // '{0}' is inaccessible due to its protection level
MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}'
AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer
NoConstructors, // The type '{0}' has no constructors defined
BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor
PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor
ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead
AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer)
RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor)
AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only
AbstractBaseCall, // Cannot call an abstract base member: '{0}'
RefProperty, // A property or indexer may not be passed as an out or ref parameter
ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')
FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression
UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers
BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters
MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false
CheckedOverflow, // The operation overflows at compile time in checked mode
ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override)
AmbigMember, // Ambiguity between '{0}' and '{1}'
SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}'
CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.
CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor.
BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression
NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?)
InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible
InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible
BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments
BadTypeArgument, // The type '{0}' may not be used as a type argument
TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments
HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments
NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}'
GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'.
GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints.
GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'.
TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.
BadRetType, // '{1} {0}' has the wrong return type
CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.
MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?
RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'
ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}'
CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}'
BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}'
ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}'
AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}'
PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported
PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly
BindToBogus, // '{0}' is not supported by the language
CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor
BogusType, // '{0}' is a type not supported by the language
MissingPredefinedMember, // Missing compiler required member '{0}.{1}'
LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type
UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions
ConvertToStaticClass, // Cannot convert to static type '{0}'
GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments
PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration
IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer
NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?)
ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates
BadArgCount, // No overload for method '{0}' takes '{1}' arguments
BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments
BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}'
RefLvalueExpected, // A ref or out argument must be an assignable variable
BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it)
BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}'
BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}'
BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments
BadDelArgTypes, // Delegate '{0}' has some invalid arguments
AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only
RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only
ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable
BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword
// DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED)
BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword
AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer)
RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor)
AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}'
RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}'
ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead.
DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>'
BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments
BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments
BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}'
BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments
InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.
NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method.
NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified
BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}'
BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}'
DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times
NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given
}
public enum RuntimeErrorId
{
None,
// RuntimeBinderInternalCompilerException
InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation
// ArgumentException
BindRequireArguments, // Cannot bind call with no calling object
// RuntimeBinderException
BindCallFailedOverloadResolution, // Overload resolution failed
// ArgumentException
BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments
// ArgumentException
BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument
// RuntimeBinderException
BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property
// RuntimeBinderException
BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -=
// RuntimeBinderException
BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type
// ArgumentException
BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument
// ArgumentException
BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument
// ArgumentException
BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument
// RuntimeBinderException
BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference
// RuntimeBinderException
NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference
// RuntimeBinderException
BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute
// RuntimeBinderException
BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object'
// EE?
EmptyDynamicView, // No further information on this object could be discovered
// MissingMemberException
GetValueonWriteOnlyProperty, // Write Only properties are not supported
}
public class ErrorVerifier
{
private static Assembly s_asm;
private static ResourceManager s_rm1;
private static ResourceManager s_rm2;
public static string GetErrorElement(ErrorElementId id)
{
return string.Empty;
}
public static bool Verify(ErrorMessageId id, string actualError, params string[] args)
{
return true;
}
public static bool Verify(RuntimeErrorId id, string actualError, params string[] args)
{
return true;
}
private static bool CompareMessages(ResourceManager rm, string id, string actualError, params string[] args)
{
// should not happen
if (null == rm)
return false;
if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(actualError))
{
System.Console.WriteLine("Empty error id or actual message");
return false;
}
string message = rm.GetString(id, null);
if ((null != args) && (0 < args.Length))
{
message = string.Format(CultureInfo.InvariantCulture, message, args);
}
bool ret = 0 == string.CompareOrdinal(message, actualError);
// debug
if (!ret)
{
System.Console.WriteLine("*** Expected= {0}\r\n*** Actual= {1}", message, actualError);
}
return ret;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param012.param012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier;
// <Title>Call methods that have different parameter modifiers with dynamic</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(23,23\).*CS0649</Expects>
public struct myStruct
{
public int Field;
}
public class Foo
{
public int this[params int[] x]
{
set
{
}
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
dynamic d = "foo";
try
{
f[d] = 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Foo.this[params int[]]"))
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param014.param014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier;
// <Title>Call methods that have different parameter modifiers with dynamic</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public struct myStruct
{
public int Field;
}
public class Foo
{
public int this[params int[] x]
{
set
{
}
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
dynamic d = "foo";
dynamic d2 = 3;
try
{
f[d2, d] = 3;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Foo.this[params int[]]"))
return 0;
}
return 1;
}
}
// </Code>
}
| |
// Authors: Robert M. Scheller, James B. Domingo
using System.Collections.Generic;
using System.Diagnostics;
using Landis.Utilities;
using Landis.Core;
using Landis.Library.Succession;
using Landis.Library.Parameters;
namespace Landis.Extension.Succession.Biomass
{
/// <summary>
/// The parameters for biomass succession.
/// </summary>
public class InputParameters
: IInputParameters
{
private int timestep;
private SeedingAlgorithms seedAlg;
private string climateConfigFile;
private bool calibrateMode;
private double spinupMortalityFraction;
private List<ISufficientLight> sufficientLight;
private Landis.Library.Parameters.Species.AuxParm<double> leafLongevity;
private Landis.Library.Parameters.Species.AuxParm<double> woodyDecayRate;
private Landis.Library.Parameters.Species.AuxParm<double> mortCurveShapeParm;
private Landis.Library.Parameters.Species.AuxParm<double> growthCurveShapeParm;
private Landis.Library.Parameters.Species.AuxParm<double> leafLignin;
private Landis.Library.Parameters.Ecoregions.AuxParm<int> aet;
private Landis.Library.Parameters.Ecoregions.AuxParm<Percentage>[] minRelativeBiomass;
private string dynamicInputFile;
private string initCommunities;
private string communitiesMap;
private FireReductions[] fireReductionsTable;
private List<HarvestReductions> harvestReductionsTable;
//---------------------------------------------------------------------
/// <summary>
/// Timestep (years)
/// </summary>
public int Timestep
{
get {
return timestep;
}
set {
if (value < 0)
throw new InputValueException(value.ToString(), "Timestep must be > or = 0");
timestep = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Seeding algorithm
/// </summary>
public SeedingAlgorithms SeedAlgorithm
{
get {
return seedAlg;
}
set {
seedAlg = value;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Ecoregions.AuxParm<Percentage>[] MinRelativeBiomass
{
get
{
return minRelativeBiomass;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Path to the file with the initial communities' definitions.
/// </summary>
public string InitialCommunities
{
get
{
return initCommunities;
}
set
{
if (value != null)
{
ValidatePath(value);
}
initCommunities = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Path to the raster file showing where the initial communities are.
/// </summary>
public string InitialCommunitiesMap
{
get
{
return communitiesMap;
}
set
{
if (value != null)
{
ValidatePath(value);
}
communitiesMap = value;
}
}
//---------------------------------------------------------------------
public bool CalibrateMode
{
get {
return calibrateMode;
}
set {
calibrateMode = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Background mortality rates applied during the biomass spin-up phase.
/// This represents background disturbance before year 1.
/// </summary>
public double SpinupMortalityFraction
{
get {
return spinupMortalityFraction;
}
set {
if (value < 0.0 || value > 0.5)
throw new InputValueException(value.ToString(), "SpinupMortalityFraction must be > 0.0 and < 0.5");
spinupMortalityFraction = value;
}
}
public string ClimateConfigFile
{
get
{
return climateConfigFile;
}
set
{
if (value != null)
{
ValidatePath(value);
}
climateConfigFile = value;
}
}
//---------------------------------------------------------------------
public void SetMinRelativeBiomass(byte shadeClass,
IEcoregion ecoregion,
InputValue<Percentage> newValue)
{
Debug.Assert(1 <= shadeClass && shadeClass <= 5);
Debug.Assert(ecoregion != null);
if (newValue != null)
{
if (newValue.Actual < 0.0 || newValue.Actual > 1.0)
throw new InputValueException(newValue.String,
"{0} is not between 0% and 100%", newValue.String);
}
minRelativeBiomass[shadeClass][ecoregion] = newValue;
}
//---------------------------------------------------------------------
/// <summary>
/// Definitions of sufficient light probabilities.
/// </summary>
public List<ISufficientLight> LightClassProbabilities
{
get {
return sufficientLight;
}
set
{
Debug.Assert(sufficientLight.Count != 0);
sufficientLight = value;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> LeafLongevity
{
get {
return leafLongevity;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> WoodyDecayRate
{
get {
return woodyDecayRate;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> MortCurveShapeParm
{
get {
return mortCurveShapeParm;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> GrowthCurveShapeParm
{
get
{
return growthCurveShapeParm;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Species.AuxParm<double> LeafLignin
{
get {
return leafLignin;
}
}
//---------------------------------------------------------------------
public Landis.Library.Parameters.Ecoregions.AuxParm<int> AET
{
get {
return aet;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Input file for the dynamic inputs
/// </summary>
public string DynamicInputFile
{
get
{
return dynamicInputFile;
}
set
{
dynamicInputFile = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Fire reduction of leaf and wood litter parameters.
/// </summary>
public FireReductions[] FireReductionsTable
{
get
{
return fireReductionsTable;
}
set
{
fireReductionsTable = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Harvest reduction of leaf and wood litter parameters.
/// </summary>
public List<HarvestReductions> HarvestReductionsTable
{
get
{
return harvestReductionsTable;
}
set
{
harvestReductionsTable = value;
}
}
//---------------------------------------------------------------------
public void SetLeafLongevity(ISpecies species,
double newValue)
{
Debug.Assert(species != null);
leafLongevity[species] = VerifyRange(newValue, 1.0, 10.0);
}
//---------------------------------------------------------------------
public void SetWoodyDecayRate(ISpecies species,
double newValue)
{
Debug.Assert(species != null);
woodyDecayRate[species] = VerifyRange(newValue, 0.0, 1.0);
}
//---------------------------------------------------------------------
public void SetMortCurveShapeParm(ISpecies species,
double newValue)
{
Debug.Assert(species != null);
mortCurveShapeParm[species] = VerifyRange(newValue, 5.0, 25.0);
}
//---------------------------------------------------------------------
public void SetGrowthCurveShapeParm(ISpecies species, double newValue)
{
Debug.Assert(species != null);
growthCurveShapeParm[species] = VerifyRange(newValue, 0, 1.0);
}
//---------------------------------------------------------------------
public void SetLeafLignin(ISpecies species,double newValue)
{
Debug.Assert(species != null);
leafLignin[species] = VerifyRange(newValue, 0.0, 0.4);
}
//---------------------------------------------------------------------
public void SetAET(IEcoregion ecoregion,int newValue)
{
Debug.Assert(ecoregion != null);
aet[ecoregion] = VerifyRange(newValue, 0, 10000);
}
//---------------------------------------------------------------------
public InputParameters()
{
fireReductionsTable = new FireReductions[6];
harvestReductionsTable = new List<HarvestReductions>();
sufficientLight = new List<ISufficientLight>();
leafLongevity = new Landis.Library.Parameters.Species.AuxParm<double>(PlugIn.ModelCore.Species);
woodyDecayRate = new Landis.Library.Parameters.Species.AuxParm<double>(PlugIn.ModelCore.Species);
mortCurveShapeParm = new Landis.Library.Parameters.Species.AuxParm<double>(PlugIn.ModelCore.Species);
growthCurveShapeParm = new Landis.Library.Parameters.Species.AuxParm<double>(PlugIn.ModelCore.Species);
leafLignin = new Landis.Library.Parameters.Species.AuxParm<double>(PlugIn.ModelCore.Species);
aet = new Landis.Library.Parameters.Ecoregions.AuxParm<int>(PlugIn.ModelCore.Ecoregions);
minRelativeBiomass = new Landis.Library.Parameters.Ecoregions.AuxParm<Percentage>[6];
for (byte shadeClass = 1; shadeClass <= 5; shadeClass++)
{
minRelativeBiomass[shadeClass] = new Landis.Library.Parameters.Ecoregions.AuxParm<Percentage>(PlugIn.ModelCore.Ecoregions);
}
}
//---------------------------------------------------------------------
private void ValidatePath(string path)
{
if (string.IsNullOrEmpty(path))
throw new InputValueException();
if (path.Trim(null).Length == 0)
throw new InputValueException(path,
"\"{0}\" is not a valid path.",
path);
}
public static double VerifyRange(double newValue, double minValue, double maxValue)
{
if (newValue < minValue || newValue > maxValue)
throw new InputValueException(newValue.ToString(),
"{0} is not between {1:0.0} and {2:0.0}",
newValue.ToString(), minValue, maxValue);
return newValue;
}
public static int VerifyRange(int newValue, int minValue, int maxValue)
{
if (newValue < minValue || newValue > maxValue)
throw new InputValueException(newValue.ToString(),
"{0} is not between {1:0.0} and {2:0.0}",
newValue.ToString(), minValue, maxValue);
return newValue;
}
}
}
| |
using System.IO;
using System.Web.UI;
using System.Xml;
using Rainbow.Framework;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Web.UI.WebControls;
namespace Rainbow.Content.Web.Modules
{
using Rainbow.Framework.Web.UI.WebControls;
/// <summary>
/// The OneFileModule provides basis for a module that only
/// consists of a single .ascx file.
/// See the OneFileModule Kit for documentation and examples.
/// Written by: Jakob Hansen, hansen3000@hotmail
/// </summary>
public class OneFileModule : Rainbow.Framework.Web.UI.WebControls.PortalModuleControl
{
/// <summary>
///
/// </summary>
public enum SettingsType { Off, Str, Xml, StrAndXml } // With StrAndXml SettingsStr are searched first
/// <summary>
///
/// </summary>
protected SettingsType _settingsType = SettingsType.Off;
/// <summary>
/// The content of setting "Settings string"
/// </summary>
protected string _settingsStr = string.Empty; //
/// <summary>
/// The filename in setting "XML settings file"
/// </summary>
protected string _xmlFileName = string.Empty; //
/// <summary>
/// The XML in file _xmlFileName
/// </summary>
protected XmlDocument _settingsXml; //
/// <summary>
/// True if setting "Debug Mode" is clicked
/// </summary>
protected bool _debugMode = false; //
/// <summary>
/// False if settings are missing
/// </summary>
protected bool _settingsExists = false; //
/// <summary>
/// Same as "Settings string" in the setting system
/// </summary>
/// <value>The settings STR.</value>
public string SettingsStr
{
get { return _settingsStr; }
}
/// <summary>
/// Same as "XML settings file" in the setting system
/// </summary>
/// <value>The name of the XML file.</value>
public string XmlFileName
{
get { return _xmlFileName; }
}
/// <summary>
/// The XML in file XmlFileName
/// </summary>
/// <value>The settings XML.</value>
public XmlDocument SettingsXml
{
get { return _settingsXml; }
}
/// <summary>
/// Same as "Debug Mode" in the setting system.
/// </summary>
/// <value><c>true</c> if [debug mode]; otherwise, <c>false</c>.</value>
public bool DebugMode
{
get { return _debugMode; }
set { _debugMode = value; }
}
/// <summary>
/// False if settings are missing
/// </summary>
/// <value><c>true</c> if [settings exists]; otherwise, <c>false</c>.</value>
public bool SettingsExists
{
get { return _settingsExists; }
}
/// <summary>
/// Fills all settings: SettingsStr, SettingsXml and DebugMode
/// InitSettings() should be the first line of code in Page_Load().
/// If settings is missing settingsExists is set to false
/// Note: It is not mandatory to use InitSettings() in the
/// Page_Load() - The programmer can just leave it out if he
/// decides that he is not going to use the setting system that
/// class OneFileModule provides.
/// </summary>
/// <param name="settingsType">Type of the settings.</param>
protected void InitSettings(SettingsType settingsType)
{
_settingsType = settingsType;
if (_settingsType == SettingsType.Off)
return;
_debugMode = "True" == Settings["Debug Mode"].ToString();
_xmlFileName = Settings["XML settings file"].ToString();
_settingsExists = true;
if (_settingsType == SettingsType.Str || _settingsType == SettingsType.StrAndXml)
{
_settingsStr = Settings["Settings string"].ToString();
if (_settingsStr == string.Empty)
{
_settingsExists = false;
Controls.Add(new LiteralControl("<br><span class='Error'>Settings string is missing</span><br>"));
}
}
if (_settingsType == SettingsType.Xml || _settingsType == SettingsType.StrAndXml)
{
_settingsXml = new XmlDocument();
if (GetSettingsXml(ref _settingsXml, _xmlFileName) == false)
{
_settingsExists = false;
Controls.Add(new LiteralControl("<br>" + "<span class='Error'>XML " + General.GetString("FILE_NOT_FOUND").Replace("%1%", _xmlFileName) + "<br>"));
}
}
}
/// <summary>
/// Creates 3 fields in the settings system:
/// "Settings string", "XML settings file" and "Debug Mode"
/// </summary>
public OneFileModule()
{
SettingItem setting = new SettingItem(new StringDataType());
setting.Required = false;
setting.Order = 1;
setting.Value = string.Empty;
setting.EnglishName = "Settings string";
setting.Description = "Settings are in pairs like: FirstName=Elvis;LastName=Presly;";
this._baseSettings.Add("Settings string", setting);
SettingItem xmlFile = new SettingItem(new PortalUrlDataType());
xmlFile.Required = false;
xmlFile.Order = 2;
xmlFile.EnglishName = "XML settings file";
xmlFile.Description = "Name of file in folder Rainbow\\_Portalfolder (typically _Rainbow). Do not add a path!";
this._baseSettings.Add("XML settings file", xmlFile);
SettingItem debugMode = new SettingItem(new BooleanDataType());
debugMode.Order = 3;
debugMode.Value = "True";
debugMode.EnglishName = "Debug Mode";
debugMode.Description = "Primarily for the developer. Controls property DebugMode";
this._baseSettings.Add("Debug Mode", debugMode);
}
/// <summary>
/// Get the setting value from SettingsStr.
/// If not found in SettingsStr then SettingsXml are searched.
/// This function uses GetStrSetting() and GetXmlSetting
/// </summary>
/// <param name="settingName">Name of the setting.</param>
/// <returns></returns>
protected string GetSetting(string settingName)
{
if (_settingsType == SettingsType.Off)
return string.Empty;
string retVal;
retVal = GetStrSetting(settingName);
if (retVal == string.Empty)
retVal = GetXmlSetting(settingName);
return retVal;
}
/// <summary>
/// Get the setting value from SettingsStr which has the form:
/// nameA=valueA;nameB=valueB;nameC=valueC
/// </summary>
/// <param name="settingName">Name of the setting.</param>
/// <returns></returns>
protected string GetStrSetting(string settingName)
{
if (_settingsType == SettingsType.Off ||
_settingsType == SettingsType.Xml ||
_settingsStr == string.Empty)
return string.Empty;
int idxStart = _settingsStr.IndexOf(settingName);
if (idxStart == -1)
return string.Empty;
idxStart = _settingsStr.IndexOf('=', idxStart);
if (idxStart == -1)
return string.Empty;
string val;
int idxEnd = _settingsStr.IndexOf(';', idxStart);
if (idxEnd == -1)
{
if (_settingsStr.Substring(idxStart).Length == 0)
val = string.Empty;
else
val = _settingsStr.Substring(++idxStart);
}
else
{
idxStart++;
val = _settingsStr.Substring(idxStart, (idxEnd - idxStart));
}
return val;
}
/// <summary>
/// Fills the settingsXml parameter with the xml from a file
/// </summary>
/// <param name="settingsXml">The settings XML.</param>
/// <param name="file">The file.</param>
/// <returns></returns>
protected bool GetSettingsXml(ref XmlDocument settingsXml, string file)
{
bool retValue = true;
PortalUrlDataType pt = new PortalUrlDataType();
pt.Value = file;
string xmlFile = pt.FullPath;
if ((xmlFile != null) && (xmlFile.Length != 0))
{
if (File.Exists(Server.MapPath(xmlFile)))
{
settingsXml.Load(Server.MapPath(xmlFile));
}
else
{
retValue = false;
}
}
return retValue;
}
/// <summary>
/// Get the setting value from the XML Document SettingsXml.
/// settingName is a XPath expression.
/// </summary>
/// <param name="settingName">Name of the setting.</param>
/// <returns></returns>
protected string GetXmlSetting(string settingName)
{
if (_settingsType == SettingsType.Off || _settingsType == SettingsType.Str)
return string.Empty;
string val = string.Empty;
// Add default root to the xpath expression if missing
if (settingName.IndexOf('/') == -1)
settingName = "settings/" + settingName;
XmlNodeReader xmlNodeReader = new XmlNodeReader(_settingsXml.SelectSingleNode(settingName));
try
{
if (xmlNodeReader.Read())
{
// If we get here the setting is in the xml file
// Move to next node (the text node containg the actual setting value)
if (xmlNodeReader.Read())
val = xmlNodeReader.Value;
}
}
finally
{
xmlNodeReader.Close(); //by Manu, fixed bug 807858
}
return val;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// SmtpClientTest.cs - NUnit Test Cases for System.Net.Mail.SmtpClient
//
// Authors:
// John Luke ([email protected])
//
// (C) 2006 John Luke
//
using System.IO;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Mail.Tests
{
public class SmtpClientTest : FileCleanupTestBase
{
private SmtpClient _smtp;
private SmtpClient Smtp
{
get
{
return _smtp ?? (_smtp = new SmtpClient());
}
}
private string TempFolder
{
get
{
return TestDirectory;
}
}
protected override void Dispose(bool disposing)
{
if (_smtp != null)
{
_smtp.Dispose();
}
base.Dispose(disposing);
}
[Theory]
[InlineData(SmtpDeliveryMethod.SpecifiedPickupDirectory)]
[InlineData(SmtpDeliveryMethod.PickupDirectoryFromIis)]
[InlineData(SmtpDeliveryMethod.PickupDirectoryFromIis)]
public void DeliveryMethodTest(SmtpDeliveryMethod method)
{
Smtp.DeliveryMethod = method;
Assert.Equal(method, Smtp.DeliveryMethod);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void EnableSslTest(bool value)
{
Smtp.EnableSsl = value;
Assert.Equal(value, Smtp.EnableSsl);
}
[Theory]
[InlineData("127.0.0.1")]
[InlineData("smtp.ximian.com")]
public void HostTest(string host)
{
Smtp.Host = host;
Assert.Equal(host, Smtp.Host);
}
[Fact]
public void InvalidHostTest()
{
Assert.Throws<ArgumentNullException>(() => Smtp.Host = null);
AssertExtensions.Throws<ArgumentException>("value", () => Smtp.Host = "");
}
[Fact]
public void ServicePoint_GetsCachedInstanceSpecificToHostPort()
{
using (var smtp1 = new SmtpClient("localhost1", 25))
using (var smtp2 = new SmtpClient("localhost1", 25))
using (var smtp3 = new SmtpClient("localhost2", 25))
using (var smtp4 = new SmtpClient("localhost2", 26))
{
ServicePoint s1 = smtp1.ServicePoint;
ServicePoint s2 = smtp2.ServicePoint;
ServicePoint s3 = smtp3.ServicePoint;
ServicePoint s4 = smtp4.ServicePoint;
Assert.NotNull(s1);
Assert.NotNull(s2);
Assert.NotNull(s3);
Assert.NotNull(s4);
Assert.Same(s1, s2);
Assert.NotSame(s2, s3);
Assert.NotSame(s2, s4);
Assert.NotSame(s3, s4);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[Fact]
public void ServicePoint_NetCoreApp_AddressIsAccessible()
{
using (var smtp = new SmtpClient("localhost", 25))
{
Assert.Equal("mailto", smtp.ServicePoint.Address.Scheme);
Assert.Equal("localhost", smtp.ServicePoint.Address.Host);
Assert.Equal(25, smtp.ServicePoint.Address.Port);
}
}
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
[Fact]
public void ServicePoint_NetFramework_AddressIsInaccessible()
{
using (var smtp = new SmtpClient("localhost", 25))
{
ServicePoint sp = smtp.ServicePoint;
Assert.Throws<NotSupportedException>(() => sp.Address);
}
}
[Fact]
public void ServicePoint_ReflectsHostAndPortChange()
{
using (var smtp = new SmtpClient("localhost1", 25))
{
ServicePoint s1 = smtp.ServicePoint;
smtp.Host = "localhost2";
ServicePoint s2 = smtp.ServicePoint;
smtp.Host = "localhost2";
ServicePoint s3 = smtp.ServicePoint;
Assert.NotSame(s1, s2);
Assert.Same(s2, s3);
smtp.Port = 26;
ServicePoint s4 = smtp.ServicePoint;
smtp.Port = 26;
ServicePoint s5 = smtp.ServicePoint;
Assert.NotSame(s3, s4);
Assert.Same(s4, s5);
}
}
[Theory]
[InlineData("")]
[InlineData(null)]
[InlineData("shouldnotexist")]
[InlineData("\0")]
[InlineData("C:\\some\\path\\like\\string")]
public void PickupDirectoryLocationTest(string folder)
{
Smtp.PickupDirectoryLocation = folder;
Assert.Equal(folder, Smtp.PickupDirectoryLocation);
}
[Theory]
[InlineData(25)]
[InlineData(1)]
[InlineData(int.MaxValue)]
public void PortTest(int value)
{
Smtp.Port = value;
Assert.Equal(value, Smtp.Port);
}
[Fact]
public void TestDefaultsOnProperties()
{
Assert.Equal(25, Smtp.Port);
Assert.Equal(100000, Smtp.Timeout);
Assert.Null(Smtp.Host);
Assert.Null(Smtp.Credentials);
Assert.False(Smtp.EnableSsl);
Assert.False(Smtp.UseDefaultCredentials);
Assert.Equal(SmtpDeliveryMethod.Network, Smtp.DeliveryMethod);
Assert.Null(Smtp.PickupDirectoryLocation);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(int.MinValue)]
public void Port_Value_Invalid(int value)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Smtp.Port = value);
}
[Fact]
public void Send_Message_Null()
{
Assert.Throws<ArgumentNullException>(() => Smtp.Send(null));
}
[Fact]
public void Send_Network_Host_Null()
{
Assert.Throws<InvalidOperationException>(() => Smtp.Send("[email protected]", "[email protected]", "introduction", "hello"));
}
[Fact]
public void Send_Network_Host_Whitespace()
{
Smtp.Host = " \r\n ";
Assert.Throws<InvalidOperationException>(() => Smtp.Send("[email protected]", "[email protected]", "introduction", "hello"));
}
[Fact]
public void Send_SpecifiedPickupDirectory()
{
Smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
Smtp.PickupDirectoryLocation = TempFolder;
Smtp.Send("[email protected]", "[email protected]", "introduction", "hello");
string[] files = Directory.GetFiles(TempFolder, "*");
Assert.Equal(1, files.Length);
Assert.Equal(".eml", Path.GetExtension(files[0]));
}
[Theory]
[InlineData("some_path_not_exist")]
[InlineData("")]
[InlineData(null)]
[InlineData("\0abc")]
public void Send_SpecifiedPickupDirectoryInvalid(string location)
{
Smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
Smtp.PickupDirectoryLocation = location;
Assert.Throws<SmtpException>(() => Smtp.Send("[email protected]", "[email protected]", "introduction", "hello"));
}
[Theory]
[InlineData(0)]
[InlineData(50)]
[InlineData(int.MaxValue)]
[InlineData(int.MinValue)]
[InlineData(-1)]
public void TestTimeout(int value)
{
if (value < 0)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Smtp.Timeout = value);
return;
}
Smtp.Timeout = value;
Assert.Equal(value, Smtp.Timeout);
}
[Fact]
public void Send_ServerDoesntExist_Throws()
{
using (var smtp = new SmtpClient(Guid.NewGuid().ToString("N")))
{
Assert.Throws<SmtpException>(() => smtp.Send("[email protected]", "[email protected]", "subject", "body"));
}
}
[Fact]
public async Task SendAsync_ServerDoesntExist_Throws()
{
using (var smtp = new SmtpClient(Guid.NewGuid().ToString("N")))
{
await Assert.ThrowsAsync<SmtpException>(() => smtp.SendMailAsync("[email protected]", "[email protected]", "subject", "body"));
}
}
[Fact]
public void TestMailDelivery()
{
SmtpServer server = new SmtpServer();
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
client.Credentials = new NetworkCredential("user", "password");
MailMessage msg = new MailMessage("[email protected]", "[email protected]", "hello", "howdydoo");
string clientDomain = IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower();
try
{
Thread t = new Thread(server.Run);
t.Start();
client.Send(msg);
t.Join();
Assert.Equal("<[email protected]>", server.MailFrom);
Assert.Equal("<[email protected]>", server.MailTo);
Assert.Equal("hello", server.Subject);
Assert.Equal("howdydoo", server.Body);
Assert.Equal(clientDomain, server.ClientDomain);
}
finally
{
server.Stop();
}
}
[Fact]
public async Task TestMailDeliveryAsync()
{
SmtpServer server = new SmtpServer();
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
MailMessage msg = new MailMessage("[email protected]", "[email protected]", "hello", "howdydoo");
string clientDomain = IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower();
try
{
Thread t = new Thread(server.Run);
t.Start();
await client.SendMailAsync(msg);
t.Join();
Assert.Equal("<[email protected]>", server.MailFrom);
Assert.Equal("<[email protected]>", server.MailTo);
Assert.Equal("hello", server.Subject);
Assert.Equal("howdydoo", server.Body);
Assert.Equal(clientDomain, server.ClientDomain);
}
finally
{
server.Stop();
}
}
[Fact]
public async Task TestCredentialsCopyInAsyncContext()
{
SmtpServer server = new SmtpServer();
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
MailMessage msg = new MailMessage("[email protected]", "[email protected]", "hello", "howdydoo");
string clientDomain = IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower();
CredentialCache cache = new CredentialCache();
cache.Add("localhost", server.EndPoint.Port, "NTLM", CredentialCache.DefaultNetworkCredentials);
client.Credentials = cache;
try
{
Thread t = new Thread(server.Run);
t.Start();
await client.SendMailAsync(msg);
t.Join();
Assert.Equal("<[email protected]>", server.MailFrom);
Assert.Equal("<[email protected]>", server.MailTo);
Assert.Equal("hello", server.Subject);
Assert.Equal("howdydoo", server.Body);
Assert.Equal(clientDomain, server.ClientDomain);
}
finally
{
server.Stop();
}
}
}
}
| |
using NetDimension.NanUI.JavaScript.Renderer;
using Xilium.CefGlue;
namespace NetDimension.NanUI.JavaScript;
internal static class JavaScriptTypeConverterExtension
{
public static JavaScriptValue ToJavaScriptValue(this CefV8Value v8Value)
{
JavaScriptValue jsValue;
if (v8Value == null/* || !v8Value.IsValid*/)
{
jsValue = JavaScriptValue.CreateUndefined();
return jsValue;
}
if (v8Value.IsFunction)
{
var context = CefV8Context.GetEnteredContext();
jsValue = JavaScriptRenderSideFunction.Create(context, v8Value);
JavaScriptObjectRepositoryOnRenderSide.StoredFunctions.Add((JavaScriptRenderSideFunction)jsValue);
}
else if (v8Value.IsArray)
{
var array = new JavaScriptArray();
for (int i = 0; i < v8Value.GetArrayLength(); i++)
{
array.Add(v8Value.GetValue(i).ToJavaScriptValue());
}
jsValue = array;
}
else if (v8Value.IsObject)
{
var obj = new JavaScriptObject();
foreach (var key in v8Value.GetKeys())
{
var item = v8Value.GetValue(key);
if (item != null && item.IsValid)
{
obj.Add(key, item.ToJavaScriptValue());
}
}
jsValue = obj;
}
else if (v8Value.IsBool)
{
jsValue = new JavaScriptValue(v8Value.GetBoolValue());
}
else if (v8Value.IsDate)
{
jsValue = new JavaScriptValue(v8Value.GetDateValue());
}
else if (v8Value.IsDouble)
{
var v = v8Value.GetDoubleValue();
if (Math.Abs(v % 1) < double.Epsilon)
{
jsValue = new JavaScriptValue(v8Value.GetIntValue());
}
else
{
jsValue = new JavaScriptValue(v);
}
}
else if (v8Value.IsInt || v8Value.IsUInt)
{
jsValue = new JavaScriptValue(v8Value.GetIntValue());
}
else if (v8Value.IsString)
{
jsValue = new JavaScriptValue(v8Value.GetStringValue());
}
else
{
jsValue = new JavaScriptValue();
}
return jsValue;
}
public static CefV8Value[] ToCefV8Arguments(this JavaScriptArray array)
{
var retval = new List<CefV8Value>();
for (int i = 0; i < array.Count; i++)
{
var source = array[i];
retval.Add(source.ToCefV8Value());
}
return retval.ToArray();
}
public static CefV8Value ToCefV8Value(this JavaScriptValue source)
{
switch (source.ValueType)
{
case JavaScriptValueType.Null:
return CefV8Value.CreateNull();
case JavaScriptValueType.Bool:
return CefV8Value.CreateBool(source.GetBool());
case JavaScriptValueType.Int:
return CefV8Value.CreateInt(source.GetInt());
case JavaScriptValueType.Double:
return CefV8Value.CreateDouble(source.GetDouble());
case JavaScriptValueType.String:
return CefV8Value.CreateString(source.GetString());
case JavaScriptValueType.JSON:
{
var context = CefV8Context.GetEnteredContext();
var json = context.GetGlobal().GetValue("JSON");
var parse = json.GetValue("parse");
var jsonValue = CefV8Value.CreateString(source.GetString());
var retval = parse.ExecuteFunction(null, new CefV8Value[] { jsonValue });
jsonValue.Dispose();
return retval;
}
case JavaScriptValueType.DateTime:
return CefV8Value.CreateDate(source.GetDateTime());
case JavaScriptValueType.Object:
{
var context = CefV8Context.GetEnteredContext();
var target = source.ToObject();
var obj = CefV8Value.CreateObject(new JavaScriptObjectAccessor(target, context));
foreach (var name in target.PropertyNames)
{
if (target.TryGetValue(name, out var retval) && retval != null)
{
var cefV8PropertyAttribute = CefV8PropertyAttribute.DontDelete;
if (retval.IsProperty)
{
var accessControl = CefV8AccessControl.AllCanRead;
var prop = (JavaScriptProperty)retval;
if (prop.Writable)
{
accessControl |= CefV8AccessControl.AllCanWrite;
}
else
{
cefV8PropertyAttribute |= CefV8PropertyAttribute.ReadOnly;
}
obj.SetValue(name, accessControl, cefV8PropertyAttribute);
}
else
{
obj.SetValue(name, retval.ToCefV8Value(), cefV8PropertyAttribute);
}
}
}
return obj;
}
case JavaScriptValueType.Array:
{
var result = new List<CefV8Value>();
var target = source.ToArray();
for (int i = 0; i < target.Count; i++)
{
var retval = target[i]?.ToCefV8Value();
if (retval != null)
{
result.Add(retval);
}
}
var array = CefV8Value.CreateArray(result.Count);
for (int i = 0; i < result.Count; i++)
{
array.SetValue(i, result[i]);
}
return array;
}
case JavaScriptValueType.Function:
{
var context = CefV8Context.GetEnteredContext();
var func = CefV8Value.CreateFunction(source.Name, new BrowserSideFunctionHandler(source, context));
return func;
}
case JavaScriptValueType.Property:
{
}
break;
}
return CefV8Value.CreateUndefined();
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_WDVMODUU
{
using System.Collections.Specialized;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Traditional tests for IgnoredHeaders scenario.
/// </summary>
[TestClass]
public class S02_IgnoredHeaders : TestSuiteBase
{
#region ClassInitialize method
/// <summary>
/// Initialize the class.
/// </summary>
/// <param name="testContext">VSTS test context.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestSuiteBase.Initialize(testContext);
}
#endregion
#region ClassCleanup method
/// <summary>
/// Clear the class.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestSuiteBase.Cleanup();
}
#endregion
#region IgnoredHeaders test cases
/// <summary>
/// This test case is used to partially test that the server ignores some headers in HTTP GET request.
/// </summary>
[TestCategory("MSWDVMODUU"), TestMethod()]
public void MSWDVMODUU_S02_TC01_IgnoredHeaders_Get()
{
// This test case is used to partially test that the server ignores following headers in HTTP GET request.
// Moss-Uid
// Moss-Did
// Moss-VerFrom
// Moss-CBFile
// MS-Set-Repl-Uid
// MS-BinDiff
// X-Office-Version
// User-Agent
// This test case calls the private help method "CompareHttpResponses_Get" for each above ignored header to partially test ignored headers.
// This help method has two input parameters, one is for the ignored header name, and another is for the value of the ignored header.
// The method "CompareHttpResponses_Get" will call HTTP GET method twice, in the first time the HTTP GET request includes the ignored header,
// and in the second time the HTTP GET request does NOT include the ignored header.
// And then the help method compare the key data in the two HTTP responses, if they are same then the help method return true, else return false.
// Get the request URI from the property "Server_NewFile001Uri".
string requestUri = Common.GetConfigurationPropertyValue("Server_NewFile001Uri", this.Site);
// Test the ignored header "Moss-Uid" in HTTP GET method.
// Call private help method "CompareHttpResponses_Get" with the ignored header "Moss-Uid" and its value.
// And capture MS-WDVMODUU_R80 if the method "CompareHttpResponses_Get" return true.
bool doesCaptureR80 = false;
doesCaptureR80 = this.CompareHttpResponses_Get(requestUri, "Moss-Uid", "{E6AA0E42-D27C-4FD8-89C6-EDB73AB1C741}");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR80,
80,
@"[In Moss-Uid Header] [The reply of implementation does be the same whether Moss-Uid header is included in the request or not.]");
// Test the ignored header "Moss-Did" in HTTP GET method.
// Call private help method "CompareHttpResponses_Get" with the ignored header "Moss-Did" and its value.
// And capture MS-WDVMODUU_R82 if the method "CompareHttpResponses_Get" return true.
bool doesCaptureR82 = false;
doesCaptureR82 = this.CompareHttpResponses_Get(requestUri, "Moss-Did", "{A5660731-CA3B-8654-B786-76A540E7AD34}");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR82,
82,
@"[In Moss-Did Header] [The reply of implementation does be the same whether Moss-Did header is included in the request or not.]");
// Test the ignored header "Moss-VerFrom" in HTTP GET method.
// Call private help method "CompareHttpResponses_Get" with the ignored header "Moss-VerFrom" and its value.
// And capture MS-WDVMODUU_R84 if the method "CompareHttpResponses_Get" return true.
bool doesCaptureR84 = false;
doesCaptureR84 = this.CompareHttpResponses_Get(requestUri, "Moss-VerFrom", "1");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR84,
84,
@"[In Moss-VerFrom Header] [The reply of implementation does be the same whether Moss-VerFrom header is included in the request or not.]");
// Test the ignored header "Moss-CBFile" in HTTP GET method.
// Call private help method "CompareHttpResponses_Get" with the ignored header "Moss-CBFile" and its value.
// And capture MS-WDVMODUU_R86 if the method "CompareHttpResponses_Get" return true.
bool doesCaptureR86 = false;
doesCaptureR86 = this.CompareHttpResponses_Get(requestUri, "Moss-CBFile", "0");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR86,
86,
@"[In Moss-CBFile Header] [The reply of implementation does be the same whether Moss-CBFile header is included in the request or not.]");
// Test the ignored header "MS-Set-Repl-Uid" in HTTP GET method.
// Call private help method "CompareHttpResponses_Get" with the ignored header "MS-Set-Repl-Uid" and its value.
// And capture MS-WDVMODUU_R88 if the method "CompareHttpResponses_Get" return true.
bool doesCaptureR88 = false;
doesCaptureR88 = this.CompareHttpResponses_Get(requestUri, "MS-Set-Repl-Uid", "rid:{E819DFCB-DB60-49D7-A70E-51E31F5344BE}");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR88,
88,
@"[In MS-Set-Repl-Uid Header] [The reply of implementation does be the same whether MS-Set-Repl-Uid header is included in the request or not.]");
// Test the ignored header "MS-BinDiff" in HTTP GET method.
// Call private help method "CompareHttpResponses_Get" with the ignored header "MS-BinDiff" and its value.
// And capture MS-WDVMODUU_R90 if the method "CompareHttpResponses_Get" return true.
bool doesCaptureR90 = false;
doesCaptureR90 = this.CompareHttpResponses_Get(requestUri, "MS-BinDiff", "1.0");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR90,
90,
@"[In MS-BinDiff Header] [The reply of implementation does be the same whether MS-BinDiff header is included in the request or not.]");
// Test the ignored header "X-Office-Version" in HTTP GET method.
// Call private help method "CompareHttpResponses_Get" with the ignored header "X-Office-Version" and its value.
// And capture MS-WDVMODUU_R92 if the method "CompareHttpResponses_Get" return true.
bool doesCaptureR92 = false;
doesCaptureR92 = this.CompareHttpResponses_Get(requestUri, "X-Office-Version", "12.0.6234");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR92,
92,
@"[In X-Office-Version Header] [The reply of implementation does be the same whether X-Office-Version header is included in the request or not.]");
// Test the ignored header "User-Agent" in HTTP GET method.
// Call private help method "CompareHttpResponses_Get" with the ignored header "User-Agent" and its value.
// And capture MS-WDVMODUU_R922 if the method "CompareHttpResponses_Get" return true.
bool doesCaptureR922 = false;
doesCaptureR922 = this.CompareHttpResponses_Get(requestUri, "User-Agent", "Microsoft Office/12.0 (Windows NT 5.2; SyncMan 12.0.6234; Pro)");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR922,
922,
@"[In User-Agent Header] The reply of implementation does be the same whether WebDAV header is included in the request or not.");
}
/// <summary>
/// This test case is used to partially test that the server ignores some headers in HTTP PUT request.
/// </summary>
[TestCategory("MSWDVMODUU"), TestMethod()]
public void MSWDVMODUU_S02_TC02_IgnoredHeaders_Put()
{
// This test case is used to partially test that the server ignores following headers in HTTP PUT request.
// Moss-Uid
// Moss-Did
// Moss-VerFrom
// Moss-CBFile
// MS-Set-Repl-Uid
// X-Office-Version
// User-Agent
// This test case calls the private help method "CompareHttpResponses_Put" for each above ignored header to partially test ignored headers.
// This help method has two input parameters, one is for the ignored header name, and another is for the value of the ignored header.
// The method "CompareHttpResponses_Put" will call HTTP PUT method and DELETE method twice, PUT method will upload a test file to the server,
// and the DELETE method will remove the test file from the server.
// In the first time the HTTP PUT and DELETE requests do NOT include the ignored header, and in the second time the HTTP PUT and DELETE requests include the ignored header.
// And then the help method compare the key data in the HTTP responses, if they are same then the help method return true, else return false.
// Get the request URI from the property "Server_TestTxtFileUri_Put".
string requestUri = Common.GetConfigurationPropertyValue("Server_TestTxtFileUri_Put", this.Site);
// Get file name from the property "Client_TestTxtFileName", and read its content into byte array.
byte[] bytesTxtFile = GetLocalFileContent(Common.GetConfigurationPropertyValue("Client_TestTxtFileName", this.Site));
// Test the ignored header "Moss-Uid" in HTTP PUT method.
// Call private help method "CompareHttpResponses_Put" with the ignored header "Moss-Uid" and its value.
// And capture MS-WDVMODUU_R80 if the method "CompareHttpResponses_Put" return true.
bool doesCaptureR80 = false;
doesCaptureR80 = this.CompareHttpResponses_Put(requestUri, bytesTxtFile, "Moss-Uid", "{E6AA0E42-D27C-4FD8-89C6-EDB73AB1C741}");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR80,
80,
@"[In Moss-Uid Header] [The reply of implementation does be the same whether Moss-Uid header is included in the request or not.]");
// Test the ignored header "Moss-Did" in HTTP PUT method.
// Call private help method "CompareHttpResponses_Put" with the ignored header "Moss-Did" and its value.
// And capture MS-WDVMODUU_R82 if the method "CompareHttpResponses_Put" return true.
bool doesCaptureR82 = false;
doesCaptureR82 = this.CompareHttpResponses_Put(requestUri, bytesTxtFile, "Moss-Did", "{A5660731-CA3B-8654-B786-76A540E7AD34}");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR82,
82,
@"[In Moss-Did Header] [The reply of implementation does be the same whether Moss-Did header is included in the request or not.]");
// Test the ignored header "Moss-VerFrom" in HTTP PUT method.
// Call private help method "CompareHttpResponses_Put" with the ignored header "Moss-VerFrom" and its value.
// And capture MS-WDVMODUU_R84 if the method "CompareHttpResponses_Put" return true.
bool doesCaptureR84 = false;
doesCaptureR84 = this.CompareHttpResponses_Put(requestUri, bytesTxtFile, "Moss-VerFrom", "1");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR84,
84,
@"[In Moss-VerFrom Header] [The reply of implementation does be the same whether Moss-VerFrom header is included in the request or not.]");
// Test the ignored header "Moss-CBFile" in HTTP PUT method.
// Call private help method "CompareHttpResponses_Put" with the ignored header "Moss-CBFile" and its value.
// And capture MS-WDVMODUU_R86 if the method "CompareHttpResponses_Put" return true.
bool doesCaptureR86 = false;
doesCaptureR86 = this.CompareHttpResponses_Put(requestUri, bytesTxtFile, "Moss-CBFile", bytesTxtFile.Length.ToString());
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR86,
86,
@"[In Moss-CBFile Header] [The reply of implementation does be the same whether Moss-CBFile header is included in the request or not.]");
// Test the ignored header "MS-Set-Repl-Uid" in HTTP PUT method.
// Call private help method "CompareHttpResponses_Put" with the ignored header "MS-Set-Repl-Uid" and its value.
// And capture MS-WDVMODUU_R88 if the method "CompareHttpResponses_Put" return true.
bool doesCaptureR88 = false;
doesCaptureR88 = this.CompareHttpResponses_Put(requestUri, bytesTxtFile, "MS-Set-Repl-Uid", "rid:{E819DFCB-DB60-49D7-A70E-51E31F5344BE}");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR88,
88,
@"[In MS-Set-Repl-Uid Header] [The reply of implementation does be the same whether MS-Set-Repl-Uid header is included in the request or not.]");
// Test the ignored header "X-Office-Version" in HTTP PUT method.
// Call private help method "CompareHttpResponses_Put" with the ignored header "X-Office-Version" and its value.
// And capture MS-WDVMODUU_R92 if the method "CompareHttpResponses_Put" return true.
bool doesCaptureR92 = false;
doesCaptureR92 = this.CompareHttpResponses_Put(requestUri, bytesTxtFile, "X-Office-Version", "12.0.6234");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR92,
92,
@"[In X-Office-Version Header] [The reply of implementation does be the same whether X-Office-Version header is included in the request or not.]");
// Test the ignored header "User-Agent" in HTTP PUT method.
// Call private help method "CompareHttpResponses_Put" with the ignored header "User-Agent" and its value.
// And capture MS-WDVMODUU_R922 if the method "CompareHttpResponses_Put" return true.
bool doesCaptureR922 = false;
doesCaptureR922 = this.CompareHttpResponses_Put(requestUri, bytesTxtFile, "User-Agent", "Microsoft Office/12.0 (Windows NT 5.2; SyncMan 12.0.6234; Pro)");
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR922,
922,
@"[In User-Agent Header] The reply of implementation does be the same whether WebDAV header is included in the request or not.");
}
/// <summary>
/// This test case is used to verify that, in Windows SharePoint Services 3.0, the reply of implementation does be the same whether "SyncMan []" is included in the User-Agent Header or not.
/// </summary>
[TestCategory("MSWDVMODUU"), TestMethod()]
public void MSWDVMODUU_S02_TC03_IgnoredHeaders_UserAgent()
{
if (Common.IsRequirementEnabled(128, this.Site))
{
string requestUri = Common.GetConfigurationPropertyValue("Server_NewFile001Uri", this.Site);
// Call HTTP GET method with User-Agent header that include "SyncMan []" comments.
WDVMODUUResponse responseForGetRequestWithSyncManComment = null;
NameValueCollection headersCollectionWithSyncManComment = this.GetHttpHeadersCollection(null, null);
headersCollectionWithSyncManComment.Add("User-Agent", "Microsoft Office/12.0 (Windows NT 5.2; SyncMan 12.0.6234; Pro)");
headersCollectionWithSyncManComment.Add("X-Office-Version", "12.0.6234");
responseForGetRequestWithSyncManComment = this.Adapter.Get(requestUri, headersCollectionWithSyncManComment);
// Call HTTP GET method with User-Agent header that does not include "SyncMan []" comments.
WDVMODUUResponse responseForGetRequestWithoutSyncManComment = null;
NameValueCollection headersCollectionWithoutSyncManComment = this.GetHttpHeadersCollection(null, null);
headersCollectionWithoutSyncManComment.Add("User-Agent", "Microsoft Office/12.0 (Windows NT 5.2; Pro)");
headersCollectionWithoutSyncManComment.Add("X-Office-Version", "12.0.6234");
responseForGetRequestWithoutSyncManComment = this.Adapter.Get(requestUri, headersCollectionWithoutSyncManComment);
#region Compare the two above responses of HTTP GET method
string errorLog = string.Empty;
// Compare status code values in the two response.
bool isSameStatusCode = false;
if (responseForGetRequestWithSyncManComment.StatusCode == responseForGetRequestWithoutSyncManComment.StatusCode)
{
isSameStatusCode = true;
}
else
{
isSameStatusCode = false;
errorLog = "Test Failed: The status codes in two response are not same! \r\n";
errorLog += string.Format("responseForGetRequestWithSyncManComment.StatusCode={0}\r\n", responseForGetRequestWithSyncManComment.StatusCode);
errorLog += string.Format("responseForGetRequestWithoutSyncManComment.StatusCode={0}\r\n", responseForGetRequestWithoutSyncManComment.StatusCode);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
// Compare status description values in the two response.
bool isSameStatusDescription = false;
if (string.Compare(responseForGetRequestWithSyncManComment.StatusDescription, responseForGetRequestWithoutSyncManComment.StatusDescription, true) == 0)
{
isSameStatusDescription = true;
}
else
{
isSameStatusDescription = false;
errorLog = "Test Failed: The status description in two response are not same! \r\n";
errorLog += string.Format("responseForGetRequestWithSyncManComment.StatusDescription={0}\r\n", responseForGetRequestWithSyncManComment.StatusDescription);
errorLog += string.Format("responseForGetRequestWithoutSyncManComment.StatusDescription={0}\r\n", responseForGetRequestWithoutSyncManComment.StatusDescription);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
// Compare content length values in the two response.
bool isSameContentLength = false;
if (responseForGetRequestWithSyncManComment.ContentLength == responseForGetRequestWithoutSyncManComment.ContentLength)
{
isSameContentLength = true;
}
else
{
isSameContentLength = false;
errorLog = "Test Failed: The content length in two response are not same! \r\n";
errorLog += string.Format("responseForGetRequestWithSyncManComment.ContentLength={0}\r\n", responseForGetRequestWithSyncManComment.ContentLength);
errorLog += string.Format("responseForGetRequestWithoutSyncManComment.ContentLength={0}\r\n", responseForGetRequestWithoutSyncManComment.ContentLength);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
// Compare content type values in the two response.
bool isSameContentType = false;
if (string.Compare(responseForGetRequestWithSyncManComment.ContentType, responseForGetRequestWithoutSyncManComment.ContentType, true) == 0)
{
isSameContentType = true;
}
else
{
isSameContentType = false;
errorLog = "Test Failed: The content type in two response are not same! \r\n";
errorLog += string.Format("responseForGetRequestWithSyncManComment.ContentType={0}\r\n", responseForGetRequestWithSyncManComment.ContentType);
errorLog += string.Format("responseForGetRequestWithoutSyncManComment.ContentType={0}\r\n", responseForGetRequestWithoutSyncManComment.ContentType);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
// Compare body data values in the two response.
bool isSameBodyData = false;
if (responseForGetRequestWithSyncManComment.BodyData == responseForGetRequestWithoutSyncManComment.BodyData)
{
isSameBodyData = true;
}
else
{
isSameBodyData = false;
errorLog = "Test Failed: The body data in two response are not same! \r\n";
errorLog += string.Format("responseForGetRequestWithSyncManComment.BodyData={0}\r\n", responseForGetRequestWithSyncManComment.BodyData);
errorLog += string.Format("responseForGetRequestWithoutSyncManComment.BodyData={0}\r\n", responseForGetRequestWithoutSyncManComment.BodyData);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
#endregion Compare the two above responses of HTTP GET method
// Capture MS-WDVMODUU_R128, if the key data in the above two responses of HTTP GET method are same.
bool doesCaptureR128 = false;
if (isSameStatusCode && isSameStatusDescription && isSameContentLength && isSameContentType && isSameBodyData)
{
doesCaptureR128 = true;
}
this.Site.CaptureRequirementIfIsTrue(
doesCaptureR128,
128,
@"[In Appendix B: Product Behavior] Implementation does reply the same response whether ""SyncMan []"" is included in the User-Agent Header or not.[In Appendix B: Product Behavior] <9> Section 2.2.1.9: Servers running Windows SharePoint Services 3.0 ignore comments [""SyncMan[]""] of this value in the User-Agent Header.");
}
else
{
this.Site.Assume.Inconclusive("Test is executed only when R128Enabled is set to true.");
}
}
#endregion
#region Help methods in Scenario 02
/// <summary>
/// Get the HTTP collection that main HTTP headers and their values are included.
/// If the special HTTP header and its value are set, then the special HTTP header and the value is also included the HTTP collection
/// </summary>
/// <param name="specialHttpHeaderName">The special HTTP header name.</param>
/// <param name="specialHttpHeaderValue">The special HTTP header value.</param>
/// <returns>Return the HTTP collection that is constructed in this method. </returns>
private NameValueCollection GetHttpHeadersCollection(string specialHttpHeaderName, string specialHttpHeaderValue)
{
NameValueCollection headersCollection = new NameValueCollection();
headersCollection.Add("Cache-Control", "no-cache");
headersCollection.Add("ContentType", "text/xml");
headersCollection.Add("Depth", "0");
headersCollection.Add("Pragma", "no-cache");
headersCollection.Add("ProtocolVersion", "HTTP/1.1");
if ((specialHttpHeaderName != null) && (specialHttpHeaderValue != null)
&& (specialHttpHeaderName != string.Empty) && (specialHttpHeaderValue != string.Empty))
{
headersCollection.Add(specialHttpHeaderName, specialHttpHeaderValue);
}
else
{
string errorInfo = "In GetHttpHeadersCollection, the input parameters are not correct!";
if (specialHttpHeaderName != null)
{
errorInfo += "\r\n specialHttpHeaderName = " + specialHttpHeaderName;
}
else
{
errorInfo += "\r\n specialHttpHeaderName is null! ";
}
if (specialHttpHeaderValue != null)
{
errorInfo += "\r\n specialHttpHeaderValue = " + specialHttpHeaderValue;
}
else
{
errorInfo += "\r\n specialHttpHeaderValue is null! ";
}
this.Site.Log.Add(LogEntryKind.TestError, errorInfo);
}
return headersCollection;
}
/// <summary>
/// The method will call HTTP GET method twice, in the first time the HTTP GET request includes the ignored header,
/// and in the second time the HTTP GET request does NOT include the ignored header.
/// And then the help method compare the key data in the two HTTP responses, if they are same then the help method return true, else return false.
/// </summary>
/// <param name="requestUri">The request URI that is used in HTTP GET method</param>
/// <param name="ignoredHttpHeaderName">The ignored header name.</param>
/// <param name="ignoredHttpHeaderValue">The ignored header value.</param>
/// <returns>Return true if the key data are same by comparing the responses, else return false.</returns>
private bool CompareHttpResponses_Get(string requestUri, string ignoredHttpHeaderName, string ignoredHttpHeaderValue)
{
this.Site.Assert.IsNotNull(requestUri, "In CompareHttpResponses_Get method, the request URI should not be null!");
this.Site.Assert.IsTrue(requestUri != string.Empty, "In CompareHttpResponses_Get method, the request URI should not be empty string!");
this.Site.Assert.IsNotNull(ignoredHttpHeaderName, "In CompareHttpResponses_Get method, the ignored header name should not be null!");
this.Site.Assert.IsNotNull(ignoredHttpHeaderValue, "In CompareHttpResponses_Get method, the ignored header value should not be null!");
this.Site.Assert.IsTrue(ignoredHttpHeaderName != string.Empty, "In CompareHttpResponses_Get method, the ignored header name should not be empty string!");
this.Site.Assert.IsTrue(ignoredHttpHeaderValue != string.Empty, "In CompareHttpResponses_Get method, the ignored header value should not be empty string!");
// Call HTTP GET method with ignored header.
WDVMODUUResponse responseForGetRequestWithIgnoredHeader = null;
NameValueCollection headersCollectionWithIgnoredHeader = this.GetHttpHeadersCollection(ignoredHttpHeaderName, ignoredHttpHeaderValue);
responseForGetRequestWithIgnoredHeader = this.Adapter.Get(requestUri, headersCollectionWithIgnoredHeader);
// Call HTTP GET method without ignored header.
WDVMODUUResponse responseForGetRequestWithoutIgnoredHeader = null;
NameValueCollection headersCollectionWithoutIgnoredHeader = this.GetHttpHeadersCollection(null, null);
responseForGetRequestWithoutIgnoredHeader = this.Adapter.Get(requestUri, headersCollectionWithoutIgnoredHeader);
string errorLog = string.Empty;
this.Site.Log.Add(TestTools.LogEntryKind.Comment, "The ignored header is {0}. The ignored header value is {1}.", ignoredHttpHeaderName, ignoredHttpHeaderValue);
#region Compare the two responses of HTTP GET method
this.Site.Log.Add(TestTools.LogEntryKind.Comment, "Compare the two responses of HTTP GET method.");
// Compare status code values in the two response.
bool isSameStatusCode = false;
if (responseForGetRequestWithIgnoredHeader.StatusCode == responseForGetRequestWithoutIgnoredHeader.StatusCode)
{
isSameStatusCode = true;
}
else
{
isSameStatusCode = false;
errorLog = "Test Failed: The status codes in two response are not same! \r\n";
errorLog += string.Format("responseForGetRequestWithIgnoredHeader.StatusCode={0}\r\n", (int)responseForGetRequestWithIgnoredHeader.StatusCode);
errorLog += string.Format("responseForGetRequestWithoutIgnoredHeader.StatusCode={0}\r\n", (int)responseForGetRequestWithoutIgnoredHeader.StatusCode);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
// Compare status description values in the two response.
bool isSameStatusDescription = false;
if (string.Compare(responseForGetRequestWithIgnoredHeader.StatusDescription, responseForGetRequestWithoutIgnoredHeader.StatusDescription, true) == 0)
{
isSameStatusDescription = true;
}
else
{
isSameStatusDescription = false;
errorLog = "Test Failed: The status description in two response are not same! \r\n";
errorLog += string.Format("responseForGetRequestWithIgnoredHeader.StatusDescription={0}\r\n", responseForGetRequestWithIgnoredHeader.StatusDescription);
errorLog += string.Format("responseForGetRequestWithoutIgnoredHeader.StatusDescription={0}\r\n", responseForGetRequestWithoutIgnoredHeader.StatusDescription);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
// Compare content length values in the two response.
bool isSameContentLength = false;
if (responseForGetRequestWithIgnoredHeader.ContentLength == responseForGetRequestWithoutIgnoredHeader.ContentLength)
{
isSameContentLength = true;
}
else
{
isSameContentLength = false;
errorLog = "Test Failed: The content length in two response are not same! \r\n";
errorLog += string.Format("responseForGetRequestWithIgnoredHeader.ContentLength={0}\r\n", responseForGetRequestWithIgnoredHeader.ContentLength);
errorLog += string.Format("responseForGetRequestWithoutIgnoredHeader.ContentLength={0}\r\n", responseForGetRequestWithoutIgnoredHeader.ContentLength);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
// Compare content type values in the two response.
bool isSameContentType = false;
if (string.Compare(responseForGetRequestWithIgnoredHeader.ContentType, responseForGetRequestWithoutIgnoredHeader.ContentType, true) == 0)
{
isSameContentType = true;
}
else
{
isSameContentType = false;
errorLog = "Test Failed: The content type in two response are not same! \r\n";
errorLog += string.Format("responseForGetRequestWithIgnoredHeader.ContentType={0}\r\n", responseForGetRequestWithIgnoredHeader.ContentType);
errorLog += string.Format("responseForGetRequestWithoutIgnoredHeader.ContentType={0}\r\n", responseForGetRequestWithoutIgnoredHeader.ContentType);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
// Compare body data values in the two response.
bool isSameBodyData = false;
if (responseForGetRequestWithIgnoredHeader.BodyData == responseForGetRequestWithoutIgnoredHeader.BodyData)
{
isSameBodyData = true;
}
else
{
isSameBodyData = false;
errorLog = "Test Failed: The body data in two response are not same! \r\n";
errorLog += string.Format("responseForGetRequestWithIgnoredHeader.BodyData={0}\r\n", responseForGetRequestWithIgnoredHeader.BodyData);
errorLog += string.Format("responseForGetRequestWithoutIgnoredHeader.BodyData={0}\r\n", responseForGetRequestWithoutIgnoredHeader.BodyData);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
#endregion Compare the two responses of HTTP GET method
// Judge if the two response are same.
bool isSameResponse = false;
if (isSameStatusCode && isSameStatusDescription && isSameContentLength && isSameContentType && isSameBodyData)
{
isSameResponse = true;
}
return isSameResponse;
}
/// <summary>
/// The method "CompareHttpResponses_Put" will call HTTP PUT method and DELETE method twice, PUT method will upload a test file to the server,
/// and the DELETE method will remove the test file from the server.
/// In the first time the HTTP PUT and DELETE requests do NOT include the ignored header, and in the second time the HTTP PUT and DELETE requests include the ignored header.
/// And then the help method compare the key data in the HTTP responses, if they are same then the help method return true, else return false.
/// </summary>
/// <param name="requestUri">The request URI that is used in HTTP PUT and DELETE method</param>
/// <param name="bytesTxtFile">The file content that will be used in HTTP body</param>
/// <param name="ignoredHttpHeaderName">The ignored header name.</param>
/// <param name="ignoredHttpHeaderValue">The ignored header value.</param>
/// <returns>Return true if the key data are same by comparing the responses, else return false.</returns>
private bool CompareHttpResponses_Put(string requestUri, byte[] bytesTxtFile, string ignoredHttpHeaderName, string ignoredHttpHeaderValue)
{
this.Site.Assert.IsNotNull(ignoredHttpHeaderName, "In CompareHttpResponses_Put method, the ignored header name should not be null!");
this.Site.Assert.IsNotNull(ignoredHttpHeaderValue, "In CompareHttpResponses_Put method, the ignored header value should not be null!");
this.Site.Assert.IsTrue(ignoredHttpHeaderName != string.Empty, "In CompareHttpResponses_Put method, the ignored header name should not be empty string!");
this.Site.Assert.IsTrue(ignoredHttpHeaderValue != string.Empty, "In CompareHttpResponses_Put method, the ignored header value should not be empty string!");
WDVMODUUResponse responseForPutRequestWithIgnoredHeader = null;
WDVMODUUResponse responseForPutRequestWithoutIgnoredHeader = null;
WDVMODUUResponse responseForDeleteRequestWithIgnoredHeader = null;
WDVMODUUResponse responseForDeleteRequestWithoutIgnoredHeader = null;
NameValueCollection headersCollectionWithIgnoredHeader = this.GetHttpHeadersCollection(ignoredHttpHeaderName, ignoredHttpHeaderValue);
NameValueCollection headersCollectionWithoutIgnoredHeader = this.GetHttpHeadersCollection(null, null);
// Call HTTP PUT method without ignored header.
responseForPutRequestWithoutIgnoredHeader = this.Adapter.Put(requestUri, bytesTxtFile, headersCollectionWithoutIgnoredHeader);
this.ArrayListForDeleteFile.Add(requestUri);
// Call HTTP DELETE method without ignored header.
responseForDeleteRequestWithoutIgnoredHeader = this.Adapter.Delete(requestUri, headersCollectionWithoutIgnoredHeader);
this.RemoveFileUriFromDeleteList(requestUri);
// Call HTTP PUT method with ignored header.
responseForPutRequestWithIgnoredHeader = this.Adapter.Put(requestUri, bytesTxtFile, headersCollectionWithIgnoredHeader);
this.ArrayListForDeleteFile.Add(requestUri);
// Call HTTP DELETE method with ignored header.
responseForDeleteRequestWithIgnoredHeader = this.Adapter.Delete(requestUri, headersCollectionWithIgnoredHeader);
this.RemoveFileUriFromDeleteList(requestUri);
string errorLog = string.Empty;
this.Site.Log.Add(TestTools.LogEntryKind.Comment, "The ignored header is {0}. The ignored header value is {1}.", ignoredHttpHeaderName, ignoredHttpHeaderValue);
#region Compare the two responses of HTTP PUT method
this.Site.Log.Add(TestTools.LogEntryKind.Comment, "Compare the two responses of HTTP PUT method.");
// Compare status code values in the two response.
bool isSameStatusCode_Put = false;
if (responseForPutRequestWithIgnoredHeader.StatusCode == responseForPutRequestWithoutIgnoredHeader.StatusCode)
{
isSameStatusCode_Put = true;
}
else
{
isSameStatusCode_Put = false;
errorLog = "Test Failed: The status codes in two response are not same! \r\n";
errorLog += string.Format("responseForPutRequestWithIgnoredHeader.StatusCode={0}\r\n", (int)responseForPutRequestWithIgnoredHeader.StatusCode);
errorLog += string.Format("responseForPutRequestWithoutIgnoredHeader.StatusCode={0}\r\n", (int)responseForPutRequestWithoutIgnoredHeader.StatusCode);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
// Compare status description values in the two response.
bool isSameStatusDescription_Put = false;
if (string.Compare(responseForPutRequestWithIgnoredHeader.StatusDescription, responseForPutRequestWithoutIgnoredHeader.StatusDescription, true) == 0)
{
isSameStatusDescription_Put = true;
}
else
{
isSameStatusDescription_Put = false;
errorLog = "Test Failed: The status description in two response are not same! \r\n";
errorLog += string.Format("responseForPutRequestWithIgnoredHeader.StatusDescription={0}\r\n", responseForPutRequestWithIgnoredHeader.StatusDescription);
errorLog += string.Format("responseForPutRequestWithoutIgnoredHeader.StatusDescription={0}\r\n", responseForPutRequestWithoutIgnoredHeader.StatusDescription);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
// Judge if the two response for PUT methods are same.
bool isSameResponse_Put = false;
if (isSameStatusCode_Put && isSameStatusDescription_Put)
{
isSameResponse_Put = true;
}
#endregion Compare the two responses of HTTP PUT method
#region Compare the two responses of HTTP DELETE method
this.Site.Log.Add(TestTools.LogEntryKind.Comment, "Compare the two responses of HTTP DELETE method.");
// Compare status code values in the two response.
bool isSameStatusCode_Delete = false;
if (responseForDeleteRequestWithIgnoredHeader.StatusCode == responseForDeleteRequestWithoutIgnoredHeader.StatusCode)
{
isSameStatusCode_Delete = true;
}
else
{
isSameStatusCode_Delete = false;
errorLog = "Test Failed: The status codes in two response are not same! \r\n";
errorLog += string.Format("responseForDeleteRequestWithIgnoredHeader.StatusCode={0}\r\n", (int)responseForDeleteRequestWithIgnoredHeader.StatusCode);
errorLog += string.Format("responseForDeleteRequestWithoutIgnoredHeader.StatusCode={0}\r\n", (int)responseForDeleteRequestWithoutIgnoredHeader.StatusCode);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
// Compare status description values in the two response.
bool isSameStatusDescription_Delete = false;
if (string.Compare(responseForDeleteRequestWithIgnoredHeader.StatusDescription, responseForDeleteRequestWithoutIgnoredHeader.StatusDescription, true) == 0)
{
isSameStatusDescription_Delete = true;
}
else
{
isSameStatusDescription_Delete = false;
errorLog = "Test Failed: The status description in two response are not same! \r\n";
errorLog += string.Format("responseForDeleteRequestWithIgnoredHeader.StatusDescription={0}\r\n", responseForDeleteRequestWithIgnoredHeader.StatusDescription);
errorLog += string.Format("responseForDeleteRequestWithoutIgnoredHeader.StatusDescription={0}\r\n", responseForDeleteRequestWithoutIgnoredHeader.StatusDescription);
this.Site.Log.Add(TestTools.LogEntryKind.TestFailed, errorLog);
}
// Judge if the two response for PUT methods are same.
bool isSameResponse_Delete = false;
if (isSameStatusCode_Delete && isSameStatusDescription_Delete)
{
isSameResponse_Delete = true;
}
#endregion Compare the two responses of HTTP DELETE method
// Judge if the responses in PUT and DELETE methods are same.
bool isSameResponse = false;
if (isSameResponse_Put && isSameResponse_Delete)
{
isSameResponse = true;
}
return isSameResponse;
}
#endregion Help methods in Scenario 02
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using Validation;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable stack.
/// </summary>
/// <typeparam name="T">The type of element stored by the stack.</typeparam>
[DebuggerDisplay("IsEmpty = {IsEmpty}; Top = {head}")]
[DebuggerTypeProxy(typeof(ImmutableStackDebuggerProxy<>))]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Ignored")]
public sealed class ImmutableStack<T> : IImmutableStack<T>
{
/// <summary>
/// The singleton empty stack.
/// </summary>
/// <remarks>
/// Additional instances representing the empty stack may exist on deserialized stacks.
/// </remarks>
private static readonly ImmutableStack<T> EmptyField = new ImmutableStack<T>();
/// <summary>
/// The element on the top of the stack.
/// </summary>
private readonly T head;
/// <summary>
/// A stack that contains the rest of the elements (under the top element).
/// </summary>
private readonly ImmutableStack<T> tail;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableStack<T>"/> class
/// that acts as the empty stack.
/// </summary>
private ImmutableStack()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableStack<T>"/> class.
/// </summary>
/// <param name="head">The head element on the stack.</param>
/// <param name="tail">The rest of the elements on the stack.</param>
private ImmutableStack(T head, ImmutableStack<T> tail)
{
Requires.NotNull(tail, "tail");
this.head = head;
this.tail = tail;
}
/// <summary>
/// Gets the empty stack, upon which all stacks are built.
/// </summary>
public static ImmutableStack<T> Empty
{
get
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty);
Contract.Assume(EmptyField.IsEmpty);
return EmptyField;
}
}
/// <summary>
/// Gets the empty stack, upon which all stacks are built.
/// </summary>
public ImmutableStack<T> Clear()
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty);
Contract.Assume(EmptyField.IsEmpty);
return Empty;
}
/// <summary>
/// Gets an empty stack.
/// </summary>
IImmutableStack<T> IImmutableStack<T>.Clear()
{
return this.Clear();
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get { return this.tail == null; }
}
/// <summary>
/// Gets the element on the top of the stack.
/// </summary>
/// <returns>
/// The element on the top of the stack.
/// </returns>
/// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception>
[Pure]
public T Peek()
{
if (this.IsEmpty)
{
throw new InvalidOperationException(Strings.InvalidEmptyOperation);
}
return this.head;
}
/// <summary>
/// Pushes an element onto a stack and returns the new stack.
/// </summary>
/// <param name="value">The element to push onto the stack.</param>
/// <returns>The new stack.</returns>
[Pure]
public ImmutableStack<T> Push(T value)
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
Contract.Ensures(!Contract.Result<ImmutableStack<T>>().IsEmpty);
return new ImmutableStack<T>(value, this);
}
/// <summary>
/// Pushes an element onto a stack and returns the new stack.
/// </summary>
/// <param name="value">The element to push onto the stack.</param>
/// <returns>The new stack.</returns>
[Pure]
IImmutableStack<T> IImmutableStack<T>.Push(T value)
{
return this.Push(value);
}
/// <summary>
/// Returns a stack that lacks the top element on this stack.
/// </summary>
/// <returns>A stack; never <c>null</c></returns>
/// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception>
[Pure]
public ImmutableStack<T> Pop()
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
if (this.IsEmpty)
{
throw new InvalidOperationException(Strings.InvalidEmptyOperation);
}
return this.tail;
}
/// <summary>
/// Pops the top element off the stack.
/// </summary>
/// <param name="value">The value that was removed from the stack.</param>
/// <returns>
/// A stack; never <c>null</c>
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")]
[Pure]
public ImmutableStack<T> Pop(out T value)
{
value = this.Peek();
return this.Pop();
}
/// <summary>
/// Returns a stack that lacks the top element on this stack.
/// </summary>
/// <returns>A stack; never <c>null</c></returns>
/// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception>
[Pure]
IImmutableStack<T> IImmutableStack<T>.Pop()
{
return this.Pop();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An <see cref="T:Enumerator"/> that can be used to iterate through the collection.
/// </returns>
[Pure]
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
[Pure]
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new EnumeratorObject(this);
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
[Pure]
IEnumerator IEnumerable.GetEnumerator()
{
return new EnumeratorObject(this);
}
/// <summary>
/// Reverses the order of a stack.
/// </summary>
/// <returns>The reversed stack.</returns>
[Pure]
internal ImmutableStack<T> Reverse()
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty == this.IsEmpty);
var r = this.Clear();
for (ImmutableStack<T> f = this; !f.IsEmpty; f = f.Pop())
{
r = r.Push(f.Peek());
}
return r;
}
/// <summary>
/// Enumerates a stack with no memory allocations.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public struct Enumerator
{
/// <summary>
/// The original stack being enumerated.
/// </summary>
private readonly ImmutableStack<T> originalStack;
/// <summary>
/// The remaining stack not yet enumerated.
/// </summary>
private ImmutableStack<T> remainingStack;
/// <summary>
/// Initializes a new instance of the <see cref="Enumerator"/> struct.
/// </summary>
/// <param name="stack">The stack to enumerator.</param>
internal Enumerator(ImmutableStack<T> stack)
{
Requires.NotNull(stack, "stack");
this.originalStack = stack;
this.remainingStack = null;
}
/// <summary>
/// Gets the current element.
/// </summary>
public T Current
{
get
{
if (this.remainingStack == null || this.remainingStack.IsEmpty)
{
throw new InvalidOperationException();
}
else
{
return this.remainingStack.Peek();
}
}
}
/// <summary>
/// Moves to the first or next element.
/// </summary>
/// <returns>A value indicating whether there are any more elements.</returns>
public bool MoveNext()
{
if (this.remainingStack == null)
{
// initial move
this.remainingStack = this.originalStack;
}
else if (!this.remainingStack.IsEmpty)
{
this.remainingStack = this.remainingStack.Pop();
}
return !this.remainingStack.IsEmpty;
}
}
/// <summary>
/// Enumerates a stack with no memory allocations.
/// </summary>
private class EnumeratorObject : IEnumerator<T>
{
/// <summary>
/// The original stack being enumerated.
/// </summary>
private readonly ImmutableStack<T> originalStack;
/// <summary>
/// The remaining stack not yet enumerated.
/// </summary>
private ImmutableStack<T> remainingStack;
/// <summary>
/// A flag indicating whether this enumerator has been disposed.
/// </summary>
private bool disposed;
/// <summary>
/// Initializes a new instance of the <see cref="EnumeratorObject"/> class.
/// </summary>
/// <param name="stack">The stack to enumerator.</param>
internal EnumeratorObject(ImmutableStack<T> stack)
{
Requires.NotNull(stack, "stack");
this.originalStack = stack;
}
/// <summary>
/// Gets the current element.
/// </summary>
public T Current
{
get
{
this.ThrowIfDisposed();
if (this.remainingStack == null || this.remainingStack.IsEmpty)
{
throw new InvalidOperationException();
}
else
{
return this.remainingStack.Peek();
}
}
}
/// <summary>
/// Gets the current element.
/// </summary>
object IEnumerator.Current
{
get { return this.Current; }
}
/// <summary>
/// Moves to the first or next element.
/// </summary>
/// <returns>A value indicating whether there are any more elements.</returns>
public bool MoveNext()
{
this.ThrowIfDisposed();
if (this.remainingStack == null)
{
// initial move
this.remainingStack = this.originalStack;
}
else if (!this.remainingStack.IsEmpty)
{
this.remainingStack = this.remainingStack.Pop();
}
return !this.remainingStack.IsEmpty;
}
/// <summary>
/// Resets the position to just before the first element in the list.
/// </summary>
public void Reset()
{
this.ThrowIfDisposed();
this.remainingStack = null;
}
/// <summary>
/// Disposes this instance.
/// </summary>
public void Dispose()
{
this.disposed = true;
}
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if this
/// enumerator has already been disposed.
/// </summary>
private void ThrowIfDisposed()
{
if (this.disposed)
{
Validation.Requires.FailObjectDisposed(this);
}
}
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
[ExcludeFromCodeCoverage]
internal class ImmutableStackDebuggerProxy<T>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableStack<T> stack;
/// <summary>
/// The simple view of the collection.
/// </summary>
private T[] contents;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableStackDebuggerProxy<T>"/> class.
/// </summary>
/// <param name="stack">The collection to display in the debugger</param>
public ImmutableStackDebuggerProxy(ImmutableStack<T> stack)
{
Requires.NotNull(stack, "stack");
this.stack = stack;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] Contents
{
get
{
if (this.contents == null)
{
this.contents = this.stack.ToArray();
}
return this.contents;
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="LeftCellWrapper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common.Utils;
using System.Text;
using System.Linq;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Data.Metadata.Edm;
using System.Data.Common.Utils.Boolean;
using System.Data.Mapping.ViewGeneration.Validation;
using System.Data.Mapping.ViewGeneration.QueryRewriting;
namespace System.Data.Mapping.ViewGeneration.Structures
{
// This class essentially stores a cell but in a special form. When we
// are generating a view for an extent, we denote the extent's side (C or
// S) as the "left side" and the side being used in the view as the right
// side. For example, in query views, the C side is the left side.
//
// Each LeftCellWrapper is a cell of the form:
// Project[A1,...,An] (Select[var IN {domain}] (Extent)) = Expr
// Where
// - "domain" is a set of multiconstants that correspond to the different
// variable values allowed for the cell query
// - A1 ... An are denoted by Attributes in this and corresponds to
// the list of attributes that are projected
// - Extent is the extent for which th view is being generated
// - Expr is the expression on the other side to produce the left side of
// the cell
internal class LeftCellWrapper : InternalBase
{
#region Fields
internal static readonly IEqualityComparer<LeftCellWrapper> BoolEqualityComparer = new BoolWrapperComparer();
private Set<MemberPath> m_attributes;// project: attributes computed by
// Expr (projected attributes that get set)
private MemberMaps m_memberMaps;
private CellQuery m_leftCellQuery; // expression that computes this portion
private CellQuery m_rightCellQuery; // expression that computes this portion
private HashSet<Cell> m_mergedCells; // Cells that this LeftCellWrapper (MergedCell) wraps.
// At first it starts off with a single cell and during cell merging
// cells from both LeftCellWrappers are concatenated.
private ViewTarget m_viewTarget;
private FragmentQuery m_leftFragmentQuery; // Fragment query corresponding to the left cell query of the cell
internal static readonly IComparer<LeftCellWrapper> Comparer = new LeftCellWrapperComparer();
internal static readonly IComparer<LeftCellWrapper> OriginalCellIdComparer = new CellIdComparer();
#endregion
#region Constructor
// effects: Creates a LeftCellWrapper of the form:
// Project[attrs] (Select[var IN {domain}] (Extent)) = cellquery
// memberMaps is the set of maps used for producing the query or update views
internal LeftCellWrapper(ViewTarget viewTarget, Set<MemberPath> attrs,
FragmentQuery fragmentQuery,
CellQuery leftCellQuery, CellQuery rightCellQuery, MemberMaps memberMaps, IEnumerable<Cell> inputCells)
{
m_leftFragmentQuery = fragmentQuery;
m_rightCellQuery = rightCellQuery;
m_leftCellQuery = leftCellQuery;
m_attributes = attrs;
m_viewTarget = viewTarget;
m_memberMaps = memberMaps;
m_mergedCells = new HashSet<Cell>(inputCells);
}
internal LeftCellWrapper(ViewTarget viewTarget, Set<MemberPath> attrs,
FragmentQuery fragmentQuery,
CellQuery leftCellQuery, CellQuery rightCellQuery, MemberMaps memberMaps, Cell inputCell)
: this(viewTarget, attrs, fragmentQuery, leftCellQuery, rightCellQuery, memberMaps, Enumerable.Repeat(inputCell, 1)) { }
#endregion
#region Properties
internal FragmentQuery FragmentQuery
{
get { return m_leftFragmentQuery; }
}
// effects: Returns the projected fields on the left side
internal Set<MemberPath> Attributes
{
get { return m_attributes; }
}
// effects: Returns the original cell number from which the wrapper came
internal string OriginalCellNumberString
{
get
{
return StringUtil.ToSeparatedString(m_mergedCells.Select(cell => cell.CellNumberAsString), "+", "");
}
}
// effects: Returns the right domain map associated with the right query
internal MemberDomainMap RightDomainMap
{
get { return m_memberMaps.RightDomainMap; }
}
[Conditional("DEBUG")]
internal void AssertHasUniqueCell()
{
Debug.Assert(m_mergedCells.Count == 1);
}
internal IEnumerable<Cell> Cells
{
get { return m_mergedCells; }
}
// requires: There is only one input cell in this
// effects: Returns the input cell provided to view generation as part of the mapping
internal Cell OnlyInputCell
{
get
{
AssertHasUniqueCell();
return m_mergedCells.First();
}
}
// effects: Returns the right CellQuery
internal CellQuery RightCellQuery
{
get { return m_rightCellQuery; }
}
internal CellQuery LeftCellQuery
{
get { return m_leftCellQuery; }
}
// effects: Returns the extent for which the wrapper was built
internal EntitySetBase LeftExtent
{
get
{
return m_mergedCells.First().GetLeftQuery(m_viewTarget).Extent;
}
}
// effects: Returns the extent of the right cellquery
internal EntitySetBase RightExtent
{
get
{
EntitySetBase result = m_rightCellQuery.Extent;
Debug.Assert(result != null, "Bad root value in join tree");
return result;
}
}
#endregion
#region Methods
// effects: Yields the input cells in wrappers
internal static IEnumerable<Cell> GetInputCellsForWrappers(IEnumerable<LeftCellWrapper> wrappers)
{
foreach (LeftCellWrapper wrapper in wrappers)
{
foreach (Cell cell in wrapper.m_mergedCells)
{
yield return cell;
}
}
}
// effects: Creates a boolean variable representing the right extent or association end
internal RoleBoolean CreateRoleBoolean()
{
if (RightExtent is AssociationSet)
{
Set<AssociationEndMember> ends = GetEndsForTablePrimaryKey();
if (ends.Count == 1)
{
AssociationSetEnd setEnd = ((AssociationSet)RightExtent).AssociationSetEnds[ends.First().Name];
return new RoleBoolean(setEnd);
}
}
return new RoleBoolean(RightExtent);
}
// effects: Given a set of wrappers, returns a string that contains the list of extents in the
// rightcellQueries of the wrappers
internal static string GetExtentListAsUserString(IEnumerable<LeftCellWrapper> wrappers)
{
Set<EntitySetBase> extents = new Set<EntitySetBase>(EqualityComparer<EntitySetBase>.Default);
foreach (LeftCellWrapper wrapper in wrappers)
{
extents.Add(wrapper.RightExtent);
}
StringBuilder builder = new StringBuilder();
bool isFirst = true;
foreach (EntitySetBase extent in extents)
{
if (isFirst == false)
{
builder.Append(", ");
}
isFirst = false;
builder.Append(extent.Name);
}
return builder.ToString();
}
internal override void ToFullString(StringBuilder builder)
{
builder.Append("P[");
StringUtil.ToSeparatedString(builder, m_attributes, ",");
builder.Append("] = ");
m_rightCellQuery.ToFullString(builder);
}
// effects: Modifies stringBuilder to contain the view corresponding
// to the right cellquery
internal override void ToCompactString(StringBuilder stringBuilder)
{
stringBuilder.Append(OriginalCellNumberString);
}
// effects: Writes m_cellWrappers to builder
internal static void WrappersToStringBuilder(StringBuilder builder, List<LeftCellWrapper> wrappers,
string header)
{
builder.AppendLine()
.Append(header)
.AppendLine();
// Sort them according to the original cell number
LeftCellWrapper[] cellWrappers = wrappers.ToArray();
Array.Sort(cellWrappers, LeftCellWrapper.OriginalCellIdComparer);
foreach (LeftCellWrapper wrapper in cellWrappers)
{
wrapper.ToCompactString(builder);
builder.Append(" = ");
wrapper.ToFullString(builder);
builder.AppendLine();
}
}
// requires: RightCellQuery.Extent corresponds to a relationship set
// effects: Returns the ends to which the key of the corresponding
// table (i.e., the left query) maps to in the relationship set. For
// example, if RightCellQuery.Extent is OrderOrders and it maps to
// <oid, otherOid> of table SOrders with key oid, this returns the
// end to which oid is mapped. Similarly, if we have a link table
// with the whole key mapped to two ends of the association set, it
// returns both ends
private Set<AssociationEndMember> GetEndsForTablePrimaryKey()
{
CellQuery rightQuery = RightCellQuery;
Set<AssociationEndMember> result = new Set<AssociationEndMember>(EqualityComparer<AssociationEndMember>.Default);
// Get the key slots for the table (they are in the slotMap) and
// check for that slot on the C-side
foreach (int keySlot in m_memberMaps.ProjectedSlotMap.KeySlots)
{
MemberProjectedSlot slot = (MemberProjectedSlot)rightQuery.ProjectedSlotAt(keySlot);
MemberPath path = slot.MemberPath;
// See what end it maps to in the relationSet
AssociationEndMember endMember = (AssociationEndMember)path.RootEdmMember;
Debug.Assert(endMember != null, "Element in path before scalar path is not end property?");
result.Add(endMember);
}
Debug.Assert(result != null, "No end found for keyslots of table?");
return result;
}
internal MemberProjectedSlot GetLeftSideMappedSlotForRightSideMember(MemberPath member)
{
int projectedPosition = RightCellQuery.GetProjectedPosition(new MemberProjectedSlot(member));
if (projectedPosition == -1)
{
return null;
}
ProjectedSlot slot = LeftCellQuery.ProjectedSlotAt(projectedPosition);
if (slot == null || slot is ConstantProjectedSlot)
{
return null;
}
return slot as MemberProjectedSlot;
}
internal MemberProjectedSlot GetRightSideMappedSlotForLeftSideMember(MemberPath member)
{
int projectedPosition = LeftCellQuery.GetProjectedPosition(new MemberProjectedSlot(member));
if (projectedPosition == -1)
{
return null;
}
ProjectedSlot slot = RightCellQuery.ProjectedSlotAt(projectedPosition);
if (slot == null || slot is ConstantProjectedSlot)
{
return null;
}
return slot as MemberProjectedSlot;
}
internal MemberProjectedSlot GetCSideMappedSlotForSMember(MemberPath member)
{
if (m_viewTarget == ViewTarget.QueryView)
{
return GetLeftSideMappedSlotForRightSideMember(member);
}
else
{
return GetRightSideMappedSlotForLeftSideMember(member);
}
}
#endregion
#region Equality Comparer class
// This class compares wrappers based on the Right Where Clause and
// Extent -- needed for the boolean engine
private class BoolWrapperComparer : IEqualityComparer<LeftCellWrapper>
{
public bool Equals(LeftCellWrapper left, LeftCellWrapper right)
{
// Quick check with references
if (object.ReferenceEquals(left, right))
{
// Gets the Null and Undefined case as well
return true;
}
// One of them is non-null at least
if (left == null || right == null)
{
return false;
}
// Both are non-null at this point
bool whereClauseEqual = BoolExpression.EqualityComparer.Equals(left.RightCellQuery.WhereClause,
right.RightCellQuery.WhereClause);
return left.RightExtent.Equals(right.RightExtent) && whereClauseEqual;
}
public int GetHashCode(LeftCellWrapper wrapper)
{
return BoolExpression.EqualityComparer.GetHashCode(wrapper.RightCellQuery.WhereClause) ^ wrapper.RightExtent.GetHashCode();
}
}
#endregion
#region Comparer
// A class that compares two cell wrappers. Useful for guiding heuristics
// and to ensure that the largest selection domain (i.e., the number of
// multiconstants in "mc in {...}") is first in the list
private class LeftCellWrapperComparer : IComparer<LeftCellWrapper>
{
public int Compare(LeftCellWrapper x, LeftCellWrapper y)
{
// More attributes first -- so that we get most attributes
// with very few intersections (when we use the sortings for
// that). When we are subtracting, attributes are not important
// Use FragmentQuery's attributes instead of LeftCellWrapper's original attributes in the comparison
// since the former might have got extended to include all attributes whose value is determined
// by the WHERE clause (e.g., if we have WHERE ProductName='Camera' we can assume ProductName is projected)
if (x.FragmentQuery.Attributes.Count > y.FragmentQuery.Attributes.Count)
{
return -1;
}
else if (x.FragmentQuery.Attributes.Count < y.FragmentQuery.Attributes.Count)
{
return 1;
}
// Since the sort may not be stable, we use the original cell number string to break the tie
return String.CompareOrdinal(x.OriginalCellNumberString, y.OriginalCellNumberString);
}
}
// A class that compares two cell wrappers based on original cell number
internal class CellIdComparer : IComparer<LeftCellWrapper>
{
public int Compare(LeftCellWrapper x, LeftCellWrapper y)
{
return StringComparer.Ordinal.Compare(x.OriginalCellNumberString, y.OriginalCellNumberString);
}
}
#endregion
}
}
| |
//
// System.Collections.Generic.Stack
//
// Authors:
// Martin Baulig ([email protected])
// Ben Maurer ([email protected])
//
// (C) 2003, 2004 Novell, Inc.
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
//using System.Runtime.InteropServices;
namespace System.Collections.Generic
{
public class Stack <T> : IEnumerable <T>, ICollection, IEnumerable
{
T [] _array;
int _size;
int _version;
private const int INITIAL_SIZE = 16;
public Stack ()
{
}
public Stack (int count)
{
if (count < 0)
throw new ArgumentOutOfRangeException ("count");
_array = new T [count];
}
public Stack (IEnumerable <T> collection)
{
if (collection == null)
throw new ArgumentNullException ("collection");
ICollection <T> col = collection as ICollection <T>;
if (col != null) {
_size = col.Count;
_array = new T [_size];
col.CopyTo (_array, 0);
} else {
foreach (T t in collection)
Push (t);
}
}
public void Clear ()
{
if (_array != null)
Array.Clear (_array, 0, _array.Length);
_size = 0;
_version ++;
}
public bool Contains (T t)
{
return _array != null && Array.IndexOf (_array, t, 0, _size) != -1;
}
public void CopyTo (T [] dest, int idx)
{
// this gets copied in the order that it is poped
if (_array != null) {
Array.Copy (_array, 0, dest, idx, _size);
Array.Reverse (dest, idx, _size);
}
}
public T Peek ()
{
if (_size == 0)
throw new InvalidOperationException ();
return _array [_size - 1];
}
public T Pop ()
{
if (_size == 0)
throw new InvalidOperationException ();
_version ++;
T popped = _array [--_size];
// clear stuff out to make the GC happy
_array [_size] = default(T);
return popped;
}
public void Push (T t)
{
if (_size == 0 || _size == _array.Length)
Array.Resize <T> (ref _array, _size == 0 ? INITIAL_SIZE : 2 * _size);
_version ++;
_array [_size++] = t;
}
public T [] ToArray ()
{
T [] copy = new T [_size];
CopyTo (copy, 0);
return copy;
}
public void TrimExcess ()
{
if (_array != null && (_size < _array.Length * 0.9))
Array.Resize <T> (ref _array, _size);
_version ++;
}
public int Count {
get { return _size; }
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get { return this; }
}
void ICollection.CopyTo (Array dest, int idx)
{
try {
if (_array != null) {
_array.CopyTo (dest, idx);
Array.Reverse (dest, idx, _size);
}
} catch (ArrayTypeMismatchException) {
throw new ArgumentException ();
}
}
public Enumerator GetEnumerator ()
{
return new Enumerator (this);
}
IEnumerator <T> IEnumerable<T>.GetEnumerator ()
{
return GetEnumerator ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
public struct Enumerator : IEnumerator <T>, IEnumerator, IDisposable {
const int NOT_STARTED = -2;
// this MUST be -1, because we depend on it in move next.
// we just decr the _size, so, 0 - 1 == FINISHED
const int FINISHED = -1;
Stack <T> parent;
int idx;
int _version;
internal Enumerator (Stack <T> t)
{
parent = t;
idx = NOT_STARTED;
_version = t._version;
}
public void Dispose ()
{
idx = NOT_STARTED;
}
public bool MoveNext ()
{
if (_version != parent._version)
throw new InvalidOperationException ();
if (idx == -2)
idx = parent._size;
return idx != FINISHED && -- idx != FINISHED;
}
public T Current {
get {
if (idx < 0)
throw new InvalidOperationException ();
return parent._array [idx];
}
}
void IEnumerator.Reset ()
{
if (_version != parent._version)
throw new InvalidOperationException ();
idx = NOT_STARTED;
}
object IEnumerator.Current {
get { return Current; }
}
}
}
}
| |
/*
* 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 QuantConnect.Benchmarks;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.TimeInForces;
using QuantConnect.Securities;
using QuantConnect.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using static QuantConnect.StringExtensions;
namespace QuantConnect.Brokerages
{
/// <summary>
/// Brokerage Model implementation for Samco
/// </summary>
public class SamcoBrokerageModel : DefaultBrokerageModel
{
private readonly Type[] _supportedTimeInForces =
{
typeof(GoodTilCanceledTimeInForce),
typeof(DayTimeInForce),
typeof(GoodTilDateTimeInForce)
};
private const decimal _maxLeverage = 7m;
/// <summary>
/// Initializes a new instance of the <see cref="SamcoBrokerageModel"/> class
/// </summary>
/// <param name="accountType">The type of account to be modelled, defaults to <see cref="AccountType.Margin"/></param>
public SamcoBrokerageModel(AccountType accountType = AccountType.Margin) : base(accountType)
{
}
/// <summary>
/// Returns true if the brokerage would be able to execute this order at this time assuming
/// market prices are sufficient for the fill to take place. This is used to emulate the
/// brokerage fills in backtesting and paper trading. For example some brokerages may not
/// perform executions during extended market hours. This is not intended to be checking
/// whether or not the exchange is open, that is handled in the Security.Exchange property.
/// </summary>
/// <param name="security"></param>
/// <param name="order">The order to test for execution</param>
/// <returns>True if the brokerage would be able to perform the execution, false otherwise</returns>
public override bool CanExecuteOrder(Security security, Order order)
{
// validate security type
if (security.Type != SecurityType.Equity &&
security.Type != SecurityType.Option &&
security.Type != SecurityType.Future)
{
return false;
}
// validate time in force
if (!_supportedTimeInForces.Contains(order.TimeInForce.GetType()))
{
return false;
}
return true;
}
/// <summary>
/// Returns true if the brokerage could accept this order. This takes into account order
/// type, security type, and order size limits.
/// </summary>
/// <remarks>
/// For example, a brokerage may have no connectivity at certain times, or an order
/// rate/size limit
/// </remarks>
/// <param name="security">The security being ordered</param>
/// <param name="order">The order to be processed</param>
/// <param name="message">
/// If this function returns false, a brokerage message detailing why the order may not be submitted
/// </param>
/// <returns>True if the brokerage could process the order, false otherwise</returns>
public override bool CanSubmitOrder(Security security, Order order, out BrokerageMessageEvent message)
{
message = null;
// validate security type
if (security.Type != SecurityType.Equity &&
security.Type != SecurityType.Option &&
security.Type != SecurityType.Future)
{
message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "NotSupported",
Invariant($"The {nameof(SamcoBrokerageModel)} does not support {security.Type} security type.")
);
return false;
}
// validate time in force
if (!_supportedTimeInForces.Contains(order.TimeInForce.GetType()))
{
message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "NotSupported",
Invariant($"The {nameof(SamcoBrokerageModel)} does not support {order.TimeInForce.GetType().Name} time in force.")
);
return false;
}
return true;
}
/// <summary>
/// Returns true if the brokerage would allow updating the order as specified by the request
/// </summary>
/// <param name="security">The security of the order</param>
/// <param name="order">The order to be updated</param>
/// <param name="request">The requested update to be made to the order</param>
/// <param name="message">
/// If this function returns false, a brokerage message detailing why the order may not be updated
/// </param>
/// <returns>True if the brokerage would allow updating the order, false otherwise</returns>
public override bool CanUpdateOrder(Security security, Order order, UpdateOrderRequest request, out BrokerageMessageEvent message)
{
message = null;
return true;
}
/// <summary>
/// Gets a map of the default markets to be used for each security type
/// </summary>
public override IReadOnlyDictionary<SecurityType, string> DefaultMarkets { get; } = GetDefaultMarkets();
/// <summary>
/// Gets a new buying power model for the security, returning the default model with the
/// security's configured leverage. For cash accounts, leverage = 1 is used. For margin
/// trading, max leverage = 7
/// </summary>
/// <param name="security">The security to get a buying power model for</param>
/// <returns>The buying power model for this brokerage/security</returns>
public override IBuyingPowerModel GetBuyingPowerModel(Security security)
{
return AccountType == AccountType.Cash
? (IBuyingPowerModel)new CashBuyingPowerModel()
: new SecurityMarginModel(_maxLeverage);
}
/// <summary>
/// Samco global leverage rule
/// </summary>
/// <param name="security"></param>
/// <returns></returns>
public override decimal GetLeverage(Security security)
{
if (AccountType == AccountType.Cash || security.IsInternalFeed() || security.Type == SecurityType.Base)
{
return 1m;
}
if (security.Type == SecurityType.Equity || security.Type == SecurityType.Future || security.Type == SecurityType.Option)
{
return _maxLeverage;
}
throw new ArgumentException($"Invalid security type: {security.Type}", nameof(security));
}
/// <summary>
/// Get the benchmark for this model
/// </summary>
/// <param name="securities">SecurityService to create the security with if needed</param>
/// <returns>The benchmark for this brokerage</returns>
public override IBenchmark GetBenchmark(SecurityManager securities)
{
var symbol = Symbol.Create("NIFTYBEES", SecurityType.Equity, Market.India);
return SecurityBenchmark.CreateInstance(securities, symbol);
}
/// <summary>
/// Provides Samco fee model
/// </summary>
/// <param name="security"></param>
/// <returns></returns>
public override IFeeModel GetFeeModel(Security security)
{
return new SamcoFeeModel();
}
private static IReadOnlyDictionary<SecurityType, string> GetDefaultMarkets()
{
var map = DefaultMarketMap.ToDictionary();
map[SecurityType.Equity] = Market.India;
map[SecurityType.Future] = Market.India;
map[SecurityType.Option] = Market.India;
return map.ToReadOnlyDictionary();
}
}
}
| |
using System;
using System.Linq;
using Baseline;
using Baseline.Dates;
using Weasel.Postgresql;
using Marten.Testing.Harness;
using Marten.Util;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Marten.Testing.Bugs
{
public class Bug_432_querying_with_UTC_times_with_offset: BugIntegrationContext
{
private readonly ITestOutputHelper _output;
public Bug_432_querying_with_UTC_times_with_offset(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void can_issue_queries_against_DateTime()
{
using (var session = theStore.LightweightSession())
{
var now = GenerateTestDateTime();
_output.WriteLine("now: " + now.ToString("o"));
var testClass = new DateClass
{
Id = Guid.NewGuid(),
DateTimeField = now
};
session.Store(testClass);
session.Store(new DateClass
{
DateTimeField = now.Add(5.Minutes())
});
session.Store(new DateClass
{
DateTimeField = now.Add(-5.Minutes())
});
session.SaveChanges();
var cmd = session.Query<DateClass>().Where(x => now >= x.DateTimeField)
.ToCommand();
_output.WriteLine(cmd.CommandText);
var sql = $"select {SchemaName}.mt_immutable_timestamp(d.data ->> \'DateTimeField\') as time from {SchemaName}.mt_doc_dateclass as d";
using (var reader = session.Connection.CreateCommand().Sql(sql).ExecuteReader())
{
while (reader.Read())
{
_output.WriteLine("stored: " + reader.GetDateTime(0).ToString("o"));
}
}
session.Query<DateClass>().ToList().Each(x =>
{
_output.WriteLine(x.DateTimeField.ToString("o"));
});
session.Query<DateClass>()
.Count(x => now >= x.DateTimeField).ShouldBe(2);
}
}
[Fact]
public void can_issue_queries_against_DateTime_with_camel_casing()
{
StoreOptions(_ => _.UseDefaultSerialization(casing: Casing.CamelCase));
using (var session = theStore.LightweightSession())
{
var now = GenerateTestDateTime();
_output.WriteLine("now: " + now.ToString("o"));
var testClass = new DateClass
{
Id = Guid.NewGuid(),
DateTimeField = now
};
session.Store(testClass);
session.Store(new DateClass
{
DateTimeField = now.Add(5.Minutes())
});
session.Store(new DateClass
{
DateTimeField = now.Add(-5.Minutes())
});
session.SaveChanges();
var cmd = session.Query<DateClass>().Where(x => now >= x.DateTimeField)
.ToCommand();
_output.WriteLine(cmd.CommandText);
var sql = $"select {SchemaName}.mt_immutable_timestamp(d.data ->> \'dateTimeField\') as time from {SchemaName}.mt_doc_dateclass as d";
using (var reader = session.Connection.CreateCommand().Sql(sql).ExecuteReader())
{
while (reader.Read())
{
_output.WriteLine("stored: " + reader.GetDateTime(0).ToString("o"));
}
}
session.Query<DateClass>().ToList().Each(x =>
{
_output.WriteLine(x.DateTimeField.ToString("o"));
});
session.Query<DateClass>()
.Count(x => now >= x.DateTimeField).ShouldBe(2);
}
}
[Fact]
public void can_issue_queries_against_DateTime_with_snake_casing()
{
StoreOptions(_ => _.UseDefaultSerialization(casing: Casing.SnakeCase));
using (var session = theStore.LightweightSession())
{
var now = GenerateTestDateTime();
_output.WriteLine("now: " + now.ToString("o"));
var testClass = new DateClass
{
Id = Guid.NewGuid(),
DateTimeField = now
};
session.Store(testClass);
session.Store(new DateClass
{
DateTimeField = now.Add(5.Minutes())
});
session.Store(new DateClass
{
DateTimeField = now.Add(-5.Minutes())
});
session.SaveChanges();
var cmd = session.Query<DateClass>().Where(x => now >= x.DateTimeField)
.ToCommand();
_output.WriteLine(cmd.CommandText);
var sql = $"select {SchemaName}.mt_immutable_timestamp(d.data ->> \'date_time_field\') as time from {SchemaName}.mt_doc_dateclass as d";
using (var reader = session.Connection.CreateCommand().Sql(sql).ExecuteReader())
{
while (reader.Read())
{
_output.WriteLine("stored: " + reader.GetDateTime(0).ToString("o"));
}
}
session.Query<DateClass>().ToList().Each(x =>
{
_output.WriteLine(x.DateTimeField.ToString("o"));
});
session.Query<DateClass>()
.Count(x => now >= x.DateTimeField).ShouldBe(2);
}
}
[Fact]
public void can_issue_queries_against_DateTime_as_duplicated_column()
{
StoreOptions(_ => _.Schema.For<DateClass>().Duplicate(x => x.DateTimeField));
using (var session = theStore.LightweightSession())
{
var now = GenerateTestDateTime();
_output.WriteLine("now: " + now.ToString("o"));
var testClass = new DateClass
{
Id = Guid.NewGuid(),
DateTimeField = now
};
session.Store(testClass);
session.Store(new DateClass
{
DateTimeField = now.Add(5.Minutes())
});
session.Store(new DateClass
{
DateTimeField = now.Add(-5.Minutes())
});
session.SaveChanges();
var cmd = session.Query<DateClass>().Where(x => now >= x.DateTimeField)
.ToCommand();
_output.WriteLine(cmd.CommandText);
session.Query<DateClass>().ToList().Each(x =>
{
_output.WriteLine(x.DateTimeField.ToString("o"));
});
session.Query<DateClass>()
.Count(x => now >= x.DateTimeField).ShouldBe(2);
}
}
[Fact]
public void can_issue_queries_against_the_datetime_offset()
{
using (var session = theStore.LightweightSession())
{
var now = GenerateTestDateTime();
_output.WriteLine("now: " + now.ToString("o"));
var testClass = new DateOffsetClass
{
Id = Guid.NewGuid(),
DateTimeField = now
};
session.Store(testClass);
session.Store(new DateOffsetClass
{
DateTimeField = now.Add(5.Minutes())
});
session.Store(new DateOffsetClass
{
DateTimeField = now.Add(-5.Minutes())
});
session.SaveChanges();
var cmd = session.Query<DateOffsetClass>().Where(x => now >= x.DateTimeField)
.ToCommand();
_output.WriteLine(cmd.CommandText);
session.Query<DateOffsetClass>().ToList().Each(x =>
{
_output.WriteLine(x.DateTimeField.ToString("o"));
});
session.Query<DateOffsetClass>()
.Count(x => now >= x.DateTimeField).ShouldBe(2);
}
}
[Fact]
public void can_issue_queries_against_the_datetime_offset_as_duplicate_field()
{
StoreOptions(_ => _.Schema.For<DateOffsetClass>().Duplicate(x => x.DateTimeField));
using (var session = theStore.LightweightSession())
{
var now = GenerateTestDateTime();
_output.WriteLine("now: " + now.ToString("o"));
var testClass = new DateOffsetClass
{
Id = Guid.NewGuid(),
DateTimeField = now
};
session.Store(testClass);
session.Store(new DateOffsetClass
{
DateTimeField = now.Add(5.Minutes())
});
session.Store(new DateOffsetClass
{
DateTimeField = now.Add(-5.Minutes())
});
session.SaveChanges();
var cmd = session.Query<DateOffsetClass>().Where(x => now >= x.DateTimeField)
.ToCommand();
_output.WriteLine(cmd.CommandText);
session.Query<DateOffsetClass>().ToList().Each(x =>
{
_output.WriteLine(x.DateTimeField.ToString("o"));
});
session.Query<DateOffsetClass>()
.Count(x => now >= x.DateTimeField).ShouldBe(2);
}
}
private static DateTime GenerateTestDateTime()
{
var now = DateTime.UtcNow;
return now.AddTicks(-(now.Ticks % TimeSpan.TicksPerMillisecond));
}
}
public class DateClass
{
public Guid Id { get; set; }
public DateTime DateTimeField { get; set; }
}
public class DateOffsetClass
{
public Guid Id { get; set; }
public DateTimeOffset DateTimeField { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Html;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
/// <summary>
/// Label-related extensions for <see cref="IHtmlHelper"/> and <see cref="IHtmlHelper{TModel}"/>.
/// </summary>
public static class HtmlHelperLabelExtensions
{
/// <summary>
/// Returns a <label> element for the specified <paramref name="expression"/>.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="expression">Expression name, relative to the current model.</param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <label> element.</returns>
public static IHtmlContent Label(this IHtmlHelper htmlHelper, string expression)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.Label(expression, labelText: null, htmlAttributes: null);
}
/// <summary>
/// Returns a <label> element for the specified <paramref name="expression"/>.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="expression">Expression name, relative to the current model.</param>
/// <param name="labelText">The inner text of the element.</param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <label> element.</returns>
public static IHtmlContent Label(this IHtmlHelper htmlHelper, string expression, string labelText)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.Label(expression, labelText, htmlAttributes: null);
}
/// <summary>
/// Returns a <label> element for the specified <paramref name="expression"/>.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper{TModel}"/> instance this method extends.</param>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <label> element.</returns>
public static IHtmlContent LabelFor<TModel, TResult>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
return htmlHelper.LabelFor(expression, labelText: null, htmlAttributes: null);
}
/// <summary>
/// Returns a <label> element for the specified <paramref name="expression"/>.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper{TModel}"/> instance this method extends.</param>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="labelText">The inner text of the element.</param>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <label> element.</returns>
public static IHtmlContent LabelFor<TModel, TResult>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
string labelText)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
return htmlHelper.LabelFor<TResult>(expression, labelText, htmlAttributes: null);
}
/// <summary>
/// Returns a <label> element for the specified <paramref name="expression"/>.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper{TModel}"/> instance this method extends.</param>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an
/// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the HTML
/// attributes.
/// </param>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <label> element.</returns>
public static IHtmlContent LabelFor<TModel, TResult>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
object htmlAttributes)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
return htmlHelper.LabelFor<TResult>(expression, labelText: null, htmlAttributes: htmlAttributes);
}
/// <summary>
/// Returns a <label> element for the current model.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <label> element.</returns>
public static IHtmlContent LabelForModel(this IHtmlHelper htmlHelper)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.Label(expression: null, labelText: null, htmlAttributes: null);
}
/// <summary>
/// Returns a <label> element for the current model.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="labelText">The inner text of the element.</param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <label> element.</returns>
public static IHtmlContent LabelForModel(this IHtmlHelper htmlHelper, string labelText)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.Label(expression: null, labelText: labelText, htmlAttributes: null);
}
/// <summary>
/// Returns a <label> element for the current model.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an
/// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the HTML
/// attributes.
/// </param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <label> element.</returns>
public static IHtmlContent LabelForModel(this IHtmlHelper htmlHelper, object htmlAttributes)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.Label(expression: null, labelText: null, htmlAttributes: htmlAttributes);
}
/// <summary>
/// Returns a <label> element for the current model.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="labelText">The inner text of the element.</param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an
/// <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance containing the HTML
/// attributes.
/// </param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <label> element.</returns>
public static IHtmlContent LabelForModel(
this IHtmlHelper htmlHelper,
string labelText,
object htmlAttributes)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.Label(expression: null, labelText: labelText, htmlAttributes: htmlAttributes);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Task.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.AI.BehaviorTrees.Implementations
{
using System;
using System.Collections.Generic;
using Slash.AI.BehaviorTrees.Enums;
using Slash.AI.BehaviorTrees.Interfaces;
using Slash.AI.BehaviorTrees.Tree;
/// <summary>
/// Base class for tasks to have no need to implement empty methods in classes which implement the ITask interface.
/// </summary>
[Serializable]
public class Task : ITask
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="Task" /> class. Constructor.
/// </summary>
public Task()
{
this.Name = string.Empty;
}
#endregion
#region Public Events
/// <summary>
/// Called when decider finished successful.
/// </summary>
public event OnSuccess OnSuccess;
#endregion
#region Public Properties
/// <summary>
/// Debug name.
/// </summary>
public string Name { get; set; }
#endregion
#region Public Methods and Operators
/// <summary>
/// Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions.
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <param name="decisionData"> Decision data to use in activate method. </param>
/// <returns> Execution status after activation. </returns>
public virtual ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData)
{
return ExecutionStatus.Running;
}
/// <summary>
/// Deactivation.
/// </summary>
/// <param name="agentData"> Agent data. </param>
public virtual void Deactivate(IAgentData agentData)
{
}
/// <summary>
/// Depending on the group policy of its parent, the floating point return value indicates whether the decider will be activated.
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <param name="decisionData"> Decision data to use in activate method. </param>
/// <returns> Floating point value used to decide if the decider will be activated. </returns>
public virtual float Decide(IAgentData agentData, ref IDecisionData decisionData)
{
return 1.0f;
}
/// <summary>
/// The equals.
/// </summary>
/// <param name="other"> The other. </param>
/// <returns> The System.Boolean. </returns>
public bool Equals(Task other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Equals(other.Name, this.Name);
}
/// <summary>
/// The equals.
/// </summary>
/// <param name="obj"> The obj. </param>
/// <returns> The System.Boolean. </returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(Task))
{
return false;
}
return this.Equals((Task)obj);
}
/// <summary>
/// Searches for tasks which forfill the passed predicate.
/// </summary>
/// <param name="taskNode"> Task node of this task. </param>
/// <param name="predicate"> Predicate to forfill. </param>
/// <param name="tasks"> List of tasks which forfill the passed predicate. </param>
public virtual void FindTasks(TaskNode taskNode, Func<ITask, bool> predicate, ref ICollection<TaskNode> tasks)
{
}
/// <summary>
/// Generates a collection of active task nodes under this task. Used for debugging only.
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <param name="taskNode"> Task node of this task. </param>
/// <param name="activeTasks"> Collection of active task nodes. </param>
public virtual void GetActiveTasks(
IAgentData agentData, TaskNode taskNode, ref ICollection<TaskNode> activeTasks)
{
}
/// <summary>
/// The get hash code.
/// </summary>
/// <returns> The System.Int32. </returns>
public override int GetHashCode()
{
return this.Name != null ? this.Name.GetHashCode() : 0;
}
/// <summary>
/// Per frame update.
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <returns> Execution status after this update. </returns>
public virtual ExecutionStatus Update(IAgentData agentData)
{
return ExecutionStatus.Running;
}
#endregion
#region Methods
/// <summary>
/// Invoke callback when decider finished successful.
/// </summary>
protected void InvokeOnSuccess()
{
OnSuccess handler = this.OnSuccess;
if (handler != null)
{
handler();
}
}
#endregion
}
/// <summary>
/// Base class for tasks to have no need to implement empty methods in classes which implement the ITask interface.
/// </summary>
/// <typeparam name="TTaskData"> </typeparam>
[Serializable]
public class BaseTask<TTaskData> : Task
where TTaskData : ITaskData, new()
{
#region Public Methods and Operators
/// <summary>
/// Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions.
/// </summary>
/// <param name="agentData"> Agent data. </param>
/// <param name="decisionData"> Decision data to use in activate method. </param>
/// <returns> Execution status after activation. </returns>
public override ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData)
{
agentData.CurrentTaskData = new TTaskData();
return ExecutionStatus.Running;
}
/// <summary>
/// Deactivation.
/// </summary>
/// <param name="agentData"> Agent data. </param>
public override void Deactivate(IAgentData agentData)
{
agentData.CurrentTaskData = null;
}
/// <summary>
/// The equals.
/// </summary>
/// <param name="other"> The other. </param>
/// <returns> The System.Boolean. </returns>
public bool Equals(BaseTask<TTaskData> other)
{
return base.Equals(other);
}
/// <summary>
/// The equals.
/// </summary>
/// <param name="obj"> The obj. </param>
/// <returns> The System.Boolean. </returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
return this.Equals(obj as BaseTask<TTaskData>);
}
/// <summary>
/// The get hash code.
/// </summary>
/// <returns> The System.Int32. </returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
}
}
| |
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using java.lang;
using java.util;
namespace stab.reflection {
public class SignatureParser {
private String signature;
private int position;
private int current;
public SignatureParser(String signature) {
this.signature = signature;
this.position = -1;
advance();
}
public ClassSignature parseClassSignature() {
var result = new ClassSignature();
if (current == '<') {
result.formalTypeParameters = parseFormalTypeParameters();
} else {
result.formalTypeParameters = Collections.emptyList<TypeSignature>();
}
result.superclass = parseClassTypeSignature();
var superinterfaces = new ArrayList<TypeSignature>();
result.superinterfaces = superinterfaces;
while (current != -1) {
superinterfaces.add(parseClassTypeSignature());
}
return result;
}
public TypeSignature parseFieldTypeSignature() {
switch (current) {
case 'T':
return parseTypeVariableSignature();
case 'L':
return parseClassTypeSignature();
case '[':
return parseArrayTypeSignature();
default:
throw new IllegalStateException(signature);
}
}
public final MethodTypeSignature parseMethodTypeSignature() {
var result = new MethodTypeSignature();
if (current == '<') {
result.formalTypeParameters = parseFormalTypeParameters();
} else {
result.formalTypeParameters = Collections.emptyList<TypeSignature>();
}
if (current != '(') {
throw new IllegalStateException();
}
advance();
var parameters = new ArrayList<TypeSignature>();
result.parameters = parameters;
while (current != ')') {
parameters.add(parseTypeSignature());
}
advance();
if (current == 'V') {
result.returnType = PrimitiveTypeSignature.VoidSignature;
advance();
} else {
result.returnType = parseTypeSignature();
}
var exceptions = new ArrayList<TypeSignature>();
result.exceptions = exceptions;
while (current != -1) {
if (current != '^') {
throw new IllegalStateException();
}
advance();
if (current == 'T') {
exceptions.add(parseTypeVariableSignature());
} else {
exceptions.add(parseClassTypeSignature());
}
}
return result;
}
private TypeSignature parseTypeSignature() {
switch (current) {
case 'B':
advance();
return PrimitiveTypeSignature.ByteSignature;
case 'C':
advance();
return PrimitiveTypeSignature.CharSignature;
case 'F':
advance();
return PrimitiveTypeSignature.FloatSignature;
case 'D':
advance();
return PrimitiveTypeSignature.DoubleSignature;
case 'I':
advance();
return PrimitiveTypeSignature.IntSignature;
case 'J':
advance();
return PrimitiveTypeSignature.LongSignature;
case 'S':
advance();
return PrimitiveTypeSignature.ShortSignature;
case 'Z':
advance();
return PrimitiveTypeSignature.BooleanSignature;
default:
return parseFieldTypeSignature();
}
}
private TypeSignature parseTypeVariableSignature() {
if (current != 'T') {
throw new IllegalStateException();
}
advance();
int pos = position;
for (;;) {
switch (current) {
case ';':
advance();
return new TypeVariableSignature(signature.substring(pos, position - 1));
default:
advance();
break;
case -1:
throw new IllegalStateException();
}
}
}
private TypeSignature parseArrayTypeSignature() {
if (current != '[') {
throw new IllegalStateException();
}
advance();
return new ArrayTypeSignature(parseTypeSignature());
}
private TypeSignature parseClassTypeSignature() {
if (current != 'L') {
throw new IllegalStateException();
}
advance();
int pos = position;
ClassTypeSignature outerType = null;
for (;;) {
switch (current) {
case '.':
case '<':
if (outerType == null) {
outerType = new ClassTypeSignature(TypeSignatureKind.ClassType, "L" + signature.substring(pos, position) + ";");
} else {
var outerName = outerType.getName().substring(1, outerType.getName().length() - 1);
outerType = new ClassTypeSignature(TypeSignatureKind.ClassType,
"L" + outerName + "$" + signature.substring(pos, position) + ";");
}
if (current == '.') {
advance();
} else {
parseTypeArguments(outerType);
if (current == '.') {
advance();
}
}
pos = position;
break;
default:
advance();
break;
case ';':
if (outerType == null) {
outerType = new ClassTypeSignature(TypeSignatureKind.ClassType, "L" + signature.substring(pos, position) + ";");
}
advance();
return outerType;
case -1:
throw new IllegalStateException();
}
}
}
private void parseTypeArguments(ClassTypeSignature genericTypeDeclaration) {
if (current != '<') {
throw new IllegalStateException();
}
advance();
var typeArguments = genericTypeDeclaration.typeArguments;
for (;;) {
switch (current) {
case '*':
advance();
typeArguments.add(new WildcardTypeSignature(TypeSignatureKind.UnboundedWildcardType, null));
break;
case '+':
advance();
typeArguments.add(new WildcardTypeSignature(TypeSignatureKind.UpperBoundedWildcardType, parseFieldTypeSignature()));
break;
case '-':
advance();
typeArguments.add(new WildcardTypeSignature(TypeSignatureKind.LowerBoundedWildcardType, parseFieldTypeSignature()));
break;
default:
typeArguments.add(parseFieldTypeSignature());
break;
case '>':
if (typeArguments.isEmpty()) {
throw new IllegalStateException();
}
advance();
return;
case -1:
throw new IllegalStateException();
}
}
}
private List<TypeSignature> parseFormalTypeParameters() {
if (current != '<') {
throw new IllegalStateException();
}
advance();
var result = new ArrayList<TypeSignature>();
int pos = position;
FormalTypeParameterSignature currentParameterType = null;
for (;;) {
switch (current) {
case ':':
if (position == pos && currentParameterType == null) {
throw new IllegalStateException();
}
if (currentParameterType == null) {
var name = signature.substring(pos, position);
currentParameterType = new FormalTypeParameterSignature(name);
result.add(currentParameterType);
}
switch (advance()) {
case ':':
case '>':
break;
default:
currentParameterType.formalTypeParameterBounds.add(parseFieldTypeSignature());
pos = position;
break;
}
break;
case '>':
if (currentParameterType == null) {
var name = signature.substring(pos, position);
currentParameterType = new FormalTypeParameterSignature(name);
result.add(currentParameterType);
}
advance();
return result;
default:
currentParameterType = null;
advance();
break;
case -1:
throw new IllegalStateException();
}
}
}
private int advance() {
if (position + 1 < signature.length()) {
return current = signature[++position];
} else {
++position;
return current = -1;
}
}
}
}
| |
// <copyright file="LinearAlgebraProviderTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2015 Math.NET
//
// 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>
using System;
using System.Collections.Generic;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.Providers.LinearAlgebra;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraProviderTests.Double
{
/// <summary>
/// Base class for linear algebra provider tests.
/// </summary>
[TestFixture, Category("LAProvider")]
public class LinearAlgebraProviderTests
{
/// <summary>
/// The Y double test vector.
/// </summary>
readonly double[] _y = {1.1, 2.2, 3.3, 4.4, 5.5};
/// <summary>
/// The X double test vector.
/// </summary>
readonly double[] _x = {6.6, 7.7, 8.8, 9.9, 10.1};
static readonly IContinuousDistribution Dist = new Normal();
/// <summary>
/// Test matrix to use.
/// </summary>
readonly IDictionary<string, DenseMatrix> _matrices = new Dictionary<string, DenseMatrix>
{
{ "Singular3x3", (DenseMatrix)Matrix<double>.Build.DenseOfArray(new[,] { { 1.0, 1.0, 2.0 }, { 1.0, 1.0, 2.0 }, { 1.0, 1.0, 2.0 } }) },
{ "Square3x3", (DenseMatrix)Matrix<double>.Build.DenseOfArray(new[,] { { -1.1, -2.2, -3.3 }, { 0.0, 1.1, 2.2 }, { -4.4, 5.5, 6.6 } }) },
{ "Square4x4", (DenseMatrix)Matrix<double>.Build.DenseOfArray(new[,] { { -1.1, -2.2, -3.3, -4.4 }, { 0.0, 1.1, 2.2, 3.3 }, { 1.0, 2.1, 6.2, 4.3 }, { -4.4, 5.5, 6.6, -7.7 } }) },
{ "Singular4x4", (DenseMatrix)Matrix<double>.Build.DenseOfArray(new[,] { { -1.1, -2.2, -3.3, -4.4 }, { -1.1, -2.2, -3.3, -4.4 }, { -1.1, -2.2, -3.3, -4.4 }, { -1.1, -2.2, -3.3, -4.4 } }) },
{ "Tall3x2", (DenseMatrix)Matrix<double>.Build.DenseOfArray(new[,] { { -1.1, -2.2 }, { 0.0, 1.1 }, { -4.4, 5.5 } }) },
{ "Wide2x3", (DenseMatrix)Matrix<double>.Build.DenseOfArray(new[,] { { -1.1, -2.2, -3.3 }, { 0.0, 1.1, 2.2 } }) },
{ "Tall50000x10", (DenseMatrix)Matrix<double>.Build.Random(50000, 10, Dist) },
{ "Wide10x50000", (DenseMatrix)Matrix<double>.Build.Random(10, 50000, Dist) },
{ "Square1000x1000", (DenseMatrix)Matrix<double>.Build.Random(1000, 1000, Dist) }
};
/// <summary>
/// Can add a vector to scaled vector
/// </summary>
[Test]
public void CanAddVectorToScaledVectorDouble()
{
var result = new double[_y.Length];
Control.LinearAlgebraProvider.AddVectorToScaledVector(_y, 0, _x, result);
for (var i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i], result[i]);
}
Array.Copy(_y, result, _y.Length);
Control.LinearAlgebraProvider.AddVectorToScaledVector(result, 1, _x, result);
for (var i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i] + _x[i], result[i]);
}
Array.Copy(_y, result, _y.Length);
Control.LinearAlgebraProvider.AddVectorToScaledVector(result, Math.PI, _x, result);
for (var i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i] + (Math.PI*_x[i]), result[i]);
}
}
/// <summary>
/// Can scale an array.
/// </summary>
[Test]
public void CanScaleArray()
{
var result = new double[_y.Length];
Control.LinearAlgebraProvider.ScaleArray(1, _y, result);
for (var i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i], result[i]);
}
Array.Copy(_y, result, _y.Length);
Control.LinearAlgebraProvider.ScaleArray(Math.PI, result, result);
for (var i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i]*Math.PI, result[i]);
}
}
/// <summary>
/// Can compute the dot product.
/// </summary>
[Test]
public void CanComputeDotProduct()
{
var result = Control.LinearAlgebraProvider.DotProduct(_x, _y);
AssertHelpers.AlmostEqualRelative(152.35, result, 14);
}
/// <summary>
/// Can add two arrays.
/// </summary>
[Test]
public void CanAddArrays()
{
var result = new double[_y.Length];
Control.LinearAlgebraProvider.AddArrays(_x, _y, result);
for (var i = 0; i < result.Length; i++)
{
Assert.AreEqual(_x[i] + _y[i], result[i]);
}
}
/// <summary>
/// Can subtract two arrays.
/// </summary>
[Test]
public void CanSubtractArrays()
{
var result = new double[_y.Length];
Control.LinearAlgebraProvider.SubtractArrays(_x, _y, result);
for (var i = 0; i < result.Length; i++)
{
Assert.AreEqual(_x[i] - _y[i], result[i]);
}
}
/// <summary>
/// Can pointwise multiply two arrays.
/// </summary>
[Test]
public void CanPointWiseMultiplyArrays()
{
var result = new double[_y.Length];
Control.LinearAlgebraProvider.PointWiseMultiplyArrays(_x, _y, result);
for (var i = 0; i < result.Length; i++)
{
Assert.AreEqual(_x[i]*_y[i], result[i]);
}
}
/// <summary>
/// Can pointwise divide two arrays.
/// </summary>
[Test]
public void CanPointWiseDivideArrays()
{
var result = new double[_y.Length];
Control.LinearAlgebraProvider.PointWiseDivideArrays(_x, _y, result);
for (var i = 0; i < result.Length; i++)
{
Assert.AreEqual(_x[i]/_y[i], result[i]);
}
}
/// <summary>
/// Can compute L1 norm.
/// </summary>
[Test]
public void CanComputeMatrixL1Norm()
{
var matrix = _matrices["Square3x3"];
var norm = Control.LinearAlgebraProvider.MatrixNorm(Norm.OneNorm, matrix.RowCount, matrix.ColumnCount, matrix.Values);
AssertHelpers.AlmostEqualRelative(12.1, norm, 6);
}
/// <summary>
/// Can compute Frobenius norm.
/// </summary>
[Test]
public void CanComputeMatrixFrobeniusNorm()
{
var matrix = _matrices["Square3x3"];
var norm = Control.LinearAlgebraProvider.MatrixNorm(Norm.FrobeniusNorm, matrix.RowCount, matrix.ColumnCount, matrix.Values);
AssertHelpers.AlmostEqualRelative(10.777754868246, norm, 8);
}
/// <summary>
/// Can compute Infinity norm.
/// </summary>
[Test]
public void CanComputeMatrixInfinityNorm()
{
var matrix = _matrices["Square3x3"];
var norm = Control.LinearAlgebraProvider.MatrixNorm(Norm.InfinityNorm, matrix.RowCount, matrix.ColumnCount, matrix.Values);
Assert.AreEqual(16.5, norm);
}
/// <summary>
/// Can multiply two square matrices.
/// </summary>
[Test]
public void CanMultiplySquareMatrices()
{
var x = _matrices["Singular3x3"];
var y = _matrices["Square3x3"];
var c = new DenseMatrix(x.RowCount, y.ColumnCount);
Control.LinearAlgebraProvider.MatrixMultiply(x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, c.Values);
for (var i = 0; i < c.RowCount; i++)
{
for (var j = 0; j < c.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(x.Row(i)*y.Column(j), c[i, j], 14);
}
}
}
/// <summary>
/// Can multiply a wide and tall matrix.
/// </summary>
[Test]
public void CanMultiplyWideAndTallMatrices()
{
var x = _matrices["Wide2x3"];
var y = _matrices["Tall3x2"];
var c = new DenseMatrix(x.RowCount, y.ColumnCount);
Control.LinearAlgebraProvider.MatrixMultiply(x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, c.Values);
for (var i = 0; i < c.RowCount; i++)
{
for (var j = 0; j < c.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(x.Row(i)*y.Column(j), c[i, j], 14);
}
}
}
/// <summary>
/// Can multiply a tall and wide matrix.
/// </summary>
[Test]
public void CanMultiplyTallAndWideMatrices()
{
var x = _matrices["Tall3x2"];
var y = _matrices["Wide2x3"];
var c = new DenseMatrix(x.RowCount, y.ColumnCount);
Control.LinearAlgebraProvider.MatrixMultiply(x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, c.Values);
for (var i = 0; i < c.RowCount; i++)
{
for (var j = 0; j < c.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(x.Row(i)*y.Column(j), c[i, j], 14);
}
}
}
/// <summary>
/// Can multiply two square matrices.
/// </summary>
[Test]
public void CanMultiplySquareMatricesWithUpdate()
{
var x = _matrices["Singular3x3"];
var y = _matrices["Square3x3"];
var c = new DenseMatrix(x.RowCount, y.ColumnCount);
Control.LinearAlgebraProvider.MatrixMultiplyWithUpdate(Transpose.DontTranspose, Transpose.DontTranspose, 2.2, x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, 1.0, c.Values);
for (var i = 0; i < c.RowCount; i++)
{
for (var j = 0; j < c.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(2.2*x.Row(i)*y.Column(j), c[i, j], 14);
}
}
}
/// <summary>
/// Can multiply a wide and tall matrix.
/// </summary>
[Test]
public void CanMultiplyWideAndTallMatricesWithUpdate()
{
var x = _matrices["Wide2x3"];
var y = _matrices["Tall3x2"];
var c = new DenseMatrix(x.RowCount, y.ColumnCount);
Control.LinearAlgebraProvider.MatrixMultiplyWithUpdate(Transpose.DontTranspose, Transpose.DontTranspose, 2.2, x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, 1.0, c.Values);
for (var i = 0; i < c.RowCount; i++)
{
for (var j = 0; j < c.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(2.2*x.Row(i)*y.Column(j), c[i, j], 14);
}
}
}
/// <summary>
/// Can multiply a tall and wide matrix.
/// </summary>
[Test]
public void CanMultiplyTallAndWideMatricesWithUpdate()
{
var x = _matrices["Tall3x2"];
var y = _matrices["Wide2x3"];
var c = new DenseMatrix(x.RowCount, y.ColumnCount);
Control.LinearAlgebraProvider.MatrixMultiplyWithUpdate(Transpose.DontTranspose, Transpose.DontTranspose, 2.2, x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, 1.0, c.Values);
for (var i = 0; i < c.RowCount; i++)
{
for (var j = 0; j < c.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(2.2*x.Row(i)*y.Column(j), c[i, j], 14);
}
}
}
/// <summary>
/// Can compute the LU factor of a matrix.
/// </summary>
[Test]
public void CanComputeLuFactor()
{
var matrix = _matrices["Square3x3"];
var a = new double[matrix.RowCount*matrix.RowCount];
Array.Copy(matrix.Values, a, a.Length);
var ipiv = new int[matrix.RowCount];
Control.LinearAlgebraProvider.LUFactor(a, matrix.RowCount, ipiv);
AssertHelpers.AlmostEqualRelative(a[0], -4.4, 14);
AssertHelpers.AlmostEqualRelative(a[1], 0.25, 14);
AssertHelpers.AlmostEqualRelative(a[2], 0, 14);
AssertHelpers.AlmostEqualRelative(a[3], 5.5, 14);
AssertHelpers.AlmostEqualRelative(a[4], -3.575, 14);
AssertHelpers.AlmostEqualRelative(a[5], -0.307692307692308, 14);
AssertHelpers.AlmostEqualRelative(a[6], 6.6, 14);
AssertHelpers.AlmostEqualRelative(a[7], -4.95, 14);
AssertHelpers.AlmostEqualRelative(a[8], 0.676923076923077, 14);
Assert.AreEqual(ipiv[0], 2);
Assert.AreEqual(ipiv[1], 2);
Assert.AreEqual(ipiv[2], 2);
}
/// <summary>
/// Can compute the inverse of a matrix using LU factorization.
/// </summary>
[Test]
public void CanComputeLuInverse()
{
var matrix = _matrices["Square3x3"];
var a = new double[matrix.RowCount*matrix.RowCount];
Array.Copy(matrix.Values, a, a.Length);
Control.LinearAlgebraProvider.LUInverse(a, matrix.RowCount);
AssertHelpers.AlmostEqualRelative(a[0], -0.454545454545454, 13);
AssertHelpers.AlmostEqualRelative(a[1], -0.909090909090908, 13);
AssertHelpers.AlmostEqualRelative(a[2], 0.454545454545454, 13);
AssertHelpers.AlmostEqualRelative(a[3], -0.340909090909090, 13);
AssertHelpers.AlmostEqualRelative(a[4], -2.045454545454543, 13);
AssertHelpers.AlmostEqualRelative(a[5], 1.477272727272726, 13);
AssertHelpers.AlmostEqualRelative(a[6], -0.113636363636364, 13);
AssertHelpers.AlmostEqualRelative(a[7], 0.227272727272727, 13);
AssertHelpers.AlmostEqualRelative(a[8], -0.113636363636364, 13);
}
/// <summary>
/// Can compute the inverse of a matrix using LU factorization
/// using a previously factored matrix.
/// </summary>
[Test]
public void CanComputeLuInverseOnFactoredMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new double[matrix.RowCount*matrix.RowCount];
Array.Copy(matrix.Values, a, a.Length);
var ipiv = new int[matrix.RowCount];
Control.LinearAlgebraProvider.LUFactor(a, matrix.RowCount, ipiv);
Control.LinearAlgebraProvider.LUInverseFactored(a, matrix.RowCount, ipiv);
AssertHelpers.AlmostEqualRelative(a[0], -0.454545454545454, 13);
AssertHelpers.AlmostEqualRelative(a[1], -0.909090909090908, 13);
AssertHelpers.AlmostEqualRelative(a[2], 0.454545454545454, 13);
AssertHelpers.AlmostEqualRelative(a[3], -0.340909090909090, 13);
AssertHelpers.AlmostEqualRelative(a[4], -2.045454545454543, 13);
AssertHelpers.AlmostEqualRelative(a[5], 1.477272727272726, 13);
AssertHelpers.AlmostEqualRelative(a[6], -0.113636363636364, 13);
AssertHelpers.AlmostEqualRelative(a[7], 0.227272727272727, 13);
AssertHelpers.AlmostEqualRelative(a[8], -0.113636363636364, 13);
}
/// <summary>
/// Can solve Ax=b using LU factorization.
/// </summary>
[Test]
public void CanSolveUsingLU()
{
var matrix = _matrices["Square3x3"];
var a = new double[matrix.RowCount*matrix.RowCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
Control.LinearAlgebraProvider.LUSolve(2, a, matrix.RowCount, b);
AssertHelpers.AlmostEqualRelative(b[0], -1.477272727272726, 13);
AssertHelpers.AlmostEqualRelative(b[1], -4.318181818181815, 13);
AssertHelpers.AlmostEqualRelative(b[2], 3.068181818181816, 13);
AssertHelpers.AlmostEqualRelative(b[3], -4.204545454545451, 13);
AssertHelpers.AlmostEqualRelative(b[4], -12.499999999999989, 13);
AssertHelpers.AlmostEqualRelative(b[5], 8.522727272727266, 13);
NotModified(matrix.RowCount, matrix.ColumnCount, a, matrix);
}
/// <summary>
/// Can solve Ax=b using LU factorization using a factored matrix.
/// </summary>
[Test]
public void CanSolveUsingLUOnFactoredMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new double[matrix.RowCount*matrix.RowCount];
Array.Copy(matrix.Values, a, a.Length);
var ipiv = new int[matrix.RowCount];
Control.LinearAlgebraProvider.LUFactor(a, matrix.RowCount, ipiv);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
Control.LinearAlgebraProvider.LUSolveFactored(2, a, matrix.RowCount, ipiv, b);
AssertHelpers.AlmostEqualRelative(b[0], -1.477272727272726, 13);
AssertHelpers.AlmostEqualRelative(b[1], -4.318181818181815, 13);
AssertHelpers.AlmostEqualRelative(b[2], 3.068181818181816, 13);
AssertHelpers.AlmostEqualRelative(b[3], -4.204545454545451, 13);
AssertHelpers.AlmostEqualRelative(b[4], -12.499999999999989, 13);
AssertHelpers.AlmostEqualRelative(b[5], 8.522727272727266, 13);
}
/// <summary>
/// Can compute the <c>Cholesky</c> factorization.
/// </summary>
[Test]
public void CanComputeCholeskyFactor()
{
var matrix = new double[] {1, 1, 1, 1, 1, 5, 5, 5, 1, 5, 14, 14, 1, 5, 14, 15};
Control.LinearAlgebraProvider.CholeskyFactor(matrix, 4);
Assert.AreEqual(matrix[0], 1);
Assert.AreEqual(matrix[1], 1);
Assert.AreEqual(matrix[2], 1);
Assert.AreEqual(matrix[3], 1);
Assert.AreEqual(matrix[4], 0);
Assert.AreEqual(matrix[5], 2);
Assert.AreEqual(matrix[6], 2);
Assert.AreEqual(matrix[7], 2);
Assert.AreEqual(matrix[8], 0);
Assert.AreEqual(matrix[9], 0);
Assert.AreEqual(matrix[10], 3);
Assert.AreEqual(matrix[11], 3);
Assert.AreEqual(matrix[12], 0);
Assert.AreEqual(matrix[13], 0);
Assert.AreEqual(matrix[14], 0);
Assert.AreEqual(matrix[15], 1);
}
/// <summary>
/// Can solve Ax=b using Cholesky factorization.
/// </summary>
[Test]
public void CanSolveUsingCholesky()
{
var matrix = Matrix<double>.Build.Dense(3, 3, new double[] { 1, 1, 1, 1, 2, 3, 1, 3, 6 });
var a = new double[] {1, 1, 1, 1, 2, 3, 1, 3, 6};
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
Control.LinearAlgebraProvider.CholeskySolve(a, 3, b, 2);
AssertHelpers.AlmostEqualRelative(b[0], 0, 14);
AssertHelpers.AlmostEqualRelative(b[1], 1, 14);
AssertHelpers.AlmostEqualRelative(b[2], 0, 14);
AssertHelpers.AlmostEqualRelative(b[3], 3, 14);
AssertHelpers.AlmostEqualRelative(b[4], 1, 14);
AssertHelpers.AlmostEqualRelative(b[5], 0, 14);
NotModified(3, 3, a, matrix);
}
/// <summary>
/// Can solve Ax=b using LU factorization using a factored matrix.
/// </summary>
[Test]
public void CanSolveUsingCholeskyOnFactoredMatrix()
{
var a = new double[] {1, 1, 1, 1, 2, 3, 1, 3, 6};
Control.LinearAlgebraProvider.CholeskyFactor(a, 3);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
Control.LinearAlgebraProvider.CholeskySolveFactored(a, 3, b, 2);
AssertHelpers.AlmostEqualRelative(b[0], 0, 14);
AssertHelpers.AlmostEqualRelative(b[1], 1, 14);
AssertHelpers.AlmostEqualRelative(b[2], 0, 14);
AssertHelpers.AlmostEqualRelative(b[3], 3, 14);
AssertHelpers.AlmostEqualRelative(b[4], 1, 14);
AssertHelpers.AlmostEqualRelative(b[5], 0, 14);
}
/// <summary>
/// Can compute QR factorization of a square matrix.
/// </summary>
[Test]
public void CanComputeQRFactorSquareMatrix()
{
var matrix = _matrices["Square3x3"];
var r = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, r, r.Length);
var tau = new double[3];
var q = new double[matrix.RowCount*matrix.RowCount];
Control.LinearAlgebraProvider.QRFactor(r, matrix.RowCount, matrix.ColumnCount, q, tau);
var mq = Matrix<double>.Build.Dense(matrix.RowCount, matrix.RowCount, q);
var mr = Matrix<double>.Build.Dense(matrix.RowCount, matrix.ColumnCount, r).UpperTriangle();
var a = mq*mr;
for (var row = 0; row < matrix.RowCount; row++)
{
for (var col = 0; col < matrix.ColumnCount; col++)
{
AssertHelpers.AlmostEqualRelative(matrix[row, col], a[row, col], 14);
}
}
}
/// <summary>
/// Can compute QR factorization of a tall matrix.
/// </summary>
[Test]
public void CanComputeQRFactorTallMatrix()
{
var matrix = _matrices["Tall3x2"];
var r = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, r, r.Length);
var tau = new double[3];
var q = new double[matrix.RowCount*matrix.RowCount];
Control.LinearAlgebraProvider.QRFactor(r, matrix.RowCount, matrix.ColumnCount, q, tau);
var mr = Matrix<double>.Build.Dense(matrix.RowCount, matrix.ColumnCount, r).UpperTriangle();
var mq = Matrix<double>.Build.Dense(matrix.RowCount, matrix.RowCount, q);
var a = mq*mr;
for (var row = 0; row < matrix.RowCount; row++)
{
for (var col = 0; col < matrix.ColumnCount; col++)
{
AssertHelpers.AlmostEqualRelative(matrix[row, col], a[row, col], 14);
}
}
}
/// <summary>
/// Can compute QR factorization of a wide matrix.
/// </summary>
[Test]
public void CanComputeQRFactorWideMatrix()
{
var matrix = _matrices["Wide2x3"];
var r = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, r, r.Length);
var tau = new double[3];
var q = new double[matrix.RowCount*matrix.RowCount];
Control.LinearAlgebraProvider.QRFactor(r, matrix.RowCount, matrix.ColumnCount, q, tau);
var mr = Matrix<double>.Build.Dense(matrix.RowCount, matrix.ColumnCount, r).UpperTriangle();
var mq = Matrix<double>.Build.Dense(matrix.RowCount, matrix.RowCount, q);
var a = mq*mr;
for (var row = 0; row < matrix.RowCount; row++)
{
for (var col = 0; col < matrix.ColumnCount; col++)
{
AssertHelpers.AlmostEqualRelative(matrix[row, col], a[row, col], 14);
}
}
}
/// <summary>
/// Can compute thin QR factorization of a square matrix.
/// </summary>
[Test]
public void CanComputeThinQRFactorSquareMatrix()
{
var matrix = _matrices["Square3x3"];
var r = new double[matrix.ColumnCount*matrix.ColumnCount];
var tau = new double[3];
var q = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, q, q.Length);
Control.LinearAlgebraProvider.ThinQRFactor(q, matrix.RowCount, matrix.ColumnCount, r, tau);
var mq = Matrix<double>.Build.Dense(matrix.RowCount, matrix.ColumnCount, q);
var mr = Matrix<double>.Build.Dense(matrix.ColumnCount, matrix.ColumnCount, r);
var a = mq*mr;
for (var row = 0; row < matrix.RowCount; row++)
{
for (var col = 0; col < matrix.ColumnCount; col++)
{
AssertHelpers.AlmostEqualRelative(matrix[row, col], a[row, col], 14);
}
}
}
/// <summary>
/// Can compute thin QR factorization of a tall matrix.
/// </summary>
[Test]
public void CanComputeThinQRFactorTallMatrix()
{
var matrix = _matrices["Tall3x2"];
var r = new double[matrix.ColumnCount*matrix.ColumnCount];
var tau = new double[3];
var q = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, q, q.Length);
Control.LinearAlgebraProvider.ThinQRFactor(q, matrix.RowCount, matrix.ColumnCount, r, tau);
var mq = Matrix<double>.Build.Dense(matrix.RowCount, matrix.ColumnCount, q);
var mr = Matrix<double>.Build.Dense(matrix.ColumnCount, matrix.ColumnCount, r);
var a = mq*mr;
for (var row = 0; row < matrix.RowCount; row++)
{
for (var col = 0; col < matrix.ColumnCount; col++)
{
AssertHelpers.AlmostEqualRelative(matrix[row, col], a[row, col], 14);
}
}
}
/// <summary>
/// Can solve Ax=b using QR factorization with a square A matrix.
/// </summary>
[Test]
public void CanSolveUsingQRSquareMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new double[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x);
NotModified(3, 3, a, matrix);
var mx = Matrix<double>.Build.Dense(matrix.ColumnCount, 2, x);
var mb = matrix*mx;
AssertHelpers.AlmostEqualRelative(mb[0, 0], b[0], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 0], b[1], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 0], b[2], 13);
AssertHelpers.AlmostEqualRelative(mb[0, 1], b[3], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 1], b[4], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 1], b[5], 13);
}
/// <summary>
/// Can solve Ax=b using QR factorization with a tall A matrix.
/// </summary>
[Test]
public void CanSolveUsingQRTallMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new double[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x);
NotModified(3, 2, a, matrix);
var mb = Matrix<double>.Build.Dense(matrix.RowCount, 2, b);
var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb;
AssertHelpers.AlmostEqualRelative(test[0, 0], x[0], 13);
AssertHelpers.AlmostEqualRelative(test[1, 0], x[1], 13);
AssertHelpers.AlmostEqualRelative(test[0, 1], x[2], 13);
AssertHelpers.AlmostEqualRelative(test[1, 1], x[3], 13);
}
/// <summary>
/// Can solve Ax=b using QR factorization with a square A matrix
/// using a factored A matrix.
/// </summary>
[Test]
public void CanSolveUsingQRSquareMatrixOnFactoredMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new double[matrix.RowCount*matrix.RowCount];
Array.Copy(matrix.Values, a, a.Length);
var tau = new double[matrix.ColumnCount];
var q = new double[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.QRFactor(a, matrix.RowCount, matrix.ColumnCount, q, tau);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new double[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolveFactored(q, a, matrix.RowCount, matrix.ColumnCount, tau, b, 2, x);
var mx = Matrix<double>.Build.Dense(matrix.ColumnCount, 2, x);
var mb = matrix*mx;
AssertHelpers.AlmostEqualRelative(mb[0, 0], b[0], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 0], b[1], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 0], b[2], 13);
AssertHelpers.AlmostEqualRelative(mb[0, 1], b[3], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 1], b[4], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 1], b[5], 13);
}
/// <summary>
/// Can solve Ax=b using QR factorization with a tall A matrix
/// using a factored A matrix.
/// </summary>
[Test]
public void CanSolveUsingQRTallMatrixOnFactoredMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var tau = new double[matrix.ColumnCount];
var q = new double[matrix.RowCount*matrix.RowCount];
Control.LinearAlgebraProvider.QRFactor(a, matrix.RowCount, matrix.ColumnCount, q, tau);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new double[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolveFactored(q, a, matrix.RowCount, matrix.ColumnCount, tau, b, 2, x);
var mb = Matrix<double>.Build.Dense(matrix.RowCount, 2, b);
var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb;
AssertHelpers.AlmostEqualRelative(test[0, 0], x[0], 13);
AssertHelpers.AlmostEqualRelative(test[1, 0], x[1], 13);
AssertHelpers.AlmostEqualRelative(test[0, 1], x[2], 13);
AssertHelpers.AlmostEqualRelative(test[1, 1], x[3], 13);
}
/// <summary>
/// Can solve Ax=b using thin QR factorization with a square A matrix.
/// </summary>
[Test]
public void CanSolveUsingThinQRSquareMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new double[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x, QRMethod.Thin);
NotModified(3, 3, a, matrix);
var mx = Matrix<double>.Build.Dense(matrix.ColumnCount, 2, x);
var mb = matrix*mx;
AssertHelpers.AlmostEqualRelative(mb[0, 0], b[0], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 0], b[1], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 0], b[2], 13);
AssertHelpers.AlmostEqualRelative(mb[0, 1], b[3], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 1], b[4], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 1], b[5], 13);
}
/// <summary>
/// Can solve Ax=b using thin QR factorization with a tall A matrix.
/// </summary>
[Test]
public void CanSolveUsingThinQRTallMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new double[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x, QRMethod.Thin);
NotModified(3, 2, a, matrix);
var mb = Matrix<double>.Build.Dense(matrix.RowCount, 2, b);
var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb;
AssertHelpers.AlmostEqualRelative(test[0, 0], x[0], 13);
AssertHelpers.AlmostEqualRelative(test[1, 0], x[1], 13);
AssertHelpers.AlmostEqualRelative(test[0, 1], x[2], 13);
AssertHelpers.AlmostEqualRelative(test[1, 1], x[3], 13);
}
/// <summary>
/// Can solve Ax=b using thin QR factorization with a square A matrix
/// using a factored A matrix.
/// </summary>
[Test]
public void CanSolveUsingThinQRSquareMatrixOnFactoredMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var tau = new double[matrix.ColumnCount];
var r = new double[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.ThinQRFactor(a, matrix.RowCount, matrix.ColumnCount, r, tau);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new double[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolveFactored(a, r, matrix.RowCount, matrix.ColumnCount, tau, b, 2, x, QRMethod.Thin);
var mx = Matrix<double>.Build.Dense(matrix.ColumnCount, 2, x);
var mb = matrix*mx;
AssertHelpers.AlmostEqualRelative(mb[0, 0], b[0], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 0], b[1], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 0], b[2], 13);
AssertHelpers.AlmostEqualRelative(mb[0, 1], b[3], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 1], b[4], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 1], b[5], 13);
}
/// <summary>
/// Can solve Ax=b using thin QR factorization with a tall A matrix
/// using a factored A matrix.
/// </summary>
[Test]
public void CanSolveUsingThinQRTallMatrixOnFactoredMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var tau = new double[matrix.ColumnCount];
var r = new double[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.ThinQRFactor(a, matrix.RowCount, matrix.ColumnCount, r, tau);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new double[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolveFactored(a, r, matrix.RowCount, matrix.ColumnCount, tau, b, 2, x, QRMethod.Thin);
var mb = Matrix<double>.Build.Dense(matrix.RowCount, 2, b);
var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb;
AssertHelpers.AlmostEqualRelative(test[0, 0], x[0], 13);
AssertHelpers.AlmostEqualRelative(test[1, 0], x[1], 13);
AssertHelpers.AlmostEqualRelative(test[0, 1], x[2], 13);
AssertHelpers.AlmostEqualRelative(test[1, 1], x[3], 13);
}
/// <summary>
/// Can compute the SVD factorization of a square matrix.
/// </summary>
[Test]
public void CanComputeSVDFactorizationOfSquareMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var s = new double[matrix.RowCount];
var u = new double[matrix.RowCount*matrix.RowCount];
var vt = new double[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.SingularValueDecomposition(true, a, matrix.RowCount, matrix.ColumnCount, s, u, vt);
var w = new DenseMatrix(matrix.RowCount, matrix.ColumnCount);
for (var index = 0; index < s.Length; index++)
{
w[index, index] = s[index];
}
var mU = Matrix<double>.Build.Dense(matrix.RowCount, matrix.RowCount, u);
var mV = Matrix<double>.Build.Dense(matrix.ColumnCount, matrix.ColumnCount, vt);
var result = mU*w*mV;
AssertHelpers.AlmostEqualRelative(matrix[0, 0], result[0, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 0], result[1, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[2, 0], result[2, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[0, 1], result[0, 1], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 1], result[1, 1], 14);
AssertHelpers.AlmostEqualRelative(matrix[2, 1], result[2, 1], 14);
AssertHelpers.AlmostEqualRelative(matrix[0, 2], result[0, 2], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 2], result[1, 2], 14);
AssertHelpers.AlmostEqualRelative(matrix[2, 2], result[2, 2], 14);
}
/// <summary>
/// Can compute the SVD factorization of a tall matrix.
/// </summary>
[Test]
public void CanComputeSVDFactorizationOfTallMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var s = new double[matrix.ColumnCount];
var u = new double[matrix.RowCount*matrix.RowCount];
var vt = new double[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.SingularValueDecomposition(true, a, matrix.RowCount, matrix.ColumnCount, s, u, vt);
var w = new DenseMatrix(matrix.RowCount, matrix.ColumnCount);
for (var index = 0; index < s.Length; index++)
{
w[index, index] = s[index];
}
var mU = Matrix<double>.Build.Dense(matrix.RowCount, matrix.RowCount, u);
var mV = Matrix<double>.Build.Dense(matrix.ColumnCount, matrix.ColumnCount, vt);
var result = mU*w*mV;
AssertHelpers.AlmostEqualRelative(matrix[0, 0], result[0, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 0], result[1, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[2, 0], result[2, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[0, 1], result[0, 1], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 1], result[1, 1], 14);
AssertHelpers.AlmostEqualRelative(matrix[2, 1], result[2, 1], 14);
}
/// <summary>
/// Can compute the SVD factorization of a wide matrix.
/// </summary>
[Test]
public void CanComputeSVDFactorizationOfWideMatrix()
{
var matrix = _matrices["Wide2x3"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var s = new double[matrix.RowCount];
var u = new double[matrix.RowCount*matrix.RowCount];
var vt = new double[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.SingularValueDecomposition(true, a, matrix.RowCount, matrix.ColumnCount, s, u, vt);
var w = new DenseMatrix(matrix.RowCount, matrix.ColumnCount);
for (var index = 0; index < s.Length; index++)
{
w[index, index] = s[index];
}
var mU = Matrix<double>.Build.Dense(matrix.RowCount, matrix.RowCount, u);
var mV = Matrix<double>.Build.Dense(matrix.ColumnCount, matrix.ColumnCount, vt);
var result = mU*w*mV;
AssertHelpers.AlmostEqualRelative(matrix[0, 0], result[0, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 0], result[1, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[0, 1], result[0, 1], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 1], result[1, 1], 14);
AssertHelpers.AlmostEqualRelative(matrix[0, 2], result[0, 2], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 2], result[1, 2], 14);
}
/// <summary>
/// Can solve Ax=b using SVD factorization with a square A matrix.
/// </summary>
[Test]
public void CanSolveUsingSVDSquareMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new double[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.SvdSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x);
NotModified(3, 3, a, matrix);
var mx = Matrix<double>.Build.Dense(matrix.ColumnCount, 2, x);
var mb = matrix*mx;
AssertHelpers.AlmostEqual(mb[0, 0], b[0], 13);
AssertHelpers.AlmostEqual(mb[1, 0], b[1], 13);
AssertHelpers.AlmostEqual(mb[2, 0], b[2], 13);
AssertHelpers.AlmostEqual(mb[0, 1], b[3], 13);
AssertHelpers.AlmostEqual(mb[1, 1], b[4], 13);
AssertHelpers.AlmostEqual(mb[2, 1], b[5], 13);
}
/// <summary>
/// Can solve Ax=b using SVD factorization with a tall A matrix.
/// </summary>
[Test]
public void CanSolveUsingSVDTallMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new double[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.SvdSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x);
NotModified(3, 2, a, matrix);
var mb = Matrix<double>.Build.Dense(matrix.RowCount, 2, b);
var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb;
AssertHelpers.AlmostEqual(test[0, 0], x[0], 14);
AssertHelpers.AlmostEqual(test[1, 0], x[1], 14);
AssertHelpers.AlmostEqual(test[0, 1], x[2], 14);
AssertHelpers.AlmostEqual(test[1, 1], x[3], 14);
}
/// <summary>
/// Can solve Ax=b using SVD factorization with a square A matrix
/// using a factored matrix.
/// </summary>
[Test]
public void CanSolveUsingSVDSquareMatrixOnFactoredMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var s = new double[matrix.RowCount];
var u = new double[matrix.RowCount*matrix.RowCount];
var vt = new double[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.SingularValueDecomposition(true, a, matrix.RowCount, matrix.ColumnCount, s, u, vt);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new double[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.SvdSolveFactored(matrix.RowCount, matrix.ColumnCount, s, u, vt, b, 2, x);
var mx = Matrix<double>.Build.Dense(matrix.ColumnCount, 2, x);
var mb = matrix*mx;
AssertHelpers.AlmostEqual(mb[0, 0], b[0], 13);
AssertHelpers.AlmostEqual(mb[1, 0], b[1], 13);
AssertHelpers.AlmostEqual(mb[2, 0], b[2], 13);
AssertHelpers.AlmostEqual(mb[0, 1], b[3], 13);
AssertHelpers.AlmostEqual(mb[1, 1], b[4], 13);
AssertHelpers.AlmostEqual(mb[2, 1], b[5], 13);
}
/// <summary>
/// Can solve Ax=b using SVD factorization with a tall A matrix
/// using a factored matrix.
/// </summary>
[Test]
public void CanSolveUsingSVDTallMatrixOnFactoredMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new double[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var s = new double[matrix.ColumnCount];
var u = new double[matrix.RowCount*matrix.RowCount];
var vt = new double[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.SingularValueDecomposition(true, a, matrix.RowCount, matrix.ColumnCount, s, u, vt);
var b = new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new double[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.SvdSolveFactored(matrix.RowCount, matrix.ColumnCount, s, u, vt, b, 2, x);
var mb = Matrix<double>.Build.Dense(matrix.RowCount, 2, b);
var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb;
AssertHelpers.AlmostEqual(test[0, 0], x[0], 14);
AssertHelpers.AlmostEqual(test[1, 0], x[1], 14);
AssertHelpers.AlmostEqual(test[0, 1], x[2], 14);
AssertHelpers.AlmostEqual(test[1, 1], x[3], 14);
}
[TestCase("Wide10x50000", "Tall50000x10")]
[TestCase("Square1000x1000", "Square1000x1000")]
[Explicit, Timeout(1000*5)]
public void IsMatrixMultiplicationPerformant(string leftMatrixKey, string rightMatrixKey)
{
var leftMatrix = _matrices[leftMatrixKey];
var rightMatrix = _matrices[rightMatrixKey];
var result = leftMatrix*rightMatrix;
Assert.That(result, Is.Not.Null);
}
/// <summary>
/// Checks to see if a matrix and array contain the same values.
/// </summary>
/// <param name="rows">number of rows.</param>
/// <param name="columns">number of columns.</param>
/// <param name="array">array to check.</param>
/// <param name="matrix">matrix to check against.</param>
static void NotModified(int rows, int columns, IList<double> array, Matrix<double> matrix)
{
var index = 0;
for (var col = 0; col < columns; col++)
{
for (var row = 0; row < rows; row++)
{
Assert.AreEqual(array[index++], matrix[row, col]);
}
}
}
}
}
| |
using System;
using Raksha.Crypto.Engines;
using Raksha.Crypto.Parameters;
using Raksha.Crypto.Utilities;
using Raksha.Utilities;
namespace Raksha.Crypto.Digests
{
/**
* implementation of GOST R 34.11-94
*/
public class Gost3411Digest
: IDigest
{
private const int DIGEST_LENGTH = 32;
private byte[] H = new byte[32], L = new byte[32],
M = new byte[32], Sum = new byte[32];
private byte[][] C = MakeC();
private byte[] xBuf = new byte[32];
private int xBufOff;
private ulong byteCount;
private readonly IBlockCipher cipher = new Gost28147Engine();
private readonly byte[] sBox;
private static byte[][] MakeC()
{
byte[][] c = new byte[4][];
for (int i = 0; i < 4; ++i)
{
c[i] = new byte[32];
}
return c;
}
/**
* Standard constructor
*/
public Gost3411Digest()
{
sBox = Gost28147Engine.GetSBox("D-A");
cipher.Init(true, new ParametersWithSBox(null, sBox));
Reset();
}
/**
* Constructor to allow use of a particular sbox with GOST28147
* @see GOST28147Engine#getSBox(String)
*/
public Gost3411Digest(byte[] sBoxParam)
{
sBox = Arrays.Clone(sBoxParam);
cipher.Init(true, new ParametersWithSBox(null, sBox));
Reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public Gost3411Digest(Gost3411Digest t)
{
this.sBox = t.sBox;
cipher.Init(true, new ParametersWithSBox(null, sBox));
Reset();
Array.Copy(t.H, 0, this.H, 0, t.H.Length);
Array.Copy(t.L, 0, this.L, 0, t.L.Length);
Array.Copy(t.M, 0, this.M, 0, t.M.Length);
Array.Copy(t.Sum, 0, this.Sum, 0, t.Sum.Length);
Array.Copy(t.C[1], 0, this.C[1], 0, t.C[1].Length);
Array.Copy(t.C[2], 0, this.C[2], 0, t.C[2].Length);
Array.Copy(t.C[3], 0, this.C[3], 0, t.C[3].Length);
Array.Copy(t.xBuf, 0, this.xBuf, 0, t.xBuf.Length);
this.xBufOff = t.xBufOff;
this.byteCount = t.byteCount;
}
public string AlgorithmName
{
get { return "Gost3411"; }
}
public int GetDigestSize()
{
return DIGEST_LENGTH;
}
public void Update(
byte input)
{
xBuf[xBufOff++] = input;
if (xBufOff == xBuf.Length)
{
sumByteArray(xBuf); // calc sum M
processBlock(xBuf, 0);
xBufOff = 0;
}
byteCount++;
}
public void BlockUpdate(
byte[] input,
int inOff,
int length)
{
while ((xBufOff != 0) && (length > 0))
{
Update(input[inOff]);
inOff++;
length--;
}
while (length > xBuf.Length)
{
Array.Copy(input, inOff, xBuf, 0, xBuf.Length);
sumByteArray(xBuf); // calc sum M
processBlock(xBuf, 0);
inOff += xBuf.Length;
length -= xBuf.Length;
byteCount += (uint)xBuf.Length;
}
// load in the remainder.
while (length > 0)
{
Update(input[inOff]);
inOff++;
length--;
}
}
// (i + 1 + 4(k - 1)) = 8i + k i = 0-3, k = 1-8
private byte[] K = new byte[32];
private byte[] P(byte[] input)
{
int fourK = 0;
for(int k = 0; k < 8; k++)
{
K[fourK++] = input[k];
K[fourK++] = input[8 + k];
K[fourK++] = input[16 + k];
K[fourK++] = input[24 + k];
}
return K;
}
//A (x) = (x0 ^ x1) || x3 || x2 || x1
byte[] a = new byte[8];
private byte[] A(byte[] input)
{
for(int j=0; j<8; j++)
{
a[j]=(byte)(input[j] ^ input[j+8]);
}
Array.Copy(input, 8, input, 0, 24);
Array.Copy(a, 0, input, 24, 8);
return input;
}
//Encrypt function, ECB mode
private void E(byte[] key, byte[] s, int sOff, byte[] input, int inOff)
{
cipher.Init(true, new KeyParameter(key));
cipher.ProcessBlock(input, inOff, s, sOff);
}
// (in:) n16||..||n1 ==> (out:) n1^n2^n3^n4^n13^n16||n16||..||n2
internal short[] wS = new short[16], w_S = new short[16];
private void fw(byte[] input)
{
cpyBytesToShort(input, wS);
w_S[15] = (short)(wS[0] ^ wS[1] ^ wS[2] ^ wS[3] ^ wS[12] ^ wS[15]);
Array.Copy(wS, 1, w_S, 0, 15);
cpyShortToBytes(w_S, input);
}
// block processing
internal byte[] S = new byte[32], U = new byte[32], V = new byte[32], W = new byte[32];
private void processBlock(byte[] input, int inOff)
{
Array.Copy(input, inOff, M, 0, 32);
//key step 1
// H = h3 || h2 || h1 || h0
// S = s3 || s2 || s1 || s0
H.CopyTo(U, 0);
M.CopyTo(V, 0);
for (int j=0; j<32; j++)
{
W[j] = (byte)(U[j]^V[j]);
}
// Encrypt gost28147-ECB
E(P(W), S, 0, H, 0); // s0 = EK0 [h0]
//keys step 2,3,4
for (int i=1; i<4; i++)
{
byte[] tmpA = A(U);
for (int j=0; j<32; j++)
{
U[j] = (byte)(tmpA[j] ^ C[i][j]);
}
V = A(A(V));
for (int j=0; j<32; j++)
{
W[j] = (byte)(U[j]^V[j]);
}
// Encrypt gost28147-ECB
E(P(W), S, i * 8, H, i * 8); // si = EKi [hi]
}
// x(M, H) = y61(H^y(M^y12(S)))
for(int n = 0; n < 12; n++)
{
fw(S);
}
for(int n = 0; n < 32; n++)
{
S[n] = (byte)(S[n] ^ M[n]);
}
fw(S);
for(int n = 0; n < 32; n++)
{
S[n] = (byte)(H[n] ^ S[n]);
}
for(int n = 0; n < 61; n++)
{
fw(S);
}
Array.Copy(S, 0, H, 0, H.Length);
}
private void finish()
{
ulong bitCount = byteCount * 8;
Pack.UInt64_To_LE(bitCount, L);
while (xBufOff != 0)
{
Update((byte)0);
}
processBlock(L, 0);
processBlock(Sum, 0);
}
public int DoFinal(
byte[] output,
int outOff)
{
finish();
H.CopyTo(output, outOff);
Reset();
return DIGEST_LENGTH;
}
/**
* reset the chaining variables to the IV values.
*/
private static readonly byte[] C2 = {
0x00,(byte)0xFF,0x00,(byte)0xFF,0x00,(byte)0xFF,0x00,(byte)0xFF,
(byte)0xFF,0x00,(byte)0xFF,0x00,(byte)0xFF,0x00,(byte)0xFF,0x00,
0x00,(byte)0xFF,(byte)0xFF,0x00,(byte)0xFF,0x00,0x00,(byte)0xFF,
(byte)0xFF,0x00,0x00,0x00,(byte)0xFF,(byte)0xFF,0x00,(byte)0xFF
};
public void Reset()
{
byteCount = 0;
xBufOff = 0;
Array.Clear(H, 0, H.Length);
Array.Clear(L, 0, L.Length);
Array.Clear(M, 0, M.Length);
Array.Clear(C[1], 0, C[1].Length); // real index C = +1 because index array with 0.
Array.Clear(C[3], 0, C[3].Length);
Array.Clear(Sum, 0, Sum.Length);
Array.Clear(xBuf, 0, xBuf.Length);
C2.CopyTo(C[2], 0);
}
// 256 bitsblock modul -> (Sum + a mod (2^256))
private void sumByteArray(
byte[] input)
{
int carry = 0;
for (int i = 0; i != Sum.Length; i++)
{
int sum = (Sum[i] & 0xff) + (input[i] & 0xff) + carry;
Sum[i] = (byte)sum;
carry = sum >> 8;
}
}
private static void cpyBytesToShort(byte[] S, short[] wS)
{
for(int i = 0; i < S.Length / 2; i++)
{
wS[i] = (short)(((S[i*2+1]<<8)&0xFF00)|(S[i*2]&0xFF));
}
}
private static void cpyShortToBytes(short[] wS, byte[] S)
{
for(int i=0; i<S.Length/2; i++)
{
S[i*2 + 1] = (byte)(wS[i] >> 8);
S[i*2] = (byte)wS[i];
}
}
public int GetByteLength()
{
return 32;
}
}
}
| |
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.Win32.SafeHandles;
namespace Microsoft.VisualStudioTools.Project {
internal static class NativeMethods {
// IIDS
public static readonly Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}");
public const int ERROR_FILE_NOT_FOUND = 2;
public const int
CLSCTX_INPROC_SERVER = 0x1;
public const int
S_FALSE = 0x00000001,
S_OK = 0x00000000,
IDOK = 1,
IDCANCEL = 2,
IDABORT = 3,
IDRETRY = 4,
IDIGNORE = 5,
IDYES = 6,
IDNO = 7,
IDCLOSE = 8,
IDHELP = 9,
IDTRYAGAIN = 10,
IDCONTINUE = 11,
OLECMDERR_E_NOTSUPPORTED = unchecked((int)0x80040100),
OLECMDERR_E_UNKNOWNGROUP = unchecked((int)0x80040104),
UNDO_E_CLIENTABORT = unchecked((int)0x80044001),
E_OUTOFMEMORY = unchecked((int)0x8007000E),
E_INVALIDARG = unchecked((int)0x80070057),
E_FAIL = unchecked((int)0x80004005),
E_NOINTERFACE = unchecked((int)0x80004002),
E_POINTER = unchecked((int)0x80004003),
E_NOTIMPL = unchecked((int)0x80004001),
E_UNEXPECTED = unchecked((int)0x8000FFFF),
E_HANDLE = unchecked((int)0x80070006),
E_ABORT = unchecked((int)0x80004004),
E_ACCESSDENIED = unchecked((int)0x80070005),
E_PENDING = unchecked((int)0x8000000A);
public const int
OLECLOSE_SAVEIFDIRTY = 0,
OLECLOSE_NOSAVE = 1,
OLECLOSE_PROMPTSAVE = 2;
public const int
OLEIVERB_PRIMARY = 0,
OLEIVERB_SHOW = -1,
OLEIVERB_OPEN = -2,
OLEIVERB_HIDE = -3,
OLEIVERB_UIACTIVATE = -4,
OLEIVERB_INPLACEACTIVATE = -5,
OLEIVERB_DISCARDUNDOSTATE = -6,
OLEIVERB_PROPERTIES = -7;
public const int
OFN_READONLY = unchecked((int)0x00000001),
OFN_OVERWRITEPROMPT = unchecked((int)0x00000002),
OFN_HIDEREADONLY = unchecked((int)0x00000004),
OFN_NOCHANGEDIR = unchecked((int)0x00000008),
OFN_SHOWHELP = unchecked((int)0x00000010),
OFN_ENABLEHOOK = unchecked((int)0x00000020),
OFN_ENABLETEMPLATE = unchecked((int)0x00000040),
OFN_ENABLETEMPLATEHANDLE = unchecked((int)0x00000080),
OFN_NOVALIDATE = unchecked((int)0x00000100),
OFN_ALLOWMULTISELECT = unchecked((int)0x00000200),
OFN_EXTENSIONDIFFERENT = unchecked((int)0x00000400),
OFN_PATHMUSTEXIST = unchecked((int)0x00000800),
OFN_FILEMUSTEXIST = unchecked((int)0x00001000),
OFN_CREATEPROMPT = unchecked((int)0x00002000),
OFN_SHAREAWARE = unchecked((int)0x00004000),
OFN_NOREADONLYRETURN = unchecked((int)0x00008000),
OFN_NOTESTFILECREATE = unchecked((int)0x00010000),
OFN_NONETWORKBUTTON = unchecked((int)0x00020000),
OFN_NOLONGNAMES = unchecked((int)0x00040000),
OFN_EXPLORER = unchecked((int)0x00080000),
OFN_NODEREFERENCELINKS = unchecked((int)0x00100000),
OFN_LONGNAMES = unchecked((int)0x00200000),
OFN_ENABLEINCLUDENOTIFY = unchecked((int)0x00400000),
OFN_ENABLESIZING = unchecked((int)0x00800000),
OFN_USESHELLITEM = unchecked((int)0x01000000),
OFN_DONTADDTORECENT = unchecked((int)0x02000000),
OFN_FORCESHOWHIDDEN = unchecked((int)0x10000000);
// for READONLYSTATUS
public const int
ROSTATUS_NotReadOnly = 0x0,
ROSTATUS_ReadOnly = 0x1,
ROSTATUS_Unknown = unchecked((int)0xFFFFFFFF);
public const int
IEI_DoNotLoadDocData = 0x10000000;
public const int
CB_SETDROPPEDWIDTH = 0x0160,
GWL_STYLE = (-16),
GWL_EXSTYLE = (-20),
DWL_MSGRESULT = 0,
SW_SHOWNORMAL = 1,
HTMENU = 5,
WS_POPUP = unchecked((int)0x80000000),
WS_CHILD = 0x40000000,
WS_MINIMIZE = 0x20000000,
WS_VISIBLE = 0x10000000,
WS_DISABLED = 0x08000000,
WS_CLIPSIBLINGS = 0x04000000,
WS_CLIPCHILDREN = 0x02000000,
WS_MAXIMIZE = 0x01000000,
WS_CAPTION = 0x00C00000,
WS_BORDER = 0x00800000,
WS_DLGFRAME = 0x00400000,
WS_VSCROLL = 0x00200000,
WS_HSCROLL = 0x00100000,
WS_SYSMENU = 0x00080000,
WS_THICKFRAME = 0x00040000,
WS_TABSTOP = 0x00010000,
WS_MINIMIZEBOX = 0x00020000,
WS_MAXIMIZEBOX = 0x00010000,
WS_EX_DLGMODALFRAME = 0x00000001,
WS_EX_MDICHILD = 0x00000040,
WS_EX_TOOLWINDOW = 0x00000080,
WS_EX_CLIENTEDGE = 0x00000200,
WS_EX_CONTEXTHELP = 0x00000400,
WS_EX_RIGHT = 0x00001000,
WS_EX_LEFT = 0x00000000,
WS_EX_RTLREADING = 0x00002000,
WS_EX_LEFTSCROLLBAR = 0x00004000,
WS_EX_CONTROLPARENT = 0x00010000,
WS_EX_STATICEDGE = 0x00020000,
WS_EX_APPWINDOW = 0x00040000,
WS_EX_LAYERED = 0x00080000,
WS_EX_TOPMOST = 0x00000008,
WS_EX_NOPARENTNOTIFY = 0x00000004,
LVM_SETEXTENDEDLISTVIEWSTYLE = (0x1000 + 54),
LVS_EX_LABELTIP = 0x00004000,
// winuser.h
WH_JOURNALPLAYBACK = 1,
WH_GETMESSAGE = 3,
WH_MOUSE = 7,
WSF_VISIBLE = 0x0001,
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DELETEITEM = 0x002D,
WM_DESTROY = 0x0002,
WM_MOVE = 0x0003,
WM_SIZE = 0x0005,
WM_ACTIVATE = 0x0006,
WA_INACTIVE = 0,
WA_ACTIVE = 1,
WA_CLICKACTIVE = 2,
WM_SETFOCUS = 0x0007,
WM_KILLFOCUS = 0x0008,
WM_ENABLE = 0x000A,
WM_SETREDRAW = 0x000B,
WM_SETTEXT = 0x000C,
WM_GETTEXT = 0x000D,
WM_GETTEXTLENGTH = 0x000E,
WM_PAINT = 0x000F,
WM_CLOSE = 0x0010,
WM_QUERYENDSESSION = 0x0011,
WM_QUIT = 0x0012,
WM_QUERYOPEN = 0x0013,
WM_ERASEBKGND = 0x0014,
WM_SYSCOLORCHANGE = 0x0015,
WM_ENDSESSION = 0x0016,
WM_SHOWWINDOW = 0x0018,
WM_WININICHANGE = 0x001A,
WM_SETTINGCHANGE = 0x001A,
WM_DEVMODECHANGE = 0x001B,
WM_ACTIVATEAPP = 0x001C,
WM_FONTCHANGE = 0x001D,
WM_TIMECHANGE = 0x001E,
WM_CANCELMODE = 0x001F,
WM_SETCURSOR = 0x0020,
WM_MOUSEACTIVATE = 0x0021,
WM_CHILDACTIVATE = 0x0022,
WM_QUEUESYNC = 0x0023,
WM_GETMINMAXINFO = 0x0024,
WM_PAINTICON = 0x0026,
WM_ICONERASEBKGND = 0x0027,
WM_NEXTDLGCTL = 0x0028,
WM_SPOOLERSTATUS = 0x002A,
WM_DRAWITEM = 0x002B,
WM_MEASUREITEM = 0x002C,
WM_VKEYTOITEM = 0x002E,
WM_CHARTOITEM = 0x002F,
WM_SETFONT = 0x0030,
WM_GETFONT = 0x0031,
WM_SETHOTKEY = 0x0032,
WM_GETHOTKEY = 0x0033,
WM_QUERYDRAGICON = 0x0037,
WM_COMPAREITEM = 0x0039,
WM_GETOBJECT = 0x003D,
WM_COMPACTING = 0x0041,
WM_COMMNOTIFY = 0x0044,
WM_WINDOWPOSCHANGING = 0x0046,
WM_WINDOWPOSCHANGED = 0x0047,
WM_POWER = 0x0048,
WM_COPYDATA = 0x004A,
WM_CANCELJOURNAL = 0x004B,
WM_NOTIFY = 0x004E,
WM_INPUTLANGCHANGEREQUEST = 0x0050,
WM_INPUTLANGCHANGE = 0x0051,
WM_TCARD = 0x0052,
WM_HELP = 0x0053,
WM_USERCHANGED = 0x0054,
WM_NOTIFYFORMAT = 0x0055,
WM_CONTEXTMENU = 0x007B,
WM_STYLECHANGING = 0x007C,
WM_STYLECHANGED = 0x007D,
WM_DISPLAYCHANGE = 0x007E,
WM_GETICON = 0x007F,
WM_SETICON = 0x0080,
WM_NCCREATE = 0x0081,
WM_NCDESTROY = 0x0082,
WM_NCCALCSIZE = 0x0083,
WM_NCHITTEST = 0x0084,
WM_NCPAINT = 0x0085,
WM_NCACTIVATE = 0x0086,
WM_GETDLGCODE = 0x0087,
WM_NCMOUSEMOVE = 0x00A0,
WM_NCLBUTTONDOWN = 0x00A1,
WM_NCLBUTTONUP = 0x00A2,
WM_NCLBUTTONDBLCLK = 0x00A3,
WM_NCRBUTTONDOWN = 0x00A4,
WM_NCRBUTTONUP = 0x00A5,
WM_NCRBUTTONDBLCLK = 0x00A6,
WM_NCMBUTTONDOWN = 0x00A7,
WM_NCMBUTTONUP = 0x00A8,
WM_NCMBUTTONDBLCLK = 0x00A9,
WM_NCXBUTTONDOWN = 0x00AB,
WM_NCXBUTTONUP = 0x00AC,
WM_NCXBUTTONDBLCLK = 0x00AD,
WM_KEYFIRST = 0x0100,
WM_KEYDOWN = 0x0100,
WM_KEYUP = 0x0101,
WM_CHAR = 0x0102,
WM_DEADCHAR = 0x0103,
WM_CTLCOLOR = 0x0019,
WM_SYSKEYDOWN = 0x0104,
WM_SYSKEYUP = 0x0105,
WM_SYSCHAR = 0x0106,
WM_SYSDEADCHAR = 0x0107,
WM_KEYLAST = 0x0108,
WM_IME_STARTCOMPOSITION = 0x010D,
WM_IME_ENDCOMPOSITION = 0x010E,
WM_IME_COMPOSITION = 0x010F,
WM_IME_KEYLAST = 0x010F,
WM_INITDIALOG = 0x0110,
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
WM_TIMER = 0x0113,
WM_HSCROLL = 0x0114,
WM_VSCROLL = 0x0115,
WM_INITMENU = 0x0116,
WM_INITMENUPOPUP = 0x0117,
WM_MENUSELECT = 0x011F,
WM_MENUCHAR = 0x0120,
WM_ENTERIDLE = 0x0121,
WM_CHANGEUISTATE = 0x0127,
WM_UPDATEUISTATE = 0x0128,
WM_QUERYUISTATE = 0x0129,
WM_CTLCOLORMSGBOX = 0x0132,
WM_CTLCOLOREDIT = 0x0133,
WM_CTLCOLORLISTBOX = 0x0134,
WM_CTLCOLORBTN = 0x0135,
WM_CTLCOLORDLG = 0x0136,
WM_CTLCOLORSCROLLBAR = 0x0137,
WM_CTLCOLORSTATIC = 0x0138,
WM_MOUSEFIRST = 0x0200,
WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_LBUTTONDBLCLK = 0x0203,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205,
WM_RBUTTONDBLCLK = 0x0206,
WM_MBUTTONDOWN = 0x0207,
WM_MBUTTONUP = 0x0208,
WM_MBUTTONDBLCLK = 0x0209,
WM_XBUTTONDOWN = 0x020B,
WM_XBUTTONUP = 0x020C,
WM_XBUTTONDBLCLK = 0x020D,
WM_MOUSEWHEEL = 0x020A,
WM_MOUSELAST = 0x020A,
WM_PARENTNOTIFY = 0x0210,
WM_ENTERMENULOOP = 0x0211,
WM_EXITMENULOOP = 0x0212,
WM_NEXTMENU = 0x0213,
WM_SIZING = 0x0214,
WM_CAPTURECHANGED = 0x0215,
WM_MOVING = 0x0216,
WM_POWERBROADCAST = 0x0218,
WM_DEVICECHANGE = 0x0219,
WM_IME_SETCONTEXT = 0x0281,
WM_IME_NOTIFY = 0x0282,
WM_IME_CONTROL = 0x0283,
WM_IME_COMPOSITIONFULL = 0x0284,
WM_IME_SELECT = 0x0285,
WM_IME_CHAR = 0x0286,
WM_IME_KEYDOWN = 0x0290,
WM_IME_KEYUP = 0x0291,
WM_MDICREATE = 0x0220,
WM_MDIDESTROY = 0x0221,
WM_MDIACTIVATE = 0x0222,
WM_MDIRESTORE = 0x0223,
WM_MDINEXT = 0x0224,
WM_MDIMAXIMIZE = 0x0225,
WM_MDITILE = 0x0226,
WM_MDICASCADE = 0x0227,
WM_MDIICONARRANGE = 0x0228,
WM_MDIGETACTIVE = 0x0229,
WM_MDISETMENU = 0x0230,
WM_ENTERSIZEMOVE = 0x0231,
WM_EXITSIZEMOVE = 0x0232,
WM_DROPFILES = 0x0233,
WM_MDIREFRESHMENU = 0x0234,
WM_MOUSEHOVER = 0x02A1,
WM_MOUSELEAVE = 0x02A3,
WM_CUT = 0x0300,
WM_COPY = 0x0301,
WM_PASTE = 0x0302,
WM_CLEAR = 0x0303,
WM_UNDO = 0x0304,
WM_RENDERFORMAT = 0x0305,
WM_RENDERALLFORMATS = 0x0306,
WM_DESTROYCLIPBOARD = 0x0307,
WM_DRAWCLIPBOARD = 0x0308,
WM_PAINTCLIPBOARD = 0x0309,
WM_VSCROLLCLIPBOARD = 0x030A,
WM_SIZECLIPBOARD = 0x030B,
WM_ASKCBFORMATNAME = 0x030C,
WM_CHANGECBCHAIN = 0x030D,
WM_HSCROLLCLIPBOARD = 0x030E,
WM_QUERYNEWPALETTE = 0x030F,
WM_PALETTEISCHANGING = 0x0310,
WM_PALETTECHANGED = 0x0311,
WM_HOTKEY = 0x0312,
WM_PRINT = 0x0317,
WM_PRINTCLIENT = 0x0318,
WM_HANDHELDFIRST = 0x0358,
WM_HANDHELDLAST = 0x035F,
WM_AFXFIRST = 0x0360,
WM_AFXLAST = 0x037F,
WM_PENWINFIRST = 0x0380,
WM_PENWINLAST = 0x038F,
WM_APP = unchecked((int)0x8000),
WM_USER = 0x0400,
WM_REFLECT =
WM_USER + 0x1C00,
WS_OVERLAPPED = 0x00000000,
WPF_SETMINPOSITION = 0x0001,
WM_CHOOSEFONT_GETLOGFONT = (0x0400 + 1),
WHEEL_DELTA = 120,
DWLP_MSGRESULT = 0,
PSNRET_NOERROR = 0,
PSNRET_INVALID = 1,
PSNRET_INVALID_NOCHANGEPAGE = 2,
EM_SETCUEBANNER = 0x1501;
public const int
PSN_APPLY = ((0 - 200) - 2),
PSN_KILLACTIVE = ((0 - 200) - 1),
PSN_RESET = ((0 - 200) - 3),
PSN_SETACTIVE = ((0 - 200) - 0);
public const int
GMEM_MOVEABLE = 0x0002,
GMEM_ZEROINIT = 0x0040,
GMEM_DDESHARE = 0x2000;
public const int
SWP_NOACTIVATE = 0x0010,
SWP_NOZORDER = 0x0004,
SWP_NOSIZE = 0x0001,
SWP_NOMOVE = 0x0002,
SWP_FRAMECHANGED = 0x0020;
public const int
TVM_SETINSERTMARK = (0x1100 + 26),
TVM_GETEDITCONTROL = (0x1100 + 15);
public const int
FILE_ATTRIBUTE_READONLY = 0x00000001,
FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
public const int
PSP_DEFAULT = 0x00000000,
PSP_DLGINDIRECT = 0x00000001,
PSP_USEHICON = 0x00000002,
PSP_USEICONID = 0x00000004,
PSP_USETITLE = 0x00000008,
PSP_RTLREADING = 0x00000010,
PSP_HASHELP = 0x00000020,
PSP_USEREFPARENT = 0x00000040,
PSP_USECALLBACK = 0x00000080,
PSP_PREMATURE = 0x00000400,
PSP_HIDEHEADER = 0x00000800,
PSP_USEHEADERTITLE = 0x00001000,
PSP_USEHEADERSUBTITLE = 0x00002000;
public const int
PSH_DEFAULT = 0x00000000,
PSH_PROPTITLE = 0x00000001,
PSH_USEHICON = 0x00000002,
PSH_USEICONID = 0x00000004,
PSH_PROPSHEETPAGE = 0x00000008,
PSH_WIZARDHASFINISH = 0x00000010,
PSH_WIZARD = 0x00000020,
PSH_USEPSTARTPAGE = 0x00000040,
PSH_NOAPPLYNOW = 0x00000080,
PSH_USECALLBACK = 0x00000100,
PSH_HASHELP = 0x00000200,
PSH_MODELESS = 0x00000400,
PSH_RTLREADING = 0x00000800,
PSH_WIZARDCONTEXTHELP = 0x00001000,
PSH_WATERMARK = 0x00008000,
PSH_USEHBMWATERMARK = 0x00010000, // user pass in a hbmWatermark instead of pszbmWatermark
PSH_USEHPLWATERMARK = 0x00020000, //
PSH_STRETCHWATERMARK = 0x00040000, // stretchwatermark also applies for the header
PSH_HEADER = 0x00080000,
PSH_USEHBMHEADER = 0x00100000,
PSH_USEPAGELANG = 0x00200000, // use frame dialog template matched to page
PSH_WIZARD_LITE = 0x00400000,
PSH_NOCONTEXTHELP = 0x02000000;
public const int
PSBTN_BACK = 0,
PSBTN_NEXT = 1,
PSBTN_FINISH = 2,
PSBTN_OK = 3,
PSBTN_APPLYNOW = 4,
PSBTN_CANCEL = 5,
PSBTN_HELP = 6,
PSBTN_MAX = 6;
public const int
TRANSPARENT = 1,
OPAQUE = 2,
FW_BOLD = 700;
[StructLayout(LayoutKind.Sequential)]
public struct NMHDR {
public IntPtr hwndFrom;
public int idFrom;
public int code;
}
/// <devdoc>
/// Helper class for setting the text parameters to OLECMDTEXT structures.
/// </devdoc>
public static class OLECMDTEXT {
public static void SetText(IntPtr pCmdTextInt, string text) {
Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT pCmdText = (Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT)Marshal.PtrToStructure(pCmdTextInt, typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT));
char[] menuText = text.ToCharArray();
// Get the offset to the rgsz param. This is where we will stuff our text
//
IntPtr offset = Marshal.OffsetOf(typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT), "rgwz");
IntPtr offsetToCwActual = Marshal.OffsetOf(typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT), "cwActual");
// The max chars we copy is our string, or one less than the buffer size,
// since we need a null at the end.
//
int maxChars = Math.Min((int)pCmdText.cwBuf - 1, menuText.Length);
Marshal.Copy(menuText, 0, (IntPtr)((long)pCmdTextInt + (long)offset), maxChars);
// append a null character
Marshal.WriteInt16((IntPtr)((long)pCmdTextInt + (long)offset + maxChars * 2), 0);
// write out the length
// +1 for the null char
Marshal.WriteInt32((IntPtr)((long)pCmdTextInt + (long)offsetToCwActual), maxChars + 1);
}
/// <summary>
/// Gets the flags of the OLECMDTEXT structure
/// </summary>
/// <param name="pCmdTextInt">The structure to read.</param>
/// <returns>The value of the flags.</returns>
public static OLECMDTEXTF GetFlags(IntPtr pCmdTextInt) {
Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT pCmdText = (Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT)Marshal.PtrToStructure(pCmdTextInt, typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT));
if ((pCmdText.cmdtextf & (int)OLECMDTEXTF.OLECMDTEXTF_NAME) != 0)
return OLECMDTEXTF.OLECMDTEXTF_NAME;
if ((pCmdText.cmdtextf & (int)OLECMDTEXTF.OLECMDTEXTF_STATUS) != 0)
return OLECMDTEXTF.OLECMDTEXTF_STATUS;
return OLECMDTEXTF.OLECMDTEXTF_NONE;
}
/// <summary>
/// Flags for the OLE command text
/// </summary>
public enum OLECMDTEXTF {
/// <summary>No flag</summary>
OLECMDTEXTF_NONE = 0,
/// <summary>The name of the command is required.</summary>
OLECMDTEXTF_NAME = 1,
/// <summary>A description of the status is required.</summary>
OLECMDTEXTF_STATUS = 2
}
}
/// <devdoc>
/// OLECMDF enums for IOleCommandTarget
/// </devdoc>
public enum tagOLECMDF {
OLECMDF_SUPPORTED = 1,
OLECMDF_ENABLED = 2,
OLECMDF_LATCHED = 4,
OLECMDF_NINCHED = 8,
OLECMDF_INVISIBLE = 16
}
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern IntPtr GetParent(IntPtr hWnd);
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern bool GetClientRect(IntPtr hWnd, out User32RECT lpRect);
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode)]
public static extern IntPtr SendMessageW(IntPtr hWnd, uint msg, IntPtr wParam, string lParam);
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
public static void SetErrorDescription(string description, params object[] args) {
ICreateErrorInfo errInfo;
ErrorHandler.ThrowOnFailure(CreateErrorInfo(out errInfo));
errInfo.SetDescription(String.Format(description, args));
var guidNull = Guid.Empty;
errInfo.SetGUID(ref guidNull);
errInfo.SetHelpFile(null);
errInfo.SetHelpContext(0);
errInfo.SetSource("");
IErrorInfo errorInfo = errInfo as IErrorInfo;
SetErrorInfo(0, errorInfo);
}
[DllImport("oleaut32")]
static extern int CreateErrorInfo(out ICreateErrorInfo errInfo);
[DllImport("oleaut32")]
static extern int SetErrorInfo(uint dwReserved, IErrorInfo perrinfo);
[ComImport(), Guid("9BDA66AE-CA28-4e22-AA27-8A7218A0E3FA"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IEventHandler {
// converts the underlying codefunction into an event handler for the given event
// if the given event is NULL, then the function will handle no events
[PreserveSig]
int AddHandler(string bstrEventName);
[PreserveSig]
int RemoveHandler(string bstrEventName);
IVsEnumBSTR GetHandledEvents();
bool HandlesEvent(string bstrEventName);
}
[ComImport(), Guid("A55CCBCC-7031-432d-B30A-A68DE7BDAD75"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IParameterKind {
void SetParameterPassingMode(PARAMETER_PASSING_MODE ParamPassingMode);
void SetParameterArrayDimensions(int uDimensions);
int GetParameterArrayCount();
int GetParameterArrayDimensions(int uIndex);
int GetParameterPassingMode();
}
public enum PARAMETER_PASSING_MODE {
cmParameterTypeIn = 1,
cmParameterTypeOut = 2,
cmParameterTypeInOut = 3
}
[
ComImport, ComVisible(true), Guid("3E596484-D2E4-461a-A876-254C4F097EBB"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)
]
public interface IMethodXML {
// Generate XML describing the contents of this function's body.
void GetXML(ref string pbstrXML);
// Parse the incoming XML with respect to the CodeModel XML schema and
// use the result to regenerate the body of the function.
/// <include file='doc\NativeMethods.uex' path='docs/doc[@for="IMethodXML.SetXML"]/*' />
[PreserveSig]
int SetXML(string pszXML);
// This is really a textpoint
[PreserveSig]
int GetBodyPoint([MarshalAs(UnmanagedType.Interface)]out object bodyPoint);
}
[ComImport(), Guid("EA1A87AD-7BC5-4349-B3BE-CADC301F17A3"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVBFileCodeModelEvents {
[PreserveSig]
int StartEdit();
[PreserveSig]
int EndEdit();
}
///--------------------------------------------------------------------------
/// ICodeClassBase:
///--------------------------------------------------------------------------
[GuidAttribute("23BBD58A-7C59-449b-A93C-43E59EFC080C")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport()]
public interface ICodeClassBase {
[PreserveSig()]
int GetBaseName(out string pBaseName);
}
public const ushort CF_HDROP = 15; // winuser.h
public const uint MK_CONTROL = 0x0008; //winuser.h
public const uint MK_SHIFT = 0x0004;
public const int MAX_PATH = 260; // windef.h
public const int MAX_FOLDER_PATH = MAX_PATH - 12; // folders need to allow 8.3 filenames, so MAX_PATH - 12
/// <summary>
/// Specifies options for a bitmap image associated with a task item.
/// </summary>
public enum VSTASKBITMAP {
BMP_COMPILE = -1,
BMP_SQUIGGLE = -2,
BMP_COMMENT = -3,
BMP_SHORTCUT = -4,
BMP_USER = -5
};
public const int ILD_NORMAL = 0x0000,
ILD_TRANSPARENT = 0x0001,
ILD_MASK = 0x0010,
ILD_ROP = 0x0040;
/// <summary>
/// Defines the values that are not supported by the System.Environment.SpecialFolder enumeration
/// </summary>
[ComVisible(true)]
public enum ExtendedSpecialFolder {
/// <summary>
/// Identical to CSIDL_COMMON_STARTUP
/// </summary>
CommonStartup = 0x0018,
/// <summary>
/// Identical to CSIDL_WINDOWS
/// </summary>
Windows = 0x0024,
}
// APIS
/// <summary>
/// Changes the parent window of the specified child window.
/// </summary>
/// <param name="hWnd">Handle to the child window.</param>
/// <param name="hWndParent">Handle to the new parent window. If this parameter is NULL, the desktop window becomes the new parent window.</param>
/// <returns>A handle to the previous parent window indicates success. NULL indicates failure.</returns>
[DllImport("User32", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern bool DestroyIcon(IntPtr handle);
[DllImport("user32.dll", EntryPoint = "IsDialogMessageA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool IsDialogMessageA(IntPtr hDlg, ref MSG msg);
[DllImport("kernel32", EntryPoint = "GetBinaryTypeW", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)]
private static extern bool _GetBinaryType(string lpApplicationName, out GetBinaryTypeResult lpBinaryType);
private enum GetBinaryTypeResult : uint {
SCS_32BIT_BINARY = 0,
SCS_DOS_BINARY = 1,
SCS_WOW_BINARY = 2,
SCS_PIF_BINARY = 3,
SCS_POSIX_BINARY = 4,
SCS_OS216_BINARY = 5,
SCS_64BIT_BINARY = 6
}
public static ProcessorArchitecture GetBinaryType(string path) {
GetBinaryTypeResult result;
if (_GetBinaryType(path, out result)) {
switch (result) {
case GetBinaryTypeResult.SCS_32BIT_BINARY:
return ProcessorArchitecture.X86;
case GetBinaryTypeResult.SCS_64BIT_BINARY:
return ProcessorArchitecture.Amd64;
case GetBinaryTypeResult.SCS_DOS_BINARY:
case GetBinaryTypeResult.SCS_WOW_BINARY:
case GetBinaryTypeResult.SCS_PIF_BINARY:
case GetBinaryTypeResult.SCS_POSIX_BINARY:
case GetBinaryTypeResult.SCS_OS216_BINARY:
default:
break;
}
}
return ProcessorArchitecture.None;
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
[DllImport("ADVAPI32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(
[In] string lpszUsername,
[In] string lpszDomain,
[In] string lpszPassword,
[In] LogonType dwLogonType,
[In] LogonProvider dwLogonProvider,
[In, Out] ref IntPtr hToken
);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern uint GetFinalPathNameByHandle(
SafeHandle hFile,
[Out]StringBuilder lpszFilePath,
uint cchFilePath,
uint dwFlags
);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern SafeFileHandle CreateFile(
string lpFileName,
FileDesiredAccess dwDesiredAccess,
FileShareFlags dwShareMode,
IntPtr lpSecurityAttributes,
FileCreationDisposition dwCreationDisposition,
FileFlagsAndAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile
);
[Flags]
public enum FileDesiredAccess : uint {
FILE_LIST_DIRECTORY = 1
}
[Flags]
public enum FileShareFlags : uint {
FILE_SHARE_READ = 0x00000001,
FILE_SHARE_WRITE = 0x00000002,
FILE_SHARE_DELETE = 0x00000004
}
[Flags]
public enum FileCreationDisposition : uint {
OPEN_EXISTING = 3
}
[Flags]
public enum FileFlagsAndAttributes : uint {
FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
}
public static IntPtr INVALID_FILE_HANDLE = new IntPtr(-1);
public static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
public enum LogonType {
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK,
LOGON32_LOGON_BATCH,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEARTEXT,
LOGON32_LOGON_NEW_CREDENTIALS
}
public enum LogonProvider {
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_PROVIDER_WINNT35,
LOGON32_PROVIDER_WINNT40,
LOGON32_PROVIDER_WINNT50
}
[DllImport("msi.dll", CharSet = CharSet.Unicode)]
internal static extern MsiInstallState MsiGetComponentPath(string szProduct, string szComponent, [Out]StringBuilder lpPathBuf, ref uint pcchBuf);
/// <summary>
/// Buffer for lpProductBuf must be 39 characters long.
/// </summary>
/// <param name="szComponent"></param>
/// <param name="lpProductBuf"></param>
/// <returns></returns>
[DllImport("msi.dll", CharSet = CharSet.Unicode)]
internal static extern uint MsiGetProductCode(string szComponent, [Out]StringBuilder lpProductBuf);
internal enum MsiInstallState {
NotUsed = -7, // component disabled
BadConfig = -6, // configuration data corrupt
Incomplete = -5, // installation suspended or in progress
SourceAbsent = -4, // run from source, source is unavailable
MoreData = -3, // return buffer overflow
InvalidArg = -2, // invalid function argument
Unknown = -1, // unrecognized product or feature
Broken = 0, // broken
Advertised = 1, // advertised feature
Removed = 1, // component being removed (action state, not settable)
Absent = 2, // uninstalled (or action state absent but clients remain)
Local = 3, // installed on local drive
Source = 4, // run from source, CD or net
Default = 5 // use default, local or source
}
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern bool AllowSetForegroundWindow(int dwProcessId);
[DllImport("mpr", CharSet = CharSet.Unicode)]
public static extern uint WNetAddConnection3(IntPtr handle, ref _NETRESOURCE lpNetResource, string lpPassword, string lpUsername, uint dwFlags);
public const int CONNECT_INTERACTIVE = 0x08;
public const int CONNECT_PROMPT = 0x10;
public const int RESOURCETYPE_DISK = 1;
public struct _NETRESOURCE {
public uint dwScope;
public uint dwType;
public uint dwDisplayType;
public uint dwUsage;
public string lpLocalName;
public string lpRemoteName;
public string lpComment;
public string lpProvider;
}
[DllImport(ExternDll.Kernel32, EntryPoint = "GetFinalPathNameByHandleW", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetFinalPathNameByHandle(SafeFileHandle handle, [In, Out] StringBuilder path, int bufLen, int flags);
[DllImport(ExternDll.Kernel32, EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeFileHandle CreateFile(
string lpFileName,
int dwDesiredAccess,
[MarshalAs(UnmanagedType.U4)] FileShare dwShareMode,
IntPtr SecurityAttributes,
[MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition,
int dwFlagsAndAttributes,
IntPtr hTemplateFile);
/// <summary>
/// Given a directory, actual or symbolic, return the actual directory path.
/// </summary>
/// <param name="symlink">DirectoryInfo object for the suspected symlink.</param>
/// <returns>A string of the actual path.</returns>
internal static string GetAbsolutePathToDirectory(string symlink) {
const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
const int DEVICE_QUERY_ACCESS = 0;
using (SafeFileHandle directoryHandle = CreateFile(
symlink,
DEVICE_QUERY_ACCESS,
FileShare.Write,
System.IntPtr.Zero,
FileMode.Open,
FILE_FLAG_BACKUP_SEMANTICS,
System.IntPtr.Zero)) {
if (directoryHandle.IsInvalid) {
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
StringBuilder path = new StringBuilder(512);
int pathSize = GetFinalPathNameByHandle(directoryHandle, path, path.Capacity, 0);
if (pathSize < 0) {
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
// UNC Paths will start with \\?\. Remove this if present as this isn't really expected on a path.
var pathString = path.ToString();
return pathString.StartsWith(@"\\?\") ? pathString.Substring(4) : pathString;
}
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool FindClose(IntPtr hFindFile);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool DeleteFile(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool RemoveDirectory(string lpPathName);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool MoveFile(String src, String dst);
}
internal class CredUI {
private const string advapi32Dll = "advapi32.dll";
private const string credUIDll = "credui.dll";
public const int
ERROR_INVALID_FLAGS = 1004, // Invalid flags.
ERROR_NOT_FOUND = 1168, // Element not found.
ERROR_NO_SUCH_LOGON_SESSION = 1312, // A specified logon session does not exist. It may already have been terminated.
ERROR_LOGON_FAILURE = 1326; // Logon failure: unknown user name or bad password.
[Flags]
public enum CREDUI_FLAGS : uint {
INCORRECT_PASSWORD = 0x1,
DO_NOT_PERSIST = 0x2,
REQUEST_ADMINISTRATOR = 0x4,
EXCLUDE_CERTIFICATES = 0x8,
REQUIRE_CERTIFICATE = 0x10,
SHOW_SAVE_CHECK_BOX = 0x40,
ALWAYS_SHOW_UI = 0x80,
REQUIRE_SMARTCARD = 0x100,
PASSWORD_ONLY_OK = 0x200,
VALIDATE_USERNAME = 0x400,
COMPLETE_USERNAME = 0x800,
PERSIST = 0x1000,
SERVER_CREDENTIAL = 0x4000,
EXPECT_CONFIRMATION = 0x20000,
GENERIC_CREDENTIALS = 0x40000,
USERNAME_TARGET_CREDENTIALS = 0x80000,
KEEP_USERNAME = 0x100000,
}
[StructLayout(LayoutKind.Sequential)]
public class CREDUI_INFO {
public int cbSize;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
public IntPtr hwndParentCERParent;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszMessageText;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszCaptionText;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
public IntPtr hbmBannerCERHandle;
}
public enum CredUIReturnCodes : uint {
NO_ERROR = 0,
ERROR_CANCELLED = 1223,
ERROR_NO_SUCH_LOGON_SESSION = 1312,
ERROR_NOT_FOUND = 1168,
ERROR_INVALID_ACCOUNT_NAME = 1315,
ERROR_INSUFFICIENT_BUFFER = 122,
ERROR_INVALID_PARAMETER = 87,
ERROR_INVALID_FLAGS = 1004,
}
// Copied from wincred.h
public const uint
// Values of the Credential Type field.
CRED_TYPE_GENERIC = 1,
CRED_TYPE_DOMAIN_PASSWORD = 2,
CRED_TYPE_DOMAIN_CERTIFICATE = 3,
CRED_TYPE_DOMAIN_VISIBLE_PASSWORD = 4,
CRED_TYPE_MAXIMUM = 5, // Maximum supported cred type
CRED_TYPE_MAXIMUM_EX = (CRED_TYPE_MAXIMUM + 1000), // Allow new applications to run on old OSes
// String limits
CRED_MAX_CREDENTIAL_BLOB_SIZE = 512, // Maximum size of the CredBlob field (in bytes)
CRED_MAX_STRING_LENGTH = 256, // Maximum length of the various credential string fields (in characters)
CRED_MAX_USERNAME_LENGTH = (256 + 1 + 256), // Maximum length of the UserName field. The worst case is <User>@<DnsDomain>
CRED_MAX_GENERIC_TARGET_NAME_LENGTH = 32767, // Maximum length of the TargetName field for CRED_TYPE_GENERIC (in characters)
CRED_MAX_DOMAIN_TARGET_NAME_LENGTH = (256 + 1 + 80), // Maximum length of the TargetName field for CRED_TYPE_DOMAIN_* (in characters). Largest one is <DfsRoot>\<DfsShare>
CRED_MAX_VALUE_SIZE = 256, // Maximum size of the Credential Attribute Value field (in bytes)
CRED_MAX_ATTRIBUTES = 64, // Maximum number of attributes per credential
CREDUI_MAX_MESSAGE_LENGTH = 32767,
CREDUI_MAX_CAPTION_LENGTH = 128,
CREDUI_MAX_GENERIC_TARGET_LENGTH = CRED_MAX_GENERIC_TARGET_NAME_LENGTH,
CREDUI_MAX_DOMAIN_TARGET_LENGTH = CRED_MAX_DOMAIN_TARGET_NAME_LENGTH,
CREDUI_MAX_USERNAME_LENGTH = CRED_MAX_USERNAME_LENGTH,
CREDUI_MAX_PASSWORD_LENGTH = (CRED_MAX_CREDENTIAL_BLOB_SIZE / 2);
internal enum CRED_PERSIST : uint {
NONE = 0,
SESSION = 1,
LOCAL_MACHINE = 2,
ENTERPRISE = 3,
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct NativeCredential {
public uint flags;
public uint type;
public string targetName;
public string comment;
public int lastWritten_lowDateTime;
public int lastWritten_highDateTime;
public uint credentialBlobSize;
public IntPtr credentialBlob;
public uint persist;
public uint attributeCount;
public IntPtr attributes;
public string targetAlias;
public string userName;
};
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport(advapi32Dll, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CredReadW")]
public static extern bool
CredRead(
[MarshalAs(UnmanagedType.LPWStr)]
string targetName,
[MarshalAs(UnmanagedType.U4)]
uint type,
[MarshalAs(UnmanagedType.U4)]
uint flags,
out IntPtr credential
);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport(advapi32Dll, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CredWriteW")]
public static extern bool
CredWrite(
ref NativeCredential Credential,
[MarshalAs(UnmanagedType.U4)]
uint flags
);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport(advapi32Dll, SetLastError = true)]
public static extern bool
CredFree(
IntPtr buffer
);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport(credUIDll, EntryPoint = "CredUIPromptForCredentialsW", CharSet = CharSet.Unicode)]
public static extern CredUIReturnCodes CredUIPromptForCredentials(
CREDUI_INFO pUiInfo, // Optional (one can pass null here)
[MarshalAs(UnmanagedType.LPWStr)]
string targetName,
IntPtr Reserved, // Must be 0 (IntPtr.Zero)
int iError,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder pszUserName,
[MarshalAs(UnmanagedType.U4)]
uint ulUserNameMaxChars,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder pszPassword,
[MarshalAs(UnmanagedType.U4)]
uint ulPasswordMaxChars,
ref int pfSave,
CREDUI_FLAGS dwFlags);
/// <returns>
/// Win32 system errors:
/// NO_ERROR
/// ERROR_INVALID_ACCOUNT_NAME
/// ERROR_INSUFFICIENT_BUFFER
/// ERROR_INVALID_PARAMETER
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport(credUIDll, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CredUIParseUserNameW")]
public static extern CredUIReturnCodes CredUIParseUserName(
[MarshalAs(UnmanagedType.LPWStr)]
string strUserName,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder strUser,
[MarshalAs(UnmanagedType.U4)]
uint iUserMaxChars,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder strDomain,
[MarshalAs(UnmanagedType.U4)]
uint iDomainMaxChars
);
}
struct User32RECT {
public int left;
public int top;
public int right;
public int bottom;
public int Width {
get {
return right - left;
}
}
public int Height {
get {
return bottom - top;
}
}
}
[Guid("22F03340-547D-101B-8E65-08002B2BD119")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface ICreateErrorInfo {
int SetGUID(
ref Guid rguid
);
int SetSource(string szSource);
int SetDescription(string szDescription);
int SetHelpFile(string szHelpFile);
int SetHelpContext(uint dwHelpContext);
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct WIN32_FIND_DATA {
public uint dwFileAttributes;
public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwReserved0;
public uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
}
| |
#region License Agreement - READ THIS FIRST!!!
/*
**********************************************************************************
* Copyright (c) 2008, Kristian Trenskow *
* All rights reserved. *
**********************************************************************************
* This code is subject to terms of the BSD License. A copy of this license is *
* included with this software distribution in the file COPYING. If you do not *
* have a copy of, you can contain a copy by visiting this URL: *
* *
* http://www.opensource.org/licenses/bsd-license.php *
* *
* Replace <OWNER>, <ORGANISATION> and <YEAR> with the info in the above *
* copyright notice. *
* *
**********************************************************************************
*/
#endregion
using System;
using System.Net;
using System.Net.Sockets;
using System.Timers;
using ircsharp;
namespace ircsharp
{
internal class DccStateObject
{
internal const int BufferSize = 8192;
internal byte[] Buffer = new byte[BufferSize];
}
/// <summary>
/// Class used for DCC transfers and DCC chats. This class can only be instanced by Connection.
/// </summary>
public abstract class DCCBase : IRCBase
{
/// <summary>
/// Internal variable.
/// </summary>
protected Socket socket;
private Socket listenSocket;
/// <summary>
/// Internal variable.
/// </summary>
protected IPEndPoint RemoteEndPoint;
/// <summary>
/// Internal variable.
/// </summary>
protected string strNickname;
private Timer timer;
public event EventHandler EtablishTimeout;
public event EventHandler EtablishFailed;
private DCCContainerBase container;
private int intID = 0;
internal DCCBase(ServerConnection creatorsServerConnection, long RemoteHost, int Port, string Nickname, DCCContainerBase parent) : base(creatorsServerConnection)
{
container = parent;
intID = Port;
IPAddress ip = GetIP(RemoteHost);
RemoteEndPoint = new IPEndPoint(ip, Port);
strNickname = Nickname;
}
internal DCCBase(ServerConnection creatorsServerConnection, string Nickname, int Port, DCCContainerBase parent) : base(creatorsServerConnection)
{
strNickname = Nickname;
intID = Port;
container = parent;
listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
timer = new Timer(60000);
timer.Elapsed += new ElapsedEventHandler(TimerProc);
timer.AutoReset = true;
timer.Enabled = true;
listenSocket.Bind(new IPEndPoint(IPAddress.Any, Port));
listenSocket.Listen(100);
listenSocket.BeginAccept(new AsyncCallback(acceptCallback), null);
}
private IPAddress GetIP(long Host)
{
long[] ips = new long[] {0,0,0,0};
ips[0] = (long) Math.Floor((double)Host / (256*256*256));
Host = Host - (ips[0] * (256*256*256));
ips[1] = (long) Math.Floor((double)Host / (256*256));
Host = Host - (ips[1] * (256*256));
ips[2] = (long) Math.Floor((double)Host / 256);
Host = Host - (ips[2] * 256);
ips[3] = Host;
string strIP = ips[0].ToString() + "." + ips[1].ToString() + "." + ips[2].ToString() + "." + ips[3].ToString();
return Dns.GetHostEntry(strIP).AddressList[0];
}
/// <summary>
/// Internal function.
/// </summary>
protected void EtablishConnection()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.BeginConnect(RemoteEndPoint, new AsyncCallback(connectCallback), null);
}
/// <summary>
/// Internal function
/// </summary>
protected void CloseSocket()
{
if (socket!=null&&socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
container.Remove(this);
}
/// <summary>
/// Internal function.
/// </summary>
/// <param name="toSend"></param>
protected void SendData(string toSend)
{
SendData(System.Text.Encoding.Default.GetBytes(toSend), false);
}
/// <summary>
/// Internal function
/// </summary>
/// <param name="toSend"></param>
protected void SendData(byte[] toSend)
{
SendData(toSend, false);
}
/// <summary>
/// Internal function.
/// </summary>
/// <param name="toSend"></param>
/// <param name="blCloseAfterSend"></param>
protected void SendData(byte[] toSend, bool blCloseAfterSend)
{
if (socket.Connected)
socket.BeginSend(toSend, 0, toSend.Length, SocketFlags.None, new AsyncCallback(sendCallback), blCloseAfterSend);
}
/// <summary>
/// Internal function.
/// </summary>
protected abstract void Connected();
protected abstract void OnData(byte[] buffer, int Length);
protected abstract void Disconnected();
/// <summary>
/// Gets the nickname of the remote user.
/// </summary>
public string Nick
{
get { return strNickname; }
}
/// <summary>
/// Gets wheather the DCC is etablished.
/// </summary>
public bool Etablished
{
get { return socket.Connected; }
}
internal int Identifier
{
get { return intID; }
}
private void TimerProc(object sender, ElapsedEventArgs e)
{
listenSocket.Close();
if (EtablishTimeout!=null)
EtablishTimeout(this, new EventArgs());
container.Remove(this);
}
#region Socket Async functions
private void connectCallback(IAsyncResult ar)
{
try
{
socket.EndConnect(ar);
}
catch
{
if (EtablishFailed != null)
EtablishFailed(this, new EventArgs());
return;
}
if (socket.Connected)
{
DccStateObject dso = new DccStateObject();
socket.BeginReceive(dso.Buffer, 0, DccStateObject.BufferSize, SocketFlags.None, new AsyncCallback(receiveCallback), dso);
Connected();
}
else
{
CloseSocket();
if (EtablishFailed!=null)
EtablishFailed(this, new EventArgs());
container.Remove(this);
}
}
private void acceptCallback(IAsyncResult ar)
{
try
{
timer.Enabled = false;
socket = listenSocket.EndAccept(ar);
DccStateObject dso = new DccStateObject();
socket.BeginReceive(dso.Buffer, 0, DccStateObject.BufferSize, SocketFlags.None, new AsyncCallback(receiveCallback), dso);
listenSocket.Close();
if (socket.Connected)
Connected();
else
{
if (EtablishFailed!=null)
EtablishFailed(this, new EventArgs());
container.Remove(this);
}
}
catch
{
if (EtablishFailed!=null)
EtablishFailed(this, new EventArgs());
container.Remove(this);
}
}
private void receiveCallback(IAsyncResult ar)
{
DccStateObject dso = (DccStateObject) ar.AsyncState;
try
{
int intRead = socket.EndReceive(ar);
if (intRead>0)
{
OnData(dso.Buffer, intRead);
socket.BeginReceive(dso.Buffer, 0, DccStateObject.BufferSize, SocketFlags.None, new AsyncCallback(receiveCallback), dso);
}
else
{
CloseSocket();
Disconnected();
container.Remove(this);
}
}
catch
{
CloseSocket();
Disconnected();
container.Remove(this);
}
}
private void sendCallback(IAsyncResult ar)
{
if ((bool) ar.AsyncState)
{
Disconnected();
CloseSocket();
}
}
#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.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This Class defines behaviors specific to a writing system.
// A writing system is the collection of scripts and
// orthographic rules required to represent a language as text.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Text;
namespace System.Globalization
{
public partial class TextInfo : ICloneable, IDeserializationCallback
{
////--------------------------------------------------------------------//
//// Internal Information //
////--------------------------------------------------------------------//
private enum Tristate : byte
{
NotInitialized,
True,
False,
}
////
//// Variables.
////
private String _listSeparator;
private bool _isReadOnly = false;
//// _cultureName is the name of the creating culture. Note that we consider this authoratative,
//// if the culture's textinfo changes when deserializing, then behavior may change.
//// (ala Whidbey behavior). This is the only string Arrowhead needs to serialize.
//// _cultureData is the data that backs this class.
//// _textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO)
//// this can be the same as _cultureName on Silverlight since the OS knows
//// how to do the sorting. However in the desktop, when we call the sorting dll, it doesn't
//// know how to resolve custom locle names to sort ids so we have to have alredy resolved this.
////
private readonly String _cultureName; // Name of the culture that created this text info
private CultureData _cultureData; // Data record for the culture that made us, not for this textinfo
private String _textInfoName; // Name of the text info we're using (ie: _cultureData.STEXTINFO)
private Tristate _isAsciiCasingSameAsInvariant = Tristate.NotInitialized;
// Invariant text info
internal static TextInfo Invariant
{
get
{
if (s_Invariant == null)
s_Invariant = new TextInfo(CultureData.Invariant);
return s_Invariant;
}
}
internal volatile static TextInfo s_Invariant;
void IDeserializationCallback.OnDeserialization(Object sender)
{
throw new PlatformNotSupportedException();
}
//
// Internal ordinal comparison functions
//
internal static int GetHashCodeOrdinalIgnoreCase(String s)
{
// This is the same as an case insensitive hash for Invariant
// (not necessarily true for sorting, but OK for casing & then we apply normal hash code rules)
return (Invariant.GetCaseInsensitiveHashCode(s));
}
// Currently we don't have native functions to do this, so we do it the hard way
internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
if (count > source.Length || count < 0 || startIndex < 0 || startIndex >= source.Length || startIndex + count > source.Length)
{
return -1;
}
return CompareInfo.IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
// Currently we don't have native functions to do this, so we do it the hard way
internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
if (count > source.Length || count < 0 || startIndex < 0 || startIndex > source.Length - 1 || (startIndex - count + 1 < 0))
{
return -1;
}
return CompareInfo.LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
////////////////////////////////////////////////////////////////////////
//
// CodePage
//
// Returns the number of the code page used by this writing system.
// The type parameter can be any of the following values:
// ANSICodePage
// OEMCodePage
// MACCodePage
//
////////////////////////////////////////////////////////////////////////
public virtual int ANSICodePage
{
get
{
return (_cultureData.IDEFAULTANSICODEPAGE);
}
}
public virtual int OEMCodePage
{
get
{
return (_cultureData.IDEFAULTOEMCODEPAGE);
}
}
public virtual int MacCodePage
{
get
{
return (_cultureData.IDEFAULTMACCODEPAGE);
}
}
public virtual int EBCDICCodePage
{
get
{
return (_cultureData.IDEFAULTEBCDICCODEPAGE);
}
}
public int LCID
{
get
{
// Just use the LCID from our text info name
return CultureInfo.GetCultureInfo(_textInfoName).LCID;
}
}
//////////////////////////////////////////////////////////////////////////
////
//// CultureName
////
//// The name of the culture associated with the current TextInfo.
////
//////////////////////////////////////////////////////////////////////////
public string CultureName
{
get
{
return _textInfoName;
}
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
public bool IsReadOnly
{
get { return (_isReadOnly); }
}
//////////////////////////////////////////////////////////////////////////
////
//// Clone
////
//// Is the implementation of ICloneable.
////
//////////////////////////////////////////////////////////////////////////
public virtual object Clone()
{
object o = MemberwiseClone();
((TextInfo)o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
public static TextInfo ReadOnly(TextInfo textInfo)
{
if (textInfo == null) { throw new ArgumentNullException(nameof(textInfo)); }
Contract.EndContractBlock();
if (textInfo.IsReadOnly) { return (textInfo); }
TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone());
clonedTextInfo.SetReadOnlyState(true);
return (clonedTextInfo);
}
private void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
_isReadOnly = readOnly;
}
////////////////////////////////////////////////////////////////////////
//
// ListSeparator
//
// Returns the string used to separate items in a list.
//
////////////////////////////////////////////////////////////////////////
public virtual String ListSeparator
{
get
{
if (_listSeparator == null)
{
_listSeparator = _cultureData.SLIST;
}
return (_listSeparator);
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String);
}
VerifyWritable();
_listSeparator = value;
}
}
////////////////////////////////////////////////////////////////////////
//
// ToLower
//
// Converts the character or string to lower case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual char ToLower(char c)
{
if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
{
return ToLowerAsciiInvariant(c);
}
return (ChangeCase(c, toUpper: false));
}
public unsafe virtual String ToLower(String str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
return ChangeCase(str, toUpper: false);
}
private static Char ToLowerAsciiInvariant(Char c)
{
if ((uint)(c - 'A') <= (uint)('Z' - 'A'))
{
c = (Char)(c | 0x20);
}
return c;
}
////////////////////////////////////////////////////////////////////////
//
// ToUpper
//
// Converts the character or string to upper case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual char ToUpper(char c)
{
if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
{
return ToUpperAsciiInvariant(c);
}
return (ChangeCase(c, toUpper: true));
}
public unsafe virtual String ToUpper(String str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
return ChangeCase(str, toUpper: true);
}
private static Char ToUpperAsciiInvariant(Char c)
{
if ((uint)(c - 'a') <= (uint)('z' - 'a'))
{
c = (Char)(c & ~0x20);
}
return c;
}
private static bool IsAscii(Char c)
{
return c < 0x80;
}
private bool IsAsciiCasingSameAsInvariant
{
get
{
if (_isAsciiCasingSameAsInvariant == Tristate.NotInitialized)
{
_isAsciiCasingSameAsInvariant = CultureInfo.GetCultureInfo(_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
CompareOptions.IgnoreCase) == 0 ? Tristate.True : Tristate.False;
}
return _isAsciiCasingSameAsInvariant == Tristate.True;
}
}
// IsRightToLeft
//
// Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars
//
public bool IsRightToLeft
{
get
{
return _cultureData.IsRightToLeft;
}
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CultureInfo as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object obj)
{
TextInfo that = obj as TextInfo;
if (that != null)
{
return this.CultureName.Equals(that.CultureName);
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for CultureInfo A
// and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.CultureName.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// TextInfo.
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return ("TextInfo - " + _cultureData.CultureName);
}
//
// Titlecasing:
// -----------
// Titlecasing refers to a casing practice wherein the first letter of a word is an uppercase letter
// and the rest of the letters are lowercase. The choice of which words to titlecase in headings
// and titles is dependent on language and local conventions. For example, "The Merry Wives of Windor"
// is the appropriate titlecasing of that play's name in English, with the word "of" not titlecased.
// In German, however, the title is "Die lustigen Weiber von Windsor," and both "lustigen" and "von"
// are not titlecased. In French even fewer words are titlecased: "Les joyeuses commeres de Windsor."
//
// Moreover, the determination of what actually constitutes a word is language dependent, and this can
// influence which letter or letters of a "word" are uppercased when titlecasing strings. For example
// "l'arbre" is considered two words in French, whereas "can't" is considered one word in English.
//
public unsafe String ToTitleCase(String str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
if (str.Length == 0)
{
return (str);
}
StringBuilder result = new StringBuilder();
string lowercaseData = null;
// Store if the current culture is Dutch (special case)
bool isDutchCulture = CultureName.StartsWith("nl-", StringComparison.OrdinalIgnoreCase);
for (int i = 0; i < str.Length; i++)
{
UnicodeCategory charType;
int charLen;
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
if (Char.CheckLetter(charType))
{
// Special case to check for Dutch specific titlecasing with "IJ" characters
// at the beginning of a word
if (isDutchCulture && i < str.Length - 1 && (str[i] == 'i' || str[i] == 'I') && (str[i + 1] == 'j' || str[i + 1] == 'J'))
{
result.Append("IJ");
i += 2;
}
else
{
// Do the titlecasing for the first character of the word.
i = AddTitlecaseLetter(ref result, ref str, i, charLen) + 1;
}
//
// Convert the characters until the end of the this word
// to lowercase.
//
int lowercaseStart = i;
//
// Use hasLowerCase flag to prevent from lowercasing acronyms (like "URT", "USA", etc)
// This is in line with Word 2000 behavior of titlecasing.
//
bool hasLowerCase = (charType == UnicodeCategory.LowercaseLetter);
// Use a loop to find all of the other letters following this letter.
while (i < str.Length)
{
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
if (IsLetterCategory(charType))
{
if (charType == UnicodeCategory.LowercaseLetter)
{
hasLowerCase = true;
}
i += charLen;
}
else if (str[i] == '\'')
{
i++;
if (hasLowerCase)
{
if (lowercaseData == null)
{
lowercaseData = this.ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, i - lowercaseStart);
}
else
{
result.Append(str, lowercaseStart, i - lowercaseStart);
}
lowercaseStart = i;
hasLowerCase = true;
}
else if (!IsWordSeparator(charType))
{
// This category is considered to be part of the word.
// This is any category that is marked as false in wordSeprator array.
i += charLen;
}
else
{
// A word separator. Break out of the loop.
break;
}
}
int count = i - lowercaseStart;
if (count > 0)
{
if (hasLowerCase)
{
if (lowercaseData == null)
{
lowercaseData = this.ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, count);
}
else
{
result.Append(str, lowercaseStart, count);
}
}
if (i < str.Length)
{
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
else
{
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
return (result.ToString());
}
private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
if (charLen == 2)
{
// Surrogate pair
result.Append(input[inputIndex++]);
result.Append(input[inputIndex]);
}
else
{
result.Append(input[inputIndex]);
}
return inputIndex;
}
private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
// for surrogate pairs do a simple ToUpper operation on the substring
if (charLen == 2)
{
// Surrogate pair
result.Append(ToUpper(input.Substring(inputIndex, charLen)));
inputIndex++;
}
else
{
switch (input[inputIndex])
{
//
// For AppCompat, the Titlecase Case Mapping data from NDP 2.0 is used below.
case (char)0x01C4: // DZ with Caron -> Dz with Caron
case (char)0x01C5: // Dz with Caron -> Dz with Caron
case (char)0x01C6: // dz with Caron -> Dz with Caron
result.Append((char)0x01C5);
break;
case (char)0x01C7: // LJ -> Lj
case (char)0x01C8: // Lj -> Lj
case (char)0x01C9: // lj -> Lj
result.Append((char)0x01C8);
break;
case (char)0x01CA: // NJ -> Nj
case (char)0x01CB: // Nj -> Nj
case (char)0x01CC: // nj -> Nj
result.Append((char)0x01CB);
break;
case (char)0x01F1: // DZ -> Dz
case (char)0x01F2: // Dz -> Dz
case (char)0x01F3: // dz -> Dz
result.Append((char)0x01F2);
break;
default:
result.Append(ToUpper(input[inputIndex]));
break;
}
}
return inputIndex;
}
//
// Used in ToTitleCase():
// When we find a starting letter, the following array decides if a category should be
// considered as word seprator or not.
//
private const int c_wordSeparatorMask =
/* false */ (0 << 0) | // UppercaseLetter = 0,
/* false */ (0 << 1) | // LowercaseLetter = 1,
/* false */ (0 << 2) | // TitlecaseLetter = 2,
/* false */ (0 << 3) | // ModifierLetter = 3,
/* false */ (0 << 4) | // OtherLetter = 4,
/* false */ (0 << 5) | // NonSpacingMark = 5,
/* false */ (0 << 6) | // SpacingCombiningMark = 6,
/* false */ (0 << 7) | // EnclosingMark = 7,
/* false */ (0 << 8) | // DecimalDigitNumber = 8,
/* false */ (0 << 9) | // LetterNumber = 9,
/* false */ (0 << 10) | // OtherNumber = 10,
/* true */ (1 << 11) | // SpaceSeparator = 11,
/* true */ (1 << 12) | // LineSeparator = 12,
/* true */ (1 << 13) | // ParagraphSeparator = 13,
/* true */ (1 << 14) | // Control = 14,
/* true */ (1 << 15) | // Format = 15,
/* false */ (0 << 16) | // Surrogate = 16,
/* false */ (0 << 17) | // PrivateUse = 17,
/* true */ (1 << 18) | // ConnectorPunctuation = 18,
/* true */ (1 << 19) | // DashPunctuation = 19,
/* true */ (1 << 20) | // OpenPunctuation = 20,
/* true */ (1 << 21) | // ClosePunctuation = 21,
/* true */ (1 << 22) | // InitialQuotePunctuation = 22,
/* true */ (1 << 23) | // FinalQuotePunctuation = 23,
/* true */ (1 << 24) | // OtherPunctuation = 24,
/* true */ (1 << 25) | // MathSymbol = 25,
/* true */ (1 << 26) | // CurrencySymbol = 26,
/* true */ (1 << 27) | // ModifierSymbol = 27,
/* true */ (1 << 28) | // OtherSymbol = 28,
/* false */ (0 << 29); // OtherNotAssigned = 29;
private static bool IsWordSeparator(UnicodeCategory category)
{
return (c_wordSeparatorMask & (1 << (int)category)) != 0;
}
private static bool IsLetterCategory(UnicodeCategory uc)
{
return (uc == UnicodeCategory.UppercaseLetter
|| uc == UnicodeCategory.LowercaseLetter
|| uc == UnicodeCategory.TitlecaseLetter
|| uc == UnicodeCategory.ModifierLetter
|| uc == UnicodeCategory.OtherLetter);
}
//
// Get case-insensitive hash code for the specified string.
//
internal unsafe int GetCaseInsensitiveHashCode(String str)
{
// Validate inputs
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
// This code assumes that ASCII casing is safe for whatever context is passed in.
// this is true today, because we only ever call these methods on Invariant. It would be ideal to refactor
// these methods so they were correct by construction and we could only ever use Invariant.
uint hash = 5381;
uint c;
// Note: We assume that str contains only ASCII characters until
// we hit a non-ASCII character to optimize the common case.
for (int i = 0; i < str.Length; i++)
{
c = str[i];
if (c >= 0x80)
{
return GetCaseInsensitiveHashCodeSlow(str);
}
// If we have a lowercase character, ANDing off 0x20
// will make it an uppercase character.
if ((c - 'a') <= ('z' - 'a'))
{
c = (uint)((int)c & ~0x20);
}
hash = ((hash << 5) + hash) ^ c;
}
return (int)hash;
}
private unsafe int GetCaseInsensitiveHashCodeSlow(String str)
{
Debug.Assert(str != null);
string upper = ToUpper(str);
uint hash = 5381;
uint c;
for (int i = 0; i < upper.Length; i++)
{
c = upper[i];
hash = ((hash << 5) + hash) ^ c;
}
return (int)hash;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmAddProcedure.
/// </summary>
public partial class frmUpdProject : System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
public SqlConnection epsDbConn=new SqlConnection(strDB);
private int GetIndexOfVisibility (string s)
{
return (lstVisibility.Items.IndexOf (lstVisibility.Items.FindByValue(s)));
}
private int GetIndexOfType (string s)
{
return (lstType.Items.IndexOf (lstType.Items.FindByValue(s)));
}
/*private int GetIndexOfLocs (string s)
{
return (lstLocations.Items.IndexOf (lstLocations.Items.FindByValue(s)));
}*/
private int GetIndexOfStatus (string s)
{
switch(s)
{
case "Planned":
return 0;
case "Started":
return 1;
case "Completed":
return 2;
case "Cancelled":
return 3;
default:
return 0;
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
if (Session["MgrName"] != null)
{
lblMgr.Text=Session["MgrName"].ToString();
}
else
{
lblMgr.Text=Session["OrgName"].ToString();
}
/*lblBud.Text = "Budget: " + Session["BudName"].ToString();*/
lblService.Text="Service: " + Session["ServiceName"].ToString();
lblLocation.Text="Location: " + Session["LocName"].ToString();
if (Session["CProjects"] == "frmPSEvents")
{
lblEventName.Text = "Type of " + Session["PJNameS"].ToString() + ": " + Session["EventName"].ToString();
}
else if (Session["CProjects"] == "frmOrgLocServices")
{
lblEventName.Text = "";
}
loadVisibility();
//loadType();
if (Session["ProjectId"] == null)
{
btnAction.Text= "Add";
lblContents1.Text="Add " + Session["PJNameS"].ToString();
}
else
{
btnAction.Text= "OK";
lblContents1.Text="Update " + Session["PJNameS"].ToString();
lblProj.Text=Session["PJNameS"].ToString()
+ ": "
+ Session["ProjName"].ToString();
projData();
}
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
private void projData()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="wms_RetrieveProjdata";
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=Session["ProjectId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"Projdata");
txtName.Text=ds.Tables["Projdata"].Rows[0][0].ToString();
rblStatus.SelectedIndex=GetIndexOfStatus(ds.Tables["Projdata"].Rows[0][1].ToString());
lstVisibility.SelectedIndex=GetIndexOfVisibility(ds.Tables["Projdata"].Rows[0][2].ToString());
txtStartTime.Text=ds.Tables["Projdata"].Rows[0][3].ToString();
txtEndTime.Text=ds.Tables["Projdata"].Rows[0][4].ToString();
txtDesc.Text=ds.Tables["Projdata"].Rows[0][5].ToString();
//lstType.SelectedIndex=GetIndexOfType(ds.Tables["Projdata"].Rows[0][5].ToString());
/*lstLocations.SelectedIndex=
GetIndexOfLocs(ds.Tables["StaffAction"].Rows[0][5].ToString());*/
}
/*private void loadLocs()
{
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_RetrieveLocations";
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int);
cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString();
cmd.Parameters.Add ("@LicenseId",SqlDbType.Int);
cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString();
cmd.Parameters.Add ("@DomainId",SqlDbType.Int);
cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"Locations");
lstLocations.DataSource = ds;
lstLocations.DataMember= "Locations";
lstLocations.DataTextField = "Name";
lstLocations.DataValueField = "Id";
lstLocations.DataBind();
}*/
private void loadVisibility()
{
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="ams_RetrieveVisibility";
cmd.Parameters.Add ("@Vis",SqlDbType.Int);
cmd.Parameters["@Vis"].Value=Session["OrgVis"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"Visibility");
lstVisibility.DataSource = ds;
lstVisibility.DataMember= "Visibility";
lstVisibility.DataTextField = "Name";
lstVisibility.DataValueField = "Id";
lstVisibility.DataBind();
}
/*private void loadType()
{
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_RetrieveProjectType";
cmd.Parameters.Add ("@PSEPID",SqlDbType.Int);
cmd.Parameters["@PSEPID"].Value=Session["PSEPID"].ToString();
cmd.Parameters.Add ("@ProfileId",SqlDbType.Int);
cmd.Parameters["@ProfileId"].Value=Session["ProfileId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"Type");
lstType.DataSource = ds;
lstType.DataMember= "Type";
lstType.DataTextField = "Name";
lstType.DataValueField = "Id";
lstType.DataBind();
}*/
protected void btnAction_Click(object sender, System.EventArgs e)
{
{
if (btnAction.Text == "OK")
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_UpdateProject";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=Int32.Parse(Session["ProjectId"].ToString());
cmd.Parameters.Add ("@Name",SqlDbType.NVarChar);
cmd.Parameters["@Name"].Value=txtName.Text;
cmd.Parameters.Add ("@Desc",SqlDbType.NVarChar);
cmd.Parameters["@Desc"].Value=txtDesc.Text;
cmd.Parameters.Add ("@Vis",SqlDbType.Int);
cmd.Parameters["@Vis"].Value=lstVisibility.SelectedItem.Value;
cmd.Parameters.Add ("@Status",SqlDbType.NVarChar);
cmd.Parameters["@Status"].Value=rblStatus.SelectedItem.Value;
cmd.Parameters.Add ("@StartTime",SqlDbType.SmallDateTime);
if (txtStartTime.Text != "") cmd.Parameters["@StartTime"].Value=txtStartTime.Text;
else cmd.Parameters["@StartTime"].Value = null;
cmd.Parameters.Add ("@EndTime",SqlDbType.SmallDateTime);
if (txtEndTime.Text != "") cmd.Parameters["@EndTime"].Value=txtEndTime.Text;
else cmd.Parameters["@EndTime"].Value = null;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Done();
}
catch
{
lblDate.ForeColor=Color.Orange;
}
else if (btnAction.Text == "Add")
{
try
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_AddProject";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Name",SqlDbType.NVarChar);
cmd.Parameters["@Name"].Value= txtName.Text;
cmd.Parameters.Add ("@Desc",SqlDbType.NVarChar);
cmd.Parameters["@Desc"].Value=txtDesc.Text;
cmd.Parameters.Add ("@Status",SqlDbType.NVarChar);
cmd.Parameters["@Status"].Value=rblStatus.SelectedItem.Value;
cmd.Parameters.Add ("@Vis",SqlDbType.Int);
cmd.Parameters["@Vis"].Value=lstVisibility.SelectedItem.Value;
cmd.Parameters.Add ("@PSEventsId",SqlDbType.Int);
cmd.Parameters["@PSEventsId"].Value=Session["PSEventsId"].ToString();
/*cmd.Parameters.Add ("@ProjectTypesId",SqlDbType.Int);
cmd.Parameters["@ProjectTypesId"].Value=lstType.SelectedItem.Value;*/
cmd.Parameters.Add ("@StartTime",SqlDbType.SmallDateTime);
if (txtStartTime.Text != "") cmd.Parameters["@StartTime"].Value=txtStartTime.Text;
else cmd.Parameters["@StartTime"].Value = null;
cmd.Parameters.Add ("@EndTime",SqlDbType.SmallDateTime);
if (txtEndTime.Text != "") cmd.Parameters["@EndTime"].Value=txtEndTime.Text;
else cmd.Parameters["@EndTime"].Value = null;
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString();
cmd.Parameters.Add("@LocationsId", SqlDbType.Int);
cmd.Parameters["@LocationsId"].Value = Session["LocationsId"].ToString();
//cmd.Parameters.Add ("@ProjectTypesId",SqlDbType.Int);
//cmd.Parameters["@ProjectTypesId"].Value=Session["ProjectTypesId"].ToString();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
//retrieveProjPeople();
Done();
}
catch
{
lblDate.ForeColor=Color.Orange;
}
}
}
}
/*private void retrieveProjPeople()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="wms_RetrieveProjdataNew";
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=Session["ProjectId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"Projdata");
txtName.Text=ds.Tables["Projdata"].Rows[0][0].ToString();
rblStatus.SelectedIndex=GetIndexOfStatus(ds.Tables["Projdata"].Rows[0][1].ToString());
lblStatus.Text="Current Status: " + ds.Tables["Projdata"].Rows[0][1].ToString();
lstVisibility.SelectedIndex=GetIndexOfVisibility(ds.Tables["Projdata"].Rows[0][2].ToString());
txtStartTime.Text=ds.Tables["Projdata"].Rows[0][3].ToString();
txtEndTime.Text=ds.Tables["Projdata"].Rows[0][4].ToString();
}
private void updateProjPeople()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_UpdateProjectsPeople";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@ProjectId", SqlDbType.Int);
cmd.Parameters ["@ProjectId"].Value=I;
cmd.Parameters.Add("@PeopleId", SqlDbType.Int);
cmd.Parameters ["@PeopleId"].Value=Session["PeopleId"].ToString();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}*/
private void Done()
{
if (Session["startForm"].ToString() == "frmMainOrgLocInd")
{
Session["ProjectId"]=null;
}
Response.Redirect (strURL + Session["CUpdProject"].ToString() + ".aspx?");
}
protected void btnCancel_Click(object sender, System.EventArgs e)
{
Done();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Factotum
{
public partial class MeterView : Form
{
// ----------------------------------------------------------------------
// Initialization
// ----------------------------------------------------------------------
// Form constructor
public MeterView()
{
InitializeComponent();
// Take care of settings that are not as easily managed in the designer.
InitializeControls();
}
// Take care of the non-default DataGridView settings that are not as easily managed
// in the designer.
private void InitializeControls()
{
}
// Set the status filter to show active tools by default
// and update the tool selector combo box
private void MeterView_Load(object sender, EventArgs e)
{
// Set the status combo first. The selector DataGridView depends on it.
cboStatusFilter.SelectedIndex = (int)FilterActiveStatus.ShowActive;
// Apply the current filters and set the selector row.
// Passing a null selects the first row if there are any rows.
UpdateSelector(null);
// Now that we have some rows and columns, we can do some customization.
CustomizeGrid();
// Need to do this because the customization clears the row selection.
SelectGridRow(null);
// Wire up the handler for the Entity changed event
EMeter.Changed += new EventHandler<EntityChangedEventArgs>(EMeter_Changed);
}
private void MeterView_FormClosed(object sender, FormClosedEventArgs e)
{
EMeter.Changed -= new EventHandler<EntityChangedEventArgs>(EMeter_Changed);
}
// ----------------------------------------------------------------------
// Event Handlers
// ----------------------------------------------------------------------
// If any of this type of entity object was saved or deleted, we want to update the selector
// The event args contain the ID of the entity that was added, mofified or deleted.
void EMeter_Changed(object sender, EntityChangedEventArgs e)
{
UpdateSelector(e.ID);
}
// Handle the user's decision to edit the current tool
private void EditCurrentSelection()
{
// Make sure there's a row selected
if (dgvMeters.SelectedRows.Count != 1) return;
Guid? currentEditItem = (Guid?)(dgvMeters.SelectedRows[0].Cells["ID"].Value);
// First check to see if an instance of the form set to the selected ID already exists
if (!Globals.CanActivateForm(this, "MeterEdit",currentEditItem))
{
// Open the edit form with the currently selected ID.
MeterEdit frm = new MeterEdit(currentEditItem);
frm.MdiParent = this.MdiParent;
frm.Show();
}
}
// This handles the datagridview double-click as well as button click
void btnEdit_Click(object sender, System.EventArgs e)
{
EditCurrentSelection();
}
private void dgvMeters_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
EditCurrentSelection();
}
// Handle the user's decision to add a new tool
private void btnAdd_Click(object sender, EventArgs e)
{
MeterEdit frm = new MeterEdit();
frm.MdiParent = this.MdiParent;
frm.Show();
}
// Handle the user's decision to delete the selected tool
private void btnDelete_Click(object sender, EventArgs e)
{
if (dgvMeters.SelectedRows.Count != 1)
{
MessageBox.Show("Please select a Meter to delete first.", "Factotum");
return;
}
Guid? currentEditItem = (Guid?)(dgvMeters.SelectedRows[0].Cells["ID"].Value);
if (Globals.IsFormOpen(this, "MeterEdit", currentEditItem))
{
MessageBox.Show("Can't delete because that item is currently being edited.", "Factotum");
return;
}
EMeter Meter = new EMeter(currentEditItem);
Meter.Delete(true);
if (Meter.MeterErrMsg != null)
{
MessageBox.Show(Meter.MeterErrMsg, "Factotum");
Meter.MeterErrMsg = null;
}
}
// The user changed the status filter setting, so update the selector combo.
private void cboStatus_SelectedIndexChanged(object sender, EventArgs e)
{
ApplyFilters();
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
// ----------------------------------------------------------------------
// Private utilities
// ----------------------------------------------------------------------
// Update the tool selector combo box by filling its items based on current data and filters.
// Then set the currently displayed item to that of the supplied ID.
// If the supplied ID isn't on the list because of the current filter state, just show the
// first item if there is one.
private void UpdateSelector(Guid? id)
{
// Save the sort specs if there are any, so we can re-apply them
SortOrder sortOrder = dgvMeters.SortOrder;
int sortCol = -1;
if (sortOrder != SortOrder.None)
sortCol = dgvMeters.SortedColumn.Index;
// Update the grid view selector
DataView dv = EMeter.GetDefaultDataView();
dgvMeters.DataSource = dv;
ApplyFilters();
// Re-apply the sort specs
if (sortOrder == SortOrder.Ascending)
dgvMeters.Sort(dgvMeters.Columns[sortCol], ListSortDirection.Ascending);
else if (sortOrder == SortOrder.Descending)
dgvMeters.Sort(dgvMeters.Columns[sortCol], ListSortDirection.Descending);
// Select the current row
SelectGridRow(id);
}
private void CustomizeGrid()
{
// Apply a default sort
dgvMeters.Sort(dgvMeters.Columns["MeterSerialNumber"], ListSortDirection.Ascending);
// Fix up the column headings
dgvMeters.Columns["MeterSerialNumber"].HeaderText = "Serial Number";
dgvMeters.Columns["MeterModelName"].HeaderText = "Model Name";
dgvMeters.Columns["MeterKitName"].HeaderText = "Kit";
dgvMeters.Columns["MeterIsActive"].HeaderText = "Active";
// Hide some columns
dgvMeters.Columns["ID"].Visible = false;
dgvMeters.Columns["MeterIsActive"].Visible = false;
dgvMeters.Columns["MeterIsLclChg"].Visible = false;
dgvMeters.Columns["MeterUsedInOutage"].Visible = false;
dgvMeters.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
}
// Apply the current filters to the DataView. The DataGridView will auto-refresh.
private void ApplyFilters()
{
if (dgvMeters.DataSource == null) return;
StringBuilder sb = new StringBuilder("MeterIsActive = ", 255);
sb.Append(cboStatusFilter.SelectedIndex == (int)FilterActiveStatus.ShowActive ? "'Yes'" : "'No'");
DataView dv = (DataView)dgvMeters.DataSource;
dv.RowFilter = sb.ToString();
}
// Select the row with the specified ID if it is currently displayed and scroll to it.
// If the ID is not in the list,
private void SelectGridRow(Guid? id)
{
bool found = false;
int rows = dgvMeters.Rows.Count;
if (rows == 0) return;
int r = 0;
DataGridViewCell firstCell = dgvMeters.FirstDisplayedCell;
if (id != null)
{
// Find the row with the specified key id and select it.
for (r = 0; r < rows; r++)
{
if ((Guid?)dgvMeters.Rows[r].Cells["ID"].Value == id)
{
dgvMeters.CurrentCell = dgvMeters[firstCell.ColumnIndex, r];
dgvMeters.Rows[r].Selected = true;
found = true;
break;
}
}
}
if (found)
{
if (!dgvMeters.Rows[r].Displayed)
{
// Scroll to the selected row if the ID was in the list.
dgvMeters.FirstDisplayedScrollingRowIndex = r;
}
}
else
{
// Select the first item
dgvMeters.CurrentCell = firstCell;
dgvMeters.Rows[0].Selected = true;
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Threading;
namespace EarLab.Viewers.Layouts
{
/// <summary>
/// Summary description for Layout2DColor.
/// </summary>
public class Layout2DColor : System.Windows.Forms.UserControl
{
private EarLab.Viewers.Panels.PanelAxisNew viewerAxisPanel;
private EarLab.Viewers.Panels.PanelAxisNew colorbarAxisPanel;
private EarLab.Viewers.Panels.PanelColorbarNew colorbarPanel;
private EarLab.Viewers.Panels.Panel2DColor viewerPanel;
private System.Windows.Forms.Panel backgroundPanel;
private BackgroundWorker backgroundWorker;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private double[,] dataArray;
private Bitmap viewerBitmap;
public Layout2DColor()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// we set the axes controls to know what controls they are hosting
this.viewerAxisPanel.TopAxisControl = this.viewerPanel;
this.viewerAxisPanel.LeftAxisControl = this.viewerPanel;
this.viewerAxisPanel.BottomAxisControl = this.viewerPanel;
this.colorbarAxisPanel.RightAxisControl = this.colorbarPanel;
this.backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
}
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.backgroundPanel = new System.Windows.Forms.Panel();
this.colorbarPanel = new EarLab.Viewers.Panels.PanelColorbarNew();
this.colorbarAxisPanel = new EarLab.Viewers.Panels.PanelAxisNew();
this.viewerAxisPanel = new EarLab.Viewers.Panels.PanelAxisNew();
this.viewerPanel = new EarLab.Viewers.Panels.Panel2DColor();
this.backgroundWorker = new System.ComponentModel.BackgroundWorker();
this.backgroundPanel.SuspendLayout();
this.viewerAxisPanel.SuspendLayout();
this.SuspendLayout();
//
// backgroundPanel
//
this.backgroundPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.backgroundPanel.BackColor = System.Drawing.Color.White;
this.backgroundPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.backgroundPanel.Controls.Add(this.colorbarPanel);
this.backgroundPanel.Controls.Add(this.colorbarAxisPanel);
this.backgroundPanel.Controls.Add(this.viewerAxisPanel);
this.backgroundPanel.Location = new System.Drawing.Point(0, 0);
this.backgroundPanel.Name = "backgroundPanel";
this.backgroundPanel.Size = new System.Drawing.Size(584, 232);
this.backgroundPanel.TabIndex = 3;
//
// colorbarPanel
//
this.colorbarPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.colorbarPanel.BackColor = System.Drawing.SystemColors.Control;
this.colorbarPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.colorbarPanel.Cursor = System.Windows.Forms.Cursors.SizeAll;
this.colorbarPanel.Location = new System.Drawing.Point(478, 24);
this.colorbarPanel.Name = "colorbarPanel";
this.colorbarPanel.Size = new System.Drawing.Size(40, 174);
this.colorbarPanel.TabIndex = 2;
this.colorbarPanel.CurrentValuesChanged += new EarLab.Viewers.Panels.PanelColorbarNew.CurrentValuesChangedHandler(this.colorbarPanel_CurrentValuesChanged);
//
// colorbarAxisPanel
//
this.colorbarAxisPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.colorbarAxisPanel.BottomAxisEndValue = 0F;
this.colorbarAxisPanel.BottomAxisLabel = "Axis Label Not Set";
this.colorbarAxisPanel.BottomAxisLabelShow = true;
this.colorbarAxisPanel.BottomAxisMajorTickHeight = 3;
this.colorbarAxisPanel.BottomAxisMajorTickNumbersFormat = "0";
this.colorbarAxisPanel.BottomAxisMajorTickNumbersShow = true;
this.colorbarAxisPanel.BottomAxisMajorTickNumbersSpacing = 10;
this.colorbarAxisPanel.BottomAxisMajorTickOffset = 2;
this.colorbarAxisPanel.BottomAxisShow = false;
this.colorbarAxisPanel.BottomAxisStartValue = 0F;
this.colorbarAxisPanel.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
this.colorbarAxisPanel.LeftAxisEndValue = 0F;
this.colorbarAxisPanel.LeftAxisLabel = "Axis Label Not Set";
this.colorbarAxisPanel.LeftAxisLabelShow = true;
this.colorbarAxisPanel.LeftAxisMajorTickHeight = 3;
this.colorbarAxisPanel.LeftAxisMajorTickNumbersFormat = "0";
this.colorbarAxisPanel.LeftAxisMajorTickNumbersShow = true;
this.colorbarAxisPanel.LeftAxisMajorTickNumbersSpacing = 10;
this.colorbarAxisPanel.LeftAxisMajorTickOffset = 2;
this.colorbarAxisPanel.LeftAxisShow = false;
this.colorbarAxisPanel.LeftAxisStartValue = 0F;
this.colorbarAxisPanel.Location = new System.Drawing.Point(518, 0);
this.colorbarAxisPanel.Name = "colorbarAxisPanel";
this.colorbarAxisPanel.RightAxisEndValue = 0F;
this.colorbarAxisPanel.RightAxisLabel = "Axis Label Not Set";
this.colorbarAxisPanel.RightAxisLabelShow = true;
this.colorbarAxisPanel.RightAxisMajorTickHeight = 3;
this.colorbarAxisPanel.RightAxisMajorTickNumbersFormat = "0.00e00";
this.colorbarAxisPanel.RightAxisMajorTickNumbersShow = true;
this.colorbarAxisPanel.RightAxisMajorTickNumbersSpacing = 10;
this.colorbarAxisPanel.RightAxisMajorTickOffset = 2;
this.colorbarAxisPanel.RightAxisShow = true;
this.colorbarAxisPanel.RightAxisStartValue = 0F;
this.colorbarAxisPanel.Size = new System.Drawing.Size(64, 230);
this.colorbarAxisPanel.TabIndex = 1;
this.colorbarAxisPanel.TopAxisEndValue = 0F;
this.colorbarAxisPanel.TopAxisLabel = "Axis Label Not Set";
this.colorbarAxisPanel.TopAxisLabelShow = true;
this.colorbarAxisPanel.TopAxisMajorTickHeight = 10;
this.colorbarAxisPanel.TopAxisMajorTickNumbersFormat = "0";
this.colorbarAxisPanel.TopAxisMajorTickNumbersShow = true;
this.colorbarAxisPanel.TopAxisMajorTickNumbersSpacing = 10;
this.colorbarAxisPanel.TopAxisMajorTickOffset = 2;
this.colorbarAxisPanel.TopAxisShow = false;
this.colorbarAxisPanel.TopAxisStartValue = 0F;
//
// viewerAxisPanel
//
this.viewerAxisPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.viewerAxisPanel.BottomAxisEndValue = 0F;
this.viewerAxisPanel.BottomAxisLabel = "Axis Label Not Set";
this.viewerAxisPanel.BottomAxisLabelShow = true;
this.viewerAxisPanel.BottomAxisMajorTickHeight = 3;
this.viewerAxisPanel.BottomAxisMajorTickNumbersFormat = "0";
this.viewerAxisPanel.BottomAxisMajorTickNumbersShow = true;
this.viewerAxisPanel.BottomAxisMajorTickNumbersSpacing = 10;
this.viewerAxisPanel.BottomAxisMajorTickOffset = 2;
this.viewerAxisPanel.BottomAxisShow = true;
this.viewerAxisPanel.BottomAxisStartValue = 0F;
this.viewerAxisPanel.Controls.Add(this.viewerPanel);
this.viewerAxisPanel.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
this.viewerAxisPanel.LeftAxisEndValue = 0F;
this.viewerAxisPanel.LeftAxisLabel = "Axis Label Not Set";
this.viewerAxisPanel.LeftAxisLabelShow = true;
this.viewerAxisPanel.LeftAxisMajorTickHeight = 3;
this.viewerAxisPanel.LeftAxisMajorTickNumbersFormat = "0.00e00";
this.viewerAxisPanel.LeftAxisMajorTickNumbersShow = true;
this.viewerAxisPanel.LeftAxisMajorTickNumbersSpacing = 10;
this.viewerAxisPanel.LeftAxisMajorTickOffset = 2;
this.viewerAxisPanel.LeftAxisShow = true;
this.viewerAxisPanel.LeftAxisStartValue = 0F;
this.viewerAxisPanel.Location = new System.Drawing.Point(0, 0);
this.viewerAxisPanel.Name = "viewerAxisPanel";
this.viewerAxisPanel.RightAxisEndValue = 0F;
this.viewerAxisPanel.RightAxisLabel = "Axis Label Not Set";
this.viewerAxisPanel.RightAxisLabelShow = true;
this.viewerAxisPanel.RightAxisMajorTickHeight = 3;
this.viewerAxisPanel.RightAxisMajorTickNumbersFormat = "0";
this.viewerAxisPanel.RightAxisMajorTickNumbersShow = true;
this.viewerAxisPanel.RightAxisMajorTickNumbersSpacing = 10;
this.viewerAxisPanel.RightAxisMajorTickOffset = 2;
this.viewerAxisPanel.RightAxisShow = false;
this.viewerAxisPanel.RightAxisStartValue = 0F;
this.viewerAxisPanel.Size = new System.Drawing.Size(510, 230);
this.viewerAxisPanel.TabIndex = 0;
this.viewerAxisPanel.TopAxisEndValue = 0F;
this.viewerAxisPanel.TopAxisLabel = "Axis Label Not Set";
this.viewerAxisPanel.TopAxisLabelShow = true;
this.viewerAxisPanel.TopAxisMajorTickHeight = 10;
this.viewerAxisPanel.TopAxisMajorTickNumbersFormat = "0";
this.viewerAxisPanel.TopAxisMajorTickNumbersShow = true;
this.viewerAxisPanel.TopAxisMajorTickNumbersSpacing = 10;
this.viewerAxisPanel.TopAxisMajorTickOffset = 2;
this.viewerAxisPanel.TopAxisShow = true;
this.viewerAxisPanel.TopAxisStartValue = 0F;
//
// viewerPanel
//
this.viewerPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.viewerPanel.BackColor = System.Drawing.SystemColors.Control;
this.viewerPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.viewerPanel.Box = new System.Drawing.Rectangle(0, 0, 0, 0);
this.viewerPanel.Location = new System.Drawing.Point(64, 24);
this.viewerPanel.Name = "viewerPanel";
this.viewerPanel.Size = new System.Drawing.Size(406, 174);
this.viewerPanel.TabIndex = 0;
//
// backgroundWorker
//
this.backgroundWorker.WorkerSupportsCancellation = true;
//
// Layout2DColor
//
this.BackColor = System.Drawing.SystemColors.Control;
this.Controls.Add(this.backgroundPanel);
this.Name = "Layout2DColor";
this.Size = new System.Drawing.Size(584, 232);
this.backgroundPanel.ResumeLayout(false);
this.viewerAxisPanel.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
#region Bitmap Methods
public bool View(double [,] dataArray)
{
// store the data array and axis internally
this.dataArray = dataArray;
// create the bitmap and refresh colors in it
this.CreateBitmap();
this.ColorRefresh();
return true;
}
private void CreateBitmap()
{
this.viewerBitmap = new Bitmap(this.dataArray.GetLength(0), this.dataArray.GetLength(1), PixelFormat.Format24bppRgb);
}
private void ColorRefresh()
{
if (this.dataArray != null && this.viewerBitmap != null)
{
this.colorbarPanel.ColorRefresh(this.dataArray, ref this.viewerBitmap);
this.viewerPanel.Bitmap = this.viewerBitmap;
this.viewerPanel.Invalidate();
}
}
private void ConvertPoint(Point devicePoint, out int xIndex, out int yIndex)
{
if (devicePoint.X > this.viewerPanel.ClientSize.Width - 1)
xIndex = this.dataArray.GetLength(0) - 1;
else if (devicePoint.X < 0)
xIndex = 0;
else
xIndex = (int)Math.Round((this.dataArray.GetLength(0) / (double)this.viewerPanel.ClientSize.Width) * devicePoint.X);
if (devicePoint.Y > this.viewerPanel.ClientSize.Height - 1)
yIndex = this.dataArray.GetLength(1) - 1;
else if (devicePoint.Y < 0)
yIndex = 0;
else
yIndex = (int)Math.Floor((this.dataArray.GetLength(1) / (double)this.viewerPanel.ClientSize.Height) * devicePoint.Y);
//xIndex = (int)Math.Floor((devicePoint.X/(double)(this.viewerPanel.ClientSize.Width-1))*this.dataArray.GetLength(0));
//yIndex = (int)Math.Floor((devicePoint.Y/(double)(this.viewerPanel.ClientSize.Height-1))*this.dataArray.GetLength(1));
// we flip the y coordinate because the viewer panel is showing data flipped on Y (ggrrrr)
yIndex = this.dataArray.GetLength(1)-yIndex-1;
}
public double[][] CrosshairData(Point clickPoint)
{
int xIndex, yIndex;
this.ConvertPoint(clickPoint, out xIndex, out yIndex);
double[][] returnArray = new double[2][];
returnArray[0] = new double[this.dataArray.GetLength(0)];
for (int i=0;i<this.dataArray.GetLength(0);i++)
returnArray[0][i] = this.dataArray[i, yIndex];
returnArray[1] = new double[this.dataArray.GetLength(1)];
for (int i=0;i<this.dataArray.GetLength(1);i++)
returnArray[1][i] = this.dataArray[xIndex, i];
return returnArray;
}
public double[,] BoxData(Point startPoint, Point endPoint)
{
int xStart, yStart, xEnd, yEnd;
this.ConvertPoint(startPoint, out xStart, out yStart);
this.ConvertPoint(endPoint, out xEnd, out yEnd);
int width = xEnd-xStart+1;
int height = yStart-yEnd+1;
double[,] returnArray = new double[width, height];
for (int i=0; i<width; i++)
for (int j=0; j<height; j++)
returnArray[i,j] = this.dataArray[xStart+i, yEnd+j];
return returnArray;
}
public double PointData(Point mousePoint, out int xIndex, out int yIndex)
{
this.ConvertPoint(mousePoint, out xIndex, out yIndex);
return this.dataArray[xIndex, yIndex];
}
#endregion
#region Colorbar Event and Thread Code
private void colorbarPanel_CurrentValuesChanged(double minCurrent, double maxCurrent)
{
if (!this.backgroundWorker.IsBusy)
this.backgroundWorker.RunWorkerAsync();
else
{
//this.backgroundWorker.CancelAsync();
//this.backgroundWorker.RunWorkerAsync();
}
///ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProcedure), null);
// slow down
//if (refreshThread != null)
// refreshThread.Join(5);
// we launch a thread to do the refresh, otherwise things get really really sluggish
//this.refreshThread = new System.Threading.Thread(new System.Threading.ThreadStart(ColorRefresh));
//refreshThread.Name = "Layout2DColor ColorRefresh Thread";
//refreshThread.IsBackground = true;
//refreshThread.Priority = System.Threading.ThreadPriority.BelowNormal;
//refreshThread.Start();
}
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
this.ColorRefresh();
}
//void ThreadProcedure(Object stateInfo) { this.ColorRefresh(); }
#endregion
#region Properties
public Point Crosshair
{
set { this.viewerPanel.Crosshair = value; }
}
public Rectangle Box
{
set { this.viewerPanel.Box = value; }
}
public Size ArraySize
{
get { return new Size(this.dataArray.GetLength(0), this.dataArray.GetLength(1)); }
}
public EarLab.Viewers.Panels.Panel2DColor ViewerPanel
{
get { return this.viewerPanel; }
}
public EarLab.Viewers.Panels.PanelColorbarNew ColorbarPanel
{
get { return this.colorbarPanel; }
}
public EarLab.Viewers.Panels.PanelAxisNew ViewerAxisPanel
{
get { return this.viewerAxisPanel; }
}
public EarLab.Viewers.Panels.PanelAxisNew ColorbarAxisPanel
{
get { return this.colorbarAxisPanel; }
}
#endregion
}
}
| |
//
// Main.cs
//
// Author:
// Jonathan Pobst <[email protected]>
//
// Copyright (c) 2010 Jonathan Pobst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Gtk;
using Mono.Options;
using System.Collections.Generic;
using Pinta.Core;
using Mono.Unix;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Pinta
{
class MainClass
{
[STAThread]
public static void Main (string[] args)
{
string app_dir = Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location);
string locale_dir;
bool devel_mode = File.Exists (Path.Combine (Path.Combine (app_dir, ".."), "Pinta.sln"));
if (SystemManager.GetOperatingSystem () != OS.X11 || devel_mode)
locale_dir = Path.Combine (app_dir, "locale");
else {
// From MonoDevelop:
// Pinta is located at $prefix/lib/pinta
// adding "../.." should give us $prefix
string prefix = Path.Combine (Path.Combine (app_dir, ".."), "..");
//normalise it
prefix = Path.GetFullPath (prefix);
//catalog is installed to "$prefix/share/locale" by default
locale_dir = Path.Combine (Path.Combine (prefix, "share"), "locale");
}
try {
Catalog.Init ("pinta", locale_dir);
} catch (Exception ex) {
Console.WriteLine (ex);
}
int threads = -1;
var p = new OptionSet () {
{ "rt|render-threads=", Catalog.GetString ("number of threads to use for rendering"), (int v) => threads = v }
};
List<string> extra;
try {
extra = p.Parse (args);
} catch (OptionException e) {
Console.Write ("Pinta: ");
Console.WriteLine (e.Message);
return;
}
GLib.ExceptionManager.UnhandledException += new GLib.UnhandledExceptionHandler (ExceptionManager_UnhandledException);
if (SystemManager.GetOperatingSystem () == OS.Windows) {
SetWindowsGtkPath ();
}
Application.Init ();
MainWindow win = new MainWindow ();
//win.Show ();
if (threads != -1)
Pinta.Core.PintaCore.System.RenderThreads = threads;
if (SystemManager.GetOperatingSystem () == OS.Mac) {
RegisterForAppleEvents ();
}
OpenFilesFromCommandLine (extra);
Application.Run ();
}
private static void OpenFilesFromCommandLine (List<string> extra)
{
// Ignore the process serial number parameter on Mac OS X
if (PintaCore.System.OperatingSystem == OS.Mac && extra.Count > 0)
{
if (extra[0].StartsWith ("-psn_"))
{
extra.RemoveAt (0);
}
}
if (extra.Count > 0)
{
foreach (var file in extra)
PintaCore.Workspace.OpenFile (file);
}
else
{
// Create a blank document
PintaCore.Workspace.NewDocument (new Gdk.Size (800, 600), false);
}
}
private static void ExceptionManager_UnhandledException (GLib.UnhandledExceptionArgs args)
{
Exception ex = (Exception)args.ExceptionObject;
PintaCore.Chrome.ShowErrorDialog (PintaCore.Chrome.MainWindow,
string.Format ("{0}:\n{1}", "Unhandled exception", ex.Message),
ex.ToString ());
}
/// <summary>
/// Registers for OSX-specific events, like quitting from the dock.
/// </summary>
static void RegisterForAppleEvents ()
{
MacInterop.ApplicationEvents.Quit += (sender, e) => {
GLib.Timeout.Add (10, delegate {
PintaCore.Actions.File.Exit.Activate ();
return false;
});
e.Handled = true;
};
MacInterop.ApplicationEvents.Reopen += (sender, e) => {
var window = PintaCore.Chrome.MainWindow;
window.Deiconify ();
window.Hide ();
window.Show ();
window.Present ();
e.Handled = true;
};
MacInterop.ApplicationEvents.OpenDocuments += (sender, e) => {
if (e.Documents != null) {
GLib.Timeout.Add (10, delegate {
foreach (string filename in e.Documents.Keys) {
System.Console.Error.WriteLine ("Opening: {0}", filename);
PintaCore.Workspace.OpenFile (filename);
}
return false;
});
}
e.Handled = true;
};
}
[DllImport ("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs (UnmanagedType.Bool)]
static extern bool SetDllDirectory (string lpPathName);
/// <summary>
/// Explicitly add GTK+ to the search path.
/// From MonoDevelop: https://bugzilla.xamarin.com/show_bug.cgi?id=10558
/// </summary>
private static void SetWindowsGtkPath ()
{
string location = null;
using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SOFTWARE\Xamarin\GtkSharp\InstallFolder")) {
if (key != null) {
location = key.GetValue (null) as string;
}
}
if (location == null || !File.Exists (Path.Combine (location, "bin", "libgtk-win32-2.0-0.dll"))) {
System.Console.Error.WriteLine ("Did not find registered GTK# installation");
return;
}
var path = Path.Combine (location, @"bin");
try {
if (SetDllDirectory (path)) {
return;
}
}
catch (EntryPointNotFoundException) {
}
System.Console.Error.WriteLine ("Unable to set GTK# dll directory");
}
}
}
| |
// 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;
using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices
{
#if RHTESTCL
static class InteropExtensions1
{
public static bool IsNull(this RuntimeTypeHandle handle)
{
return handle.Equals(default(RuntimeTypeHandle));
}
public static bool IsOfType(this Object obj, RuntimeTypeHandle handle)
{
return handle.Equals(obj.GetType().TypeHandle);
}
}
#endif
/// <summary>
/// Simple fixed-size hash table. Create once and use to speed table lookup.
/// Good for tool time generated data table lookup. The hash table itself be generated at tool time, but runtime generation will take less disk space
///
/// 1. Size is given in construtor and never change afterwards
/// 2. Only add is supported, but remove can be added quite easily
/// 3. For each entry, an integer index can be stored and received. If index is always the same as inserting order, this can be removed too.
/// 4. Value is not stored. It should be managed seperately
/// 5. Non-generic, there there is single copy in memory
/// 6. Searching is implemented using two methods: GetFirst and GetNext
///
/// Check StringMap below for a Dictionary<string, int> like implementation where strings are stored elsewhere, possibly in compressed form
/// </summary>
internal class FixedHashTable
{
const int slot_bucket = 0;
const int slot_next = 1;
const int slot_index = 2;
int[] m_entries;
int m_size;
int m_count;
static internal bool IsPrime(int num)
{
int t = 3;
while (t * t < num)
{
if ((num % t) == 0)
{
return false;
}
t += 2;
}
return true;
}
/// <summary>
/// HashHelpers.GetPrime not accessible here
/// </summary>
static internal int GetNextPrime(int num)
{
if ((num & 1) == 0)
{
num++;
}
while (!IsPrime(num))
{
num += 2;
}
return num;
}
/// <summary>
/// Construct empty hash table
/// </summary>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal FixedHashTable(int size)
{
// Prime number is essential to reduce hash collision
// Add 10%, minimum 11 to make sure hash table has around 10% free entries to reduce collision
m_size = GetNextPrime(Math.Max(11, size * 11 / 10));
// Using int array instead of creating an Entry[] array with three ints to avoid
// adding a new array type, which costs around 3kb in binary size
m_entries = new int[m_size * 3];
}
/// <summary>
/// Add an entry: Dictionay<K,V>.Add(Key(index), index) = > FixedHashTable.Add(Key(index).GetHashCode(), index)
/// </summary>
/// <param name="hashCode">Hash code for data[slot]</param>
/// <param name="index">Normally index to external table</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal void Add(int hashCode, int index)
{
int bucket = (hashCode & 0x7FFFFFFF) % m_size;
m_entries[m_count * 3 + slot_index] = index; // This is not needed if m_count === index
m_entries[m_count * 3 + slot_next] = m_entries[bucket * 3 + slot_bucket];
m_entries[bucket * 3 + slot_bucket] = m_count + 1; // 0 for missing now
m_count++;
}
/// <summary>
/// Get first matching entry based on hash code for enumeration, -1 for missing
/// </summary>
internal int GetFirst(int hashCode)
{
int bucket = (hashCode & 0x7FFFFFFF) % m_size;
return m_entries[bucket * 3 + slot_bucket] - 1;
}
internal int GetIndex(int bucket)
{
return m_entries[bucket * 3 + slot_index];
}
/// <summary>
/// Get next entry for enumeration, -1 for missing
/// </summary>
internal int GetNext(int bucket)
{
return m_entries[bucket * 3 + slot_next] - 1;
}
}
/// <summary>
/// Virtual Dictionary<string, int> where strings are stored elsewhere, possibly in compressed form
/// </summary>
internal abstract class StringMap
{
int m_size;
FixedHashTable m_map;
internal StringMap(int size)
{
m_size = size;
}
internal abstract String GetString(int i);
/// <summary>
/// String(i).GetHashCode
/// </summary>
internal abstract int GetStringHash(int i);
/// <summary>
/// String(i) == name
/// </summary>
internal abstract bool IsStringEqual(string name, int i);
/// <summary>
/// Dictionary.TryGetValue(string)
/// </summary>
internal int FindString(string name)
{
if (m_map == null)
{
FixedHashTable map = new FixedHashTable(m_size);
for (int i = 0; i < m_size; i++)
{
map.Add(GetStringHash(i), i);
}
m_map = map;
}
int hash = StringPool.StableStringHash(name);
// Search hash table
for (int slot = m_map.GetFirst(hash); slot >= 0; slot = m_map.GetNext(slot))
{
int index = m_map.GetIndex(slot);
if (IsStringEqual(name, index))
{
return index;
}
}
return -1;
}
}
/// <summary>
/// StringMap using 16-bit indices, for normal applications
/// </summary>
internal class StringMap16 : StringMap
{
StringPool m_pool;
UInt16[] m_indices;
internal StringMap16(StringPool pool, UInt16[] indices) : base(indices.Length)
{
m_pool = pool;
m_indices = indices;
}
internal override string GetString(int i)
{
return m_pool.GetString(m_indices[i]);
}
internal override int GetStringHash(int i)
{
return m_pool.StableStringHash(m_indices[i]);
}
internal override bool IsStringEqual(string name, int i)
{
return m_pool.IsStringEqual(name, m_indices[i]);
}
}
/// <summary>
/// StringMap using 32-bit indices, for bigger applications
/// </summary>
internal class StringMap32 : StringMap
{
StringPool m_pool;
UInt32[] m_indices;
internal StringMap32(StringPool pool, UInt32[] indices) : base(indices.Length)
{
m_pool = pool;
m_indices = indices;
}
internal override string GetString(int i)
{
return m_pool.GetString(m_indices[i]);
}
internal override int GetStringHash(int i)
{
return m_pool.StableStringHash(m_indices[i]);
}
internal override bool IsStringEqual(string name, int i)
{
return m_pool.IsStringEqual(name, m_indices[i]);
}
}
/// <summary>
/// Fixed Dictionary<RuntimeTypeHandle, int> using delegate Func<int, RuntimeTypeHandle> to provide data
/// </summary>
internal class RuntimeTypeHandleMap : FixedHashTable
{
Func<int, RuntimeTypeHandle> m_getHandle;
internal RuntimeTypeHandleMap(int size, Func<int, RuntimeTypeHandle> getHandle) : base(size)
{
m_getHandle = getHandle;
for (int i = 0; i < size; i++)
{
RuntimeTypeHandle handle = getHandle(i);
if (!handle.Equals(McgModule.s_DependencyReductionTypeRemovedTypeHandle))
{
Add(handle.GetHashCode(), i);
}
}
}
internal int Lookup(RuntimeTypeHandle handle)
{
for (int slot = GetFirst(handle.GetHashCode()); slot >= 0; slot = GetNext(slot))
{
int index = GetIndex(slot);
if (handle.Equals(m_getHandle(index)))
{
return index;
}
}
return -1;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Globalization;
using System.ComponentModel;
using System.Windows.Markup;// For ValueSerializerAttribute
using System.Windows.Threading; // For DispatcherObject
using System.Security.Permissions; // For LinkDemand
using MS.Utility;
using MS.Internal.WindowsBase;
using System.Reflection; // for IsInstanceOfType
using MS.Internal;
#pragma warning disable 1634, 1691 // suppressing PreSharp warnings
namespace System.Windows
{
/// <summary>
/// An attached dependency-based property
/// </summary>
[TypeConverter("System.Windows.Markup.DependencyPropertyConverter, PresentationFramework, Version=" + BuildInfo.WCP_VERSION + ", Culture=neutral, PublicKeyToken=" + BuildInfo.WCP_PUBLIC_KEY_TOKEN + ", Custom=null")]
[ValueSerializer(typeof(DependencyPropertyValueSerializer))]
public sealed class DependencyProperty
{
/// <summary>
/// Register a Dependency Property
/// </summary>
/// <param name="name">Name of property</param>
/// <param name="propertyType">Type of the property</param>
/// <param name="ownerType">Type that is registering the property</param>
/// <returns>Dependency Property</returns>
public static DependencyProperty Register(string name, Type propertyType, Type ownerType)
{
// Forwarding
return Register(name, propertyType, ownerType, null, null);
}
/// <summary>
/// Register a Dependency Property
/// </summary>
/// <param name="name">Name of property</param>
/// <param name="propertyType">Type of the property</param>
/// <param name="ownerType">Type that is registering the property</param>
/// <param name="typeMetadata">Metadata to use if current type doesn't specify type-specific metadata</param>
/// <returns>Dependency Property</returns>
public static DependencyProperty Register(string name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata)
{
// Forwarding
return Register(name, propertyType, ownerType, typeMetadata, null);
}
/// <summary>
/// Register a Dependency Property
/// </summary>
/// <param name="name">Name of property</param>
/// <param name="propertyType">Type of the property</param>
/// <param name="ownerType">Type that is registering the property</param>
/// <param name="typeMetadata">Metadata to use if current type doesn't specify type-specific metadata</param>
/// <param name="validateValueCallback">Provides additional value validation outside automatic type validation</param>
/// <returns>Dependency Property</returns>
public static DependencyProperty Register(string name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata, ValidateValueCallback validateValueCallback)
{
RegisterParameterValidation(name, propertyType, ownerType);
// Register an attached property
PropertyMetadata defaultMetadata = null;
if (typeMetadata != null && typeMetadata.DefaultValueWasSet())
{
defaultMetadata = new PropertyMetadata(typeMetadata.DefaultValue);
}
DependencyProperty property = RegisterCommon(name, propertyType, ownerType, defaultMetadata, validateValueCallback);
if (typeMetadata != null)
{
// Apply type-specific metadata to owner type only
property.OverrideMetadata(ownerType, typeMetadata);
}
return property;
}
/// <summary>
/// Simple registration, metadata, validation, and a read-only property
/// key. Calling this version restricts the property such that it can
/// only be set via the corresponding overload of DependencyObject.SetValue.
/// </summary>
public static DependencyPropertyKey RegisterReadOnly(
string name,
Type propertyType,
Type ownerType,
PropertyMetadata typeMetadata )
{
return RegisterReadOnly( name, propertyType, ownerType, typeMetadata, null );
}
/// <summary>
/// Simple registration, metadata, validation, and a read-only property
/// key. Calling this version restricts the property such that it can
/// only be set via the corresponding overload of DependencyObject.SetValue.
/// </summary>
public static DependencyPropertyKey RegisterReadOnly(
string name,
Type propertyType,
Type ownerType,
PropertyMetadata typeMetadata,
ValidateValueCallback validateValueCallback )
{
RegisterParameterValidation(name, propertyType, ownerType);
PropertyMetadata defaultMetadata = null;
if (typeMetadata != null && typeMetadata.DefaultValueWasSet())
{
defaultMetadata = new PropertyMetadata(typeMetadata.DefaultValue);
}
else
{
defaultMetadata = AutoGeneratePropertyMetadata(propertyType,validateValueCallback,name,ownerType);
}
// We create a DependencyPropertyKey at this point with a null property
// and set that in the _readOnlyKey field. This is so the property is
// marked as requiring a key immediately. If something fails in the
// initialization path, the property is still marked as needing a key.
// This is better than the alternative of creating and setting the key
// later, because if that code fails the read-only property would not
// be marked read-only. The intent of this mildly convoluted code
// is so we fail securely.
DependencyPropertyKey authorizationKey = new DependencyPropertyKey(null); // No property yet, use null as placeholder.
DependencyProperty property = RegisterCommon(name, propertyType, ownerType, defaultMetadata, validateValueCallback);
property._readOnlyKey = authorizationKey;
authorizationKey.SetDependencyProperty(property);
if (typeMetadata == null )
{
// No metadata specified, generate one so we can specify the authorized key.
typeMetadata = AutoGeneratePropertyMetadata(propertyType,validateValueCallback,name,ownerType);
}
// Authorize registering type for read-only access, create key.
#pragma warning suppress 6506 // typeMetadata is never null, since we generate default metadata if none is provided.
// Apply type-specific metadata to owner type only
property.OverrideMetadata(ownerType, typeMetadata, authorizationKey);
return authorizationKey;
}
/// <summary>
/// Simple registration, metadata, validation, and a read-only property
/// key. Calling this version restricts the property such that it can
/// only be set via the corresponding overload of DependencyObject.SetValue.
/// </summary>
public static DependencyPropertyKey RegisterAttachedReadOnly(string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata)
{
return RegisterAttachedReadOnly( name, propertyType, ownerType, defaultMetadata, null );
}
/// <summary>
/// Simple registration, metadata, validation, and a read-only property
/// key. Calling this version restricts the property such that it can
/// only be set via the corresponding overload of DependencyObject.SetValue.
/// </summary>
public static DependencyPropertyKey RegisterAttachedReadOnly(string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata, ValidateValueCallback validateValueCallback)
{
RegisterParameterValidation(name, propertyType, ownerType);
// Establish default metadata for all types, if none is provided
if (defaultMetadata == null)
{
defaultMetadata = AutoGeneratePropertyMetadata( propertyType, validateValueCallback, name, ownerType );
}
// We create a DependencyPropertyKey at this point with a null property
// and set that in the _readOnlyKey field. This is so the property is
// marked as requiring a key immediately. If something fails in the
// initialization path, the property is still marked as needing a key.
// This is better than the alternative of creating and setting the key
// later, because if that code fails the read-only property would not
// be marked read-only. The intent of this mildly convoluted code
// is so we fail securely.
DependencyPropertyKey authorizedKey = new DependencyPropertyKey(null);
DependencyProperty property = RegisterCommon( name, propertyType, ownerType, defaultMetadata, validateValueCallback);
property._readOnlyKey = authorizedKey;
authorizedKey.SetDependencyProperty(property);
return authorizedKey;
}
/// <summary>
/// Register an attached Dependency Property
/// </summary>
/// <param name="name">Name of property</param>
/// <param name="propertyType">Type of the property</param>
/// <param name="ownerType">Type that is registering the property</param>
/// <returns>Dependency Property</returns>
public static DependencyProperty RegisterAttached(string name, Type propertyType, Type ownerType)
{
// Forwarding
return RegisterAttached(name, propertyType, ownerType, null, null );
}
/// <summary>
/// Register an attached Dependency Property
/// </summary>
/// <param name="name">Name of property</param>
/// <param name="propertyType">Type of the property</param>
/// <param name="ownerType">Type that is registering the property</param>
/// <param name="defaultMetadata">Metadata to use if current type doesn't specify type-specific metadata</param>
/// <returns>Dependency Property</returns>
public static DependencyProperty RegisterAttached(string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata)
{
// Forwarding
return RegisterAttached(name, propertyType, ownerType, defaultMetadata, null );
}
/// <summary>
/// Register an attached Dependency Property
/// </summary>
/// <param name="name">Name of property</param>
/// <param name="propertyType">Type of the property</param>
/// <param name="ownerType">Type that is registering the property</param>
/// <param name="defaultMetadata">Metadata to use if current type doesn't specify type-specific metadata</param>
/// <param name="validateValueCallback">Provides additional value validation outside automatic type validation</param>
/// <returns>Dependency Property</returns>
public static DependencyProperty RegisterAttached(string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata, ValidateValueCallback validateValueCallback)
{
RegisterParameterValidation(name, propertyType, ownerType);
return RegisterCommon( name, propertyType, ownerType, defaultMetadata, validateValueCallback );
}
private static void RegisterParameterValidation(string name, Type propertyType, Type ownerType)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (name.Length == 0)
{
throw new ArgumentException(SR.Get(SRID.StringEmpty), "name");
}
if (ownerType == null)
{
throw new ArgumentNullException("ownerType");
}
if (propertyType == null)
{
throw new ArgumentNullException("propertyType");
}
}
private static DependencyProperty RegisterCommon(string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata, ValidateValueCallback validateValueCallback)
{
FromNameKey key = new FromNameKey(name, ownerType);
lock (Synchronized)
{
if (PropertyFromName.Contains(key))
{
throw new ArgumentException(SR.Get(SRID.PropertyAlreadyRegistered, name, ownerType.Name));
}
}
// Establish default metadata for all types, if none is provided
if (defaultMetadata == null)
{
defaultMetadata = AutoGeneratePropertyMetadata( propertyType, validateValueCallback, name, ownerType );
}
else // Metadata object is provided.
{
// If the defaultValue wasn't specified auto generate one
if (!defaultMetadata.DefaultValueWasSet())
{
defaultMetadata.DefaultValue = AutoGenerateDefaultValue(propertyType);
}
ValidateMetadataDefaultValue( defaultMetadata, propertyType, name, validateValueCallback );
}
// Create property
DependencyProperty dp = new DependencyProperty(name, propertyType, ownerType, defaultMetadata, validateValueCallback);
// Seal (null means being used for default metadata, calls OnApply)
defaultMetadata.Seal(dp, null);
if (defaultMetadata.IsInherited)
{
dp._packedData |= Flags.IsPotentiallyInherited;
}
if (defaultMetadata.UsingDefaultValueFactory)
{
dp._packedData |= Flags.IsPotentiallyUsingDefaultValueFactory;
}
// Map owner type to this property
// Build key
lock (Synchronized)
{
PropertyFromName[key] = dp;
}
if( TraceDependencyProperty.IsEnabled )
{
TraceDependencyProperty.TraceActivityItem(
TraceDependencyProperty.Register,
dp,
dp.OwnerType );
}
return dp;
}
private static object AutoGenerateDefaultValue(
Type propertyType)
{
// Default per-type metadata not provided, create
object defaultValue = null;
// Auto-assigned default value
if (propertyType.IsValueType)
{
// Value-types have default-constructed type default values
defaultValue = Activator.CreateInstance(propertyType);
}
return defaultValue;
}
private static PropertyMetadata AutoGeneratePropertyMetadata(
Type propertyType,
ValidateValueCallback validateValueCallback,
string name,
Type ownerType)
{
// Default per-type metadata not provided, create
object defaultValue = AutoGenerateDefaultValue(propertyType);
// If a validator is passed in, see if the default value makes sense.
if ( validateValueCallback != null &&
!validateValueCallback(defaultValue))
{
// Didn't work - require the caller to specify one.
throw new ArgumentException(SR.Get(SRID.DefaultValueAutoAssignFailed, name, ownerType.Name));
}
return new PropertyMetadata(defaultValue);
}
// Validate the default value in the given metadata
private static void ValidateMetadataDefaultValue(
PropertyMetadata defaultMetadata,
Type propertyType,
string propertyName,
ValidateValueCallback validateValueCallback )
{
// If we are registered to use the DefaultValue factory we can
// not validate the DefaultValue at registration time, so we
// early exit.
if (defaultMetadata.UsingDefaultValueFactory)
{
return;
}
ValidateDefaultValueCommon(defaultMetadata.DefaultValue, propertyType,
propertyName, validateValueCallback, /*checkThreadAffinity = */ true);
}
// Validate the given default value, used by PropertyMetadata.GetDefaultValue()
// when the DefaultValue factory is used.
// These default values are allowed to have thread-affinity.
internal void ValidateFactoryDefaultValue(object defaultValue)
{
ValidateDefaultValueCommon(defaultValue, PropertyType, Name, ValidateValueCallback, false);
}
private static void ValidateDefaultValueCommon(
object defaultValue,
Type propertyType,
string propertyName,
ValidateValueCallback validateValueCallback,
bool checkThreadAffinity)
{
// Ensure default value is the correct type
if (!IsValidType(defaultValue, propertyType))
{
throw new ArgumentException(SR.Get(SRID.DefaultValuePropertyTypeMismatch, propertyName));
}
// An Expression used as default value won't behave as expected since
// it doesn't get evaluated. We explicitly fail it here.
if (defaultValue is Expression )
{
throw new ArgumentException(SR.Get(SRID.DefaultValueMayNotBeExpression));
}
if (checkThreadAffinity)
{
// If the default value is a DispatcherObject with thread affinity
// we cannot accept it as a default value. If it implements ISealable
// we attempt to seal it; if not we throw an exception. Types not
// deriving from DispatcherObject are allowed - it is up to the user to
// make any custom types free-threaded.
DispatcherObject dispatcherObject = defaultValue as DispatcherObject;
if (dispatcherObject != null && dispatcherObject.Dispatcher != null)
{
// Try to make the DispatcherObject free-threaded if it's an
// ISealable.
ISealable valueAsISealable = dispatcherObject as ISealable;
if (valueAsISealable != null && valueAsISealable.CanSeal)
{
Invariant.Assert (!valueAsISealable.IsSealed,
"A Sealed ISealable must not have dispatcher affinity");
valueAsISealable.Seal();
Invariant.Assert(dispatcherObject.Dispatcher == null,
"ISealable.Seal() failed after ISealable.CanSeal returned true");
}
else
{
throw new ArgumentException(SR.Get(SRID.DefaultValueMustBeFreeThreaded, propertyName));
}
}
}
// After checking for correct type, check default value against
// validator (when one is given)
if ( validateValueCallback != null &&
!validateValueCallback(defaultValue))
{
throw new ArgumentException(SR.Get(SRID.DefaultValueInvalid, propertyName));
}
}
/// <summary>
/// Parameter validation for OverrideMetadata, includes code to force
/// all base classes of "forType" to register their metadata so we know
/// what we are overriding.
/// </summary>
private void SetupOverrideMetadata(
Type forType,
PropertyMetadata typeMetadata,
out DependencyObjectType dType,
out PropertyMetadata baseMetadata )
{
if (forType == null)
{
throw new ArgumentNullException("forType");
}
if (typeMetadata == null)
{
throw new ArgumentNullException("typeMetadata");
}
if (typeMetadata.Sealed)
{
throw new ArgumentException(SR.Get(SRID.TypeMetadataAlreadyInUse));
}
if (!typeof(DependencyObject).IsAssignableFrom(forType))
{
throw new ArgumentException(SR.Get(SRID.TypeMustBeDependencyObjectDerived, forType.Name));
}
// Ensure default value is a correct value (if it was supplied,
// otherwise, the default value will be taken from the base metadata
// which was already validated)
if (typeMetadata.IsDefaultValueModified)
{
// Will throw ArgumentException if fails.
ValidateMetadataDefaultValue( typeMetadata, PropertyType, Name, ValidateValueCallback );
}
// Force all base classes to register their metadata
dType = DependencyObjectType.FromSystemType(forType);
// Get metadata for the base type
baseMetadata = GetMetadata(dType.BaseType);
// Make sure overriding metadata is the same type or derived type of
// the base metadata
if (!baseMetadata.GetType().IsAssignableFrom(typeMetadata.GetType()))
{
throw new ArgumentException(SR.Get(SRID.OverridingMetadataDoesNotMatchBaseMetadataType));
}
}
/// <summary>
/// Supply metadata for given type & run static constructors if needed.
/// </summary>
/// <remarks>
/// The supplied metadata will be merged with the type's base
/// metadata
/// </remarks>
public void OverrideMetadata(Type forType, PropertyMetadata typeMetadata)
{
DependencyObjectType dType;
PropertyMetadata baseMetadata;
SetupOverrideMetadata(forType, typeMetadata, out dType, out baseMetadata);
if (ReadOnly)
{
// Readonly and no DependencyPropertyKey - not allowed.
throw new InvalidOperationException(SR.Get(SRID.ReadOnlyOverrideNotAllowed, Name));
}
ProcessOverrideMetadata(forType, typeMetadata, dType, baseMetadata);
}
/// <summary>
/// Supply metadata for a given type, overriding a property that is
/// read-only. If property is not read only, tells user to use the Plain
/// Jane OverrideMetadata instead.
/// </summary>
public void OverrideMetadata(Type forType, PropertyMetadata typeMetadata, DependencyPropertyKey key)
{
DependencyObjectType dType;
PropertyMetadata baseMetadata;
SetupOverrideMetadata(forType, typeMetadata, out dType, out baseMetadata);
if (key == null)
{
throw new ArgumentNullException("key");
}
if (ReadOnly)
{
// If the property is read-only, the key must match this property
// and the key must match that in the base metadata.
if (key.DependencyProperty != this)
{
throw new ArgumentException(SR.Get(SRID.ReadOnlyOverrideKeyNotAuthorized, Name));
}
VerifyReadOnlyKey(key);
}
else
{
throw new InvalidOperationException(SR.Get(SRID.PropertyNotReadOnly));
}
// Either the property doesn't require a key, or the key match was
// successful. Proceed with the metadata override.
ProcessOverrideMetadata(forType, typeMetadata, dType, baseMetadata);
}
/// <summary>
/// After parameters have been validated for OverrideMetadata, this
/// method is called to actually update the data structures.
/// </summary>
private void ProcessOverrideMetadata(
Type forType,
PropertyMetadata typeMetadata,
DependencyObjectType dType,
PropertyMetadata baseMetadata)
{
// Store per-Type metadata for this property. Locks only on Write.
// Datastructure guaranteed to be valid for non-locking readers
lock (Synchronized)
{
if (DependencyProperty.UnsetValue == _metadataMap[dType.Id])
{
_metadataMap[dType.Id] = typeMetadata;
}
else
{
throw new ArgumentException(SR.Get(SRID.TypeMetadataAlreadyRegistered, forType.Name));
}
}
// Merge base's metadata into this metadata
// CALLBACK
typeMetadata.InvokeMerge(baseMetadata, this);
// Type metadata may no longer change (calls OnApply)
typeMetadata.Seal(this, forType);
if (typeMetadata.IsInherited)
{
_packedData |= Flags.IsPotentiallyInherited;
}
if (typeMetadata.DefaultValueWasSet() && (typeMetadata.DefaultValue != DefaultMetadata.DefaultValue))
{
_packedData |= Flags.IsDefaultValueChanged;
}
if (typeMetadata.UsingDefaultValueFactory)
{
_packedData |= Flags.IsPotentiallyUsingDefaultValueFactory;
}
}
[FriendAccessAllowed] // Built into Base, also used by Core & Framework.
internal object GetDefaultValue(DependencyObjectType dependencyObjectType)
{
if (!IsDefaultValueChanged)
{
return DefaultMetadata.DefaultValue;
}
return GetMetadata(dependencyObjectType).DefaultValue;
}
[FriendAccessAllowed] // Built into Base, also used by Core & Framework.
internal object GetDefaultValue(Type forType)
{
if (!IsDefaultValueChanged)
{
return DefaultMetadata.DefaultValue;
}
return GetMetadata(DependencyObjectType.FromSystemTypeInternal(forType)).DefaultValue;
}
/// <summary>
/// Retrieve metadata for a provided type
/// </summary>
/// <param name="forType">Type to get metadata</param>
/// <returns>Property metadata</returns>
public PropertyMetadata GetMetadata(Type forType)
{
if (forType != null)
{
return GetMetadata(DependencyObjectType.FromSystemType(forType));
}
throw new ArgumentNullException("forType");
}
/// <summary>
/// Retrieve metadata for a provided DependencyObject
/// </summary>
/// <param name="dependencyObject">DependencyObject to get metadata</param>
/// <returns>Property metadata</returns>
public PropertyMetadata GetMetadata(DependencyObject dependencyObject)
{
if (dependencyObject != null)
{
return GetMetadata(dependencyObject.DependencyObjectType);
}
throw new ArgumentNullException("dependencyObject");
}
/// <summary>
/// Reteive metadata for a DependencyObject type described by the
/// given DependencyObjectType
/// </summary>
//CASRemoval:[StrongNameIdentityPermission(SecurityAction.LinkDemand, PublicKey = BuildInfo.WCP_PUBLIC_KEY_STRING)]
public PropertyMetadata GetMetadata(DependencyObjectType dependencyObjectType)
{
// All static constructors for this DType and all base types have already
// been run. If no overriden metadata was provided, then look up base types.
// If no metadata found on base types, then return default
if (null != dependencyObjectType)
{
// Do we in fact have any overrides at all?
int index = _metadataMap.Count - 1;
int Id;
object value;
if (index < 0)
{
// No overrides or it's the base class
return _defaultMetadata;
}
else if (index == 0)
{
// Only 1 override
_metadataMap.GetKeyValuePair(index, out Id, out value);
// If there is overriden metadata, then there is a base class with
// lower or equal Id of this class, or this class is already a base class
// of the overridden one. Therefore dependencyObjectType won't ever
// become null before we exit the while loop
while (dependencyObjectType.Id > Id)
{
dependencyObjectType = dependencyObjectType.BaseType;
}
if (Id == dependencyObjectType.Id)
{
// Return the override
return (PropertyMetadata)value;
}
// Return default metadata
}
else
{
// We have more than 1 override for this class, so we will have to loop through
// both the overrides and the class Id
if (0 != dependencyObjectType.Id)
{
do
{
// Get the Id of the most derived class with overridden metadata
_metadataMap.GetKeyValuePair(index, out Id, out value);
--index;
// If the Id of this class is less than the override, then look for an override
// with an equal or lower Id until we run out of overrides
while ((dependencyObjectType.Id < Id) && (index >= 0))
{
_metadataMap.GetKeyValuePair(index, out Id, out value);
--index;
}
// If there is overriden metadata, then there is a base class with
// lower or equal Id of this class, or this class is already a base class
// of the overridden one. Therefore dependencyObjectType won't ever
// become null before we exit the while loop
while (dependencyObjectType.Id > Id)
{
dependencyObjectType = dependencyObjectType.BaseType;
}
if (Id == dependencyObjectType.Id)
{
// Return the override
return (PropertyMetadata)value;
}
}
while (index >= 0);
}
}
}
return _defaultMetadata;
}
/// <summary>
/// Associate another owner type with this property
/// </summary>
/// <remarks>
/// The owner type is used when resolving a property by name (<see cref="FromName"/>)
/// </remarks>
/// <param name="ownerType">Additional owner type</param>
/// <returns>This property</returns>
public DependencyProperty AddOwner(Type ownerType)
{
// Forwarding
return AddOwner(ownerType, null);
}
/// <summary>
/// Associate another owner type with this property
/// </summary>
/// <remarks>
/// The owner type is used when resolving a property by name (<see cref="FromName"/>)
/// </remarks>
/// <param name="ownerType">Additional owner type</param>
/// <param name="typeMetadata">Optional type metadata to override on owner's behalf</param>
/// <returns>This property</returns>
public DependencyProperty AddOwner(Type ownerType, PropertyMetadata typeMetadata)
{
if (ownerType == null)
{
throw new ArgumentNullException("ownerType");
}
// Map owner type to this property
// Build key
FromNameKey key = new FromNameKey(Name, ownerType);
lock (Synchronized)
{
if (PropertyFromName.Contains(key))
{
throw new ArgumentException(SR.Get(SRID.PropertyAlreadyRegistered, Name, ownerType.Name));
}
}
if (typeMetadata != null)
{
OverrideMetadata(ownerType, typeMetadata);
}
lock (Synchronized)
{
PropertyFromName[key] = this;
}
return this;
}
/// <summary>
/// Name of the property
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Type of the property
/// </summary>
public Type PropertyType
{
get { return _propertyType; }
}
/// <summary>
/// Owning type of the property
/// </summary>
public Type OwnerType
{
get { return _ownerType; }
}
/// <summary>
/// Default metadata for the property
/// </summary>
public PropertyMetadata DefaultMetadata
{
get { return _defaultMetadata; }
}
/// <summary>
/// Value validation callback
/// </summary>
public ValidateValueCallback ValidateValueCallback
{
get { return _validateValueCallback; }
}
/// <summary>
/// Zero-based globally unique index of the property
/// </summary>
public int GlobalIndex
{
get { return (int) (_packedData & Flags.GlobalIndexMask); }
}
internal bool IsObjectType
{
get { return (_packedData & Flags.IsObjectType) != 0; }
}
internal bool IsValueType
{
get { return (_packedData & Flags.IsValueType) != 0; }
}
internal bool IsFreezableType
{
get { return (_packedData & Flags.IsFreezableType) != 0; }
}
internal bool IsStringType
{
get { return (_packedData & Flags.IsStringType) != 0; }
}
internal bool IsPotentiallyInherited
{
get { return (_packedData & Flags.IsPotentiallyInherited) != 0; }
}
internal bool IsDefaultValueChanged
{
get { return (_packedData & Flags.IsDefaultValueChanged) != 0; }
}
internal bool IsPotentiallyUsingDefaultValueFactory
{
get { return (_packedData & Flags.IsPotentiallyUsingDefaultValueFactory) != 0; }
}
/// <summary>
/// Serves as a hash function for a particular type, suitable for use in
/// hashing algorithms and data structures like a hash table
/// </summary>
/// <returns>The DependencyProperty's GlobalIndex</returns>
public override int GetHashCode()
{
return GlobalIndex;
}
/// <summary>
/// Used to determine if given value is appropriate for the type of the property
/// </summary>
/// <param name="value">Value to check</param>
/// <returns>true if value matches property type</returns>
public bool IsValidType(object value)
{
return IsValidType(value, PropertyType);
}
/// <summary>
/// Used to determine if given value is appropriate for the type of the property
/// and the range of values (as specified via the ValidateValueCallback) within that type
/// </summary>
/// <param name="value">Value to check</param>
/// <returns>true if value is appropriate</returns>
public bool IsValidValue(object value)
{
if (!IsValidType(value, PropertyType))
{
return false;
}
if (ValidateValueCallback != null)
{
// CALLBACK
return ValidateValueCallback(value);
}
return true;
}
/// <summary>
/// Set/Value value disabling
/// </summary>
public bool ReadOnly
{
get
{
return (_readOnlyKey != null);
}
}
/// <summary>
/// Returns the DependencyPropertyKey associated with this DP.
/// </summary>
internal DependencyPropertyKey DependencyPropertyKey
{
get
{
return _readOnlyKey;
}
}
internal void VerifyReadOnlyKey( DependencyPropertyKey candidateKey )
{
Debug.Assert( ReadOnly, "Why are we trying to validate read-only key on a property that is not read-only?");
if (_readOnlyKey != candidateKey)
{
throw new ArgumentException(SR.Get(SRID.ReadOnlyKeyNotAuthorized));
}
}
/// <summary>
/// Internal version of IsValidValue that bypasses IsValidType check;
/// Called from SetValueInternal
/// </summary>
/// <param name="value">Value to check</param>
/// <returns>true if value is appropriate</returns>
internal bool IsValidValueInternal(object value)
{
if (ValidateValueCallback != null)
{
// CALLBACK
return ValidateValueCallback(value);
}
return true;
}
/// <summary>
/// Find a property from name
/// </summary>
/// <remarks>
/// Search includes base classes of the provided type as well
/// </remarks>
/// <param name="name">Name of the property</param>
/// <param name="ownerType">Owner type of the property</param>
/// <returns>Dependency property</returns>
[FriendAccessAllowed] // Built into Base, also used by Framework.
internal static DependencyProperty FromName(string name, Type ownerType)
{
DependencyProperty dp = null;
if (name != null)
{
if (ownerType != null)
{
FromNameKey key = new FromNameKey(name, ownerType);
while ((dp == null) && (ownerType != null))
{
// Ensure static constructor of type has run
MS.Internal.WindowsBase.SecurityHelper.RunClassConstructor(ownerType);
// Locate property
key.UpdateNameKey(ownerType);
lock (Synchronized)
{
dp = (DependencyProperty)PropertyFromName[key];
}
ownerType = ownerType.BaseType;
}
}
else
{
throw new ArgumentNullException("ownerType");
}
}
else
{
throw new ArgumentNullException("name");
}
return dp;
}
/// <summary>
/// String representation
/// </summary>
public override string ToString()
{
return _name;
}
internal static bool IsValidType(object value, Type propertyType)
{
if (value == null)
{
// Null values are invalid for value-types
if (propertyType.IsValueType &&
!(propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == NullableType))
{
return false;
}
}
else
{
// Non-null default value, ensure its the correct type
if (!propertyType.IsInstanceOfType(value))
{
return false;
}
}
return true;
}
private class FromNameKey
{
public FromNameKey(string name, Type ownerType)
{
_name = name;
_ownerType = ownerType;
_hashCode = _name.GetHashCode() ^ _ownerType.GetHashCode();
}
public void UpdateNameKey(Type ownerType)
{
_ownerType = ownerType;
_hashCode = _name.GetHashCode() ^ _ownerType.GetHashCode();
}
public override int GetHashCode()
{
return _hashCode;
}
public override bool Equals(object o)
{
if ((o != null) && (o is FromNameKey))
{
return Equals((FromNameKey)o);
}
else
{
return false;
}
}
public bool Equals(FromNameKey key)
{
return (_name.Equals(key._name) && (_ownerType == key._ownerType));
}
private string _name;
private Type _ownerType;
private int _hashCode;
}
private DependencyProperty(string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata, ValidateValueCallback validateValueCallback)
{
_name = name;
_propertyType = propertyType;
_ownerType = ownerType;
_defaultMetadata = defaultMetadata;
_validateValueCallback = validateValueCallback;
Flags packedData;
lock (Synchronized)
{
packedData = (Flags) GetUniqueGlobalIndex(ownerType, name);
RegisteredPropertyList.Add(this);
}
if (propertyType.IsValueType)
{
packedData |= Flags.IsValueType;
}
if (propertyType == typeof(object))
{
packedData |= Flags.IsObjectType;
}
if (typeof(Freezable).IsAssignableFrom(propertyType))
{
packedData |= Flags.IsFreezableType;
}
if (propertyType == typeof(string))
{
packedData |= Flags.IsStringType;
}
_packedData = packedData;
}
// Synchronized: Covered by DependencyProperty.Synchronized
internal static int GetUniqueGlobalIndex(Type ownerType, string name)
{
// Prevent GlobalIndex from overflow. DependencyProperties are meant to be static members and are to be registered
// only via static constructors. However there is no cheap way of ensuring this, without having to do a stack walk. Hence
// concievably people could register DependencyProperties via instance methods and therefore cause the GlobalIndex to
// overflow. This check will explicitly catch this error, instead of silently malfuntioning.
if (GlobalIndexCount >= (int)Flags.GlobalIndexMask)
{
if (ownerType != null)
{
throw new InvalidOperationException(SR.Get(SRID.TooManyDependencyProperties, ownerType.Name + "." + name));
}
else
{
throw new InvalidOperationException(SR.Get(SRID.TooManyDependencyProperties, "ConstantProperty"));
}
}
// Covered by Synchronized by caller
return GlobalIndexCount++;
}
/// <summary>
/// This is the callback designers use to participate in the computation of property
/// values at design time. Eg. Even if the author sets Visibility to Hidden, the designer
/// wants to coerce the value to Visible at design time so that the element doesn't
/// disappear from the design surface.
/// </summary>
internal CoerceValueCallback DesignerCoerceValueCallback
{
get { return _designerCoerceValueCallback; }
set
{
if (ReadOnly)
{
throw new InvalidOperationException(SR.Get(SRID.ReadOnlyDesignerCoersionNotAllowed, Name));
}
_designerCoerceValueCallback = value;
}
}
/// <summary> Standard unset value </summary>
public static readonly object UnsetValue = new NamedObject("DependencyProperty.UnsetValue");
private string _name;
private Type _propertyType;
private Type _ownerType;
private PropertyMetadata _defaultMetadata;
private ValidateValueCallback _validateValueCallback;
private DependencyPropertyKey _readOnlyKey;
[Flags]
private enum Flags : int
{
GlobalIndexMask = 0x0000FFFF,
IsValueType = 0x00010000,
IsFreezableType = 0x00020000,
IsStringType = 0x00040000,
IsPotentiallyInherited = 0x00080000,
IsDefaultValueChanged = 0x00100000,
IsPotentiallyUsingDefaultValueFactory = 0x00200000,
IsObjectType = 0x00400000,
// 0xFF800000 free bits
}
private Flags _packedData;
// Synchronized (write locks, lock-free reads): Covered by DependencyProperty instance
// This is a map that contains the IDs of derived classes that have overriden metadata
/* property */ internal InsertionSortMap _metadataMap = new InsertionSortMap();
private CoerceValueCallback _designerCoerceValueCallback;
// Synchronized (write locks, lock-free reads): Covered by DependencyProperty.Synchronized
/* property */ internal static ItemStructList<DependencyProperty> RegisteredPropertyList = new ItemStructList<DependencyProperty>(768);
// Synchronized: Covered by DependencyProperty.Synchronized
private static Hashtable PropertyFromName = new Hashtable();
// Synchronized: Covered by DependencyProperty.Synchronized
private static int GlobalIndexCount;
// Global, cross-object synchronization
internal static object Synchronized = new object();
// Nullable Type
private static Type NullableType = typeof(Nullable<>);
/// <summary>
/// Returns the number of all registered properties.
/// </summary>
internal static int RegisteredPropertyCount {
get {
return RegisteredPropertyList.Count;
}
}
/// <summary>
/// Returns an enumeration of properties that are
/// currently registered.
/// Synchronized (write locks, lock-free reads): Covered by DependencyProperty.Synchronized
/// </summary>
internal static IEnumerable RegisteredProperties {
get {
foreach(DependencyProperty dp in RegisteredPropertyList.List) {
if (dp != null) {
yield return dp;
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Theodis.Algorithm
{
/// <summary>
/// An ordered queue.
/// </summary>
/// <typeparam name="T">The type of the items in the queue.</typeparam>
public class PriorityQueue<T>
{
private List<T> L;
private Comparison<T> cmp;
private void Fix(int i)
{
int child = i + 1;
T item = L[i];
while (child < L.Count)
{
if (child + 1 < L.Count && cmp(L[child], L[child + 1]) > 0)
child++;
if (cmp(item, L[child]) > 0)
{
L[i] = L[child];
i = child;
}
else
break;
child = i + 1;
}
L[i] = item;
}
/// <summary>
/// Removes an item at index i in the queue.
/// </summary>
/// <param name="i">Index of the item to be removed.</param>
public void Remove(int i)
{
L[i] = L[L.Count - 1];
L.RemoveAt(L.Count - 1);
if (i < L.Count - 1)
Fix(i);
}
public bool Empty { get { return L.Count == 0; } }
public T this[int i] { get { return L[i]; } }
public int Count { get { return L.Count; } }
/// <summary>
/// Adds an item to the queue.
/// </summary>
/// <param name="d">Item to be added.</param>
public void Enqueue(T d)
{
int i, j;
L.Add(d);
i = L.Count - 1;
j = i >> 1;
while (i > 0 && cmp(L[j], L[i]) > 0)
{
T tmp = L[i];
L[i] = L[j];
L[j] = tmp;
i = j;
j >>= 1;
}
}
/// <summary>
/// Removes the item at the front of the queue.
/// </summary>
/// <returns>Item at the front of the queue.</returns>
public T Dequeue()
{
T ret = L[0];
Remove(0);
return ret;
}
/// <summary>
/// Basic constructor.
/// </summary>
/// <param name="compare">The function that determines the order of the items on the queue.</param>
public PriorityQueue(Comparison<T> compare)
{
L = new List<T>();
cmp = compare;
}
/// <summary>
/// Cuts the length of the queue by removing items at the end of the line.
/// </summary>
/// <param name="newlen">The new length of the queue.</param>
public void Cut(int newlen)
{
if(newlen < L.Count)
L.RemoveRange(newlen, L.Count - newlen);
}
}
class PathNode<T>
{
public T source;
public PathNode<T> prevNode;
public double f;
public double g;
public double h;
public int nt;
public PathNode(T s, PathNode<T> p, double pg, double ph, int pnt, Dictionary<T, double> bestF)
{
source = s;
prevNode = p;
g = pg;
h = ph;
f = g + h;
nt = pnt;
if (bestF.ContainsKey(s))
bestF[s] = f;
else
bestF.Add(s, f);
}
}
/// <summary>
/// NOT_FOUND - This node is not a node being searched for
/// FINISHED - This node is a node being searched for and
/// no more nodes are being searched for.
/// ADD_PATH - This node is a node being searched for but
/// continue looking for more.
/// </summary>
public enum FinishedFlags
{
NOT_FOUND = 0,
FINISHED = 1,
ADD_PATH = 2
}
/// <summary>
/// INTERIOR - All the nodes leading to the finishing nodes.
/// FINISHED - The nodes with the terminating condition.
/// </summary>
public enum DijkstraIncludeFlags
{
INTERIOR = 1,
FINISHED = 2,
BOTH = 3
}
public class Pathfinder<T>
{
public delegate FinishedFlags Finished(T node, double g);
public delegate List<T> Adjacent(T node);
public delegate double Distance(T a, T b);
public delegate int NodeDist(T a, T b);
private static int PathWeightCompare(PathNode<T> a, PathNode<T> b)
{
return (int)(a.f - b.f);
}
/// <summary>
/// A* pathfinder.
/// </summary>
/// <param name="start">The node to begin the search at.</param>
/// <param name="end">The node to find from the start.</param>
/// <param name="adj">A function which returns nodes adjacent to the passed in node.</param>
/// <param name="dist">A function that gives the distance and estimated distance between nodes.</param>
/// <param name="maxnodes">The maximum number of nodes to keep on the open list. 0 for unlimited.</param>
/// <param name="maxnodedepth">The maximum path length that can be made. 0 for unlimited.</param>
/// <param name="mintargetdist">The minimum acceptable distance to the target before ending the search.</param>
/// <param name="minnodedist">A function that returns the minimum number of node transitions between 2 nodes. Pass in null if no such function is availible. Optimizes search time in conjunction with a passed in minnodedepth.</param>
/// <returns>A list of nodes going from start to end or null in the event no path could be found.</returns>
public static List<T> AStar(T start, T end, Adjacent adj, Distance dist, int maxnodes, int maxnodedepth, int mintargetdist, NodeDist minnodedist)
{
Comparison<PathNode<T>> pwc = new Comparison<PathNode<T>>(PathWeightCompare);
PriorityQueue<PathNode<T>> open = new PriorityQueue<PathNode<T>>(pwc);
Dictionary<T, double> bestF = new Dictionary<T, double>();
List<T> path = null;
open.Enqueue(new PathNode<T>(start, null, 0, dist(start, end), 0, bestF));
while (!open.Empty)
{
PathNode<T> cur = open.Dequeue();
bool closeenough = false;
if (mintargetdist > 0)
closeenough = dist(cur.source, end) <= mintargetdist;
if (cur.source.Equals(end) || closeenough)
{
Stack<T> s = new Stack<T>();
path = new List<T>();
s.Push(cur.source);
while (cur.prevNode != null)
{
cur = cur.prevNode;
s.Push(cur.source);
}
while (s.Count > 0)
path.Add(s.Pop());
break;
}
List<T> L = adj(cur.source);
if (minnodedist != null && maxnodedepth != 0)
{
if (minnodedist(cur.source, end) + cur.nt >= maxnodedepth)
continue;
}
else if (maxnodedepth != 0)
if (cur.nt >= maxnodedepth)
continue;
foreach (T d in L)
{
double ng = cur.g + dist(cur.source, d);
if (bestF.ContainsKey(d))
{
if (ng + dist(d, end) < bestF[d])
{
for (int i = 0; i < open.Count; i++)
if (open[i].source.Equals(d))
{
open.Remove(i);
break;
}
}
else
continue;
}
open.Enqueue(new PathNode<T>(d, cur, ng, dist(d, end), cur.nt + 1, bestF));
}
if (maxnodes != 0 && open.Count > maxnodes)
open.Cut(maxnodes);
}
return path;
}
/// <summary>
/// Dijkstra pathfinder.
/// </summary>
/// <param name="start">The node to begin the search at.</param>
/// <param name="adj">A function which returns nodes adjacent to the passed in node.</param>
/// <param name="dist">A function that gives the distance between nodes.</param>
/// <param name="fin">A function that returns whether or not the node passed in is the end of the search.</param>
/// <param name="maxnodedepth">The maximum path length.</param>
/// <returns>A list of paths to the different finishing nodes found.</returns>
public static List<List<T>> Dijkstra(T start,Adjacent adj, Distance dist, Finished fin, int maxnodedepth)
{
Comparison<PathNode<T>> pwc = new Comparison<PathNode<T>>(PathWeightCompare);
PriorityQueue<PathNode<T>> open = new PriorityQueue<PathNode<T>>(pwc);
Dictionary<T, double> bestF = new Dictionary<T, double>();
List<List<T>> path = new List<List<T>>();
open.Enqueue(new PathNode<T>(start, null, 0, 0, 0, bestF));
while (!open.Empty)
{
PathNode<T> cur = open.Dequeue();
FinishedFlags isDone = fin(cur.source, cur.g);
if (isDone != 0)
{
Stack<T> s = new Stack<T>();
s.Push(cur.source);
while (cur.prevNode != null)
{
cur = cur.prevNode;
s.Push(cur.source);
}
path.Add(new List<T>());
while (s.Count > 0)
path[path.Count-1].Add(s.Pop());
}
if ((isDone & FinishedFlags.FINISHED) != 0)
break;
List<T> L = adj(cur.source);
if (maxnodedepth != 0 && cur.nt >= maxnodedepth)
continue;
foreach (T d in L)
{
double ng = cur.g + dist(cur.source, d);
if (bestF.ContainsKey(d))
{
if (ng < bestF[d])
{
for (int i = 0; i < open.Count; i++)
if (open[i].source.Equals(d))
{
open.Remove(i);
break;
}
}
else
continue;
}
open.Enqueue(new PathNode<T>(d, cur, ng, 0, cur.nt + 1, bestF));
}
}
return path;
}
/// <summary>
/// Retrieves a field of nodes that were on the way to or the finish nodes themselves.
/// </summary>
/// <param name="start">The node to begin the search on.</param>
/// <param name="adj">A function which returns nodes adjacent to the passed in node.</param>
/// <param name="dist">A function that gives the distance between nodes.</param>
/// <param name="fin">A function that returns whether or not the node passed in is an end point.</param>
/// <param name="include">A set of flags for what to return. INTERIOR are the nodes that lead to the FINISHED nodes. BOTH returns botht he INTERIOR and FINISHED nodes.</param>
/// <param name="maxnodedepth">The maximum length path.</param>
/// <returns>A field of nodes that lead to the finishing nodes.</returns>
public static List<T> DijkstraNodeInRange(T start, Adjacent adj, Distance dist, Finished fin, DijkstraIncludeFlags include, int maxnodedepth)
{
Comparison<PathNode<T>> pwc = new Comparison<PathNode<T>>(PathWeightCompare);
PriorityQueue<PathNode<T>> open = new PriorityQueue<PathNode<T>>(pwc);
Dictionary<T, double> bestF = new Dictionary<T, double>();
List<T> closed = new List<T>();
List<T> finishedL = new List<T>();
open.Enqueue(new PathNode<T>(start, null, 0, 0, 0, bestF));
while (!open.Empty)
{
PathNode<T> cur = open.Dequeue();
closed.Add(cur.source);
if (fin(cur.source, cur.g) != 0)
{
finishedL.Add(cur.source);
continue;
}
List<T> L = adj(cur.source);
if (maxnodedepth != 0 && cur.nt >= maxnodedepth)
continue;
foreach (T d in L)
{
double ng = cur.g + dist(cur.source, d);
if (bestF.ContainsKey(d))
{
if (ng < bestF[d])
{
for (int i = 0; i < open.Count; i++)
if (open[i].source.Equals(d))
{
open.Remove(i);
break;
}
}
else
continue;
}
open.Enqueue(new PathNode<T>(d, cur, ng, 0, cur.nt + 1, bestF));
}
}
switch (include)
{
case DijkstraIncludeFlags.INTERIOR:
return closed;
case DijkstraIncludeFlags.FINISHED:
return finishedL;
case DijkstraIncludeFlags.BOTH:
foreach (T t in finishedL)
closed.Add(t);
return closed;
}
return null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum PromptType {
Ingredient,
Action,
Message
};
public class PromptControl : MonoBehaviour
{
[Header("General Parameters")]
public float popupSpeed = 10.0f;
public Vector2 finalScale = Vector2.one;
public Vector2 minimizedScale = new Vector2(0.4f, 0.4f);
public Vector2 finalPos = Vector2.zero;
public Vector2 minimizedPos = new Vector2(0f, -4f);
public PromptType type;
[Header("Ingredient prompt parameters")]
public GameObject promptIngredientPrefab;
public Transform anchor;
public float separator = 4f;
[Header("Action prompt parameters")]
public GameObject content;
private float lifeTime;
private bool opened = false;
private string ingName;
private int amount;
private ShelfControl shelfControl;
private Sprite sprite;
private void Start()
{
transform.localScale = Vector2.zero;
if (type == PromptType.Ingredient)
{
shelfControl = FindObjectOfType<ShelfControl>();
}
}
public void ShowPromptAfter(float time, float lifeTime)
{
this.lifeTime = lifeTime;
opened = false;
StartCoroutine(ShowAfter(time, null, false));
}
public void ShowPromptAfter(float time, float lifeTime, Action doAfter, bool after)
{
this.lifeTime = lifeTime;
opened = false;
StartCoroutine(ShowAfter(time, doAfter, after));
}
public void Hide(Action function)
{
StartCoroutine(AnimateScaleAndPosition(Vector2.zero, transform.position, function));
}
public void Show(Action function)
{
StartCoroutine(AnimateScaleAndPosition(minimizedScale, transform.position, function));
}
public void SetIngredient(Sprite sprt, int amount, string name)
{
sprite = sprt;
ingName = name;
this.amount = amount;
}
public void ChangeSprite()
{
foreach (Transform t in anchor)
{
Destroy(t.gameObject);
}
List<GameObject> elements = new List<GameObject>();
for (int i = 0; i < amount; ++i)
{
GameObject pi = Instantiate(promptIngredientPrefab);
pi.transform.parent = anchor;
pi.transform.localScale = new Vector2(0.8f, 0.8f);
pi.GetComponent<SpriteRenderer>().sprite = sprite;
elements.Add(pi);
}
float position;
if (elements.Count % 2 == 0)
{
position = -(elements.Count / 2) * separator + separator / 2;
}
else
{
position = -((elements.Count - 1) / 2) * separator;
}
foreach (GameObject e in elements)
{
e.transform.localPosition = new Vector2(position, 0);
position += separator;
}
}
private IEnumerator AnimateScaleAndPosition(Vector3 finalScale, Vector3 finalPosition, Action function)
{
float startTime = Time.time;
Vector3 initialScale = transform.localScale;
Vector3 initialPosition = transform.localPosition;
float distance = Vector3.Distance(initialScale, finalScale);
float distCovered = 0, fracJourney = 0;
while (fracJourney < 1)
{
distCovered = (Time.time - startTime) * popupSpeed;
fracJourney = distCovered / distance;
transform.localScale = Vector3.Lerp(initialScale, finalScale, fracJourney);
transform.localPosition = Vector3.Lerp(initialPosition, finalPosition, fracJourney);
yield return false;
}
transform.localScale = finalScale;
transform.localPosition = finalPosition;
if (function != null)
{
function();
}
}
public void PlayAnimations()
{
foreach (Animator animator in content.GetComponentsInChildren<Animator>())
{
if (animator != null)
{
Debug.Log("Anim");
animator.Play("Animation");
}
}
}
public void SetContent(GameObject gameobject)
{
content.SetActive(false);
content = gameobject;
content.SetActive(true);
}
//Shows Prompt after shelf closes
private IEnumerator ShowAfter(float time, Action function, bool after)
{
float startTime = Time.time;
while (Time.time - startTime < time)
{
yield return false;
}
if (type == PromptType.Ingredient)
{
shelfControl.PlaceIngredients();
PlaySound();
}
else if (type == PromptType.Action)
{
PlayAnimations();
}
if (after)
{
StartCoroutine(AnimateScaleAndPosition(finalScale, finalPos, () =>
{
if (!opened)
{
StartCoroutine(CloseAfter(lifeTime, function));
opened = true;
}
}));
}
else
{
function();
StartCoroutine(AnimateScaleAndPosition(finalScale, finalPos, () =>
{
if (!opened)
{
StartCoroutine(CloseAfter(lifeTime, null));
opened = true;
}
}));
}
}
//closes prompt after set period of time
private IEnumerator CloseAfter(float time, Action function)
{
float startTime = Time.time;
while (Time.time - startTime < time)
{
yield return false;
}
StartCoroutine(AnimateScaleAndPosition(minimizedScale, minimizedPos, function));
if (type == PromptType.Ingredient)
{
shelfControl.OpenShelf();
}
}
private void PlaySound() {
switch (type) {
case PromptType.Ingredient:
if (amount == 1)
{
AkSoundEngine.SetSwitch("Number", "One", GameObject.FindGameObjectWithTag("Prompt"));
}
if (amount == 2)
{
AkSoundEngine.SetSwitch("Number", "Two", GameObject.FindGameObjectWithTag("Prompt"));
}
if (ingName == "flour")
{
AkSoundEngine.SetSwitch("Ingredients", "Flour", GameObject.FindGameObjectWithTag("Prompt"));
}
if (ingName == "sugar")
{
AkSoundEngine.SetSwitch("Ingredients", "Sugar", GameObject.FindGameObjectWithTag("Prompt"));
}
if (ingName == "salt")
{
AkSoundEngine.SetSwitch("Ingredients", "Salt", GameObject.FindGameObjectWithTag("Prompt"));
}
if (ingName == "butter")
{
AkSoundEngine.SetSwitch("Ingredients", "Butter", GameObject.FindGameObjectWithTag("Prompt"));
}
AkSoundEngine.PostEvent("IngredientPrompt", GameObject.FindGameObjectWithTag("Prompt"));
break;
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Extensions;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.DragDrop;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
namespace DragAndDrop
{
internal class DragAndDropDockpane1ViewModel : DockPane, IDragSource
{
private const string _dockPaneID = "DragAndDrop_DragAndDropDockpane1";
protected DragAndDropDockpane1ViewModel() { }
/// <summary>
/// Show the DockPane.
/// </summary>
internal static void Show()
{
DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
if (pane == null)
return;
pane.Activate();
}
/// <summary>
/// Text shown near the top of the DockPane.
/// </summary>
private string _heading = "Drag and Drop Dockpane";
public string Heading
{
get { return _heading; }
set
{
SetProperty(ref _heading, value, () => Heading);
}
}
private string _name = "Drag and Drop File GDB Here";
public string Name
{
get { return _name; }
set
{
SetProperty(ref _name, value, () => Name);
}
}
private ObservableCollection<GDBBaseItem> _gdbItems = new ObservableCollection<GDBBaseItem>();
public ObservableCollection<GDBBaseItem> GDBItems
{
get { return _gdbItems; }
set
{
SetProperty(ref _gdbItems, value, () => GDBItems);
}
}
#region Drag and Drop handler
public override async void OnDrop(DropInfo dropInfo)
{
//eg, if you are accessing a dropped file
string filePath = dropInfo.Items[0].Data.ToString();
if (dropInfo.Data is List<ClipboardItem> clipboardItems) //Dropped from Catalog
{
var thisItem = clipboardItems.FirstOrDefault();
var itemInfo = thisItem.ItemInfoValue.typeID;
if (itemInfo != "database_fgdb") //Not a file gdb
{
dropInfo.Handled = false;
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show($"Drag and drop File GDB only here");
return;
}
Name = thisItem.CatalogPath;
}
else //Dropped from File Explorer
{
FileInfo file = new FileInfo(filePath);
if (string.Compare(file.Extension, ".gdb", true) == 0) //.gdb
{
Name = filePath;
dropInfo.Handled = true;
}
else //Not a .gdb
{
dropInfo.Handled = false;
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show($"Drag and drop File GDB only here");
return;
}
}
GDBItems = await GetGDBItemsAsync();
//set to true if you handled the drop
dropInfo.Handled = true;
}
public override void OnDragOver(DropInfo dropInfo)
{
//default is to accept our data types
dropInfo.Effects = DragDropEffects.All;
}
#endregion
#region Private methods
private async Task<ObservableCollection<GDBBaseItem>> GetGDBItemsAsync()
{
var gdbItems = await QueuedTask.Run<ObservableCollection<GDBBaseItem>>(() =>
{
List<GDBBaseItem> lstGDBBaseItems = new List<GDBBaseItem>();
//Database becomes the root node
var path = Name;
var root = new DatabaseGDBItem { DBName = System.IO.Path.GetFileName(Name), Name = path, Path = path };
lstGDBBaseItems.Add(root);
// use the geodatabase to get all layers
var fGdbPath = new FileGeodatabaseConnectionPath(new Uri(Name, UriKind.Absolute));
using (var gdb = new Geodatabase(fGdbPath))
{
IReadOnlyList<Definition> fcList = gdb.GetDefinitions<FeatureClassDefinition>();
//Feature class
foreach (FeatureClassDefinition fcDef in fcList)
{
var fc = gdb.OpenDataset<FeatureClass>(fcDef.GetName());
var fd = fc.GetFeatureDataset();
var fc_path = (fd == null) ? path : path + @"\" + fd.GetName();
fc.Dispose();
fd?.Dispose();
switch (fcDef.GetShapeType())
{
case GeometryType.Point:
var pointfcItem = new PointFCGDBItem { Name = fcDef.GetName(), Path = fc_path };
root.Children.Add(pointfcItem);
break;
case GeometryType.Polyline:
var linefcItem = new LineFCGDBItem { Name = fcDef.GetName(), Path = fc_path };
root.Children.Add(linefcItem);
break;
case GeometryType.Polygon:
var polyfcItem = new PolygonFCGDBItem { Name = fcDef.GetName(), Path = fc_path };
root.Children.Add(polyfcItem);
break;
}
}
}
root.IsExpanded = true;
return new ObservableCollection<GDBBaseItem>(lstGDBBaseItems);
});
return gdbItems;
}
public void StartDrag(DragInfo dragInfo)
{
var sourceItem = dragInfo.SourceItem;
if (sourceItem == null)
return;
var gdbItem = dragInfo.SourceItem as GDBBaseItem;
if (gdbItem == null)
return;
if (gdbItem is DatabaseGDBItem)
return;//no dragging of the gdb
List<ClipboardItem> clip_items = new List<ClipboardItem>();
clip_items.Add(new ClipboardItem()
{
ItemInfoValue = gdbItem.GetItemInfoValue()
});
dragInfo.Data = clip_items;
dragInfo.Effects = DragDropEffects.Copy;
}
#endregion
}
/// <summary>
/// Button implementation to show the DockPane.
/// </summary>
internal class DragAndDropDockpane1_ShowButton : Button
{
protected override void OnClick()
{
DragAndDropDockpane1ViewModel.Show();
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Candles.Algo
File: Candle.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Candles
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Serialization;
using Ecng.Common;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
using StockSharp.Localization;
using Compression;
/// <summary>
/// Base candle class (contains main parameters).
/// </summary>
[DataContract]
[Serializable]
[KnownType(typeof(TickCandle))]
[KnownType(typeof(VolumeCandle))]
[KnownType(typeof(RangeCandle))]
[KnownType(typeof(TimeFrameCandle))]
[KnownType(typeof(PnFCandle))]
[KnownType(typeof(RenkoCandle))]
public abstract class Candle : Cloneable<Candle>
{
/// <summary>
/// Security.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.SecurityKey)]
[DescriptionLoc(LocalizedStrings.SecurityKey, true)]
public Security Security { get; set; }
private DateTimeOffset _openTime;
/// <summary>
/// Open time.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.CandleOpenTimeKey)]
[DescriptionLoc(LocalizedStrings.CandleOpenTimeKey, true)]
public DateTimeOffset OpenTime
{
get { return _openTime; }
set
{
//ThrowIfFinished();
_openTime = value;
}
}
private DateTimeOffset _closeTime;
/// <summary>
/// Close time.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.CandleCloseTimeKey)]
[DescriptionLoc(LocalizedStrings.CandleCloseTimeKey, true)]
public DateTimeOffset CloseTime
{
get { return _closeTime; }
set
{
//ThrowIfFinished();
_closeTime = value;
}
}
private DateTimeOffset _highTime;
/// <summary>
/// High time.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.CandleHighTimeKey)]
[DescriptionLoc(LocalizedStrings.CandleHighTimeKey, true)]
public DateTimeOffset HighTime
{
get { return _highTime; }
set
{
//ThrowIfFinished();
_highTime = value;
}
}
private DateTimeOffset _lowTime;
/// <summary>
/// Low time.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.CandleLowTimeKey)]
[DescriptionLoc(LocalizedStrings.CandleLowTimeKey, true)]
public DateTimeOffset LowTime
{
get { return _lowTime; }
set
{
//ThrowIfFinished();
_lowTime = value;
}
}
private decimal _openPrice;
/// <summary>
/// Opening price.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.Str79Key)]
[DescriptionLoc(LocalizedStrings.Str80Key)]
public decimal OpenPrice
{
get { return _openPrice; }
set
{
//ThrowIfFinished();
_openPrice = value;
}
}
private decimal _closePrice;
/// <summary>
/// Closing price.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.ClosingPriceKey)]
[DescriptionLoc(LocalizedStrings.Str86Key)]
public decimal ClosePrice
{
get { return _closePrice; }
set
{
//ThrowIfFinished();
_closePrice = value;
}
}
private decimal _highPrice;
/// <summary>
/// Maximum price.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.Str81Key)]
[DescriptionLoc(LocalizedStrings.Str82Key)]
public decimal HighPrice
{
get { return _highPrice; }
set
{
//ThrowIfFinished();
_highPrice = value;
}
}
private decimal _lowPrice;
/// <summary>
/// Minimum price.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.Str83Key)]
[DescriptionLoc(LocalizedStrings.Str84Key)]
public decimal LowPrice
{
get { return _lowPrice; }
set
{
//ThrowIfFinished();
_lowPrice = value;
}
}
private decimal _totalPrice;
/// <summary>
/// Total trades volume.
/// </summary>
[DataMember]
public decimal TotalPrice
{
get { return _totalPrice; }
set
{
//ThrowIfFinished();
_totalPrice = value;
}
}
private decimal? _openVolume;
/// <summary>
/// Volume at open.
/// </summary>
[DataMember]
public decimal? OpenVolume
{
get { return _openVolume; }
set
{
//ThrowIfFinished();
_openVolume = value;
}
}
private decimal? _closeVolume;
/// <summary>
/// Volume at close.
/// </summary>
[DataMember]
public decimal? CloseVolume
{
get { return _closeVolume; }
set
{
//ThrowIfFinished();
_closeVolume = value;
}
}
private decimal? _highVolume;
/// <summary>
/// Volume at high.
/// </summary>
[DataMember]
public decimal? HighVolume
{
get { return _highVolume; }
set
{
//ThrowIfFinished();
_highVolume = value;
}
}
private decimal? _lowVolume;
/// <summary>
/// Minimum volume.
/// </summary>
[DataMember]
public decimal? LowVolume
{
get { return _lowVolume; }
set
{
//ThrowIfFinished();
_lowVolume = value;
}
}
private decimal _totalVolume;
/// <summary>
/// Total volume.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.VolumeKey)]
[DescriptionLoc(LocalizedStrings.TotalCandleVolumeKey)]
public decimal TotalVolume
{
get { return _totalVolume; }
set
{
//ThrowIfFinished();
_totalVolume = value;
}
}
private decimal? _relativeVolume;
/// <summary>
/// Relative colume.
/// </summary>
[DataMember]
public decimal? RelativeVolume
{
get { return _relativeVolume; }
set
{
//ThrowIfFinished();
_relativeVolume = value;
}
}
//[field: NonSerialized]
//private CandleSeries _series;
///// <summary>
///// Candles series.
///// </summary>
//public CandleSeries Series
//{
// get { return _series; }
// set { _series = value; }
//}
//[field: NonSerialized]
//private ICandleManagerSource _source;
///// <summary>
///// Candle's source.
///// </summary>
//public ICandleManagerSource Source
//{
// get { return _source; }
// set { _source = value; }
//}
/// <summary>
/// Candle arg.
/// </summary>
public abstract object Arg { get; set; }
private int? _totalTicks;
/// <summary>
/// Number of ticks.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.TicksKey)]
[DescriptionLoc(LocalizedStrings.TickCountKey)]
public int? TotalTicks
{
get { return _totalTicks; }
set
{
//ThrowIfFinished();
_totalTicks = value;
}
}
private int? _upTicks;
/// <summary>
/// Number of uptrending ticks.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.TickUpKey)]
[DescriptionLoc(LocalizedStrings.TickUpCountKey)]
public int? UpTicks
{
get { return _upTicks; }
set
{
//ThrowIfFinished();
_upTicks = value;
}
}
private int? _downTicks;
/// <summary>
/// Number of downtrending ticks.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.TickDownKey)]
[DescriptionLoc(LocalizedStrings.TickDownCountKey)]
public int? DownTicks
{
get { return _downTicks; }
set
{
//ThrowIfFinished();
_downTicks = value;
}
}
private CandleStates _state;
/// <summary>
/// State.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.StateKey)]
[DescriptionLoc(LocalizedStrings.CandleStateKey)]
public CandleStates State
{
get { return _state; }
set
{
ThrowIfFinished();
_state = value;
}
}
/// <summary>
/// Price levels.
/// </summary>
[DataMember]
public IEnumerable<CandlePriceLevel> PriceLevels { get; set; }
/// <summary>
/// Open interest.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.OIKey)]
[DescriptionLoc(LocalizedStrings.OpenInterestKey)]
public decimal? OpenInterest { get; set; }
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return "{0:HH:mm:ss} {1} (O:{2}, H:{3}, L:{4}, C:{5}, V:{6})"
.Put(OpenTime, GetType().Name + "_" + Security + "_" + Arg, OpenPrice, HighPrice, LowPrice, ClosePrice, TotalVolume);
}
private void ThrowIfFinished()
{
if (State == CandleStates.Finished)
throw new InvalidOperationException(LocalizedStrings.Str649);
}
/// <summary>
/// Copy the message into the <paramref name="destination" />.
/// </summary>
/// <typeparam name="TCandle">The candle type.</typeparam>
/// <param name="destination">The object, which copied information.</param>
/// <returns>The object, which copied information.</returns>
protected TCandle CopyTo<TCandle>(TCandle destination)
where TCandle : Candle
{
destination.Arg = Arg;
destination.ClosePrice = ClosePrice;
destination.CloseTime = CloseTime;
destination.CloseVolume = CloseVolume;
destination.DownTicks = DownTicks;
destination.HighPrice = HighPrice;
destination.HighTime = HighTime;
destination.HighVolume = HighVolume;
destination.LowPrice = LowPrice;
destination.LowTime = LowTime;
destination.LowVolume = LowVolume;
destination.OpenInterest = OpenInterest;
destination.OpenPrice = OpenPrice;
destination.OpenTime = OpenTime;
destination.OpenVolume = OpenVolume;
destination.RelativeVolume = RelativeVolume;
destination.Security = Security;
//destination.Series = Series;
//destination.Source = Source;
//destination.State = State;
destination.TotalPrice = TotalPrice;
destination.TotalTicks = TotalTicks;
destination.TotalVolume = TotalVolume;
//destination.VolumeProfileInfo = VolumeProfileInfo;
destination.PriceLevels = PriceLevels?.Select(l => l.Clone()).ToArray();
return destination;
}
// for performance reason
internal void Update(ICandleBuilderSourceValue value)
{
ThrowIfFinished();
var price = value.Price;
var volume = value.Volume;
var time = value.Time;
if (price < _lowPrice)
{
_lowPrice = price;
_lowTime = time;
}
if (price > _highPrice)
{
_highPrice = price;
_highTime = time;
}
_closePrice = price;
_totalPrice += price * volume;
_lowVolume = (_lowVolume ?? 0m).Min(volume);
_highVolume = (_highVolume ?? 0m).Max(volume);
_closeVolume = volume;
_totalVolume += volume;
var dir = value.OrderDirection;
if (dir != null)
_relativeVolume = (_relativeVolume ?? 0) + (dir.Value == Sides.Buy ? volume : -volume);
_closeTime = time;
}
}
/// <summary>
/// Time-frame candle.
/// </summary>
[DataContract]
[Serializable]
[DisplayName("Time Frame")]
public class TimeFrameCandle : Candle
{
/// <summary>
/// Time-frame.
/// </summary>
[DataMember]
public TimeSpan TimeFrame { get; set; }
/// <summary>
/// Candle arg.
/// </summary>
public override object Arg
{
get { return TimeFrame; }
set { TimeFrame = (TimeSpan)value; }
}
/// <summary>
/// Create a copy of <see cref="TimeFrameCandle"/>.
/// </summary>
/// <returns>Copy.</returns>
public override Candle Clone()
{
return CopyTo(new TimeFrameCandle());
}
}
/// <summary>
/// Tick candle.
/// </summary>
[DataContract]
[Serializable]
[DisplayName("Tick")]
public class TickCandle : Candle
{
/// <summary>
/// Maximum tick count.
/// </summary>
[DataMember]
public int MaxTradeCount { get; set; }
/// <summary>
/// Current tick count.
/// </summary>
[DataMember]
public int CurrentTradeCount { get; set; }
/// <summary>
/// Candle arg.
/// </summary>
public override object Arg
{
get { return MaxTradeCount; }
set { MaxTradeCount = (int)value; }
}
/// <summary>
/// Create a copy of <see cref="TickCandle"/>.
/// </summary>
/// <returns>Copy.</returns>
public override Candle Clone()
{
return CopyTo(new TickCandle());
}
}
/// <summary>
/// Volume candle.
/// </summary>
[DataContract]
[Serializable]
[DisplayName("Volume")]
public class VolumeCandle : Candle
{
/// <summary>
/// Maximum volume.
/// </summary>
[DataMember]
public decimal Volume { get; set; }
/// <summary>
/// Candle arg.
/// </summary>
public override object Arg
{
get { return Volume; }
set { Volume = (decimal)value; }
}
/// <summary>
/// Create a copy of <see cref="VolumeCandle"/>.
/// </summary>
/// <returns>Copy.</returns>
public override Candle Clone()
{
return CopyTo(new VolumeCandle());
}
}
/// <summary>
/// Range candle.
/// </summary>
[DataContract]
[Serializable]
[DisplayName("Range")]
public class RangeCandle : Candle
{
/// <summary>
/// Range of price.
/// </summary>
[DataMember]
public Unit PriceRange { get; set; }
/// <summary>
/// Candle arg.
/// </summary>
public override object Arg
{
get { return PriceRange; }
set { PriceRange = (Unit)value; }
}
/// <summary>
/// Create a copy of <see cref="RangeCandle"/>.
/// </summary>
/// <returns>Copy.</returns>
public override Candle Clone()
{
return CopyTo(new RangeCandle());
}
}
/// <summary>
/// The candle of point-and-figure chart (tac-toe chart).
/// </summary>
[DataContract]
[Serializable]
[DisplayName("X&0")]
public class PnFCandle : Candle
{
/// <summary>
/// Value of arguments.
/// </summary>
[DataMember]
public PnFArg PnFArg { get; set; }
/// <summary>
/// Type of symbols.
/// </summary>
[DataMember]
public PnFTypes Type { get; set; }
/// <summary>
/// Candle arg.
/// </summary>
public override object Arg
{
get { return PnFArg; }
set { PnFArg = (PnFArg)value; }
}
/// <summary>
/// Create a copy of <see cref="PnFCandle"/>.
/// </summary>
/// <returns>Copy.</returns>
public override Candle Clone()
{
return CopyTo(new PnFCandle { Type = Type });
}
}
/// <summary>
/// Renko candle.
/// </summary>
[DataContract]
[Serializable]
[DisplayName("Renko")]
public class RenkoCandle : Candle
{
/// <summary>
/// Possible price change range.
/// </summary>
[DataMember]
public Unit BoxSize { get; set; }
/// <summary>
/// Candle arg.
/// </summary>
public override object Arg
{
get { return BoxSize; }
set { BoxSize = (Unit)value; }
}
/// <summary>
/// Create a copy of <see cref="RenkoCandle"/>.
/// </summary>
/// <returns>Copy.</returns>
public override Candle Clone()
{
return CopyTo(new RenkoCandle());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Globalization;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Diagnostics.Tracing;
using Xunit;
using Sdt = SdtEventSources;
namespace BasicEventSourceTests
{
public class TestsManifestNegative
{
#region Message string building
public static string GetResourceString(string key, params object[] args)
{
string fmt = GetResourceStringFromReflection(key);
if (fmt != null)
return string.Format(fmt, args);
return key + " (" + string.Join(", ", args) + ")";
}
private static string GetResourceStringFromReflection(string key)
{
BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
if (!PlatformDetection.IsFullFramework)
{
Type sr = typeof(EventSource).Assembly.GetType("System.SR", throwOnError: true, ignoreCase: false);
PropertyInfo resourceProp = sr.GetProperty(key, flags);
return (string)resourceProp.GetValue(null);
}
Type[] paramsType = new Type[] { typeof(string) };
MethodInfo getResourceString = typeof(Environment).GetMethod("GetResourceString", flags, null, paramsType, null);
return (string)getResourceString.Invoke(null, new object[] { key });
}
#endregion
/// <summary>
/// These tests use the NuGet EventSource to validate *both* NuGet and BCL user-defined EventSources
/// For NuGet EventSources we validate both "runtime" and "validation" behavior
/// </summary>
[ActiveIssue("dotnet/corefx #19091", TargetFrameworkMonikers.NetFramework)]
[Fact]
public void Test_GenerateManifest_InvalidEventSources()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
// specify AllowEventSourceOverride - this is needed for Sdt event sources and won't make a difference for Sdt ones
var strictOptions = EventManifestOptions.Strict | EventManifestOptions.AllowEventSourceOverride;
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty));
Exception e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_TypeMustBeSealedOrAbstract"), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_TypeMustBeSealedOrAbstract"), e.Message);
// starting with NuGet we allow non-void returning methods as long as they have the [Event] attribute
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty));
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty, strictOptions));
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride));
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty));
Assert.Equal(GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride));
Assert.Equal(GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.OutOfRangeKwdEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_IllegalKeywordsValue", "Kwd1", "0x100000000000"),
GetResourceString("EventSource_KeywordCollision", "Session3", "Kwd1", "0x100000000000")),
e.Message);
#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
e = AssertExtensions.Throws<ArgumentException>(GetResourceString("EventSource_MaxChannelExceeded"),
() => EventSource.GenerateManifest(typeof(Sdt.TooManyChannelsEventSource), string.Empty));
#endif
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
e = AssertExtensions.Throws<ArgumentException>(GetResourceString("EventSource_EventWithAdminChannelMustHaveMessage", "WriteInteger", "Admin"),
() => EventSource.GenerateManifest(typeof(Sdt.EventWithAdminChannelNoMessageEventSource), string.Empty, strictOptions));
#endif // USE_ETW
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ReservedOpcodeEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_IllegalOpcodeValue", "Op1", 3),
GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1)),
e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ReservedOpcodeEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_IllegalOpcodeValue", "Op1", 3),
GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1)),
e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty));
Assert.Equal(GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger"), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_EnumKindMismatch", "Op1", "EventKeywords", "Opcodes"),
GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger")),
e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride));
Assert.Equal(GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger"), e.Message);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty));
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_MismatchIdToWriteEvent", "WriteInteger", 10, 1), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_MismatchIdToWriteEvent", "WriteInteger", 10, 1), e.Message);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty));
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_EventIdReused", "WriteInteger2", 1, "WriteInteger1"),
GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 1, "WriteInteger1", 1)),
e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_EventIdReused", "WriteInteger2", 1, "WriteInteger1"),
GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 1, "WriteInteger1", 1)),
e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventNameReusedEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_EventNameReused", "WriteInteger"), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventNameReusedEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_EventNameReused", "WriteInteger"), e.Message);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty));
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 2, "WriteInteger1", 1), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 2, "WriteInteger1", 1), e.Message);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty));
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1), e.Message);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithInvalidMessageEventSource), string.Empty));
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithInvalidMessageEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_UnsupportedMessageProperty", "WriteString", "Message = {0,12:G}"), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithKwdTaskOpcodeEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Keywords"),
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Tasks"),
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Opcodes")),
e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithKwdTaskOpcodeEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Keywords"),
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Tasks"),
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Opcodes")),
e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithEventsEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", "WriteInteger", 1), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithEventsEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", "WriteInteger", 1), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ImplementsInterfaceEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_EventMustNotBeExplicitImplementation", "SdtEventSources.ILogging.Error", 1), e.Message);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ImplementsInterfaceEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_EventMustNotBeExplicitImplementation", "SdtEventSources.ILogging.Error", 1), e.Message);
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
}
}
| |
using System;
namespace VaultAtlas.DataModel
{
[Flags]
public enum DateKnownState
{
AllKnown = 0,
YearUnknown = 1,
MonthUnknown = 2,
DayUnknown = 4
}
[Serializable]
public struct ShowDate : IComparable, IFormattable, IConvertible
{
public static char[] UnknownDigits = "?Xx".ToCharArray();
private DateTime internalDate;
public DateTime InternalDate
{
get
{
return internalDate;
}
}
private long Ticks
{
get
{
return internalDate.Ticks;
}
}
private DateKnownState dateState;
public DateKnownState KnownState
{
get
{
return dateState;
}
}
public ShowDate(string showDate)
{
dateState = DateKnownState.AllKnown;
internalDate = DateTime.Now;
var fields = (showDate ?? string.Empty).Split('-', '/', ' ');
if ( fields.Length > 2 )
{
if (fields[0].IndexOfAny( UnknownDigits ) != -1)
{
this.dateState = DateKnownState.YearUnknown;
fields[0] = "1900";
}
if (fields[1].IndexOfAny( UnknownDigits ) != -1)
{
this.dateState |= DateKnownState.MonthUnknown;
fields[1] = "1";
}
if (fields[2].IndexOfAny( UnknownDigits ) != -1)
{
this.dateState |= DateKnownState.DayUnknown;
fields[2] = "1";
}
this.internalDate = new DateTime( Int32.Parse(fields[0]), Int32.Parse(fields[1]), Int32.Parse(fields[2]) );
}
}
public ShowDate(long ticks)
{
this.internalDate = new DateTime(ticks);
this.dateState = DateKnownState.AllKnown;
}
public static ShowDate Parse(string str)
{
return new ShowDate(str);
}
#region IComparable Members
public int CompareTo(object obj)
{
if (obj == null)
return 1;
if (!(obj is ShowDate))
throw new ArgumentException("CompareTo argument must be ShowDate");
DateTime dt2 = ((ShowDate)obj).internalDate;
return this.internalDate.CompareTo(dt2);
}
#endregion
#region IFormattable Members
public string ToString(string format, IFormatProvider formatProvider)
{
return internalDate.ToString(format, formatProvider);
}
public override string ToString()
{
return Year + "-" + Month + "-" + Day;
}
#endregion
public static ShowDate Now
{
get { return new ShowDate(DateTime.Now.Ticks); }
}
private static string Stuff( int s, int mask )
{
return mask != 0 ? "??" : (s > 9) ? s + "" : "0" + s;
}
public string Year
{
get
{
return (dateState & DateKnownState.YearUnknown) != 0 ? "????" : internalDate.Year.ToString();
}
}
public string Month
{
get { return Stuff(internalDate.Month, (int) (dateState & DateKnownState.MonthUnknown)); }
}
public string Day
{
get { return Stuff(internalDate.Day, (int) (dateState & DateKnownState.DayUnknown)); }
}
#region IConvertible Members
public ulong ToUInt64(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
public sbyte ToSByte(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
public double ToDouble(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
public DateTime ToDateTime(IFormatProvider provider)
{
return new DateTime(this.Ticks);
}
public float ToSingle(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
public bool ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
public int ToInt32(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
public ushort ToUInt16(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
public short ToInt16(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
string System.IConvertible.ToString(IFormatProvider provider)
{
return this.ToString( null, provider );
}
public byte ToByte(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
public char ToChar(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
public long ToInt64(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
public System.TypeCode GetTypeCode()
{
return TypeCode.Object;
}
public decimal ToDecimal(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
public object ToType(Type conversionType, IFormatProvider provider)
{
if (conversionType == typeof(ShowDate))
return this;
throw new InvalidCastException("not supported");
}
public uint ToUInt32(IFormatProvider provider)
{
throw new InvalidCastException("not supported");
}
#endregion
public static string Format(string format, ShowDate date)
{
return format.Replace("yyyy", date.Year).Replace("MM", date.Month).Replace("dd", date.Day);
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Management.Automation.Host;
using System.Globalization;
using System.Security;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// Encodes and decodes data types and exceptions for transmission across
/// the wire. Used for transmitting remote host method call parameters, return
/// values, and exceptions. The convention is that EncodeObject converts the
/// objects into a type that can be serialized and deserialized without losing
/// fidelity. For example, EncodeObject converts Version objects to string,
/// and converts more complex classes into property bags on PSObjects. This
/// guarantees that transmitting on the wire will not change the encoded
/// object's type.
/// </summary>
internal class RemoteHostEncoder
{
/// <summary>
/// Is known type.
/// </summary>
private static bool IsKnownType(Type type)
{
TypeSerializationInfo info = KnownTypes.GetTypeSerializationInfo(type);
return (info != null);
}
/// <summary>
/// Is encoding allowed for class or struct.
/// </summary>
private static bool IsEncodingAllowedForClassOrStruct(Type type)
{
// To enable encoding and decoding for a class or struct, add it here.
return
// Struct types.
type == typeof(KeyInfo) ||
type == typeof(Coordinates) ||
type == typeof(Size) ||
type == typeof(BufferCell) ||
type == typeof(Rectangle) ||
// Class types.
type == typeof(ProgressRecord) ||
type == typeof(FieldDescription) ||
type == typeof(ChoiceDescription) ||
type == typeof(HostInfo) ||
type == typeof(HostDefaultData) ||
type == typeof(RemoteSessionCapability);
}
/// <summary>
/// Encode class or struct.
/// </summary>
private static PSObject EncodeClassOrStruct(object obj)
{
PSObject psObject = RemotingEncoder.CreateEmptyPSObject();
FieldInfo[] fieldInfos = obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
// Add all the non-null field values to the ps object.
foreach (FieldInfo fieldInfo in fieldInfos)
{
object fieldValue = fieldInfo.GetValue(obj);
if (fieldValue == null)
{
continue;
}
object encodedFieldValue = EncodeObject(fieldValue);
psObject.Properties.Add(new PSNoteProperty(fieldInfo.Name, encodedFieldValue));
}
return psObject;
}
/// <summary>
/// Decode class or struct.
/// </summary>
private static object DecodeClassOrStruct(PSObject psObject, Type type)
{
object obj = ClrFacade.GetUninitializedObject(type);
// Field values cannot be null - because for null fields we simply don't transport them.
foreach (PSPropertyInfo propertyInfo in psObject.Properties)
{
FieldInfo fieldInfo = type.GetField(propertyInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (propertyInfo.Value == null) { throw RemoteHostExceptions.NewDecodingFailedException(); }
object fieldValue = DecodeObject(propertyInfo.Value, fieldInfo.FieldType);
if (fieldValue == null) { throw RemoteHostExceptions.NewDecodingFailedException(); }
fieldInfo.SetValue(obj, fieldValue);
}
return obj;
}
/// <summary>
/// Is collection.
/// </summary>
private static bool IsCollection(Type type)
{
return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Collection<>));
}
private static bool IsGenericIEnumerableOfInt(Type type)
{
return type.Equals(typeof(IEnumerable<int>));
}
/// <summary>
/// Encode collection.
/// </summary>
private static PSObject EncodeCollection(IList collection)
{
ArrayList arrayList = new ArrayList();
foreach (object obj in collection)
{
arrayList.Add(EncodeObject(obj));
}
return new PSObject(arrayList);
}
/// <summary>
/// Decode collection.
/// </summary>
private static IList DecodeCollection(PSObject psObject, Type collectionType)
{
// Get the element type.
Type[] elementTypes = collectionType.GetGenericArguments();
Dbg.Assert(elementTypes.Length == 1, "Expected elementTypes.Length == 1");
Type elementType = elementTypes[0];
// Rehydrate the collection from the array list.
ArrayList arrayList = SafelyGetBaseObject<ArrayList>(psObject);
IList collection = (IList)Activator.CreateInstance(collectionType);
foreach (object element in arrayList)
{
collection.Add(DecodeObject(element, elementType));
}
return collection;
}
/// <summary>
/// Is dictionary.
/// </summary>
private static bool IsDictionary(Type type)
{
return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Dictionary<,>));
}
/// <summary>
/// Encode dictionary.
/// </summary>
private static PSObject EncodeDictionary(IDictionary dictionary)
{
// If element type is object then encode as object-dictionary.
if (IsObjectDictionaryType(dictionary.GetType()))
{
return EncodeObjectDictionary(dictionary);
}
Hashtable hashtable = new Hashtable();
foreach (object key in dictionary.Keys)
{
hashtable.Add(EncodeObject(key), EncodeObject(dictionary[key]));
}
return new PSObject(hashtable);
}
/// <summary>
/// Decode dictionary.
/// </summary>
private static IDictionary DecodeDictionary(PSObject psObject, Type dictionaryType)
{
// If element type is object then decode as object-dictionary.
if (IsObjectDictionaryType(dictionaryType))
{
return DecodeObjectDictionary(psObject, dictionaryType);
}
// Get the element type.
Type[] elementTypes = dictionaryType.GetGenericArguments();
Dbg.Assert(elementTypes.Length == 2, "Expected elementTypes.Length == 2");
Type keyType = elementTypes[0];
Type valueType = elementTypes[1];
// Rehydrate the dictionary from the hashtable.
Hashtable hashtable = SafelyGetBaseObject<Hashtable>(psObject);
IDictionary dictionary = (IDictionary)Activator.CreateInstance(dictionaryType);
foreach (object key in hashtable.Keys)
{
dictionary.Add(
DecodeObject(key, keyType),
DecodeObject(hashtable[key], valueType));
}
return dictionary;
}
/// <summary>
/// Encode ps object.
/// </summary>
private static PSObject EncodePSObject(PSObject psObject)
{
// We are not encoding the contents of the PSObject since these can be
// arbitrarily complex. Only objects that can be serialized and deserialized
// correctly should be wrapped in PSObjects. This logic should also just do
// the right thing with PSObject subclasses. Note: This method might seem
// trivial but it must exist in order to maintain the symmetry with
// DecodePSObject. There is no perf penalty because: (a) the compiler should
// inline it, and (b) perf optimization should be based on profiling;
// premature optimization is the root of all evil.
return psObject;
}
/// <summary>
/// Decode ps object.
/// </summary>
private static PSObject DecodePSObject(object obj)
{
if (obj is PSObject)
{
return (PSObject)obj;
}
else
{
// If this is not a PSObject, wrap it in one. This case needs to be handled
// because the serializer converts Dictionary<string,PSObject> to a Hashtable
// mapping strings to strings, when the PSObject is a simple wrapper around
// string.
return new PSObject(obj);
}
}
/// <summary>
/// Encode exception.
/// </summary>
private static PSObject EncodeException(Exception exception)
{
// We are encoding exceptions as ErrorRecord objects because exceptions written
// to the wire are lost during serialization. By sending across ErrorRecord objects
// we are able to preserve the exception as well as the stack trace.
ErrorRecord errorRecord = null;
IContainsErrorRecord containsErrorRecord = exception as IContainsErrorRecord;
if (containsErrorRecord == null)
{
// If this is a .NET exception then wrap in an ErrorRecord.
errorRecord = new ErrorRecord(exception, "RemoteHostExecutionException", ErrorCategory.NotSpecified, null);
}
else
{
// Exception inside the error record is ParentContainsErrorRecordException which
// doesn't have stack trace. Replace it with top level exception.
errorRecord = containsErrorRecord.ErrorRecord;
errorRecord = new ErrorRecord(errorRecord, exception);
}
PSObject errorRecordPSObject = RemotingEncoder.CreateEmptyPSObject();
errorRecord.ToPSObjectForRemoting(errorRecordPSObject);
return errorRecordPSObject;
}
/// <summary>
/// Decode exception.
/// </summary>
private static Exception DecodeException(PSObject psObject)
{
ErrorRecord errorRecord = ErrorRecord.FromPSObjectForRemoting(psObject);
if (errorRecord == null)
{
throw RemoteHostExceptions.NewDecodingErrorForErrorRecordException();
}
else
return errorRecord.Exception;
}
/// <summary>
/// Upcast field description subclass and drop attributes.
/// </summary>
private static FieldDescription UpcastFieldDescriptionSubclassAndDropAttributes(FieldDescription fieldDescription1)
{
// Upcasts derived types back to FieldDescription type and throws away attributes.
// Create a new field description object.
FieldDescription fieldDescription2 = new FieldDescription(fieldDescription1.Name);
// Copy the fields not initialized during construction.
fieldDescription2.Label = fieldDescription1.Label;
fieldDescription2.HelpMessage = fieldDescription1.HelpMessage;
fieldDescription2.IsMandatory = fieldDescription1.IsMandatory;
fieldDescription2.DefaultValue = fieldDescription1.DefaultValue;
// Set the type related fields.
fieldDescription2.SetParameterTypeName(fieldDescription1.ParameterTypeName);
fieldDescription2.SetParameterTypeFullName(fieldDescription1.ParameterTypeFullName);
fieldDescription2.SetParameterAssemblyFullName(fieldDescription1.ParameterAssemblyFullName);
return fieldDescription2;
}
/// <summary>
/// Encode object.
/// </summary>
internal static object EncodeObject(object obj)
{
if (obj == null)
{
return null;
}
Type type = obj.GetType();
if (obj is PSObject)
{
// The "is" keyword takes care of PSObject and subclasses.
return EncodePSObject((PSObject)obj);
}
else if (obj is ProgressRecord)
{
return ((ProgressRecord)obj).ToPSObjectForRemoting();
}
else if (IsKnownType(type))
{
return obj;
}
else if (type.GetTypeInfo().IsEnum)
{
return (int)obj;
}
else if (obj is CultureInfo)
{
// The "is" keyword takes care of CultureInfo and subclasses.
return obj.ToString();
}
else if (obj is Exception)
{
return EncodeException((Exception)obj);
}
else if (type == typeof(object[]))
{
return EncodeObjectArray((object[])obj);
}
else if (type.IsArray)
{
return EncodeArray((Array)obj);
}
else if (obj is IList && IsCollection(type))
{
return EncodeCollection((IList)obj);
}
else if (obj is IDictionary && IsDictionary(type))
{
return EncodeDictionary((IDictionary)obj);
}
else if (type.IsSubclassOf(typeof(FieldDescription)) || type == typeof(FieldDescription))
{
// The upcasting removes the Attributes, so we want to do this both when it
// is a subclass and when it is a FieldDescription object.
return EncodeClassOrStruct(UpcastFieldDescriptionSubclassAndDropAttributes((FieldDescription)obj));
}
else if (IsEncodingAllowedForClassOrStruct(type))
{
return EncodeClassOrStruct(obj);
}
else if (obj is RemoteHostCall)
{
return ((RemoteHostCall)obj).Encode();
}
else if (obj is RemoteHostResponse)
{
return ((RemoteHostResponse)obj).Encode();
}
else if (obj is SecureString)
{
return obj;
}
else if (obj is PSCredential)
{
return obj;
}
else if (IsGenericIEnumerableOfInt(type))
{
return EncodeCollection((IList)obj);
}
else
{
throw RemoteHostExceptions.NewRemoteHostDataEncodingNotSupportedException(type);
}
}
/// <summary>
/// Decode object.
/// </summary>
internal static object DecodeObject(object obj, Type type)
{
if (obj == null)
{
return null;
}
Dbg.Assert(type != null, "Expected type != null");
if (type == typeof(PSObject))
{
return DecodePSObject(obj);
}
else if (type == typeof(ProgressRecord))
{
return ProgressRecord.FromPSObjectForRemoting(PSObject.AsPSObject(obj));
}
else if (IsKnownType(type))
{
return obj;
}
else if (obj is SecureString)
{
return obj;
}
else if (obj is PSCredential)
{
return obj;
}
else if (obj is PSObject && type == typeof(PSCredential))
{
// BUGBUG: The following piece of code is a workaround
// because custom serialization is busted. If rehydration
// works correctly then PSCredential should be available
PSObject objAsPSObject = (PSObject)obj;
PSCredential cred = null;
try
{
cred = new PSCredential((String)objAsPSObject.Properties["UserName"].Value,
(SecureString)objAsPSObject.Properties["Password"].Value);
}
catch (GetValueException)
{
cred = null;
}
return cred;
}
else if (obj is int && type.GetTypeInfo().IsEnum)
{
return Enum.ToObject(type, (int)obj);
}
else if (obj is string && type == typeof(CultureInfo))
{
return new CultureInfo((string)obj);
}
else if (obj is PSObject && type == typeof(Exception))
{
return DecodeException((PSObject)obj);
}
else if (obj is PSObject && type == typeof(object[]))
{
return DecodeObjectArray((PSObject)obj);
}
else if (obj is PSObject && type.IsArray)
{
return DecodeArray((PSObject)obj, type);
}
else if (obj is PSObject && IsCollection(type))
{
return DecodeCollection((PSObject)obj, type);
}
else if (obj is PSObject && IsDictionary(type))
{
return DecodeDictionary((PSObject)obj, type);
}
else if (obj is PSObject && IsEncodingAllowedForClassOrStruct(type))
{
return DecodeClassOrStruct((PSObject)obj, type);
}
else if (obj is PSObject && IsGenericIEnumerableOfInt(type))
{
// we cannot create an instance of interface type like IEnumberable
// Since a Collection implements IEnumberable, falling back to use
// that.
return DecodeCollection((PSObject)obj, typeof(Collection<int>));
}
else if (obj is PSObject && type == typeof(RemoteHostCall))
{
return RemoteHostCall.Decode((PSObject)obj);
}
else if (obj is PSObject && type == typeof(RemoteHostResponse))
{
return RemoteHostResponse.Decode((PSObject)obj);
}
else
{
throw RemoteHostExceptions.NewRemoteHostDataDecodingNotSupportedException(type);
}
}
/// <summary>
/// Encode and add as property.
/// </summary>
internal static void EncodeAndAddAsProperty(PSObject psObject, string propertyName, object propertyValue)
{
Dbg.Assert(psObject != null, "Expected psObject != null");
Dbg.Assert(propertyName != null, "Expected propertyName != null");
if (propertyValue == null)
{
return;
}
psObject.Properties.Add(new PSNoteProperty(propertyName, EncodeObject(propertyValue)));
}
/// <summary>
/// Decode property value.
/// </summary>
internal static object DecodePropertyValue(PSObject psObject, string propertyName, Type propertyValueType)
{
Dbg.Assert(psObject != null, "Expected psObject != null");
Dbg.Assert(propertyName != null, "Expected propertyName != null");
Dbg.Assert(propertyValueType != null, "Expected propertyValueType != null");
ReadOnlyPSMemberInfoCollection<PSPropertyInfo> matches = psObject.Properties.Match(propertyName);
if (matches.Count == 0)
{
return null;
}
Dbg.Assert(matches.Count == 1, "Expected matches.Count == 1");
return DecodeObject(matches[0].Value, propertyValueType);
}
/// <summary>
/// Encode object array.
/// </summary>
private static PSObject EncodeObjectArray(object[] objects)
{
ArrayList arrayList = new ArrayList();
foreach (object obj in objects)
{
arrayList.Add(EncodeObjectWithType(obj));
}
return new PSObject(arrayList);
}
/// <summary>
/// Decode object array.
/// </summary>
private static object[] DecodeObjectArray(PSObject psObject)
{
// Rehydrate the array from the array list.
ArrayList arrayList = SafelyGetBaseObject<ArrayList>(psObject);
object[] objects = new object[arrayList.Count];
for (int i = 0; i < arrayList.Count; ++i)
{
objects[i] = DecodeObjectWithType(arrayList[i]);
}
return objects;
}
/// <summary>
/// Encode object with type.
/// </summary>
private static PSObject EncodeObjectWithType(object obj)
{
if (obj == null)
{
return null;
}
PSObject psObject = RemotingEncoder.CreateEmptyPSObject();
psObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ObjectType, obj.GetType().ToString()));
psObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ObjectValue, EncodeObject(obj)));
return psObject;
}
/// <summary>
/// Decode object with type.
/// </summary>
private static object DecodeObjectWithType(object obj)
{
if (obj == null)
{
return null;
}
PSObject psObject = SafelyCastObject<PSObject>(obj);
string typeName = SafelyGetPropertyValue<string>(psObject, RemoteDataNameStrings.ObjectType);
Type type = LanguagePrimitives.ConvertTo<Type>(typeName);
object val = SafelyGetPropertyValue<object>(psObject, RemoteDataNameStrings.ObjectValue);
return DecodeObject(val, type);
}
/// <summary>
/// Array is zero based.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private static bool ArrayIsZeroBased(Array array)
{
int rank = array.Rank;
for (int i = 0; i < rank; ++i)
{
if (array.GetLowerBound(i) != 0)
{
return false;
}
}
return true;
}
/// <summary>
/// Encode array.
/// </summary>
private static PSObject EncodeArray(Array array)
{
Dbg.Assert(array != null, "Expected array != null");
Dbg.Assert(ArrayIsZeroBased(array), "Expected ArrayIsZeroBased(array)");
Type arrayType = array.GetType();
Type elementType = arrayType.GetElementType();
int rank = array.Rank;
int[] lengths = new int[rank];
for (int i = 0; i < rank; ++i)
{
lengths[i] = array.GetUpperBound(i) + 1;
}
Indexer indexer = new Indexer(lengths);
ArrayList elements = new ArrayList();
foreach (int[] index in indexer)
{
object elementValue = array.GetValue(index);
elements.Add(EncodeObject(elementValue));
}
PSObject psObject = RemotingEncoder.CreateEmptyPSObject();
psObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodArrayElements, elements));
psObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodArrayLengths, lengths));
return psObject;
}
/// <summary>
/// Decode array.
/// </summary>
private static Array DecodeArray(PSObject psObject, Type type)
{
// Extract the type.
Dbg.Assert(type.IsArray, "Expected type.IsArray");
Type elementType = type.GetElementType();
// Extract elements from psObject.
PSObject psObjectContainingElements = SafelyGetPropertyValue<PSObject>(psObject, RemoteDataNameStrings.MethodArrayElements);
ArrayList elements = SafelyGetBaseObject<ArrayList>(psObjectContainingElements);
// Extract lengths from psObject.
PSObject psObjectContainingLengths = SafelyGetPropertyValue<PSObject>(psObject, RemoteDataNameStrings.MethodArrayLengths);
ArrayList lengthsArrayList = SafelyGetBaseObject<ArrayList>(psObjectContainingLengths);
int[] lengths = (int[])lengthsArrayList.ToArray(typeof(int));
// Reconstitute the array.
Indexer indexer = new Indexer(lengths);
Array array = Array.CreateInstance(elementType, lengths);
int elementIndex = 0;
foreach (int[] index in indexer)
{
object elementValue = DecodeObject(elements[elementIndex++], elementType);
array.SetValue(elementValue, index);
}
return array;
}
/// <summary>
/// Is object dictionary type.
/// </summary>
private static bool IsObjectDictionaryType(Type dictionaryType)
{
// True if the value-type of the dictionary is object; false otherwise.
if (!IsDictionary(dictionaryType)) { return false; }
Type[] elementTypes = dictionaryType.GetGenericArguments();
if (elementTypes.Length != 2) { return false; }
Type valueType = elementTypes[1];
return valueType == typeof(object);
}
/// <summary>
/// Encode object dictionary.
/// </summary>
private static PSObject EncodeObjectDictionary(IDictionary dictionary)
{
Dbg.Assert(IsObjectDictionaryType(dictionary.GetType()), "Expected IsObjectDictionaryType(dictionary.GetType())");
// Encode the dictionary as a hashtable.
Hashtable hashtable = new Hashtable();
foreach (object key in dictionary.Keys)
{
hashtable.Add(EncodeObject(key), EncodeObjectWithType(dictionary[key]));
}
return new PSObject(hashtable);
}
/// <summary>
/// Decode object dictionary.
/// </summary>
private static IDictionary DecodeObjectDictionary(PSObject psObject, Type dictionaryType)
{
Dbg.Assert(IsObjectDictionaryType(dictionaryType), "Expected IsObjectDictionaryType(dictionaryType)");
// Get the element type.
Type[] elementTypes = dictionaryType.GetGenericArguments();
Dbg.Assert(elementTypes.Length == 2, "Expected elementTypes.Length == 2");
Type keyType = elementTypes[0];
Type valueType = elementTypes[1];
Dbg.Assert(valueType == typeof(object), "Expected valueType == typeof(object)");
// Rehydrate the dictionary from the hashtable.
Hashtable hashtable = SafelyGetBaseObject<Hashtable>(psObject);
IDictionary dictionary = (IDictionary)Activator.CreateInstance(dictionaryType);
foreach (object key in hashtable.Keys)
{
dictionary.Add(
DecodeObject(key, keyType),
DecodeObjectWithType(hashtable[key]));
}
return dictionary;
}
/// <summary>
/// Safely get base object.
/// </summary>
private static T SafelyGetBaseObject<T>(PSObject psObject)
{
if (psObject == null || psObject.BaseObject == null || !(psObject.BaseObject is T))
{
throw RemoteHostExceptions.NewDecodingFailedException();
}
return (T)psObject.BaseObject;
}
/// <summary>
/// Safely cast object.
/// </summary>
private static T SafelyCastObject<T>(object obj)
{
if (obj is T)
{
return (T)obj;
}
throw RemoteHostExceptions.NewDecodingFailedException();
}
/// <summary>
/// Safely get property value.
/// </summary>
private static T SafelyGetPropertyValue<T>(PSObject psObject, string key)
{
PSPropertyInfo propertyInfo = psObject.Properties[key];
if (propertyInfo == null || propertyInfo.Value == null || !(propertyInfo.Value is T))
{
throw RemoteHostExceptions.NewDecodingFailedException();
}
return (T)propertyInfo.Value;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Numerics;
namespace System.Security.Cryptography.Asn1
{
internal sealed partial class AsnWriter
{
/// <summary>
/// Write an Object Identifier with a specified tag.
/// </summary>
/// <param name="oid">The object identifier to write.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="oid"/> is <c>null</c>
/// </exception>
/// <exception cref="CryptographicException">
/// <paramref name="oid"/>.<see cref="Oid.Value"/> is not a valid dotted decimal
/// object identifier
/// </exception>
/// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception>
public void WriteObjectIdentifier(Oid oid)
{
if (oid == null)
throw new ArgumentNullException(nameof(oid));
CheckDisposed();
if (oid.Value == null)
throw new CryptographicException(SR.Argument_InvalidOidValue);
WriteObjectIdentifier(oid.Value);
}
/// <summary>
/// Write an Object Identifier with a specified tag.
/// </summary>
/// <param name="oidValue">The object identifier to write.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="oidValue"/> is <c>null</c>
/// </exception>
/// <exception cref="CryptographicException">
/// <paramref name="oidValue"/> is not a valid dotted decimal
/// object identifier
/// </exception>
/// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception>
public void WriteObjectIdentifier(string oidValue)
{
if (oidValue == null)
throw new ArgumentNullException(nameof(oidValue));
WriteObjectIdentifier(oidValue.AsSpan());
}
/// <summary>
/// Write an Object Identifier with tag UNIVERSAL 6.
/// </summary>
/// <param name="oidValue">The object identifier to write.</param>
/// <exception cref="CryptographicException">
/// <paramref name="oidValue"/> is not a valid dotted decimal
/// object identifier
/// </exception>
/// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception>
public void WriteObjectIdentifier(ReadOnlySpan<char> oidValue)
{
WriteObjectIdentifierCore(Asn1Tag.ObjectIdentifier, oidValue);
}
/// <summary>
/// Write an Object Identifier with a specified tag.
/// </summary>
/// <param name="tag">The tag to write.</param>
/// <param name="oid">The object identifier to write.</param>
/// <exception cref="ArgumentException">
/// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for
/// the method
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="oid"/> is <c>null</c>
/// </exception>
/// <exception cref="CryptographicException">
/// <paramref name="oid"/>.<see cref="Oid.Value"/> is not a valid dotted decimal
/// object identifier
/// </exception>
/// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception>
public void WriteObjectIdentifier(Asn1Tag tag, Oid oid)
{
if (oid == null)
throw new ArgumentNullException(nameof(oid));
CheckUniversalTag(tag, UniversalTagNumber.ObjectIdentifier);
CheckDisposed();
if (oid.Value == null)
throw new CryptographicException(SR.Argument_InvalidOidValue);
WriteObjectIdentifier(tag, oid.Value);
}
/// <summary>
/// Write an Object Identifier with a specified tag.
/// </summary>
/// <param name="tag">The tag to write.</param>
/// <param name="oidValue">The object identifier to write.</param>
/// <exception cref="ArgumentException">
/// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for
/// the method
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="oidValue"/> is <c>null</c>
/// </exception>
/// <exception cref="CryptographicException">
/// <paramref name="oidValue"/> is not a valid dotted decimal
/// object identifier
/// </exception>
/// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception>
public void WriteObjectIdentifier(Asn1Tag tag, string oidValue)
{
if (oidValue == null)
throw new ArgumentNullException(nameof(oidValue));
WriteObjectIdentifier(tag, oidValue.AsSpan());
}
/// <summary>
/// Write an Object Identifier with a specified tag.
/// </summary>
/// <param name="tag">The tag to write.</param>
/// <param name="oidValue">The object identifier to write.</param>
/// <exception cref="ArgumentException">
/// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for
/// the method
/// </exception>
/// <exception cref="CryptographicException">
/// <paramref name="oidValue"/> is not a valid dotted decimal
/// object identifier
/// </exception>
/// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception>
public void WriteObjectIdentifier(Asn1Tag tag, ReadOnlySpan<char> oidValue)
{
CheckUniversalTag(tag, UniversalTagNumber.ObjectIdentifier);
WriteObjectIdentifierCore(tag.AsPrimitive(), oidValue);
}
// T-REC-X.690-201508 sec 8.19
private void WriteObjectIdentifierCore(Asn1Tag tag, ReadOnlySpan<char> oidValue)
{
CheckDisposed();
// T-REC-X.690-201508 sec 8.19.4
// The first character is in { 0, 1, 2 }, the second will be a '.', and a third (digit)
// will also exist.
if (oidValue.Length < 3)
throw new CryptographicException(SR.Argument_InvalidOidValue);
if (oidValue[1] != '.')
throw new CryptographicException(SR.Argument_InvalidOidValue);
// The worst case is "1.1.1.1.1", which takes 4 bytes (5 components, with the first two condensed)
// Longer numbers get smaller: "2.1.127" is only 2 bytes. (81d (0x51) and 127 (0x7F))
// So length / 2 should prevent any reallocations.
byte[] tmp = CryptoPool.Rent(oidValue.Length / 2);
int tmpOffset = 0;
try
{
int firstComponent = oidValue[0] switch
{
'0' => 0,
'1' => 1,
'2' => 2,
_ => throw new CryptographicException(SR.Argument_InvalidOidValue),
};
// The first two components are special:
// ITU X.690 8.19.4:
// The numerical value of the first subidentifier is derived from the values of the first two
// object identifier components in the object identifier value being encoded, using the formula:
// (X*40) + Y
// where X is the value of the first object identifier component and Y is the value of the
// second object identifier component.
// NOTE - This packing of the first two object identifier components recognizes that only
// three values are allocated from the root node, and at most 39 subsequent values from
// nodes reached by X = 0 and X = 1.
// skip firstComponent and the trailing .
ReadOnlySpan<char> remaining = oidValue.Slice(2);
BigInteger subIdentifier = ParseSubIdentifier(ref remaining);
subIdentifier += 40 * firstComponent;
int localLen = EncodeSubIdentifier(tmp.AsSpan(tmpOffset), ref subIdentifier);
tmpOffset += localLen;
while (!remaining.IsEmpty)
{
subIdentifier = ParseSubIdentifier(ref remaining);
localLen = EncodeSubIdentifier(tmp.AsSpan(tmpOffset), ref subIdentifier);
tmpOffset += localLen;
}
Debug.Assert(!tag.IsConstructed);
WriteTag(tag);
WriteLength(tmpOffset);
Buffer.BlockCopy(tmp, 0, _buffer, _offset, tmpOffset);
_offset += tmpOffset;
}
finally
{
CryptoPool.Return(tmp, tmpOffset);
}
}
private static BigInteger ParseSubIdentifier(ref ReadOnlySpan<char> oidValue)
{
int endIndex = oidValue.IndexOf('.');
if (endIndex == -1)
{
endIndex = oidValue.Length;
}
else if (endIndex == 0 || endIndex == oidValue.Length - 1)
{
throw new CryptographicException(SR.Argument_InvalidOidValue);
}
// The following code is equivalent to
// BigInteger.TryParse(temp, NumberStyles.None, CultureInfo.InvariantCulture, out value)
// TODO: Split this for netstandard vs netcoreapp for span-perf?.
BigInteger value = BigInteger.Zero;
for (int position = 0; position < endIndex; position++)
{
if (position > 0 && value == 0)
{
// T-REC X.680-201508 sec 12.26
throw new CryptographicException(SR.Argument_InvalidOidValue);
}
value *= 10;
value += AtoI(oidValue[position]);
}
oidValue = oidValue.Slice(Math.Min(oidValue.Length, endIndex + 1));
return value;
}
private static int AtoI(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
throw new CryptographicException(SR.Argument_InvalidOidValue);
}
// ITU-T-X.690-201508 sec 8.19.5
private static int EncodeSubIdentifier(Span<byte> dest, ref BigInteger subIdentifier)
{
Debug.Assert(dest.Length > 0);
if (subIdentifier.IsZero)
{
dest[0] = 0;
return 1;
}
BigInteger unencoded = subIdentifier;
int idx = 0;
do
{
BigInteger cur = unencoded & 0x7F;
byte curByte = (byte)cur;
if (subIdentifier != unencoded)
{
curByte |= 0x80;
}
unencoded >>= 7;
dest[idx] = curByte;
idx++;
}
while (unencoded != BigInteger.Zero);
Reverse(dest.Slice(0, idx));
return idx;
}
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace ZXing.Client.Result
{
/// <summary>
/// Represents a parsed result that encodes a calendar event at a certain time, optionally with attendees and a location.
/// </summary>
///<author>Sean Owen</author>
public sealed class CalendarParsedResult : ParsedResult
{
private static readonly Regex RFC2445_DURATION = new Regex(@"\A(?:" + "P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?" + @")\z"
#if !(SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE)
, RegexOptions.Compiled);
#else
);
#endif
private static readonly long[] RFC2445_DURATION_FIELD_UNITS =
{
7*24*60*60*1000L, // 1 week
24*60*60*1000L, // 1 day
60*60*1000L, // 1 hour
60*1000L, // 1 minute
1000L, // 1 second
};
private static readonly Regex DATE_TIME = new Regex(@"\A(?:" + "[0-9]{8}(T[0-9]{6}Z?)?" + @")\z"
#if !(SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE)
, RegexOptions.Compiled);
#else
);
#endif
private readonly String summary;
private readonly DateTime start;
private readonly bool startAllDay;
private readonly DateTime? end;
private readonly bool endAllDay;
private readonly String location;
private readonly String organizer;
private readonly String[] attendees;
private readonly String description;
private readonly double latitude;
private readonly double longitude;
public CalendarParsedResult(String summary,
String startString,
String endString,
String durationString,
String location,
String organizer,
String[] attendees,
String description,
double latitude,
double longitude)
: base(ParsedResultType.CALENDAR)
{
this.summary = summary;
try
{
this.start = parseDate(startString);
}
catch (Exception pe)
{
throw new ArgumentException(pe.ToString());
}
if (endString == null)
{
long durationMS = parseDurationMS(durationString);
end = durationMS < 0L ? null : (DateTime?) start + new TimeSpan(0, 0, 0, 0, (int) durationMS);
}
else
{
try
{
this.end = parseDate(endString);
}
catch (Exception pe)
{
throw new ArgumentException(pe.ToString());
}
}
this.startAllDay = startString.Length == 8;
this.endAllDay = endString != null && endString.Length == 8;
this.location = location;
this.organizer = organizer;
this.attendees = attendees;
this.description = description;
this.latitude = latitude;
this.longitude = longitude;
var result = new StringBuilder(100);
maybeAppend(summary, result);
maybeAppend(format(startAllDay, start), result);
maybeAppend(format(endAllDay, end), result);
maybeAppend(location, result);
maybeAppend(organizer, result);
maybeAppend(attendees, result);
maybeAppend(description, result);
displayResultValue = result.ToString();
}
public String Summary
{
get { return summary; }
}
/// <summary>
/// Gets the start.
/// </summary>
public DateTime Start
{
get { return start; }
}
/// <summary>
/// Determines whether [is start all day].
/// </summary>
/// <returns>if start time was specified as a whole day</returns>
public bool isStartAllDay()
{
return startAllDay;
}
/// <summary>
/// event end <see cref="DateTime"/>, or null if event has no duration
/// </summary>
public DateTime? End
{
get { return end; }
}
/// <summary>
/// Gets a value indicating whether this instance is end all day.
/// </summary>
/// <value>true if end time was specified as a whole day</value>
public bool isEndAllDay
{
get { return endAllDay; }
}
public String Location
{
get { return location; }
}
public String Organizer
{
get { return organizer; }
}
public String[] Attendees
{
get { return attendees; }
}
public String Description
{
get { return description; }
}
public double Latitude
{
get { return latitude; }
}
public double Longitude
{
get { return longitude; }
}
/// <summary>
/// Parses a string as a date. RFC 2445 allows the start and end fields to be of type DATE (e.g. 20081021)
/// or DATE-TIME (e.g. 20081021T123000 for local time, or 20081021T123000Z for UTC).
/// </summary>
/// <param name="when">The string to parse</param>
/// <returns></returns>
/// <exception cref="ArgumentException">if not a date formatted string</exception>
private static DateTime parseDate(String when)
{
if (!DATE_TIME.Match(when).Success)
{
throw new ArgumentException(String.Format("no date format: {0}", when));
}
if (when.Length == 8)
{
// Show only year/month/day
return DateTime.ParseExact(when, buildDateFormat(), CultureInfo.InvariantCulture);
}
else
{
// The when string can be local time, or UTC if it ends with a Z
DateTime date;
if (when.Length == 16 && when[15] == 'Z')
{
date = DateTime.ParseExact(when.Substring(0, 15), buildDateTimeFormat(), CultureInfo.InvariantCulture);
date = TimeZoneInfo.ConvertTime(date, TimeZoneInfo.Local);
}
else
{
date = DateTime.ParseExact(when, buildDateTimeFormat(), CultureInfo.InvariantCulture);
}
return date;
}
}
private static String format(bool allDay, DateTime? date)
{
if (date == null)
{
return null;
}
if (allDay)
return date.Value.ToString("D", CultureInfo.CurrentCulture);
return date.Value.ToString("F", CultureInfo.CurrentCulture);
}
private static long parseDurationMS(String durationString)
{
if (durationString == null)
{
return -1L;
}
var m = RFC2445_DURATION.Match(durationString);
if (!m.Success)
{
return -1L;
}
long durationMS = 0L;
for (int i = 0; i < RFC2445_DURATION_FIELD_UNITS.Length; i++)
{
String fieldValue = m.Groups[i + 1].Value;
if (!String.IsNullOrEmpty(fieldValue))
{
durationMS += RFC2445_DURATION_FIELD_UNITS[i]*Int32.Parse(fieldValue);
}
}
return durationMS;
}
private static string buildDateFormat()
{
//DateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
//// For dates without a time, for purposes of interacting with Android, the resulting timestamp
//// needs to be midnight of that day in GMT. See:
//// http://code.google.com/p/android/issues/detail?id=8330
//format.setTimeZone(TimeZone.getTimeZone("GMT"));
//return format;
// not sure how to handle this correctly in .Net
return "yyyyMMdd";
}
private static string buildDateTimeFormat()
{
return "yyyyMMdd'T'HHmmss";
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Tests.TestObjects.JsonTextReaderTests;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests
{
[TestFixture]
public class JsonTextWriterTest : TestFixtureBase
{
[Test]
public void BufferTest()
{
FakeArrayPool arrayPool = new FakeArrayPool();
string longString = new string('A', 2000);
string longEscapedString = "Hello!" + new string('!', 50) + new string('\n', 1000) + "Good bye!";
string longerEscapedString = "Hello!" + new string('!', 2000) + new string('\n', 1000) + "Good bye!";
for (int i = 0; i < 1000; i++)
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.ArrayPool = arrayPool;
writer.WriteStartObject();
writer.WritePropertyName("Prop1");
writer.WriteValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc));
writer.WritePropertyName("Prop2");
writer.WriteValue(longString);
writer.WritePropertyName("Prop3");
writer.WriteValue(longEscapedString);
writer.WritePropertyName("Prop4");
writer.WriteValue(longerEscapedString);
writer.WriteEndObject();
}
if ((i + 1) % 100 == 0)
{
Console.WriteLine("Allocated buffers: " + arrayPool.FreeArrays.Count);
}
}
Assert.AreEqual(0, arrayPool.UsedArrays.Count);
Assert.AreEqual(3, arrayPool.FreeArrays.Count);
}
[Test]
public void BufferTest_WithError()
{
FakeArrayPool arrayPool = new FakeArrayPool();
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
try
{
// dispose will free used buffers
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.ArrayPool = arrayPool;
writer.WriteStartObject();
writer.WritePropertyName("Prop1");
writer.WriteValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc));
writer.WritePropertyName("Prop2");
writer.WriteValue("This is an escaped \n string!");
writer.WriteValue("Error!");
}
Assert.Fail();
}
catch
{
}
Assert.AreEqual(0, arrayPool.UsedArrays.Count);
Assert.AreEqual(1, arrayPool.FreeArrays.Count);
}
#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50)
[Test]
public void BufferErroringWithInvalidSize()
{
JObject o = new JObject
{
{"BodyHtml", "<h3>Title!</h3>" + Environment.NewLine + new string(' ', 100) + "<p>Content!</p>"}
};
JsonArrayPool arrayPool = new JsonArrayPool();
StringWriter sw = new StringWriter();
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.ArrayPool = arrayPool;
o.WriteTo(writer);
}
string result = o.ToString();
Assert.AreEqual(@"{
""BodyHtml"": ""<h3>Title!</h3>\r\n <p>Content!</p>""
}", result);
}
#endif
[Test]
public void NewLine()
{
MemoryStream ms = new MemoryStream();
using (var streamWriter = new StreamWriter(ms, new UTF8Encoding(false)) { NewLine = "\n" })
using (var jsonWriter = new JsonTextWriter(streamWriter)
{
CloseOutput = true,
Indentation = 2,
Formatting = Formatting.Indented
})
{
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("prop");
jsonWriter.WriteValue(true);
jsonWriter.WriteEndObject();
}
byte[] data = ms.ToArray();
string json = Encoding.UTF8.GetString(data, 0, data.Length);
Assert.AreEqual(@"{" + '\n' + @" ""prop"": true" + '\n' + "}", json);
}
[Test]
public void QuoteNameAndStrings()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonTextWriter writer = new JsonTextWriter(sw) { QuoteName = false };
writer.WriteStartObject();
writer.WritePropertyName("name");
writer.WriteValue("value");
writer.WriteEndObject();
writer.Flush();
Assert.AreEqual(@"{name:""value""}", sb.ToString());
}
[Test]
public void CloseOutput()
{
MemoryStream ms = new MemoryStream();
JsonTextWriter writer = new JsonTextWriter(new StreamWriter(ms));
Assert.IsTrue(ms.CanRead);
writer.Close();
Assert.IsFalse(ms.CanRead);
ms = new MemoryStream();
writer = new JsonTextWriter(new StreamWriter(ms)) { CloseOutput = false };
Assert.IsTrue(ms.CanRead);
writer.Close();
Assert.IsTrue(ms.CanRead);
}
#if !(PORTABLE)
[Test]
public void WriteIConvertable()
{
var sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteValue(new ConvertibleInt(1));
Assert.AreEqual("1", sw.ToString());
}
#endif
[Test]
public void ValueFormatting()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue('@');
jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
jsonWriter.WriteValue(true);
jsonWriter.WriteValue(10);
jsonWriter.WriteValue(10.99);
jsonWriter.WriteValue(0.99);
jsonWriter.WriteValue(0.000000000000000001d);
jsonWriter.WriteValue(0.000000000000000001m);
jsonWriter.WriteValue((string)null);
jsonWriter.WriteValue((object)null);
jsonWriter.WriteValue("This is a string.");
jsonWriter.WriteNull();
jsonWriter.WriteUndefined();
jsonWriter.WriteEndArray();
}
string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]";
string result = sb.ToString();
Assert.AreEqual(expected, result);
}
[Test]
public void NullableValueFormatting()
{
StringWriter sw = new StringWriter();
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue((char?)null);
jsonWriter.WriteValue((char?)'c');
jsonWriter.WriteValue((bool?)null);
jsonWriter.WriteValue((bool?)true);
jsonWriter.WriteValue((byte?)null);
jsonWriter.WriteValue((byte?)1);
jsonWriter.WriteValue((sbyte?)null);
jsonWriter.WriteValue((sbyte?)1);
jsonWriter.WriteValue((short?)null);
jsonWriter.WriteValue((short?)1);
jsonWriter.WriteValue((ushort?)null);
jsonWriter.WriteValue((ushort?)1);
jsonWriter.WriteValue((int?)null);
jsonWriter.WriteValue((int?)1);
jsonWriter.WriteValue((uint?)null);
jsonWriter.WriteValue((uint?)1);
jsonWriter.WriteValue((long?)null);
jsonWriter.WriteValue((long?)1);
jsonWriter.WriteValue((ulong?)null);
jsonWriter.WriteValue((ulong?)1);
jsonWriter.WriteValue((double?)null);
jsonWriter.WriteValue((double?)1.1);
jsonWriter.WriteValue((float?)null);
jsonWriter.WriteValue((float?)1.1);
jsonWriter.WriteValue((decimal?)null);
jsonWriter.WriteValue((decimal?)1.1m);
jsonWriter.WriteValue((DateTime?)null);
jsonWriter.WriteValue((DateTime?)new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc));
#if !NET20
jsonWriter.WriteValue((DateTimeOffset?)null);
jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero));
#endif
jsonWriter.WriteEndArray();
}
string json = sw.ToString();
string expected;
#if !NET20
expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z"",null,""1970-01-01T00:00:00+00:00""]";
#else
expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z""]";
#endif
Assert.AreEqual(expected, json);
}
[Test]
public void WriteValueObjectWithNullable()
{
StringWriter sw = new StringWriter();
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
char? value = 'c';
jsonWriter.WriteStartArray();
jsonWriter.WriteValue((object)value);
jsonWriter.WriteEndArray();
}
string json = sw.ToString();
string expected = @"[""c""]";
Assert.AreEqual(expected, json);
}
[Test]
public void WriteValueObjectWithUnsupportedValue()
{
ExceptionAssert.Throws<JsonWriterException>(() =>
{
StringWriter sw = new StringWriter();
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(new Version(1, 1, 1, 1));
jsonWriter.WriteEndArray();
}
}, @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''.");
}
[Test]
public void StringEscaping()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(@"""These pretzels are making me thirsty!""");
jsonWriter.WriteValue("Jeff's house was burninated.");
jsonWriter.WriteValue("1. You don't talk about fight club.\r\n2. You don't talk about fight club.");
jsonWriter.WriteValue("35% of\t statistics\n are made\r up.");
jsonWriter.WriteEndArray();
}
string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]";
string result = sb.ToString();
Assert.AreEqual(expected, result);
}
[Test]
public void WriteEnd()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("CPU");
jsonWriter.WriteValue("Intel");
jsonWriter.WritePropertyName("PSU");
jsonWriter.WriteValue("500W");
jsonWriter.WritePropertyName("Drives");
jsonWriter.WriteStartArray();
jsonWriter.WriteValue("DVD read/writer");
jsonWriter.WriteComment("(broken)");
jsonWriter.WriteValue("500 gigabyte hard drive");
jsonWriter.WriteValue("200 gigabype hard drive");
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
}
string expected = @"{
""CPU"": ""Intel"",
""PSU"": ""500W"",
""Drives"": [
""DVD read/writer""
/*(broken)*/,
""500 gigabyte hard drive"",
""200 gigabype hard drive""
]
}";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void CloseWithRemainingContent()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("CPU");
jsonWriter.WriteValue("Intel");
jsonWriter.WritePropertyName("PSU");
jsonWriter.WriteValue("500W");
jsonWriter.WritePropertyName("Drives");
jsonWriter.WriteStartArray();
jsonWriter.WriteValue("DVD read/writer");
jsonWriter.WriteComment("(broken)");
jsonWriter.WriteValue("500 gigabyte hard drive");
jsonWriter.WriteValue("200 gigabype hard drive");
jsonWriter.Close();
}
string expected = @"{
""CPU"": ""Intel"",
""PSU"": ""500W"",
""Drives"": [
""DVD read/writer""
/*(broken)*/,
""500 gigabyte hard drive"",
""200 gigabype hard drive""
]
}";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void Indenting()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("CPU");
jsonWriter.WriteValue("Intel");
jsonWriter.WritePropertyName("PSU");
jsonWriter.WriteValue("500W");
jsonWriter.WritePropertyName("Drives");
jsonWriter.WriteStartArray();
jsonWriter.WriteValue("DVD read/writer");
jsonWriter.WriteComment("(broken)");
jsonWriter.WriteValue("500 gigabyte hard drive");
jsonWriter.WriteValue("200 gigabype hard drive");
jsonWriter.WriteEnd();
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
}
// {
// "CPU": "Intel",
// "PSU": "500W",
// "Drives": [
// "DVD read/writer"
// /*(broken)*/,
// "500 gigabyte hard drive",
// "200 gigabype hard drive"
// ]
// }
string expected = @"{
""CPU"": ""Intel"",
""PSU"": ""500W"",
""Drives"": [
""DVD read/writer""
/*(broken)*/,
""500 gigabyte hard drive"",
""200 gigabype hard drive""
]
}";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void State()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
jsonWriter.WriteStartObject();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual("", jsonWriter.Path);
jsonWriter.WritePropertyName("CPU");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
Assert.AreEqual("CPU", jsonWriter.Path);
jsonWriter.WriteValue("Intel");
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual("CPU", jsonWriter.Path);
jsonWriter.WritePropertyName("Drives");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
Assert.AreEqual("Drives", jsonWriter.Path);
jsonWriter.WriteStartArray();
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
jsonWriter.WriteValue("DVD read/writer");
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual("Drives[0]", jsonWriter.Path);
jsonWriter.WriteEnd();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual("Drives", jsonWriter.Path);
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
Assert.AreEqual("", jsonWriter.Path);
}
}
[Test]
public void FloatingPointNonFiniteNumbers_Symbol()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol;
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteValue(double.PositiveInfinity);
jsonWriter.WriteValue(double.NegativeInfinity);
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteValue(float.PositiveInfinity);
jsonWriter.WriteValue(float.NegativeInfinity);
jsonWriter.WriteEndArray();
jsonWriter.Flush();
}
string expected = @"[
NaN,
Infinity,
-Infinity,
NaN,
Infinity,
-Infinity
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void FloatingPointNonFiniteNumbers_Zero()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.DefaultValue;
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteValue(double.PositiveInfinity);
jsonWriter.WriteValue(double.NegativeInfinity);
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteValue(float.PositiveInfinity);
jsonWriter.WriteValue(float.NegativeInfinity);
jsonWriter.WriteValue((double?)double.NaN);
jsonWriter.WriteValue((double?)double.PositiveInfinity);
jsonWriter.WriteValue((double?)double.NegativeInfinity);
jsonWriter.WriteValue((float?)float.NaN);
jsonWriter.WriteValue((float?)float.PositiveInfinity);
jsonWriter.WriteValue((float?)float.NegativeInfinity);
jsonWriter.WriteEndArray();
jsonWriter.Flush();
}
string expected = @"[
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
null,
null,
null,
null,
null,
null
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void FloatingPointNonFiniteNumbers_String()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.String;
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteValue(double.PositiveInfinity);
jsonWriter.WriteValue(double.NegativeInfinity);
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteValue(float.PositiveInfinity);
jsonWriter.WriteValue(float.NegativeInfinity);
jsonWriter.WriteEndArray();
jsonWriter.Flush();
}
string expected = @"[
""NaN"",
""Infinity"",
""-Infinity"",
""NaN"",
""Infinity"",
""-Infinity""
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void FloatingPointNonFiniteNumbers_QuoteChar()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.String;
jsonWriter.QuoteChar = '\'';
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteValue(double.PositiveInfinity);
jsonWriter.WriteValue(double.NegativeInfinity);
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteValue(float.PositiveInfinity);
jsonWriter.WriteValue(float.NegativeInfinity);
jsonWriter.WriteEndArray();
jsonWriter.Flush();
}
string expected = @"[
'NaN',
'Infinity',
'-Infinity',
'NaN',
'Infinity',
'-Infinity'
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void WriteRawInStart()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol;
jsonWriter.WriteRaw("[1,2,3,4,5]");
jsonWriter.WriteWhitespace(" ");
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteEndArray();
}
string expected = @"[1,2,3,4,5] [
NaN
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void WriteRawInArray()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol;
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteRaw(",[1,2,3,4,5]");
jsonWriter.WriteRaw(",[1,2,3,4,5]");
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteEndArray();
}
string expected = @"[
NaN,[1,2,3,4,5],[1,2,3,4,5],
NaN
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void WriteRawInObject()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]");
jsonWriter.WriteEnd();
}
string expected = @"{""PropertyName"":[1,2,3,4,5]}";
string result = sb.ToString();
Assert.AreEqual(expected, result);
}
[Test]
public void WriteToken()
{
JsonTextReader reader = new JsonTextReader(new StringReader("[1,2,3,4,5]"));
reader.Read();
reader.Read();
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteToken(reader);
Assert.AreEqual("1", sw.ToString());
}
[Test]
public void WriteRawValue()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
int i = 0;
string rawJson = "[1,2]";
jsonWriter.WriteStartObject();
while (i < 3)
{
jsonWriter.WritePropertyName("d" + i);
jsonWriter.WriteRawValue(rawJson);
i++;
}
jsonWriter.WriteEndObject();
}
Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString());
}
[Test]
public void WriteObjectNestedInConstructor()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("con");
jsonWriter.WriteStartConstructor("Ext.data.JsonStore");
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("aa");
jsonWriter.WriteValue("aa");
jsonWriter.WriteEndObject();
jsonWriter.WriteEndConstructor();
jsonWriter.WriteEndObject();
}
Assert.AreEqual(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString());
}
[Test]
public void WriteFloatingPointNumber()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol;
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(0.0);
jsonWriter.WriteValue(0f);
jsonWriter.WriteValue(0.1);
jsonWriter.WriteValue(1.0);
jsonWriter.WriteValue(1.000001);
jsonWriter.WriteValue(0.000001);
jsonWriter.WriteValue(double.Epsilon);
jsonWriter.WriteValue(double.PositiveInfinity);
jsonWriter.WriteValue(double.NegativeInfinity);
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteValue(double.MaxValue);
jsonWriter.WriteValue(double.MinValue);
jsonWriter.WriteValue(float.PositiveInfinity);
jsonWriter.WriteValue(float.NegativeInfinity);
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteEndArray();
}
Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString());
}
[Test]
public void WriteIntegerNumber()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented })
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(int.MaxValue);
jsonWriter.WriteValue(int.MinValue);
jsonWriter.WriteValue(0);
jsonWriter.WriteValue(-0);
jsonWriter.WriteValue(9L);
jsonWriter.WriteValue(9UL);
jsonWriter.WriteValue(long.MaxValue);
jsonWriter.WriteValue(long.MinValue);
jsonWriter.WriteValue(ulong.MaxValue);
jsonWriter.WriteValue(ulong.MinValue);
jsonWriter.WriteEndArray();
}
Console.WriteLine(sb.ToString());
StringAssert.AreEqual(@"[
2147483647,
-2147483648,
0,
0,
9,
9,
9223372036854775807,
-9223372036854775808,
18446744073709551615,
0
]", sb.ToString());
}
[Test]
public void WriteTokenDirect()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteToken(JsonToken.StartArray);
jsonWriter.WriteToken(JsonToken.Integer, 1);
jsonWriter.WriteToken(JsonToken.StartObject);
jsonWriter.WriteToken(JsonToken.PropertyName, "string");
jsonWriter.WriteToken(JsonToken.Integer, int.MaxValue);
jsonWriter.WriteToken(JsonToken.EndObject);
jsonWriter.WriteToken(JsonToken.EndArray);
}
Assert.AreEqual(@"[1,{""string"":2147483647}]", sb.ToString());
}
[Test]
public void WriteTokenDirect_BadValue()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteToken(JsonToken.StartArray);
ExceptionAssert.Throws<FormatException>(() => { jsonWriter.WriteToken(JsonToken.Integer, "three"); }, "Input string was not in a correct format.");
ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(JsonToken.Integer); }, @"Value cannot be null.
Parameter name: value");
}
}
[Test]
public void WriteTokenNullCheck()
{
using (JsonWriter jsonWriter = new JsonTextWriter(new StringWriter()))
{
ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(null); });
ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(null, true); });
}
}
[Test]
public void TokenTypeOutOfRange()
{
using (JsonWriter jsonWriter = new JsonTextWriter(new StringWriter()))
{
ArgumentOutOfRangeException ex = ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => jsonWriter.WriteToken((JsonToken)int.MinValue));
Assert.AreEqual("token", ex.ParamName);
ex = ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => jsonWriter.WriteToken((JsonToken)int.MinValue, "test"));
Assert.AreEqual("token", ex.ParamName);
}
}
[Test]
public void BadWriteEndArray()
{
ExceptionAssert.Throws<JsonWriterException>(() =>
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(0.0);
jsonWriter.WriteEndArray();
jsonWriter.WriteEndArray();
}
}, "No token to close. Path ''.");
}
[Test]
public void InvalidQuoteChar()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.QuoteChar = '*';
}
}, @"Invalid JavaScript string quote character. Valid quote characters are ' and "".");
}
[Test]
public void Indentation()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol;
Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting);
jsonWriter.Indentation = 5;
Assert.AreEqual(5, jsonWriter.Indentation);
jsonWriter.IndentChar = '_';
Assert.AreEqual('_', jsonWriter.IndentChar);
jsonWriter.QuoteName = true;
Assert.AreEqual(true, jsonWriter.QuoteName);
jsonWriter.QuoteChar = '\'';
Assert.AreEqual('\'', jsonWriter.QuoteChar);
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("propertyName");
jsonWriter.WriteValue(double.NaN);
jsonWriter.IndentChar = '?';
Assert.AreEqual('?', jsonWriter.IndentChar);
jsonWriter.Indentation = 6;
Assert.AreEqual(6, jsonWriter.Indentation);
jsonWriter.WritePropertyName("prop2");
jsonWriter.WriteValue(123);
jsonWriter.WriteEndObject();
}
string expected = @"{
_____'propertyName': NaN,
??????'prop2': 123
}";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void WriteSingleBytes()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
string text = "Hello world.";
byte[] data = Encoding.UTF8.GetBytes(text);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting);
jsonWriter.WriteValue(data);
}
string expected = @"""SGVsbG8gd29ybGQu""";
string result = sb.ToString();
Assert.AreEqual(expected, result);
byte[] d2 = Convert.FromBase64String(result.Trim('"'));
Assert.AreEqual(text, Encoding.UTF8.GetString(d2, 0, d2.Length));
}
[Test]
public void WriteBytesInArray()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
string text = "Hello world.";
byte[] data = Encoding.UTF8.GetBytes(text);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting);
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(data);
jsonWriter.WriteValue(data);
jsonWriter.WriteValue((object)data);
jsonWriter.WriteValue((byte[])null);
jsonWriter.WriteValue((Uri)null);
jsonWriter.WriteEndArray();
}
string expected = @"[
""SGVsbG8gd29ybGQu"",
""SGVsbG8gd29ybGQu"",
""SGVsbG8gd29ybGQu"",
null,
null
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void Path()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
string text = "Hello world.";
byte[] data = Encoding.UTF8.GetBytes(text);
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartArray();
Assert.AreEqual("", writer.Path);
writer.WriteStartObject();
Assert.AreEqual("[0]", writer.Path);
writer.WritePropertyName("Property1");
Assert.AreEqual("[0].Property1", writer.Path);
writer.WriteStartArray();
Assert.AreEqual("[0].Property1", writer.Path);
writer.WriteValue(1);
Assert.AreEqual("[0].Property1[0]", writer.Path);
writer.WriteStartArray();
Assert.AreEqual("[0].Property1[1]", writer.Path);
writer.WriteStartArray();
Assert.AreEqual("[0].Property1[1][0]", writer.Path);
writer.WriteStartArray();
Assert.AreEqual("[0].Property1[1][0][0]", writer.Path);
writer.WriteEndObject();
Assert.AreEqual("[0]", writer.Path);
writer.WriteStartObject();
Assert.AreEqual("[1]", writer.Path);
writer.WritePropertyName("Property2");
Assert.AreEqual("[1].Property2", writer.Path);
writer.WriteStartConstructor("Constructor1");
Assert.AreEqual("[1].Property2", writer.Path);
writer.WriteNull();
Assert.AreEqual("[1].Property2[0]", writer.Path);
writer.WriteStartArray();
Assert.AreEqual("[1].Property2[1]", writer.Path);
writer.WriteValue(1);
Assert.AreEqual("[1].Property2[1][0]", writer.Path);
writer.WriteEnd();
Assert.AreEqual("[1].Property2[1]", writer.Path);
writer.WriteEndObject();
Assert.AreEqual("[1]", writer.Path);
writer.WriteEndArray();
Assert.AreEqual("", writer.Path);
}
StringAssert.AreEqual(@"[
{
""Property1"": [
1,
[
[
[]
]
]
]
},
{
""Property2"": new Constructor1(
null,
[
1
]
)
}
]", sb.ToString());
}
[Test]
public void BuildStateArray()
{
JsonWriter.State[][] stateArray = JsonWriter.BuildStateArray();
var valueStates = JsonWriter.StateArrayTempate[7];
foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken)))
{
switch (valueToken)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
Assert.AreEqual(valueStates, stateArray[(int)valueToken], "Error for " + valueToken + " states.");
break;
}
}
}
[Test]
public void DateTimeZoneHandling()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw)
{
DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc
};
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified));
Assert.AreEqual(@"""2000-01-01T01:01:01Z""", sw.ToString());
}
[Test]
public void HtmlStringEscapeHandling()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw)
{
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
string script = @"<script type=""text/javascript"">alert('hi');</script>";
writer.WriteValue(script);
string json = sw.ToString();
Assert.AreEqual(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json);
JsonTextReader reader = new JsonTextReader(new StringReader(json));
Assert.AreEqual(script, reader.ReadAsString());
}
[Test]
public void NonAsciiStringEscapeHandling()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw)
{
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};
string unicode = "\u5f20";
writer.WriteValue(unicode);
string json = sw.ToString();
Assert.AreEqual(8, json.Length);
Assert.AreEqual(@"""\u5f20""", json);
JsonTextReader reader = new JsonTextReader(new StringReader(json));
Assert.AreEqual(unicode, reader.ReadAsString());
sw = new StringWriter();
writer = new JsonTextWriter(sw)
{
StringEscapeHandling = StringEscapeHandling.Default
};
writer.WriteValue(unicode);
json = sw.ToString();
Assert.AreEqual(3, json.Length);
Assert.AreEqual("\"\u5f20\"", json);
}
[Test]
public void WriteEndOnProperty()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.QuoteChar = '\'';
writer.WriteStartObject();
writer.WritePropertyName("Blah");
writer.WriteEnd();
Assert.AreEqual("{'Blah':null}", sw.ToString());
}
[Test]
public void WriteEndOnProperty_Close()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.QuoteChar = '\'';
writer.WriteStartObject();
writer.WritePropertyName("Blah");
writer.Close();
Assert.AreEqual("{'Blah':null}", sw.ToString());
}
[Test]
public void WriteEndOnProperty_Dispose()
{
StringWriter sw = new StringWriter();
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.QuoteChar = '\'';
writer.WriteStartObject();
writer.WritePropertyName("Blah");
}
Assert.AreEqual("{'Blah':null}", sw.ToString());
}
[Test]
public void AutoCompleteOnClose_False()
{
StringWriter sw = new StringWriter();
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.AutoCompleteOnClose = false;
writer.QuoteChar = '\'';
writer.WriteStartObject();
writer.WritePropertyName("Blah");
}
Assert.AreEqual("{'Blah':", sw.ToString());
}
#if !NET20
[Test]
public void QuoteChar()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.Formatting = Formatting.Indented;
writer.QuoteChar = '\'';
writer.WriteStartArray();
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc));
writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc));
writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
writer.DateFormatString = "yyyy gg";
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc));
writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
writer.WriteValue(new byte[] { 1, 2, 3 });
writer.WriteValue(TimeSpan.Zero);
writer.WriteValue(new Uri("http://www.google.com/"));
writer.WriteValue(Guid.Empty);
writer.WriteEnd();
StringAssert.AreEqual(@"[
'2000-01-01T01:01:01Z',
'2000-01-01T01:01:01+00:00',
'\/Date(946688461000)\/',
'\/Date(946688461000+0000)\/',
'2000 A.D.',
'2000 A.D.',
'AQID',
'00:00:00',
'http://www.google.com/',
'00000000-0000-0000-0000-000000000000'
]", sw.ToString());
}
[Test]
public void Culture()
{
CultureInfo culture = new CultureInfo("en-NZ");
culture.DateTimeFormat.AMDesignator = "a.m.";
culture.DateTimeFormat.PMDesignator = "p.m.";
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.Formatting = Formatting.Indented;
writer.DateFormatString = "yyyy tt";
writer.Culture = culture;
writer.QuoteChar = '\'';
writer.WriteStartArray();
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc));
writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
writer.WriteEnd();
StringAssert.AreEqual(@"[
'2000 a.m.',
'2000 a.m.'
]", sw.ToString());
}
#endif
[Test]
public void CompareNewStringEscapingWithOld()
{
char c = (char)0;
do
{
StringWriter swNew = new StringWriter();
char[] buffer = null;
JavaScriptUtils.WriteEscapedJavaScriptString(swNew, c.ToString(), '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer);
StringWriter swOld = new StringWriter();
WriteEscapedJavaScriptStringOld(swOld, c.ToString(), '"', true);
string newText = swNew.ToString();
string oldText = swOld.ToString();
if (newText != oldText)
{
throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int)c, oldText, newText));
}
c++;
} while (c != char.MaxValue);
}
private const string EscapedUnicodeText = "!";
private static void WriteEscapedJavaScriptStringOld(TextWriter writer, string s, char delimiter, bool appendDelimiters)
{
// leading delimiter
if (appendDelimiters)
{
writer.Write(delimiter);
}
if (s != null)
{
char[] chars = null;
char[] unicodeBuffer = null;
int lastWritePosition = 0;
for (int i = 0; i < s.Length; i++)
{
var c = s[i];
// don't escape standard text/numbers except '\' and the text delimiter
if (c >= ' ' && c < 128 && c != '\\' && c != delimiter)
{
continue;
}
string escapedValue;
switch (c)
{
case '\t':
escapedValue = @"\t";
break;
case '\n':
escapedValue = @"\n";
break;
case '\r':
escapedValue = @"\r";
break;
case '\f':
escapedValue = @"\f";
break;
case '\b':
escapedValue = @"\b";
break;
case '\\':
escapedValue = @"\\";
break;
case '\u0085': // Next Line
escapedValue = @"\u0085";
break;
case '\u2028': // Line Separator
escapedValue = @"\u2028";
break;
case '\u2029': // Paragraph Separator
escapedValue = @"\u2029";
break;
case '\'':
// this charater is being used as the delimiter
escapedValue = @"\'";
break;
case '"':
// this charater is being used as the delimiter
escapedValue = "\\\"";
break;
default:
if (c <= '\u001f')
{
if (unicodeBuffer == null)
{
unicodeBuffer = new char[6];
}
StringUtils.ToCharAsUnicode(c, unicodeBuffer);
// slightly hacky but it saves multiple conditions in if test
escapedValue = EscapedUnicodeText;
}
else
{
escapedValue = null;
}
break;
}
if (escapedValue == null)
{
continue;
}
if (i > lastWritePosition)
{
if (chars == null)
{
chars = s.ToCharArray();
}
// write unchanged chars before writing escaped text
writer.Write(chars, lastWritePosition, i - lastWritePosition);
}
lastWritePosition = i + 1;
if (!string.Equals(escapedValue, EscapedUnicodeText))
{
writer.Write(escapedValue);
}
else
{
writer.Write(unicodeBuffer);
}
}
if (lastWritePosition == 0)
{
// no escaped text, write entire string
writer.Write(s);
}
else
{
if (chars == null)
{
chars = s.ToCharArray();
}
// write remaining text
writer.Write(chars, lastWritePosition, s.Length - lastWritePosition);
}
}
// trailing delimiter
if (appendDelimiters)
{
writer.Write(delimiter);
}
}
[Test]
public void CustomJsonTextWriterTests()
{
StringWriter sw = new StringWriter();
CustomJsonTextWriter writer = new CustomJsonTextWriter(sw) { Formatting = Formatting.Indented };
writer.WriteStartObject();
Assert.AreEqual(WriteState.Object, writer.WriteState);
writer.WritePropertyName("Property1");
Assert.AreEqual(WriteState.Property, writer.WriteState);
Assert.AreEqual("Property1", writer.Path);
writer.WriteNull();
Assert.AreEqual(WriteState.Object, writer.WriteState);
writer.WriteEndObject();
Assert.AreEqual(WriteState.Start, writer.WriteState);
StringAssert.AreEqual(@"{{{
""1ytreporP"": NULL!!!
}}}", sw.ToString());
}
[Test]
public void QuoteDictionaryNames()
{
var d = new Dictionary<string, int>
{
{ "a", 1 },
};
var jsonSerializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
};
var serializer = JsonSerializer.Create(jsonSerializerSettings);
using (var stringWriter = new StringWriter())
{
using (var writer = new JsonTextWriter(stringWriter) { QuoteName = false })
{
serializer.Serialize(writer, d);
writer.Close();
}
StringAssert.AreEqual(@"{
a: 1
}", stringWriter.ToString());
}
}
[Test]
public void WriteComments()
{
string json = @"//comment*//*hi*/
{//comment
Name://comment
true//comment after true" + StringUtils.CarriageReturn + @"
,//comment after comma" + StringUtils.CarriageReturnLineFeed + @"
""ExpiryDate""://comment" + StringUtils.LineFeed + @"
new
" + StringUtils.LineFeed +
@"Constructor
(//comment
null//comment
),
""Price"": 3.99,
""Sizes"": //comment
[//comment
""Small""//comment
]//comment
}//comment
//comment 1 ";
JsonTextReader r = new JsonTextReader(new StringReader(json));
StringWriter sw = new StringWriter();
JsonTextWriter w = new JsonTextWriter(sw);
w.Formatting = Formatting.Indented;
w.WriteToken(r, true);
StringAssert.AreEqual(@"/*comment*//*hi*/*/{/*comment*/
""Name"": /*comment*/ true/*comment after true*//*comment after comma*/,
""ExpiryDate"": /*comment*/ new Constructor(
/*comment*/,
null
/*comment*/
),
""Price"": 3.99,
""Sizes"": /*comment*/ [
/*comment*/
""Small""
/*comment*/
]/*comment*/
}/*comment *//*comment 1 */", sw.ToString());
}
[Test]
public void DisposeSupressesFinalization()
{
UnmanagedResourceFakingJsonWriter.CreateAndDispose();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.AreEqual(1, UnmanagedResourceFakingJsonWriter.DisposalCalls);
}
}
public class CustomJsonTextWriter : JsonTextWriter
{
protected readonly TextWriter _writer;
public CustomJsonTextWriter(TextWriter textWriter) : base(textWriter)
{
_writer = textWriter;
}
public override void WritePropertyName(string name)
{
WritePropertyName(name, true);
}
public override void WritePropertyName(string name, bool escape)
{
SetWriteState(JsonToken.PropertyName, name);
if (QuoteName)
{
_writer.Write(QuoteChar);
}
_writer.Write(new string(name.ToCharArray().Reverse().ToArray()));
if (QuoteName)
{
_writer.Write(QuoteChar);
}
_writer.Write(':');
}
public override void WriteNull()
{
SetWriteState(JsonToken.Null, null);
_writer.Write("NULL!!!");
}
public override void WriteStartObject()
{
SetWriteState(JsonToken.StartObject, null);
_writer.Write("{{{");
}
public override void WriteEndObject()
{
SetWriteState(JsonToken.EndObject, null);
}
protected override void WriteEnd(JsonToken token)
{
if (token == JsonToken.EndObject)
{
_writer.Write("}}}");
}
else
{
base.WriteEnd(token);
}
}
}
public class UnmanagedResourceFakingJsonWriter : JsonWriter
{
public static int DisposalCalls;
public static void CreateAndDispose()
{
((IDisposable)new UnmanagedResourceFakingJsonWriter()).Dispose();
}
public UnmanagedResourceFakingJsonWriter()
{
DisposalCalls = 0;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
++DisposalCalls;
}
~UnmanagedResourceFakingJsonWriter()
{
Dispose(false);
}
public override void Flush()
{
throw new NotImplementedException();
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Topic Feed
///<para>SObject Name: TopicFeed</para>
///<para>Custom Object: False</para>
///</summary>
public class SfTopicFeed : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "TopicFeed"; }
}
///<summary>
/// Feed Item ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Parent ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
[Updateable(false), Createable(false)]
public string ParentId { get; set; }
///<summary>
/// ReferenceTo: Topic
/// <para>RelationshipName: Parent</para>
///</summary>
[JsonProperty(PropertyName = "parent")]
[Updateable(false), Createable(false)]
public SfTopic Parent { get; set; }
///<summary>
/// Feed Item Type
/// <para>Name: Type</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "type")]
[Updateable(false), Createable(false)]
public string Type { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Comment Count
/// <para>Name: CommentCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "commentCount")]
[Updateable(false), Createable(false)]
public int? CommentCount { get; set; }
///<summary>
/// Like Count
/// <para>Name: LikeCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "likeCount")]
[Updateable(false), Createable(false)]
public int? LikeCount { get; set; }
///<summary>
/// Title
/// <para>Name: Title</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "title")]
[Updateable(false), Createable(false)]
public string Title { get; set; }
///<summary>
/// Body
/// <para>Name: Body</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "body")]
[Updateable(false), Createable(false)]
public string Body { get; set; }
///<summary>
/// Link Url
/// <para>Name: LinkUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "linkUrl")]
[Updateable(false), Createable(false)]
public string LinkUrl { get; set; }
///<summary>
/// Is Rich Text
/// <para>Name: IsRichText</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isRichText")]
[Updateable(false), Createable(false)]
public bool? IsRichText { get; set; }
///<summary>
/// Related Record ID
/// <para>Name: RelatedRecordId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relatedRecordId")]
[Updateable(false), Createable(false)]
public string RelatedRecordId { get; set; }
///<summary>
/// InsertedBy ID
/// <para>Name: InsertedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "insertedById")]
[Updateable(false), Createable(false)]
public string InsertedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: InsertedBy</para>
///</summary>
[JsonProperty(PropertyName = "insertedBy")]
[Updateable(false), Createable(false)]
public SfUser InsertedBy { get; set; }
///<summary>
/// Best Comment ID
/// <para>Name: BestCommentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestCommentId")]
[Updateable(false), Createable(false)]
public string BestCommentId { get; set; }
///<summary>
/// ReferenceTo: FeedComment
/// <para>RelationshipName: BestComment</para>
///</summary>
[JsonProperty(PropertyName = "bestComment")]
[Updateable(false), Createable(false)]
public SfFeedComment BestComment { get; set; }
}
}
| |
#region license
/*
DirectShowLib - Provide access to DirectShow interfaces via .NET
Copyright (C) 2007
http://sourceforge.net/projects/directshownet/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#endregion
using System;
using System.Runtime.InteropServices;
namespace DirectShowLib
{
#region Declarations
/// <summary>
/// From MPEG_REQUEST_TYPE
/// </summary>
public enum MPEGRequestType
{
// Fields
PES_STREAM = 6,
SECTION = 1,
SECTION_ASYNC = 2,
SECTIONS_STREAM = 5,
TABLE = 3,
TABLE_ASYNC = 4,
TS_STREAM = 7,
START_MPE_STREAM = 8,
UNKNOWN = 0
}
/// <summary>
/// From MPEG_CONTEXT_TYPE
/// </summary>
public enum MPEGContextType
{
BCSDeMux = 0,
WinSock = 1
}
/// <summary>
/// From MPEG_PACKET_LIST
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct MPEGPacketList
{
public short wPacketCount;
public IntPtr PacketList;
}
/// <summary>
/// From DSMCC_FILTER_OPTIONS
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct DSMCCFilterOptions
{
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifyProtocol;
public byte Protocol;
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifyType;
public byte Type;
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifyMessageId;
public short MessageId;
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifyTransactionId;
[MarshalAs(UnmanagedType.Bool)]
public bool fUseTrxIdMessageIdMask;
public int TransactionId;
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifyModuleVersion;
public byte ModuleVersion;
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifyBlockNumber;
public short BlockNumber;
[MarshalAs(UnmanagedType.Bool)]
public bool fGetModuleCall;
public short NumberOfBlocksInModule;
}
/// <summary>
/// From ATSC_FILTER_OPTIONS
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct ATSCFilterOptions
{
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifyEtmId;
public int EtmId;
}
/// <summary>
/// From MPEG2_FILTER
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public class MPEG2Filter
{
public byte bVersionNumber;
public short wFilterSize;
[MarshalAs(UnmanagedType.Bool)]
public bool fUseRawFilteringBits;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
public byte[] Filter;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
public byte[] Mask;
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifyTableIdExtension;
public short TableIdExtension;
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifyVersion;
public byte Version;
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifySectionNumber;
public byte SectionNumber;
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifyCurrentNext;
[MarshalAs(UnmanagedType.Bool)]
public bool fNext;
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifyDsmccOptions;
[MarshalAs(UnmanagedType.Struct)]
public DSMCCFilterOptions Dsmcc;
[MarshalAs(UnmanagedType.Bool)]
public bool fSpecifyAtscOptions;
[MarshalAs(UnmanagedType.Struct)]
public ATSCFilterOptions Atsc;
}
/// <summary>
/// From DVB_EIT_FILTER_OPTIONS
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class DVB_EIT_FILTER_OPTIONS
{
[MarshalAs(UnmanagedType.Bool)]
bool fSpecifySegment;
byte bSegment;
}
/// <summary>
/// From MPEG2_FILTER2
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class MPEG2Filter2 : MPEG2Filter
{
[MarshalAs(UnmanagedType.Bool)]
bool fSpecifyDvbEitOptions;
DVB_EIT_FILTER_OPTIONS DvbEit;
}
/// <summary>
/// From unnamed union
/// </summary>
[StructLayout(LayoutKind.Explicit, Pack=1)]
public struct MPEGContextUnion
{
// Fields
[FieldOffset(0)]
public BCSDeMux Demux;
[FieldOffset(0)]
public MPEGWinSock Winsock;
}
/// <summary>
/// From MPEG_BCS_DEMUX
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct BCSDeMux
{
public int AVMGraphId;
}
/// <summary>
/// From MPEG_WINSOCK
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct MPEGWinSock
{
public int AVMGraphId;
}
/// <summary>
/// From MPEG_CONTEXT
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public class MPEGContext
{
public MPEGContextType Type;
public MPEGContextUnion U;
}
/// <summary>
/// From MPEG_STREAM_BUFFER
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public class MPEGStreamBuffer
{
//[MarshalAs(UnmanagedType.Error)]
public int hr;
public int dwDataBufferSize;
public int dwSizeOfDataRead;
public IntPtr pDataBuffer;
}
#endregion
#region Interfaces
#if ALLOW_UNTESTED_INTERFACES
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("BDCDD913-9ECD-4fb2-81AE-ADF747EA75A5")]
public interface IMpeg2TableFilter
{
[PreserveSig]
int AddPID(
short pid
);
[PreserveSig]
int AddTable(
short pid,
byte tid
);
[PreserveSig]
int AddExtension(
short pid,
byte tid,
short eid
);
[PreserveSig]
int RemovePID(
short pid
);
[PreserveSig]
int RemoveTable(
short pid,
byte tid
);
[PreserveSig]
int RemoveExtension(
short pid,
byte tid,
short eid
);
}
#endif
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("9B396D40-F380-4E3C-A514-1A82BF6EBFE6")]
public interface IMpeg2Data
{
[PreserveSig]
int GetSection(
[In] short pid,
[In] byte tid,
[In] MPEG2Filter pFilter,
[In] int dwTimeout,
[MarshalAs(UnmanagedType.Interface)] out ISectionList ppSectionList
);
[PreserveSig]
int GetTable(
[In] short pid,
[In] byte tid,
[In] MPEG2Filter pFilter,
[In] int dwTimeout,
[MarshalAs(UnmanagedType.Interface)] out ISectionList ppSectionList
);
[PreserveSig]
int GetStreamOfSections(
[In] short pid,
[In] byte tid,
[In] MPEG2Filter pFilter,
[In] IntPtr hDataReadyEvent,
[MarshalAs(UnmanagedType.Interface)] out IMpeg2Stream ppMpegStream
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("400CC286-32A0-4CE4-9041-39571125A635"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMpeg2Stream
{
[PreserveSig]
int Initialize(
[In] MPEGRequestType requestType,
[In, MarshalAs(UnmanagedType.Interface)] IMpeg2Data pMpeg2Data,
[In, MarshalAs(UnmanagedType.LPStruct)] MPEGContext pContext,
[In] short pid,
[In] byte tid,
[In, MarshalAs(UnmanagedType.LPStruct)] MPEG2Filter pFilter,
[In] IntPtr hDataReadyEvent
);
[PreserveSig]
int SupplyDataBuffer(
[In] MPEGStreamBuffer pStreamBuffer
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("AFEC1EB5-2A64-46C6-BF4B-AE3CCB6AFDB0"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISectionList
{
[PreserveSig]
int Initialize(
[In] MPEGRequestType requestType,
[In, MarshalAs(UnmanagedType.Interface)] IMpeg2Data pMpeg2Data,
[In, MarshalAs(UnmanagedType.LPStruct)] MPEGContext pContext,
[In] short pid,
[In] byte tid,
[In, MarshalAs(UnmanagedType.LPStruct)] MPEG2Filter pFilter,
[In] int timeout,
[In] IntPtr hDoneEvent
);
[PreserveSig]
int InitializeWithRawSections(
[In] ref MPEGPacketList pmplSections
);
[PreserveSig]
int CancelPendingRequest();
[PreserveSig]
int GetNumberOfSections(
out short pCount
);
[PreserveSig]
int GetSectionData(
[In] short SectionNumber,
[Out] out int pdwRawPacketLength,
[Out] out IntPtr ppSection // PSECTION*
);
[PreserveSig]
int GetProgramIdentifier(
out short pPid
);
[PreserveSig]
int GetTableIdentifier(
out byte pTableId
);
}
#endregion
}
| |
using System;
using System.Windows;
using System.Windows.Forms;
using System.Drawing;
using Microsoft.Win32;
namespace Earlab
{
/// <summary>
/// Summary description for RegistryParameters.
/// </summary>
public class RegistryParameter
{
private RegistryKey mRegistryKey = null;
private string mParameterName = null;
private Object mParameter;
private Object mDefault;
public RegistryParameter(RegistryKey theKey, string ParameterName)
{
Initialize(theKey, ParameterName, null);
}
public RegistryParameter(RegistryKey theKey, string ParameterName, Object DefaultValue)
{
Initialize(theKey, ParameterName, DefaultValue);
}
private void Initialize(RegistryKey theKey, string ParameterName, Object DefaultValue)
{
// Remember parameters
mRegistryKey = theKey;
mParameterName = ParameterName;
mDefault = DefaultValue;
// Check parameters
if (mRegistryKey == null)
throw new ApplicationException("RegistryParameter: RegistryKey cannot be null");
if (mParameterName == null)
throw new ApplicationException("RegistryParameter: ParameterName cannot be null");
// Load the value from the registry
try
{
mParameter = mRegistryKey.GetValue(mParameterName, mDefault);
}
catch (ArgumentException)
{
mParameter = mDefault;
}
}
public Object Value
{
set
{
mParameter = value;
mRegistryKey.SetValue(mParameterName, mParameter);
}
get
{
return mParameter;
}
}
}
public class RegistryString: RegistryParameter
{
public RegistryString(RegistryKey theKey, string ParameterName, string DefaultValue) : base(theKey, ParameterName, DefaultValue){}
public RegistryString(RegistryKey theKey, string ParameterName) : base(theKey, ParameterName){}
public new string Value
{
set {base.Value = value;}
get {return (string)base.Value;}
}
}
public class RegistryInt: RegistryParameter
{
public RegistryInt(RegistryKey theKey, string ParameterName, int DefaultValue) : base(theKey, ParameterName, (object)DefaultValue){}
public RegistryInt(RegistryKey theKey, string ParameterName) : base(theKey, ParameterName){}
public new int Value
{
set {base.Value = (Object)value;}
get {return (int)base.Value;}
}
}
public class RegistryBool: RegistryParameter
{
public RegistryBool(RegistryKey theKey, string ParameterName, bool DefaultValue) : base(theKey, ParameterName, (object)DefaultValue){}
public RegistryBool(RegistryKey theKey, string ParameterName) : base(theKey, ParameterName){}
public new bool Value
{
set {base.Value = (Object)value;}
get {return (bool)base.Value;}
}
}
public class RegistryFloat: RegistryParameter
{
public RegistryFloat(RegistryKey theKey, string ParameterName, float DefaultValue) : base(theKey, ParameterName, (object)DefaultValue){}
public RegistryFloat(RegistryKey theKey, string ParameterName) : base(theKey, ParameterName){}
public new float Value
{
set {base.Value = (Object)value;}
get {return (float)base.Value;}
}
}
public class RegistryDouble: RegistryParameter
{
public RegistryDouble(RegistryKey theKey, string ParameterName, double DefaultValue) : base(theKey, ParameterName, (object)DefaultValue){}
public RegistryDouble(RegistryKey theKey, string ParameterName) : base(theKey, ParameterName){}
public new double Value
{
set {base.Value = (Object)value;}
get {return (double)base.Value;}
}
}
public class RegistryPoint
{
private RegistryInt X, Y;
public RegistryPoint(RegistryKey theKey, string ParameterName, Point DefaultValue)
{
Init(theKey, ParameterName, DefaultValue);
}
public RegistryPoint(RegistryKey theKey, string ParameterName)
{
Init(theKey, ParameterName, new Point(0, 0));
}
private void Init(RegistryKey theKey, string ParameterName, Point DefaultValue)
{
X = new RegistryInt(theKey, ParameterName + "_X", DefaultValue.X);
Y = new RegistryInt(theKey, ParameterName + "_Y", DefaultValue.Y);
}
public Point Value
{
set
{
X.Value = value.X;
Y.Value = value.Y;
}
get {return new Point(X.Value, Y.Value);}
}
}
public class RegistrySize
{
private RegistryInt Width, Height;
public RegistrySize(RegistryKey theKey, string ParameterName, Size DefaultValue)
{
Init(theKey, ParameterName, DefaultValue);
}
public RegistrySize(RegistryKey theKey, string ParameterName)
{
Init(theKey, ParameterName, new Size(0, 0));
}
private void Init(RegistryKey theKey, string ParameterName, Size DefaultValue)
{
Width = new RegistryInt(theKey, ParameterName + "_Width", DefaultValue.Width);
Height = new RegistryInt(theKey, ParameterName + "_Height", DefaultValue.Height);
}
public Size Value
{
set
{
Width.Value = value.Width;
Height.Value = value.Height;
}
get {return new Size(Width.Value, Height.Value);}
}
}
public class RegistryRectangle
{
private RegistryPoint Location;
private RegistrySize Size;
public RegistryRectangle(RegistryKey theKey, string ParameterName, Rectangle DefaultValue)
{
Init(theKey, ParameterName, DefaultValue);
}
public RegistryRectangle(RegistryKey theKey, string ParameterName)
{
Init(theKey, ParameterName, new Rectangle(0, 0, 0, 0));
}
private void Init(RegistryKey theKey, string ParameterName, Rectangle DefaultValue)
{
Location = new RegistryPoint(theKey, ParameterName + "_Location", DefaultValue.Location);
Size = new RegistrySize(theKey, ParameterName + "_Size", DefaultValue.Size);
}
public Rectangle Value
{
set
{
Location.Value = value.Location;
Size.Value = value.Size;
}
get {return new Rectangle(Location.Value, Size.Value);}
}
}
public class RegistryFormWindowState: RegistryParameter
{
public RegistryFormWindowState(RegistryKey theKey, string ParameterName, FormWindowState DefaultValue) : base(theKey, ParameterName, (object)DefaultValue){}
public RegistryFormWindowState(RegistryKey theKey, string ParameterName) : base(theKey, ParameterName){}
public new FormWindowState Value
{
set {base.Value = (Object)((int)value);}
get {return (FormWindowState)base.Value;}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
namespace System.Xml.Linq
{
internal class XNodeBuilder : XmlWriter
{
private List<object> _content;
private XContainer _parent;
private XName _attrName;
private string _attrValue;
private XContainer _root;
public XNodeBuilder(XContainer container)
{
_root = container;
}
public override XmlWriterSettings Settings
{
get
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.ConformanceLevel = ConformanceLevel.Auto;
return settings;
}
}
public override WriteState WriteState
{
get { throw new NotSupportedException(); } // nop
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Close();
}
}
public override void Close()
{
_root.Add(_content);
}
public override void Flush()
{
}
public override string LookupPrefix(string namespaceName)
{
throw new NotSupportedException(); // nop
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
throw new NotSupportedException(SR.NotSupported_WriteBase64);
}
public override void WriteCData(string text)
{
AddNode(new XCData(text));
}
public override void WriteCharEntity(char ch)
{
AddString(new string(ch, 1));
}
public override void WriteChars(char[] buffer, int index, int count)
{
AddString(new string(buffer, index, count));
}
public override void WriteComment(string text)
{
AddNode(new XComment(text));
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
AddNode(new XDocumentType(name, pubid, sysid, subset));
}
public override void WriteEndAttribute()
{
XAttribute a = new XAttribute(_attrName, _attrValue);
_attrName = null;
_attrValue = null;
if (_parent != null)
{
_parent.Add(a);
}
else
{
Add(a);
}
}
public override void WriteEndDocument()
{
}
public override void WriteEndElement()
{
_parent = ((XElement)_parent).parent;
}
public override void WriteEntityRef(string name)
{
switch (name)
{
case "amp":
AddString("&");
break;
case "apos":
AddString("'");
break;
case "gt":
AddString(">");
break;
case "lt":
AddString("<");
break;
case "quot":
AddString("\"");
break;
default:
throw new NotSupportedException(SR.NotSupported_WriteEntityRef);
}
}
public override void WriteFullEndElement()
{
XElement e = (XElement)_parent;
if (e.IsEmpty)
{
e.Add(string.Empty);
}
_parent = e.parent;
}
public override void WriteProcessingInstruction(string name, string text)
{
if (name == "xml")
{
return;
}
AddNode(new XProcessingInstruction(name, text));
}
public override void WriteRaw(char[] buffer, int index, int count)
{
AddString(new string(buffer, index, count));
}
public override void WriteRaw(string data)
{
AddString(data);
}
public override void WriteStartAttribute(string prefix, string localName, string namespaceName)
{
if (prefix == null) throw new ArgumentNullException(nameof(prefix));
_attrName = XNamespace.Get(prefix.Length == 0 ? string.Empty : namespaceName).GetName(localName);
_attrValue = string.Empty;
}
public override void WriteStartDocument()
{
}
public override void WriteStartDocument(bool standalone)
{
}
public override void WriteStartElement(string prefix, string localName, string namespaceName)
{
AddNode(new XElement(XNamespace.Get(namespaceName).GetName(localName)));
}
public override void WriteString(string text)
{
AddString(text);
}
public override void WriteSurrogateCharEntity(char lowCh, char highCh)
{
AddString(new string(new char[] { highCh, lowCh }));
}
public override void WriteValue(DateTimeOffset value)
{
// For compatibility with custom writers, XmlWriter writes DateTimeOffset as DateTime.
// Our internal writers should use the DateTimeOffset-String conversion from XmlConvert.
WriteString(XmlConvert.ToString(value));
}
public override void WriteWhitespace(string ws)
{
AddString(ws);
}
private void Add(object o)
{
if (_content == null)
{
_content = new List<object>();
}
_content.Add(o);
}
private void AddNode(XNode n)
{
if (_parent != null)
{
_parent.Add(n);
}
else
{
Add(n);
}
XContainer c = n as XContainer;
if (c != null)
{
_parent = c;
}
}
private void AddString(string s)
{
if (s == null)
{
return;
}
if (_attrValue != null)
{
_attrValue += s;
}
else if (_parent != null)
{
_parent.Add(s);
}
else
{
Add(s);
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Networking/Requests/Messages/FortRecallPokemonMessage.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Networking.Requests.Messages {
/// <summary>Holder for reflection information generated from POGOProtos/Networking/Requests/Messages/FortRecallPokemonMessage.proto</summary>
public static partial class FortRecallPokemonMessageReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Networking/Requests/Messages/FortRecallPokemonMessage.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static FortRecallPokemonMessageReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CkZQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVxdWVzdHMvTWVzc2FnZXMvRm9y",
"dFJlY2FsbFBva2Vtb25NZXNzYWdlLnByb3RvEidQT0dPUHJvdG9zLk5ldHdv",
"cmtpbmcuUmVxdWVzdHMuTWVzc2FnZXMicgoYRm9ydFJlY2FsbFBva2Vtb25N",
"ZXNzYWdlEg8KB2ZvcnRfaWQYASABKAkSEgoKcG9rZW1vbl9pZBgCIAEoBhIX",
"Cg9wbGF5ZXJfbGF0aXR1ZGUYAyABKAESGAoQcGxheWVyX2xvbmdpdHVkZRgE",
"IAEoAWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Requests.Messages.FortRecallPokemonMessage), global::POGOProtos.Networking.Requests.Messages.FortRecallPokemonMessage.Parser, new[]{ "FortId", "PokemonId", "PlayerLatitude", "PlayerLongitude" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class FortRecallPokemonMessage : pb::IMessage<FortRecallPokemonMessage> {
private static readonly pb::MessageParser<FortRecallPokemonMessage> _parser = new pb::MessageParser<FortRecallPokemonMessage>(() => new FortRecallPokemonMessage());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FortRecallPokemonMessage> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Networking.Requests.Messages.FortRecallPokemonMessageReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortRecallPokemonMessage() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortRecallPokemonMessage(FortRecallPokemonMessage other) : this() {
fortId_ = other.fortId_;
pokemonId_ = other.pokemonId_;
playerLatitude_ = other.playerLatitude_;
playerLongitude_ = other.playerLongitude_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortRecallPokemonMessage Clone() {
return new FortRecallPokemonMessage(this);
}
/// <summary>Field number for the "fort_id" field.</summary>
public const int FortIdFieldNumber = 1;
private string fortId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string FortId {
get { return fortId_; }
set {
fortId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "pokemon_id" field.</summary>
public const int PokemonIdFieldNumber = 2;
private ulong pokemonId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong PokemonId {
get { return pokemonId_; }
set {
pokemonId_ = value;
}
}
/// <summary>Field number for the "player_latitude" field.</summary>
public const int PlayerLatitudeFieldNumber = 3;
private double playerLatitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double PlayerLatitude {
get { return playerLatitude_; }
set {
playerLatitude_ = value;
}
}
/// <summary>Field number for the "player_longitude" field.</summary>
public const int PlayerLongitudeFieldNumber = 4;
private double playerLongitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double PlayerLongitude {
get { return playerLongitude_; }
set {
playerLongitude_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FortRecallPokemonMessage);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FortRecallPokemonMessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (FortId != other.FortId) return false;
if (PokemonId != other.PokemonId) return false;
if (PlayerLatitude != other.PlayerLatitude) return false;
if (PlayerLongitude != other.PlayerLongitude) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (FortId.Length != 0) hash ^= FortId.GetHashCode();
if (PokemonId != 0UL) hash ^= PokemonId.GetHashCode();
if (PlayerLatitude != 0D) hash ^= PlayerLatitude.GetHashCode();
if (PlayerLongitude != 0D) hash ^= PlayerLongitude.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (FortId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(FortId);
}
if (PokemonId != 0UL) {
output.WriteRawTag(17);
output.WriteFixed64(PokemonId);
}
if (PlayerLatitude != 0D) {
output.WriteRawTag(25);
output.WriteDouble(PlayerLatitude);
}
if (PlayerLongitude != 0D) {
output.WriteRawTag(33);
output.WriteDouble(PlayerLongitude);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (FortId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FortId);
}
if (PokemonId != 0UL) {
size += 1 + 8;
}
if (PlayerLatitude != 0D) {
size += 1 + 8;
}
if (PlayerLongitude != 0D) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FortRecallPokemonMessage other) {
if (other == null) {
return;
}
if (other.FortId.Length != 0) {
FortId = other.FortId;
}
if (other.PokemonId != 0UL) {
PokemonId = other.PokemonId;
}
if (other.PlayerLatitude != 0D) {
PlayerLatitude = other.PlayerLatitude;
}
if (other.PlayerLongitude != 0D) {
PlayerLongitude = other.PlayerLongitude;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
FortId = input.ReadString();
break;
}
case 17: {
PokemonId = input.ReadFixed64();
break;
}
case 25: {
PlayerLatitude = input.ReadDouble();
break;
}
case 33: {
PlayerLongitude = input.ReadDouble();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PolymorphismOperations operations.
/// </summary>
internal partial class PolymorphismOperations : Microsoft.Rest.IServiceOperations<AzureCompositeModel>, IPolymorphismOperations
{
/// <summary>
/// Initializes a new instance of the PolymorphismOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PolymorphismOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that are polymorphic
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<FishInner>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<FishInner>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<FishInner>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic
/// </summary>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// 'fishtype':'Salmon',
/// 'location':'alaska',
/// 'iswild':true,
/// 'species':'king',
/// 'length':1.0,
/// 'siblings':[
/// {
/// 'fishtype':'Shark',
/// 'age':6,
/// 'birthday': '2012-01-05T01:00:00Z',
/// 'length':20.0,
/// 'species':'predator',
/// },
/// {
/// 'fishtype':'Sawshark',
/// 'age':105,
/// 'birthday': '1900-01-05T01:00:00Z',
/// 'length':10.0,
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidWithHttpMessagesAsync(FishInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (complexBody == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.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)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic, attempting to omit required
/// 'birthday' field - the request should not be allowed from the client
/// </summary>
/// <param name='complexBody'>
/// Please attempt put a sawshark that looks like this, the client should not
/// allow this data to be sent:
/// {
/// "fishtype": "sawshark",
/// "species": "snaggle toothed",
/// "length": 18.5,
/// "age": 2,
/// "birthday": "2013-06-01T01:00:00Z",
/// "location": "alaska",
/// "picture": base64(FF FF FF FF FE),
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "birthday": "2012-01-05T01:00:00Z",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "picture": base64(FF FF FF FF FE),
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidMissingRequiredWithHttpMessagesAsync(FishInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (complexBody == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValidMissingRequired", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/missingrequired/invalid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.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)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System.IO;
using System.Linq;
using System.Text;
namespace DotKafka.Prototype.Common.Protocol.Types
{
public interface IType
{
void Write(MemoryStream buffer, object item);
object Read(MemoryStream buffer);
object Validate(object item);
int SizeOf(object item);
}
public class Struct
{
private object[] values;
public Struct(Schema schema, object[] values)
{
Schema = schema;
this.values = values;
}
public Struct(Schema schema)
{
Schema = schema;
values = new object[Schema.NumFields()];
}
public Schema Schema { get; }
private object GetFieldOrDefault(Field field)
{
var value = values[field.Index];
if (value != null)
return value;
if (field.DefaultValue != Field.NO_DEFAULT)
return field.DefaultValue;
throw new SchemaException("Missing value for field '" + field.Name + "' which has no default value.");
}
public object Get(Field field)
{
ValidateField(field);
return GetFieldOrDefault(field);
}
public object Get(string name)
{
var field = Schema.Get(name);
if (field == null)
throw new SchemaException("No such field: " + name);
return GetFieldOrDefault(field);
}
public bool HasField(string name)
{
return Schema.Get(name) != null;
}
public Struct GetStruct(Field field)
{
return (Struct) Get(field);
}
public Struct GetStruct(string name)
{
return (Struct) Get(name);
}
public byte GetByte(Field field)
{
return (byte) Get(field);
}
public byte GetByte(string name)
{
return (byte) Get(name);
}
public short GetShort(Field field)
{
return (short) Get(field);
}
public short GetShort(string name)
{
return (short) Get(name);
}
public int GetInt(Field field)
{
return (int) Get(field);
}
public int GetInt(string name)
{
return (int) Get(name);
}
public long GetInt64(Field field)
{
return (long) Get(field);
}
public long GetInt64(string name)
{
return (long) Get(name);
}
public object[] GetArray(Field field)
{
return (object[]) Get(field);
}
public object[] GetArray(string name)
{
return (object[]) Get(name);
}
public string GetString(Field field)
{
return (string) Get(field);
}
public string GetString(string name)
{
return (string) Get(name);
}
private void ValidateField(Field field)
{
if (Schema != field.Schema)
throw new SchemaException("Attempt to access field '" + field.Name +
"' from a different schema instance.");
if (field.Index > values.Length)
throw new SchemaException("Invalid field index: " + field.Index);
}
public MemoryStream GetBytes(Field field)
{
var result = Get(field);
if (result is byte[])
return new MemoryStream((byte[]) result);
return (MemoryStream) result;
}
public MemoryStream GetBytes(string name)
{
var result = Get(name);
if (result is byte[])
return new MemoryStream((byte[]) result);
return (MemoryStream) result;
}
public Struct Set(Field field, object value)
{
ValidateField(field);
values[field.Index] = value;
return this;
}
public Struct Set(string name, object value)
{
var field = Schema.Get(name);
if (field == null)
throw new SchemaException("Unknown field: " + name);
values[field.Index] = value;
return this;
}
public Struct Instance(Field field)
{
ValidateField(field);
if (field.Type is Schema)
{
return new Struct((Schema) field.Type);
}
if (field.Type is KafkaArrayOf)
{
var array = (KafkaArrayOf) field.Type;
return new Struct((Schema) array.Type);
}
throw new SchemaException("Field '" + field.Name + "' is not a container type, it is of type " +
field.Type);
}
public Struct Instance(string field)
{
return Instance(Schema.Get(field));
}
public void Clear()
{
values = new object[values.Length];
}
public int SizeOf()
{
return Schema.SizeOf(this);
}
public void WriteTo(MemoryStream buffer)
{
Schema.Write(buffer, this);
}
public void Validate()
{
Schema.Validate(this);
}
public MemoryStream[] ToBytes()
{
var buffer = new MemoryStream(new byte[SizeOf()]);
WriteTo(buffer);
return new[] {buffer};
}
public override string ToString()
{
var b = new StringBuilder();
b.Append('{');
for (var i = 0; i < values.Length; i++)
{
var f = Schema.Get(i);
b.Append(f.Name);
b.Append('=');
if (f.Type is KafkaArrayOf)
{
var arrayValue = (object[]) values[i];
b.Append('[');
for (var j = 0; j < arrayValue.Length; j++)
{
b.Append(arrayValue[j]);
if (j < arrayValue.Length - 1)
b.Append(',');
}
b.Append(']');
}
else
b.Append(values[i]);
if (i < values.Length - 1)
b.Append(',');
}
b.Append('}');
return b.ToString();
}
public override int GetHashCode()
{
var prime = 31;
var result = 1;
for (var i = 0; i < values.Length; i++)
{
var f = Schema.Get(i);
if (f.Type is KafkaArrayOf)
{
var arrayObject = (object[]) Get(f);
foreach (var arrayItem in arrayObject)
result = prime*result + arrayItem.GetHashCode();
}
else
{
result = prime*result + Get(f).GetHashCode();
}
}
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
return true;
var other = obj as Struct;
if (other == null)
return false;
if (Schema != other.Schema)
return false;
for (var i = 0; i < values.Length; i++)
{
var f = Schema.Get(i);
bool result;
if (f.Type is KafkaArrayOf)
{
result = ((object[]) Get(f)).SequenceEqual((object[]) other.Get(f));
//result = Arrays.equals();
}
else
{
result = Get(f).Equals(other.Get(f));
}
if (!result)
return false;
}
return true;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal sealed class OpenSslCertificateFinder : IFindPal
{
private readonly X509Certificate2Collection _findFrom;
private readonly X509Certificate2Collection _copyTo;
private readonly bool _validOnly;
internal OpenSslCertificateFinder(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, bool validOnly)
{
_findFrom = findFrom;
_copyTo = copyTo;
_validOnly = validOnly;
}
public string NormalizeOid(string maybeOid, OidGroup expectedGroup)
{
Oid oid = new Oid(maybeOid);
// If maybeOid is interpreted to be a FriendlyName, return the OID.
if (!StringComparer.OrdinalIgnoreCase.Equals(oid.Value, maybeOid))
{
return oid.Value;
}
FindPal.ValidateOidValue(maybeOid);
return maybeOid;
}
public void FindByThumbprint(byte[] thumbprint)
{
FindCore(cert => cert.GetCertHash().ContentsEqual(thumbprint));
}
public void FindBySubjectName(string subjectName)
{
FindCore(
cert =>
{
string formedSubject = X500NameEncoder.X500DistinguishedNameDecode(cert.SubjectName.RawData, false, X500DistinguishedNameFlags.None);
return formedSubject.IndexOf(subjectName, StringComparison.OrdinalIgnoreCase) >= 0;
});
}
public void FindBySubjectDistinguishedName(string subjectDistinguishedName)
{
FindCore(cert => StringComparer.OrdinalIgnoreCase.Equals(subjectDistinguishedName, cert.Subject));
}
public void FindByIssuerName(string issuerName)
{
FindCore(
cert =>
{
string formedIssuer = X500NameEncoder.X500DistinguishedNameDecode(cert.IssuerName.RawData, false, X500DistinguishedNameFlags.None);
return formedIssuer.IndexOf(issuerName, StringComparison.OrdinalIgnoreCase) >= 0;
});
}
public void FindByIssuerDistinguishedName(string issuerDistinguishedName)
{
FindCore(cert => StringComparer.OrdinalIgnoreCase.Equals(issuerDistinguishedName, cert.Issuer));
}
public void FindBySerialNumber(BigInteger hexValue, BigInteger decimalValue)
{
FindCore(
cert =>
{
byte[] serialBytes = cert.GetSerialNumber();
BigInteger serialNumber = FindPal.PositiveBigIntegerFromByteArray(serialBytes);
bool match = hexValue.Equals(serialNumber) || decimalValue.Equals(serialNumber);
return match;
});
}
private static DateTime NormalizeDateTime(DateTime dateTime)
{
// If it's explicitly UTC, convert it to local before a comparison, since the
// NotBefore and NotAfter are in Local time.
//
// If it was Unknown, assume it was Local.
if (dateTime.Kind == DateTimeKind.Utc)
{
return dateTime.ToLocalTime();
}
return dateTime;
}
public void FindByTimeValid(DateTime dateTime)
{
DateTime normalized = NormalizeDateTime(dateTime);
FindCore(cert => cert.NotBefore <= normalized && normalized <= cert.NotAfter);
}
public void FindByTimeNotYetValid(DateTime dateTime)
{
DateTime normalized = NormalizeDateTime(dateTime);
FindCore(cert => cert.NotBefore > normalized);
}
public void FindByTimeExpired(DateTime dateTime)
{
DateTime normalized = NormalizeDateTime(dateTime);
FindCore(cert => cert.NotAfter < normalized);
}
public void FindByTemplateName(string templateName)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.EnrollCertTypeExtension);
if (ext != null)
{
// Try a V1 template structure, just a string:
string decodedName = Interop.Crypto.DerStringToManagedString(ext.RawData);
// If this doesn't match, maybe a V2 template will
if (StringComparer.OrdinalIgnoreCase.Equals(templateName, decodedName))
{
return true;
}
}
ext = FindExtension(cert, Oids.CertificateTemplate);
if (ext != null)
{
DerSequenceReader reader = new DerSequenceReader(ext.RawData);
// SEQUENCE (
// OID oid,
// INTEGER major,
// INTEGER minor OPTIONAL
// )
if (reader.PeekTag() == (byte)DerSequenceReader.DerTag.ObjectIdentifier)
{
Oid oid = reader.ReadOid();
if (StringComparer.Ordinal.Equals(templateName, oid.Value))
{
return true;
}
}
}
return false;
});
}
public void FindByApplicationPolicy(string oidValue)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.EnhancedKeyUsage);
if (ext == null)
{
// A certificate with no EKU is valid for all extended purposes.
return true;
}
var ekuExt = (X509EnhancedKeyUsageExtension)ext;
foreach (Oid usageOid in ekuExt.EnhancedKeyUsages)
{
if (StringComparer.Ordinal.Equals(oidValue, usageOid.Value))
{
return true;
}
}
// If the certificate had an EKU extension, and the value we wanted was
// not present, then it is not valid for that usage.
return false;
});
}
public void FindByCertificatePolicy(string oidValue)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.CertPolicies);
if (ext == null)
{
// Unlike Application Policy, Certificate Policy is "assume false".
return false;
}
ISet<string> policyOids = CertificatePolicyChain.ReadCertPolicyExtension(ext);
return policyOids.Contains(oidValue);
});
}
public void FindByExtension(string oidValue)
{
FindCore(cert => FindExtension(cert, oidValue) != null);
}
public void FindByKeyUsage(X509KeyUsageFlags keyUsage)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.KeyUsage);
if (ext == null)
{
// A certificate with no key usage extension is considered valid for all key usages.
return true;
}
var kuExt = (X509KeyUsageExtension)ext;
return (kuExt.KeyUsages & keyUsage) == keyUsage;
});
}
public void FindBySubjectKeyIdentifier(byte[] keyIdentifier)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.SubjectKeyIdentifier);
byte[] certKeyId;
if (ext != null)
{
// The extension exposes the value as a hexadecimal string, or we can decode here.
// Enough parsing has gone on, let's decode.
certKeyId = OpenSslX509Encoder.DecodeX509SubjectKeyIdentifierExtension(ext.RawData);
}
else
{
// The Desktop/Windows version of this method use CertGetCertificateContextProperty
// with a property ID of CERT_KEY_IDENTIFIER_PROP_ID.
//
// MSDN says that when there's no extension, this method takes the SHA-1 of the
// SubjectPublicKeyInfo block, and returns that.
//
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa376079%28v=vs.85%29.aspx
OpenSslX509CertificateReader certPal = (OpenSslX509CertificateReader)cert.Pal;
using (HashAlgorithm hash = SHA1.Create())
{
byte[] publicKeyInfoBytes = Interop.Crypto.OpenSslEncode(
Interop.Crypto.GetX509SubjectPublicKeyInfoDerSize,
Interop.Crypto.EncodeX509SubjectPublicKeyInfo,
certPal.SafeHandle);
certKeyId = hash.ComputeHash(publicKeyInfoBytes);
}
}
return keyIdentifier.ContentsEqual(certKeyId);
});
}
public void Dispose()
{
// No resources to release, but required by the interface.
}
private static X509Extension FindExtension(X509Certificate2 cert, string extensionOid)
{
if (cert.Extensions == null || cert.Extensions.Count == 0)
{
return null;
}
foreach (X509Extension ext in cert.Extensions)
{
if (ext != null &&
ext.Oid != null &&
StringComparer.Ordinal.Equals(extensionOid, ext.Oid.Value))
{
return ext;
}
}
return null;
}
private void FindCore(Predicate<X509Certificate2> predicate)
{
foreach (X509Certificate2 cert in _findFrom)
{
if (predicate(cert))
{
if (!_validOnly || IsCertValid(cert))
{
OpenSslX509CertificateReader certPal = (OpenSslX509CertificateReader)cert.Pal;
_copyTo.Add(new X509Certificate2(certPal.DuplicateHandles()));
}
}
}
}
private static bool IsCertValid(X509Certificate2 cert)
{
try
{
// This needs to be kept in sync with VerifyCertificateIgnoringErrors in the
// Windows PAL version (and potentially any other PALs that come about)
X509Chain chain = new X509Chain
{
ChainPolicy =
{
RevocationMode = X509RevocationMode.NoCheck,
RevocationFlag = X509RevocationFlag.ExcludeRoot
}
};
return chain.Build(cert);
}
catch (CryptographicException)
{
return false;
}
}
}
}
| |
//-----------------------------------------------------------------------
//
// Microsoft Windows Client Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: PriorityQueue.cs
//
// Contents: Implementation of PriorityQueue class.
//
// Created: 2-14-2005 Niklas Borson (niklasb)
//
//------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace MS.Internal
{
/// <summary>
/// PriorityQueue provides a stack-like interface, except that objects
/// "pushed" in arbitrary order are "popped" in order of priority, i.e.,
/// from least to greatest as defined by the specified comparer.
/// </summary>
/// <remarks>
/// Push and Pop are each O(log N). Pushing N objects and them popping
/// them all is equivalent to performing a heap sort and is O(N log N).
/// </remarks>
internal class PriorityQueue<T>
{
//
// The _heap array represents a binary tree with the "shape" property.
// If we number the nodes of a binary tree from left-to-right and top-
// to-bottom as shown,
//
// 0
// / \
// / \
// 1 2
// / \ / \
// 3 4 5 6
// /\ /
// 7 8 9
//
// The shape property means that there are no gaps in the sequence of
// numbered nodes, i.e., for all N > 0, if node N exists then node N-1
// also exists. For example, the next node added to the above tree would
// be node 10, the right child of node 4.
//
// Because of this constraint, we can easily represent the "tree" as an
// array, where node number == array index, and parent/child relationships
// can be calculated instead of maintained explicitly. For example, for
// any node N > 0, the parent of N is at array index (N - 1) / 2.
//
// In addition to the above, the first _count members of the _heap array
// compose a "heap", meaning each child node is greater than or equal to
// its parent node; thus, the root node is always the minimum (i.e., the
// best match for the specified style, weight, and stretch) of the nodes
// in the heap.
//
// Initially _count < 0, which means we have not yet constructed the heap.
// On the first call to MoveNext, we construct the heap by "pushing" all
// the nodes into it. Each successive call "pops" a node off the heap
// until the heap is empty (_count == 0), at which time we've reached the
// end of the sequence.
//
#region constructors
internal PriorityQueue(int capacity, IComparer<T> comparer)
{
_heap = new T[capacity > 0 ? capacity : DefaultCapacity];
_count = 0;
_comparer = comparer;
}
#endregion
#region internal members
/// <summary>
/// Gets the number of items in the priority queue.
/// </summary>
internal int Count
{
get { return _count; }
}
/// <summary>
/// Gets the first or topmost object in the priority queue, which is the
/// object with the minimum value.
/// </summary>
internal T Top
{
get
{
Debug.Assert(_count > 0);
return _heap[0];
}
}
/// <summary>
/// Adds an object to the priority queue.
/// </summary>
internal void Push(T value)
{
// Increase the size of the array if necessary.
if (_count == _heap.Length)
{
T[] temp = new T[_count * 2];
for (int i = 0; i < _count; ++i)
{
temp[i] = _heap[i];
}
_heap = temp;
}
// Loop invariant:
//
// 1. index is a gap where we might insert the new node; initially
// it's the end of the array (bottom-right of the logical tree).
//
int index = _count;
while (index > 0)
{
int parentIndex = HeapParent(index);
if (_comparer.Compare(value, _heap[parentIndex]) < 0)
{
// value is a better match than the parent node so exchange
// places to preserve the "heap" property.
_heap[index] = _heap[parentIndex];
index = parentIndex;
}
else
{
// we can insert here.
break;
}
}
_heap[index] = value;
_count++;
}
/// <summary>
/// Removes the first node (i.e., the logical root) from the heap.
/// </summary>
internal void Pop()
{
Debug.Assert(_count != 0);
if (_count > 1)
{
// Loop invariants:
//
// 1. parent is the index of a gap in the logical tree
// 2. leftChild is
// (a) the index of parent's left child if it has one, or
// (b) a value >= _count if parent is a leaf node
//
int parent = 0;
int leftChild = HeapLeftChild(parent);
while (leftChild < _count)
{
int rightChild = HeapRightFromLeft(leftChild);
int bestChild =
(rightChild < _count && _comparer.Compare(_heap[rightChild], _heap[leftChild]) < 0) ?
rightChild : leftChild;
// Promote bestChild to fill the gap left by parent.
_heap[parent] = _heap[bestChild];
// Restore invariants, i.e., let parent point to the gap.
parent = bestChild;
leftChild = HeapLeftChild(parent);
}
// Fill the last gap by moving the last (i.e., bottom-rightmost) node.
_heap[parent] = _heap[_count - 1];
}
_count--;
}
#endregion
#region private members
/// <summary>
/// Calculate the parent node index given a child node's index, taking advantage
/// of the "shape" property.
/// </summary>
private static int HeapParent(int i)
{
return (i - 1) / 2;
}
/// <summary>
/// Calculate the left child's index given the parent's index, taking advantage of
/// the "shape" property. If there is no left child, the return value is >= _count.
/// </summary>
private static int HeapLeftChild(int i)
{
return (i * 2) + 1;
}
/// <summary>
/// Calculate the right child's index from the left child's index, taking advantage
/// of the "shape" property (i.e., sibling nodes are always adjacent). If there is
/// no right child, the return value >= _count.
/// </summary>
private static int HeapRightFromLeft(int i)
{
return i + 1;
}
private T[] _heap;
private int _count;
private IComparer<T> _comparer;
private const int DefaultCapacity = 6;
#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.Compute
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Compute.Closure;
using Apache.Ignite.Core.Impl.Deployment;
using Apache.Ignite.Core.Impl.Memory;
using Apache.Ignite.Core.Impl.Resource;
/// <summary>
/// Holder for user-provided compute job.
/// </summary>
internal class ComputeJobHolder : IBinaryWriteAware
{
/** Actual job. */
private readonly IComputeJob _job;
/** Owning grid. */
private readonly IIgniteInternal _ignite;
/** Result (set for local jobs only). */
private volatile ComputeJobResultImpl _jobRes;
/// <summary>
/// Default ctor for marshalling.
/// </summary>
/// <param name="reader"></param>
public ComputeJobHolder(BinaryReader reader)
{
Debug.Assert(reader != null);
_ignite = reader.Marshaller.Ignite;
_job = reader.ReadObject<IComputeJob>();
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="job">Job.</param>
public ComputeJobHolder(IIgniteInternal grid, IComputeJob job)
{
Debug.Assert(grid != null);
Debug.Assert(job != null);
_ignite = grid;
_job = job;
}
/// <summary>
/// Executes local job.
/// </summary>
/// <param name="cancel">Cancel flag.</param>
public void ExecuteLocal(bool cancel)
{
object res;
bool success;
Execute0(cancel, out res, out success);
_jobRes = new ComputeJobResultImpl(
success ? res : null,
success ? null : new IgniteException("Compute job has failed on local node, " +
"examine InnerException for details.", (Exception) res),
_job,
_ignite.GetIgnite().GetCluster().GetLocalNode().Id,
cancel
);
}
/// <summary>
/// Execute job serializing result to the stream.
/// </summary>
/// <param name="cancel">Whether the job must be cancelled.</param>
/// <param name="stream">Stream.</param>
public void ExecuteRemote(PlatformMemoryStream stream, bool cancel)
{
// 1. Execute job.
object res;
bool success;
using (PeerAssemblyResolver.GetInstance(_ignite, Guid.Empty))
{
Execute0(cancel, out res, out success);
}
// 2. Try writing result to the stream.
var writer = _ignite.Marshaller.StartMarshal(stream);
try
{
// 3. Marshal results.
BinaryUtils.WriteInvocationResult(writer, success, res);
}
finally
{
// 4. Process metadata.
_ignite.Marshaller.FinishMarshal(writer);
}
}
/// <summary>
/// Cancel the job.
/// </summary>
public void Cancel()
{
_job.Cancel();
}
/// <summary>
/// Serialize the job to the stream.
/// </summary>
/// <param name="stream">Stream.</param>
/// <returns>True if successfull.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "User job can throw any exception")]
internal bool Serialize(IBinaryStream stream)
{
BinaryWriter writer = _ignite.Marshaller.StartMarshal(stream);
try
{
writer.Write(this);
return true;
}
catch (Exception e)
{
writer.WriteString("Failed to marshal job [job=" + _job + ", errType=" + e.GetType().Name +
", errMsg=" + e.Message + ']');
return false;
}
finally
{
// 4. Process metadata.
_ignite.Marshaller.FinishMarshal(writer);
}
}
/// <summary>
/// Job.
/// </summary>
internal IComputeJob Job
{
get { return _job; }
}
/// <summary>
/// Job result.
/// </summary>
internal ComputeJobResultImpl JobResult
{
get { return _jobRes; }
}
/// <summary>
/// Internal job execution routine.
/// </summary>
/// <param name="cancel">Cancel flag.</param>
/// <param name="res">Result.</param>
/// <param name="success">Success flag.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "User job can throw any exception")]
private void Execute0(bool cancel, out object res, out bool success)
{
// 1. Inject resources.
IComputeResourceInjector injector = _job as IComputeResourceInjector;
if (injector != null)
injector.Inject(_ignite);
else
ResourceProcessor.Inject(_job, _ignite);
// 2. Execute.
try
{
if (cancel)
_job.Cancel();
res = _job.Execute();
success = true;
}
catch (Exception e)
{
res = e;
success = false;
}
}
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
BinaryWriter writer0 = (BinaryWriter) writer.GetRawWriter();
writer0.WriteObjectDetached(_job);
}
/// <summary>
/// Create job instance.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="stream">Stream.</param>
/// <returns></returns>
internal static ComputeJobHolder CreateJob(Ignite grid, IBinaryStream stream)
{
try
{
return grid.Marshaller.StartUnmarshal(stream).ReadObject<ComputeJobHolder>();
}
catch (Exception e)
{
throw new IgniteException("Failed to deserialize the job [errType=" + e.GetType().Name +
", errMsg=" + e.Message + ']');
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Protocols.WsFederation;
using Microsoft.IdentityModel.Tokens;
namespace Microsoft.AspNetCore.Authentication.WsFederation
{
/// <summary>
/// A per-request authentication handler for the WsFederation.
/// </summary>
public class WsFederationHandler : RemoteAuthenticationHandler<WsFederationOptions>, IAuthenticationSignOutHandler
{
private const string CorrelationProperty = ".xsrf";
private WsFederationConfiguration? _configuration;
/// <summary>
/// Creates a new WsFederationAuthenticationHandler
/// </summary>
/// <param name="options"></param>
/// <param name="encoder"></param>
/// <param name="clock"></param>
/// <param name="logger"></param>
public WsFederationHandler(IOptionsMonitor<WsFederationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
/// <summary>
/// The handler calls methods on the events which give the application control at certain points where processing is occurring.
/// If it is not provided a default instance is supplied which does nothing when the methods are called.
/// </summary>
protected new WsFederationEvents Events
{
get { return (WsFederationEvents)base.Events; }
set { base.Events = value; }
}
/// <summary>
/// Creates a new instance of the events instance.
/// </summary>
/// <returns>A new instance of the events instance.</returns>
protected override Task<object> CreateEventsAsync() => Task.FromResult<object>(new WsFederationEvents());
/// <summary>
/// Overridden to handle remote signout requests
/// </summary>
/// <returns><see langword="true" /> if request processing should stop.</returns>
public override Task<bool> HandleRequestAsync()
{
// RemoteSignOutPath and CallbackPath may be the same, fall through if the message doesn't match.
if (Options.RemoteSignOutPath.HasValue && Options.RemoteSignOutPath == Request.Path && HttpMethods.IsGet(Request.Method)
&& string.Equals(Request.Query[WsFederationConstants.WsFederationParameterNames.Wa],
WsFederationConstants.WsFederationActions.SignOutCleanup, StringComparison.OrdinalIgnoreCase))
{
// We've received a remote sign-out request
return HandleRemoteSignOutAsync();
}
return base.HandleRequestAsync();
}
/// <summary>
/// Handles Challenge
/// </summary>
/// <returns></returns>
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
if (_configuration == null)
{
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
}
// Save the original challenge URI so we can redirect back to it when we're done.
if (string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = OriginalPathBase + OriginalPath + Request.QueryString;
}
var wsFederationMessage = new WsFederationMessage()
{
IssuerAddress = _configuration.TokenEndpoint ?? string.Empty,
Wtrealm = Options.Wtrealm,
Wa = WsFederationConstants.WsFederationActions.SignIn,
};
if (!string.IsNullOrEmpty(Options.Wreply))
{
wsFederationMessage.Wreply = Options.Wreply;
}
else
{
wsFederationMessage.Wreply = BuildRedirectUri(Options.CallbackPath);
}
GenerateCorrelationId(properties);
var redirectContext = new RedirectContext(Context, Scheme, Options, properties)
{
ProtocolMessage = wsFederationMessage
};
await Events.RedirectToIdentityProvider(redirectContext);
if (redirectContext.Handled)
{
return;
}
wsFederationMessage = redirectContext.ProtocolMessage;
if (!string.IsNullOrEmpty(wsFederationMessage.Wctx))
{
properties.Items[WsFederationDefaults.UserstatePropertiesKey] = wsFederationMessage.Wctx;
}
wsFederationMessage.Wctx = Uri.EscapeDataString(Options.StateDataFormat.Protect(properties));
var redirectUri = wsFederationMessage.CreateSignInUrl();
if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
{
Logger.MalformedRedirectUri(redirectUri);
}
Response.Redirect(redirectUri);
}
/// <summary>
/// Invoked to process incoming authentication messages.
/// </summary>
/// <returns></returns>
protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync()
{
WsFederationMessage? wsFederationMessage = null;
AuthenticationProperties? properties = null;
// assumption: if the ContentType is "application/x-www-form-urlencoded" it should be safe to read as it is small.
if (HttpMethods.IsPost(Request.Method)
&& !string.IsNullOrEmpty(Request.ContentType)
// May have media/type; charset=utf-8, allow partial match.
&& Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)
&& Request.Body.CanRead)
{
var form = await Request.ReadFormAsync(Context.RequestAborted);
// ToArray handles the StringValues.IsNullOrEmpty case. We assume non-empty Value does not contain null elements.
#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
wsFederationMessage = new WsFederationMessage(form.Select(pair => new KeyValuePair<string, string[]>(pair.Key, pair.Value.ToArray())));
#pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
}
if (wsFederationMessage == null || !wsFederationMessage.IsSignInMessage)
{
if (Options.SkipUnrecognizedRequests)
{
// Not for us?
return HandleRequestResult.SkipHandler();
}
return HandleRequestResult.Fail("No message.");
}
try
{
// Retrieve our cached redirect uri
var state = wsFederationMessage.Wctx;
// WsFed allows for uninitiated logins, state may be missing. See AllowUnsolicitedLogins.
properties = Options.StateDataFormat.Unprotect(state);
if (properties == null)
{
if (!Options.AllowUnsolicitedLogins)
{
return HandleRequestResult.Fail("Unsolicited logins are not allowed.");
}
}
else
{
// Extract the user state from properties and reset.
properties.Items.TryGetValue(WsFederationDefaults.UserstatePropertiesKey, out var userState);
wsFederationMessage.Wctx = userState;
}
var messageReceivedContext = new MessageReceivedContext(Context, Scheme, Options, properties)
{
ProtocolMessage = wsFederationMessage
};
await Events.MessageReceived(messageReceivedContext);
if (messageReceivedContext.Result != null)
{
return messageReceivedContext.Result;
}
wsFederationMessage = messageReceivedContext.ProtocolMessage;
properties = messageReceivedContext.Properties!; // Provides a new instance if not set.
// If state did flow from the challenge then validate it. See AllowUnsolicitedLogins above.
if (properties.Items.TryGetValue(CorrelationProperty, out string? correlationId)
&& !ValidateCorrelationId(properties))
{
return HandleRequestResult.Fail("Correlation failed.", properties);
}
if (wsFederationMessage.Wresult == null)
{
Logger.SignInWithoutWResult();
return HandleRequestResult.Fail(Resources.SignInMessageWresultIsMissing, properties);
}
var token = wsFederationMessage.GetToken();
if (string.IsNullOrEmpty(token))
{
Logger.SignInWithoutToken();
return HandleRequestResult.Fail(Resources.SignInMessageTokenIsMissing, properties);
}
var securityTokenReceivedContext = new SecurityTokenReceivedContext(Context, Scheme, Options, properties)
{
ProtocolMessage = wsFederationMessage
};
await Events.SecurityTokenReceived(securityTokenReceivedContext);
if (securityTokenReceivedContext.Result != null)
{
return securityTokenReceivedContext.Result;
}
wsFederationMessage = securityTokenReceivedContext.ProtocolMessage;
properties = messageReceivedContext.Properties!;
if (_configuration == null)
{
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
}
// Copy and augment to avoid cross request race conditions for updated configurations.
var tvp = Options.TokenValidationParameters.Clone();
var issuers = new[] { _configuration.Issuer };
tvp.ValidIssuers = (tvp.ValidIssuers == null ? issuers : tvp.ValidIssuers.Concat(issuers));
tvp.IssuerSigningKeys = (tvp.IssuerSigningKeys == null ? _configuration.SigningKeys : tvp.IssuerSigningKeys.Concat(_configuration.SigningKeys));
ClaimsPrincipal? principal = null;
SecurityToken? parsedToken = null;
foreach (var validator in Options.SecurityTokenHandlers)
{
if (validator.CanReadToken(token))
{
principal = validator.ValidateToken(token, tvp, out parsedToken);
break;
}
}
if (principal == null)
{
throw new SecurityTokenException(Resources.Exception_NoTokenValidatorFound);
}
if (Options.UseTokenLifetime && parsedToken != null)
{
// Override any session persistence to match the token lifetime.
var issued = parsedToken.ValidFrom;
if (issued != DateTime.MinValue)
{
properties.IssuedUtc = issued.ToUniversalTime();
}
var expires = parsedToken.ValidTo;
if (expires != DateTime.MinValue)
{
properties.ExpiresUtc = expires.ToUniversalTime();
}
properties.AllowRefresh = false;
}
var securityTokenValidatedContext = new SecurityTokenValidatedContext(Context, Scheme, Options, principal, properties)
{
ProtocolMessage = wsFederationMessage,
SecurityToken = parsedToken,
};
await Events.SecurityTokenValidated(securityTokenValidatedContext);
if (securityTokenValidatedContext.Result != null)
{
return securityTokenValidatedContext.Result;
}
// Flow possible changes
principal = securityTokenValidatedContext.Principal!;
properties = securityTokenValidatedContext.Properties;
return HandleRequestResult.Success(new AuthenticationTicket(principal, properties, Scheme.Name));
}
catch (Exception exception)
{
Logger.ExceptionProcessingMessage(exception);
// Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the notification.
if (Options.RefreshOnIssuerKeyNotFound && exception is SecurityTokenSignatureKeyNotFoundException)
{
Options.ConfigurationManager.RequestRefresh();
}
var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
{
ProtocolMessage = wsFederationMessage,
Exception = exception
};
await Events.AuthenticationFailed(authenticationFailedContext);
if (authenticationFailedContext.Result != null)
{
return authenticationFailedContext.Result;
}
return HandleRequestResult.Fail(exception, properties);
}
}
/// <summary>
/// Handles Signout
/// </summary>
/// <returns></returns>
public virtual async Task SignOutAsync(AuthenticationProperties? properties)
{
var target = ResolveTarget(Options.ForwardSignOut);
if (target != null)
{
await Context.SignOutAsync(target, properties);
return;
}
if (_configuration == null)
{
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
}
var wsFederationMessage = new WsFederationMessage()
{
IssuerAddress = _configuration.TokenEndpoint ?? string.Empty,
Wtrealm = Options.Wtrealm,
Wa = WsFederationConstants.WsFederationActions.SignOut,
};
// Set Wreply in order:
// 1. properties.Redirect
// 2. Options.SignOutWreply
// 3. Options.Wreply
if (properties != null && !string.IsNullOrEmpty(properties.RedirectUri))
{
wsFederationMessage.Wreply = BuildRedirectUriIfRelative(properties.RedirectUri);
}
else if (!string.IsNullOrEmpty(Options.SignOutWreply))
{
wsFederationMessage.Wreply = BuildRedirectUriIfRelative(Options.SignOutWreply);
}
else if (!string.IsNullOrEmpty(Options.Wreply))
{
wsFederationMessage.Wreply = BuildRedirectUriIfRelative(Options.Wreply);
}
var redirectContext = new RedirectContext(Context, Scheme, Options, properties)
{
ProtocolMessage = wsFederationMessage
};
await Events.RedirectToIdentityProvider(redirectContext);
if (!redirectContext.Handled)
{
var redirectUri = redirectContext.ProtocolMessage.CreateSignOutUrl();
if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
{
Logger.MalformedRedirectUri(redirectUri);
}
Response.Redirect(redirectUri);
}
}
/// <summary>
/// Handles wsignoutcleanup1.0 messages sent to the RemoteSignOutPath
/// </summary>
/// <returns></returns>
protected virtual async Task<bool> HandleRemoteSignOutAsync()
{
// ToArray handles the StringValues.IsNullOrEmpty case. We assume non-empty Value does not contain null elements.
#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
var message = new WsFederationMessage(Request.Query.Select(pair => new KeyValuePair<string, string[]>(pair.Key, pair.Value.ToArray())));
#pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
var remoteSignOutContext = new RemoteSignOutContext(Context, Scheme, Options, message);
await Events.RemoteSignOut(remoteSignOutContext);
if (remoteSignOutContext.Result != null)
{
if (remoteSignOutContext.Result.Handled)
{
Logger.RemoteSignOutHandledResponse();
return true;
}
if (remoteSignOutContext.Result.Skipped)
{
Logger.RemoteSignOutSkipped();
return false;
}
}
Logger.RemoteSignOut();
await Context.SignOutAsync(Options.SignOutScheme);
return true;
}
/// <summary>
/// Build a redirect path if the given path is a relative path.
/// </summary>
private string BuildRedirectUriIfRelative(string uri)
{
if (string.IsNullOrEmpty(uri))
{
return uri;
}
if (!uri.StartsWith("/", StringComparison.Ordinal))
{
return uri;
}
return BuildRedirectUri(uri);
}
}
}
| |
using J2N.Text;
using J2N.Threading.Atomic;
using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Codecs.RAMOnly
{
/*
* 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.
*/
/// <summary>
/// Stores all postings data in RAM, but writes a small
/// token (header + single int) to identify which "slot" the
/// index is using in RAM dictionary.
/// <para/>
/// NOTE: this codec sorts terms by reverse-unicode-order!
/// </summary>
[PostingsFormatName("RAMOnly")] // LUCENENET specific - using PostingsFormatName attribute to ensure the default name passed from subclasses is the same as this class name
public sealed class RAMOnlyPostingsFormat : PostingsFormat
{
// For fun, test that we can override how terms are
// sorted, and basic things still work -- this comparer
// sorts in reversed unicode code point order:
private static readonly IComparer<BytesRef> reverseUnicodeComparer = new ComparerAnonymousInnerClassHelper();
#pragma warning disable 659 // LUCENENET: Overrides Equals but not GetHashCode
private class ComparerAnonymousInnerClassHelper : IComparer<BytesRef>
#pragma warning restore 659
{
public ComparerAnonymousInnerClassHelper()
{ }
public virtual int Compare(BytesRef t1, BytesRef t2)
{
var b1 = t1.Bytes;
var b2 = t2.Bytes;
int b1Stop;
int b1Upto = t1.Offset;
int b2Upto = t2.Offset;
if (t1.Length < t2.Length)
{
b1Stop = t1.Offset + t1.Length;
}
else
{
b1Stop = t1.Offset + t2.Length;
}
while (b1Upto < b1Stop)
{
int bb1 = b1[b1Upto++] & 0xff;
int bb2 = b2[b2Upto++] & 0xff;
if (bb1 != bb2)
{
//System.out.println("cmp 1=" + t1 + " 2=" + t2 + " return " + (bb2-bb1));
return bb2 - bb1;
}
}
// One is prefix of another, or they are equal
return t2.Length - t1.Length;
}
public override bool Equals(object other)
{
return this == other;
}
}
public RAMOnlyPostingsFormat()
: base()
{ }
// Postings state:
internal class RAMPostings : FieldsProducer
{
// LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java
internal readonly IDictionary<string, RAMField> fieldToTerms = new JCG.SortedDictionary<string, RAMField>(StringComparer.Ordinal);
public override Terms GetTerms(string field)
{
RAMField result;
fieldToTerms.TryGetValue(field, out result);
return result;
}
public override int Count => fieldToTerms.Count;
public override IEnumerator<string> GetEnumerator()
=> fieldToTerms.Keys.GetEnumerator();
protected override void Dispose(bool disposing)
{
}
public override long RamBytesUsed()
{
long sizeInBytes = 0;
foreach (RAMField field in fieldToTerms.Values)
{
sizeInBytes += field.RamBytesUsed();
}
return sizeInBytes;
}
public override void CheckIntegrity()
{
}
}
internal class RAMField : Terms
{
internal readonly string field;
// LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java
internal readonly JCG.SortedDictionary<string, RAMTerm> termToDocs = new JCG.SortedDictionary<string, RAMTerm>(StringComparer.Ordinal);
internal long sumTotalTermFreq;
internal long sumDocFreq;
internal int docCount;
internal readonly FieldInfo info;
internal RAMField(string field, FieldInfo info)
{
this.field = field;
this.info = info;
}
/// <summary>
/// Returns approximate RAM bytes used </summary>
public virtual long RamBytesUsed()
{
long sizeInBytes = 0;
foreach (RAMTerm term in termToDocs.Values)
{
sizeInBytes += term.RamBytesUsed();
}
return sizeInBytes;
}
public override long Count => termToDocs.Count;
public override long SumTotalTermFreq => sumTotalTermFreq;
public override long SumDocFreq => sumDocFreq;
public override int DocCount => docCount;
public override TermsEnum GetEnumerator()
{
return new RAMTermsEnum(this);
}
public override IComparer<BytesRef> Comparer => reverseUnicodeComparer;
public override bool HasFreqs
=> info.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
public override bool HasOffsets
=> info.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
public override bool HasPositions
=> info.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
public override bool HasPayloads => info.HasPayloads;
}
internal class RAMTerm
{
internal readonly string term;
internal long totalTermFreq;
internal readonly IList<RAMDoc> docs = new List<RAMDoc>();
public RAMTerm(string term)
{
this.term = term;
}
/// <summary>
/// Returns approximate RAM bytes used </summary>
public virtual long RamBytesUsed()
{
long sizeInBytes = 0;
foreach (RAMDoc rDoc in docs)
{
sizeInBytes += rDoc.RamBytesUsed();
}
return sizeInBytes;
}
}
internal class RAMDoc
{
internal readonly int docID;
internal readonly int[] positions;
internal byte[][] payloads;
public RAMDoc(int docID, int freq)
{
this.docID = docID;
positions = new int[freq];
}
/// <summary>
/// Returns approximate RAM bytes used </summary>
public virtual long RamBytesUsed()
{
long sizeInBytes = 0;
sizeInBytes += (positions != null) ? RamUsageEstimator.SizeOf(positions) : 0;
if (payloads != null)
{
foreach (var payload in payloads)
{
sizeInBytes += (payload != null) ? RamUsageEstimator.SizeOf(payload) : 0;
}
}
return sizeInBytes;
}
}
// Classes for writing to the postings state
private class RAMFieldsConsumer : FieldsConsumer
{
private readonly RAMPostings postings;
private readonly RAMTermsConsumer termsConsumer = new RAMTermsConsumer();
public RAMFieldsConsumer(RAMPostings postings)
{
this.postings = postings;
}
public override TermsConsumer AddField(FieldInfo field)
{
if (field.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0)
{
throw new NotSupportedException("this codec cannot index offsets");
}
RAMField ramField = new RAMField(field.Name, field);
postings.fieldToTerms[field.Name] = ramField;
termsConsumer.Reset(ramField);
return termsConsumer;
}
protected override void Dispose(bool disposing)
{
// TODO: finalize stuff
}
}
private class RAMTermsConsumer : TermsConsumer
{
private RAMField field;
private readonly RAMPostingsWriterImpl postingsWriter = new RAMPostingsWriterImpl();
internal RAMTerm current;
internal virtual void Reset(RAMField field)
{
this.field = field;
}
public override PostingsConsumer StartTerm(BytesRef text)
{
string term = text.Utf8ToString();
current = new RAMTerm(term);
postingsWriter.Reset(current);
return postingsWriter;
}
public override IComparer<BytesRef> Comparer
=> BytesRef.UTF8SortedAsUnicodeComparer;
public override void FinishTerm(BytesRef text, TermStats stats)
{
if (Debugging.AssertsEnabled) Debugging.Assert(stats.DocFreq > 0);
if (Debugging.AssertsEnabled) Debugging.Assert(stats.DocFreq == current.docs.Count);
current.totalTermFreq = stats.TotalTermFreq;
field.termToDocs[current.term] = current;
}
public override void Finish(long sumTotalTermFreq, long sumDocFreq, int docCount)
{
field.sumTotalTermFreq = sumTotalTermFreq;
field.sumDocFreq = sumDocFreq;
field.docCount = docCount;
}
}
internal class RAMPostingsWriterImpl : PostingsConsumer
{
private RAMTerm term;
private RAMDoc current;
private int posUpto = 0;
public virtual void Reset(RAMTerm term)
{
this.term = term;
}
public override void StartDoc(int docID, int freq)
{
current = new RAMDoc(docID, freq);
term.docs.Add(current);
posUpto = 0;
}
public override void AddPosition(int position, BytesRef payload, int startOffset, int endOffset)
{
if (Debugging.AssertsEnabled) Debugging.Assert(startOffset == -1);
if (Debugging.AssertsEnabled) Debugging.Assert(endOffset == -1);
current.positions[posUpto] = position;
if (payload != null && payload.Length > 0)
{
if (current.payloads == null)
{
current.payloads = new byte[current.positions.Length][];
}
var bytes = current.payloads[posUpto] = new byte[payload.Length];
Array.Copy(payload.Bytes, payload.Offset, bytes, 0, payload.Length);
}
posUpto++;
}
public override void FinishDoc()
{
if (Debugging.AssertsEnabled) Debugging.Assert(posUpto == current.positions.Length);
}
}
internal class RAMTermsEnum : TermsEnum
{
internal IEnumerator<string> it;
internal string current;
private readonly RAMField ramField;
public RAMTermsEnum(RAMField field)
{
this.ramField = field;
}
public override IComparer<BytesRef> Comparer
=> BytesRef.UTF8SortedAsUnicodeComparer;
public override bool MoveNext()
{
EnsureEnumeratorInitialized();
if (it.MoveNext())
{
current = it.Current;
return true;
}
else
{
return false;
}
}
[Obsolete("Use MoveNext() and Term instead. This method will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override BytesRef Next()
{
if (MoveNext())
return new BytesRef(current);
return null;
}
private void EnsureEnumeratorInitialized() // LUCENENET specific - factored out initialization step
{
if (it is null)
{
if (current is null)
{
it = ramField.termToDocs.Keys.GetEnumerator();
}
else
{
//It = RamField.TermToDocs.tailMap(Current).Keys.GetEnumerator();
it = ramField.termToDocs.Where(kvpair => string.CompareOrdinal(kvpair.Key, current) >= 0).Select(pair => pair.Key).GetEnumerator();
}
}
}
public override SeekStatus SeekCeil(BytesRef term)
{
current = term.Utf8ToString();
it = null;
if (ramField.termToDocs.ContainsKey(current))
{
return SeekStatus.FOUND;
}
else
{
if (current.CompareToOrdinal(ramField.termToDocs.Last().Key) > 0)
{
return SeekStatus.END;
}
else
{
return SeekStatus.NOT_FOUND;
}
}
}
public override void SeekExact(long ord)
=> throw new NotSupportedException();
public override long Ord
=> throw new NotSupportedException();
// TODO: reuse BytesRef
public override BytesRef Term => new BytesRef(current);
public override int DocFreq
=> ramField.termToDocs[current].docs.Count;
public override long TotalTermFreq
=> ramField.termToDocs[current].totalTermFreq;
public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags)
{
return new RAMDocsEnum(ramField.termToDocs[current], liveDocs);
}
public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags)
{
return new RAMDocsAndPositionsEnum(ramField.termToDocs[current], liveDocs);
}
}
private class RAMDocsEnum : DocsEnum
{
private readonly RAMTerm ramTerm;
private readonly IBits liveDocs;
private RAMDoc current;
private int upto = -1;
#pragma warning disable 414
private int posUpto = 0; // LUCENENET NOTE: Not used
#pragma warning restore 414
public RAMDocsEnum(RAMTerm ramTerm, IBits liveDocs)
{
this.ramTerm = ramTerm;
this.liveDocs = liveDocs;
}
public override int Advance(int targetDocID)
{
return SlowAdvance(targetDocID);
}
// TODO: override bulk read, for better perf
public override int NextDoc()
{
while (true)
{
upto++;
if (upto < ramTerm.docs.Count)
{
current = ramTerm.docs[upto];
if (liveDocs == null || liveDocs.Get(current.docID))
{
posUpto = 0;
return current.docID;
}
}
else
{
return NO_MORE_DOCS;
}
}
}
public override int Freq
=> current.positions.Length;
public override int DocID
=> current.docID;
public override long GetCost()
=> ramTerm.docs.Count;
}
private class RAMDocsAndPositionsEnum : DocsAndPositionsEnum
{
private readonly RAMTerm ramTerm;
private readonly IBits liveDocs;
private RAMDoc current;
private int upto = -1;
private int posUpto = 0;
public RAMDocsAndPositionsEnum(RAMTerm ramTerm, IBits liveDocs)
{
this.ramTerm = ramTerm;
this.liveDocs = liveDocs;
}
public override int Advance(int targetDocID)
{
return SlowAdvance(targetDocID);
}
// TODO: override bulk read, for better perf
public override int NextDoc()
{
while (true)
{
upto++;
if (upto < ramTerm.docs.Count)
{
current = ramTerm.docs[upto];
if (liveDocs == null || liveDocs.Get(current.docID))
{
posUpto = 0;
return current.docID;
}
}
else
{
return NO_MORE_DOCS;
}
}
}
public override int Freq
=> current.positions.Length;
public override int DocID
=> current.docID;
public override int NextPosition()
=> current.positions[posUpto++];
public override int StartOffset => -1;
public override int EndOffset => -1;
public override BytesRef GetPayload()
{
if (current.payloads != null && current.payloads[posUpto - 1] != null)
{
return new BytesRef(current.payloads[posUpto - 1]);
}
else
{
return null;
}
}
public override long GetCost()
=> ramTerm.docs.Count;
}
// Holds all indexes created, keyed by the ID assigned in fieldsConsumer
private readonly IDictionary<int?, RAMPostings> state = new Dictionary<int?, RAMPostings>();
private readonly AtomicInt64 nextID = new AtomicInt64();
private readonly string RAM_ONLY_NAME = "RAMOnly";
private const int VERSION_START = 0;
private const int VERSION_LATEST = VERSION_START;
private const string ID_EXTENSION = "id";
public override FieldsConsumer FieldsConsumer(SegmentWriteState writeState)
{
int id = (int)nextID.GetAndIncrement();
// TODO -- ok to do this up front instead of
// on close....? should be ok?
// Write our ID:
string idFileName = IndexFileNames.SegmentFileName(writeState.SegmentInfo.Name, writeState.SegmentSuffix, ID_EXTENSION);
IndexOutput @out = writeState.Directory.CreateOutput(idFileName, writeState.Context);
bool success = false;
try
{
CodecUtil.WriteHeader(@out, RAM_ONLY_NAME, VERSION_LATEST);
@out.WriteVInt32(id);
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(@out);
}
else
{
IOUtils.Dispose(@out);
}
}
RAMPostings postings = new RAMPostings();
RAMFieldsConsumer consumer = new RAMFieldsConsumer(postings);
lock (state)
{
state[id] = postings;
}
return consumer;
}
public override FieldsProducer FieldsProducer(SegmentReadState readState)
{
// Load our ID:
string idFileName = IndexFileNames.SegmentFileName(readState.SegmentInfo.Name, readState.SegmentSuffix, ID_EXTENSION);
IndexInput @in = readState.Directory.OpenInput(idFileName, readState.Context);
bool success = false;
int id;
try
{
CodecUtil.CheckHeader(@in, RAM_ONLY_NAME, VERSION_START, VERSION_LATEST);
id = @in.ReadVInt32();
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(@in);
}
else
{
IOUtils.Dispose(@in);
}
}
lock (state)
{
return state[id];
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * 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 Google Inc. 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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Encapsulates initialization and shutdown of gRPC library.
/// </summary>
public class GrpcEnvironment
{
const int MinDefaultThreadPoolSize = 4;
static object staticLock = new object();
static GrpcEnvironment instance;
static int refCount;
static int? customThreadPoolSize;
static int? customCompletionQueueCount;
static readonly HashSet<Channel> registeredChannels = new HashSet<Channel>();
static readonly HashSet<Server> registeredServers = new HashSet<Server>();
static ILogger logger = new NullLogger();
readonly object myLock = new object();
readonly GrpcThreadPool threadPool;
readonly DebugStats debugStats = new DebugStats();
readonly AtomicCounter cqPickerCounter = new AtomicCounter();
bool isClosed;
/// <summary>
/// Returns a reference-counted instance of initialized gRPC environment.
/// Subsequent invocations return the same instance unless reference count has dropped to zero previously.
/// </summary>
internal static GrpcEnvironment AddRef()
{
ShutdownHooks.Register();
lock (staticLock)
{
refCount++;
if (instance == null)
{
instance = new GrpcEnvironment();
}
return instance;
}
}
/// <summary>
/// Decrements the reference count for currently active environment and asynchronously shuts down the gRPC environment if reference count drops to zero.
/// </summary>
internal static async Task ReleaseAsync()
{
GrpcEnvironment instanceToShutdown = null;
lock (staticLock)
{
GrpcPreconditions.CheckState(refCount > 0);
refCount--;
if (refCount == 0)
{
instanceToShutdown = instance;
instance = null;
}
}
if (instanceToShutdown != null)
{
await instanceToShutdown.ShutdownAsync().ConfigureAwait(false);
}
}
internal static int GetRefCount()
{
lock (staticLock)
{
return refCount;
}
}
internal static void RegisterChannel(Channel channel)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(channel);
registeredChannels.Add(channel);
}
}
internal static void UnregisterChannel(Channel channel)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(channel);
GrpcPreconditions.CheckArgument(registeredChannels.Remove(channel), "Channel not found in the registered channels set.");
}
}
internal static void RegisterServer(Server server)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(server);
registeredServers.Add(server);
}
}
internal static void UnregisterServer(Server server)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(server);
GrpcPreconditions.CheckArgument(registeredServers.Remove(server), "Server not found in the registered servers set.");
}
}
/// <summary>
/// Requests shutdown of all channels created by the current process.
/// </summary>
public static Task ShutdownChannelsAsync()
{
HashSet<Channel> snapshot = null;
lock (staticLock)
{
snapshot = new HashSet<Channel>(registeredChannels);
}
return Task.WhenAll(snapshot.Select((channel) => channel.ShutdownAsync()));
}
/// <summary>
/// Requests immediate shutdown of all servers created by the current process.
/// </summary>
public static Task KillServersAsync()
{
HashSet<Server> snapshot = null;
lock (staticLock)
{
snapshot = new HashSet<Server>(registeredServers);
}
return Task.WhenAll(snapshot.Select((server) => server.KillAsync()));
}
/// <summary>
/// Gets application-wide logger used by gRPC.
/// </summary>
/// <value>The logger.</value>
public static ILogger Logger
{
get
{
return logger;
}
}
/// <summary>
/// Sets the application-wide logger that should be used by gRPC.
/// </summary>
public static void SetLogger(ILogger customLogger)
{
GrpcPreconditions.CheckNotNull(customLogger, "customLogger");
logger = customLogger;
}
/// <summary>
/// Sets the number of threads in the gRPC thread pool that polls for internal RPC events.
/// Can be only invoke before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards.
/// Setting thread pool size is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// </summary>
public static void SetThreadPoolSize(int threadCount)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcPreconditions.CheckArgument(threadCount > 0, "threadCount needs to be a positive number");
customThreadPoolSize = threadCount;
}
}
/// <summary>
/// Sets the number of completion queues in the gRPC thread pool that polls for internal RPC events.
/// Can be only invoke before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards.
/// Setting the number of completions queues is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// </summary>
public static void SetCompletionQueueCount(int completionQueueCount)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcPreconditions.CheckArgument(completionQueueCount > 0, "threadCount needs to be a positive number");
customCompletionQueueCount = completionQueueCount;
}
}
/// <summary>
/// Creates gRPC environment.
/// </summary>
private GrpcEnvironment()
{
GrpcNativeInit();
threadPool = new GrpcThreadPool(this, GetThreadPoolSizeOrDefault(), GetCompletionQueueCountOrDefault());
threadPool.Start();
}
/// <summary>
/// Gets the completion queues used by this gRPC environment.
/// </summary>
internal IReadOnlyCollection<CompletionQueueSafeHandle> CompletionQueues
{
get
{
return this.threadPool.CompletionQueues;
}
}
internal bool IsAlive
{
get
{
return this.threadPool.IsAlive;
}
}
/// <summary>
/// Picks a completion queue in a round-robin fashion.
/// Shouldn't be invoked on a per-call basis (used at per-channel basis).
/// </summary>
internal CompletionQueueSafeHandle PickCompletionQueue()
{
var cqIndex = (int) ((cqPickerCounter.Increment() - 1) % this.threadPool.CompletionQueues.Count);
return this.threadPool.CompletionQueues.ElementAt(cqIndex);
}
/// <summary>
/// Gets the completion queue used by this gRPC environment.
/// </summary>
internal DebugStats DebugStats
{
get
{
return this.debugStats;
}
}
/// <summary>
/// Gets version of gRPC C core.
/// </summary>
internal static string GetCoreVersionString()
{
var ptr = NativeMethods.Get().grpcsharp_version_string(); // the pointer is not owned
return Marshal.PtrToStringAnsi(ptr);
}
internal static void GrpcNativeInit()
{
NativeMethods.Get().grpcsharp_init();
}
internal static void GrpcNativeShutdown()
{
NativeMethods.Get().grpcsharp_shutdown();
}
/// <summary>
/// Shuts down this environment.
/// </summary>
private async Task ShutdownAsync()
{
if (isClosed)
{
throw new InvalidOperationException("Close has already been called");
}
await threadPool.StopAsync().ConfigureAwait(false);
GrpcNativeShutdown();
isClosed = true;
debugStats.CheckOK();
}
private int GetThreadPoolSizeOrDefault()
{
if (customThreadPoolSize.HasValue)
{
return customThreadPoolSize.Value;
}
// In systems with many cores, use half of the cores for GrpcThreadPool
// and the other half for .NET thread pool. This heuristic definitely needs
// more work, but seems to work reasonably well for a start.
return Math.Max(MinDefaultThreadPoolSize, Environment.ProcessorCount / 2);
}
private int GetCompletionQueueCountOrDefault()
{
if (customCompletionQueueCount.HasValue)
{
return customCompletionQueueCount.Value;
}
// by default, create a completion queue for each thread
return GetThreadPoolSizeOrDefault();
}
private static class ShutdownHooks
{
static object staticLock = new object();
static bool hooksRegistered;
public static void Register()
{
lock (staticLock)
{
if (!hooksRegistered)
{
// TODO(jtattermusch): register shutdownhooks for CoreCLR as well
#if !NETSTANDARD1_5
AppDomain.CurrentDomain.ProcessExit += ShutdownHookHandler;
AppDomain.CurrentDomain.DomainUnload += ShutdownHookHandler;
#endif
}
hooksRegistered = true;
}
}
/// <summary>
/// Handler for AppDomain.DomainUnload and AppDomain.ProcessExit hooks.
/// </summary>
private static void ShutdownHookHandler(object sender, EventArgs e)
{
Task.WaitAll(GrpcEnvironment.ShutdownChannelsAsync(), GrpcEnvironment.KillServersAsync());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.ComponentModel.DataAnnotations.Tests
{
public class CustomValidationAttributeTests : ValidationAttributeTestBase
{
private static readonly ValidationContext s_testValidationContext = new ValidationContext(new object());
protected override IEnumerable<TestCase> ValidValues()
{
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArg)), "AnyString");
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgs)), new TestClass("AnyString"));
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgStronglyTyped)), "AnyString");
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgsStronglyTyped)), new TestClass("AnyString"));
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgNullable)), null);
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgNullable)), new TestStruct() { Value = "Valid Value" });
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgsWithFirstNullable)), null);
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgsWithFirstNullable)), new TestStruct() { Value = "Valid Value" });
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgsStronglyTyped)), new DerivedTestClass("AnyString"));
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), 123);
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), false);
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), 123456L);
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), 123.456F);
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), 123.456D);
}
protected override IEnumerable<TestCase> InvalidValues()
{
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArg)), null);
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArg)), new TestClass("AnyString"));
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgs)), "AnyString");
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgStronglyTyped)), new TestClass("AnyString"));
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgsStronglyTyped)), "AnyString");
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgGenericStruct)), null);
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgNullable)), new TestStruct());
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgsWithFirstNullable)), new TestStruct() { Value = "Invalid Value" });
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), null);
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), new TestClass("NotInt"));
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), new DateTime(2014, 3, 19));
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgDateTime)), null);
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgDateTime)), "abcdef");
// Implements IConvertible (throws NotSupportedException - is caught)
yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgInt)), new IConvertibleImplementor() { IntThrow = new NotSupportedException() });
}
protected override bool RespectsErrorMessage => false;
private static CustomValidationAttribute GetAttribute(string name) => new CustomValidationAttribute(typeof(CustomValidator), name);
[Theory]
[InlineData(typeof(CustomValidator), "SomeMethod")]
[InlineData(null, null)]
[InlineData(typeof(string), "")]
[InlineData(typeof(int), " \t\r\n")]
public static void Ctor_Type_String(Type validatorType, string method)
{
CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method);
Assert.Equal(validatorType, attribute.ValidatorType);
Assert.Equal(method, attribute.Method);
}
[Theory]
[InlineData(typeof(CustomValidator), nameof(CustomValidator.ValidationMethodDerivedReturnTypeReturnsSomeError))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full .NET Frameworks had a restriction, that prevented to use custom ValidationResult. .NET Core allows to return class derived from ValidatioResult")]
public static void Ctor_Type_String_IgnoreNetFramework(Type validatorType, string method)
{
Ctor_Type_String(validatorType, method);
}
[Fact]
public void FormatErrorMessage_NotPerformedValidation_ContainsName()
{
CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArg));
string errorMessage = attribute.FormatErrorMessage("name");
Assert.Contains("name", errorMessage);
Assert.Equal(errorMessage, attribute.FormatErrorMessage("name"));
}
[Fact]
public void FormatErrorMessage_PerformedValidation_DoesNotContainName()
{
CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArg));
Assert.False(attribute.IsValid(new TestClass("AnyString")));
string errorMessage = attribute.FormatErrorMessage("name");
Assert.DoesNotContain("name", errorMessage);
Assert.Equal(errorMessage, attribute.FormatErrorMessage("name"));
}
[Theory]
[InlineData(nameof(CustomValidator.CorrectValidationMethodOneArg), false)]
[InlineData(nameof(CustomValidator.CorrectValidationMethodOneArgStronglyTyped), false)]
[InlineData(nameof(CustomValidator.CorrectValidationMethodTwoArgs), true)]
[InlineData(nameof(CustomValidator.CorrectValidationMethodTwoArgsStronglyTyped), true)]
public static void RequiresValidationContext_Get_ReturnsExpected(string method, bool expected)
{
CustomValidationAttribute attribute = GetAttribute(method);
// The full .NET Framework has a bug where CustomValidationAttribute doesn't
// validate the context. See https://github.com/dotnet/corefx/issues/18360.
if (PlatformDetection.IsFullFramework)
{
Assert.False(attribute.RequiresValidationContext);
}
else
{
Assert.Equal(expected, attribute.RequiresValidationContext);
}
}
public static IEnumerable<object[]> BadlyFormed_TestData()
{
yield return new object[] { null, "Does not matter" };
yield return new object[] { typeof(NonPublicCustomValidator), "Does not matter" };
yield return new object[] { typeof(CustomValidator), null };
yield return new object[] { typeof(CustomValidator), "" };
yield return new object[] { typeof(CustomValidator), "NonExistentMethod" };
yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.NonPublicValidationMethod) };
yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.NonStaticValidationMethod) };
yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.ValidationMethodDoesNotReturnValidationResult) };
yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.ValidationMethodWithNoArgs) };
yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.ValidationMethodWithByRefArg) };
yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.ValidationMethodTwoArgsButSecondIsNotValidationContext) };
yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.ValidationMethodThreeArgs) };
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Core fixes a bug where CustomValidationAttribute doesn't validate the context. See https://github.com/dotnet/corefx/issues/18360")]
[MemberData(nameof(BadlyFormed_TestData))]
public static void RequiresValidationContext_BadlyFormed_NetCore_ThrowsInvalidOperationException(Type validatorType, string method)
{
CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method);
Assert.Throws<InvalidOperationException>(() => attribute.RequiresValidationContext);
}
[Theory]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The full .NET Framework has a bug where CustomValidationAttribute doesn't validate the context. See https://github.com/dotnet/corefx/issues/18360")]
[MemberData(nameof(BadlyFormed_TestData))]
public static void RequiresValidationContext_BadlyFormed_NetFx_DoesNotThrow(Type validatorType, string method)
{
CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method);
Assert.False(attribute.RequiresValidationContext);
}
[Theory]
[MemberData(nameof(BadlyFormed_TestData))]
public static void Validate_BadlyFormed_ThrowsInvalidOperationException(Type validatorType, string method)
{
CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method);
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Does not matter", s_testValidationContext));
}
[Theory]
[MemberData(nameof(BadlyFormed_TestData))]
public static void FormatErrorMessage_BadlyFormed_ThrowsInvalidOperationException(Type validatorType, string method)
{
CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method);
Assert.Throws<InvalidOperationException>(() => attribute.FormatErrorMessage("name"));
}
[Fact]
public static void Validate_IConvertibleThrowsCustomException_IsNotCaught()
{
CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgInt));
Assert.Throws<ArithmeticException>(() => attribute.Validate(new IConvertibleImplementor() { IntThrow = new ArithmeticException() }, s_testValidationContext));
}
[Fact]
public static void Validate_MethodThrowsCustomException_IsNotCaught()
{
CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.ValidationMethodThrowsException));
AssertExtensions.Throws<ArgumentException>(null, () => attribute.Validate(new IConvertibleImplementor(), s_testValidationContext));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full .NET Frameworks had a restriction, that prevented to use custom ValidationResult. .NET Core allows to return class derived from ValidatioResult")]
public static void GetValidationResult_MethodReturnDerivedValidationResult_ReturnsExpected()
{
CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.ValidationMethodDerivedReturnTypeReturnsSomeError));
ValidationResult validationResult = attribute.GetValidationResult(new object(), s_testValidationContext);
Assert.Equal(DerivedValidationResult.SomeError, validationResult);
}
internal class NonPublicCustomValidator
{
public static ValidationResult ValidationMethodOneArg(object o) => ValidationResult.Success;
}
public class CustomValidator
{
internal static ValidationResult NonPublicValidationMethod(object o) => ValidationResult.Success;
public ValidationResult NonStaticValidationMethod(object o) => ValidationResult.Success;
public static string ValidationMethodDoesNotReturnValidationResult(object o) => null;
public static ValidationResult ValidationMethodWithNoArgs() => ValidationResult.Success;
public static ValidationResult ValidationMethodWithByRefArg(ref object o) => ValidationResult.Success;
public static ValidationResult ValidationMethodTwoArgsButSecondIsNotValidationContext(object o, object someOtherObject)
{
return ValidationResult.Success;
}
public static ValidationResult ValidationMethodThrowsException(object o)
{
throw new ArgumentException();
}
public static ValidationResult ValidationMethodThreeArgs(object o, ValidationContext context, object someOtherObject)
{
return ValidationResult.Success;
}
public static DerivedValidationResult ValidationMethodDerivedReturnTypeReturnsSomeError(object o) =>
DerivedValidationResult.SomeError;
public static ValidationResult CorrectValidationMethodOneArg(object o)
{
if (o is string) { return ValidationResult.Success; }
return new ValidationResult("Validation failed - not a string");
}
public static ValidationResult CorrectValidationMethodOneArgStronglyTyped(string s) => ValidationResult.Success;
public static ValidationResult CorrectValidationMethodTwoArgs(object o, ValidationContext context)
{
if (o is TestClass) { return ValidationResult.Success; }
return new ValidationResult("Validation failed - not a TestClass");
}
public static ValidationResult CorrectValidationMethodTwoArgsStronglyTyped(TestClass tc, ValidationContext context)
{
return ValidationResult.Success;
}
public static ValidationResult CorrectValidationMethodIntegerArg(int i) => ValidationResult.Success;
public static ValidationResult CorrectValidationMethodOneArgNullable(TestStruct? testStruct)
{
if (testStruct == null) { return ValidationResult.Success; }
var ts = (TestStruct)testStruct;
if ("Valid Value".Equals(ts.Value)) { return ValidationResult.Success; }
return new ValidationResult("Validation failed - neither null nor Value=\"Valid Value\"");
}
public static ValidationResult CorrectValidationMethodOneArgGenericStruct(GenericStruct<int> testStruct)
{
return ValidationResult.Success;
}
public static ValidationResult CorrectValidationMethodTwoArgsWithFirstNullable(TestStruct? testStruct, ValidationContext context)
{
if (testStruct == null) { return ValidationResult.Success; }
var ts = (TestStruct)testStruct;
if ("Valid Value".Equals(ts.Value)) { return ValidationResult.Success; }
return new ValidationResult("Validation failed - neither null nor Value=\"Valid Value\"");
}
public static ValidationResult CorrectValidationMethodOneArgDateTime(DateTime dateTime) => ValidationResult.Success;
public static ValidationResult CorrectValidationMethodOneArgInt(int i) => ValidationResult.Success;
}
public class TestClass
{
public TestClass(string message) { }
}
public class DerivedTestClass : TestClass
{
public DerivedTestClass(string message) : base(message) { }
}
public struct TestStruct
{
public string Value { get; set; }
}
public struct GenericStruct<T> { }
public class DerivedValidationResult : ValidationResult
{
public DerivedValidationResult(string errorMessage): base(errorMessage)
{
}
public static readonly DerivedValidationResult SomeError =
new DerivedValidationResult("Some Error") { AdditionalData = "Additional Data" };
public string AdditionalData { get; set; }
}
}
}
| |
//! \file ImageMAI.cs
//! \date Sun May 03 10:26:35 2015
//! \brief MAI image formats implementation.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Utility;
namespace GameRes.Formats.MAI
{
internal class CmpMetaData : ImageMetaData
{
public int Colors;
public bool IsCompressed;
public uint DataOffset;
public uint DataLength;
}
[Export(typeof(ImageFormat))]
public class CmpFormat : ImageFormat
{
public override string Tag { get { return "CMP/MAI"; } }
public override string Description { get { return "MAI image format"; } }
public override uint Signature { get { return 0; } }
public CmpFormat ()
{
Extensions = new string[] { "cmp" };
}
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("CmpFormat.Write not implemented");
}
public override ImageMetaData ReadMetaData (Stream stream)
{
if ('C' != stream.ReadByte() || 'M' != stream.ReadByte())
return null;
var header = new byte[0x1e];
if (header.Length != stream.Read (header, 0, header.Length))
return null;
if (1 != header[0x0c])
return null;
uint size = LittleEndian.ToUInt32 (header, 0);
if (size != stream.Length)
return null;
var info = new CmpMetaData();
info.Width = LittleEndian.ToUInt16 (header, 4);
info.Height = LittleEndian.ToUInt16 (header, 6);
info.Colors = LittleEndian.ToUInt16 (header, 8);
info.BPP = header[0x0a];
info.IsCompressed = 0 != header[0x0b];
info.DataOffset = LittleEndian.ToUInt32 (header, 0x0e);
info.DataLength = LittleEndian.ToUInt32 (header, 0x12);
if (info.DataLength > size)
return null;
return info;
}
public override ImageData Read (Stream stream, ImageMetaData info)
{
var meta = info as CmpMetaData;
if (null == meta)
throw new ArgumentException ("CmpFormat.Read should be supplied with CmpMetaData", "info");
var reader = new Reader (stream, meta);
reader.Unpack();
return ImageData.CreateFlipped (info, reader.Format, reader.Palette, reader.Data, reader.Stride);
}
internal class Reader
{
private Stream m_input;
private int m_width;
private int m_height;
private int m_pixel_size;
private bool m_compressed;
private int m_data_length;
private byte[] m_pixels;
public PixelFormat Format { get; private set; }
public BitmapPalette Palette { get; private set; }
public byte[] Data { get { return m_pixels; } }
public int Stride { get { return m_width * m_pixel_size; } }
public Reader (Stream stream, CmpMetaData info)
{
m_input = stream;
m_width = (int)info.Width;
m_height = (int)info.Height;
m_pixel_size = info.BPP/8;
m_compressed = info.IsCompressed;
m_data_length = (int)info.DataLength;
switch (m_pixel_size)
{
case 1: Format = PixelFormats.Indexed8; break;
case 3: Format = PixelFormats.Bgr24; break;
case 4: Format = PixelFormats.Bgr32; break;
default: throw new InvalidFormatException ("Invalid color depth");
}
m_input.Position = info.DataOffset;
if (info.Colors > 0)
Palette = RleDecoder.ReadPalette (m_input, info.Colors, 3);
int size = info.IsCompressed ? m_width*m_height*m_pixel_size : (int)info.DataLength;
m_pixels = new byte[size];
}
public void Unpack ()
{
if (m_compressed)
RleDecoder.Unpack (m_input, m_data_length, m_pixels, m_pixel_size);
else
m_input.Read (m_pixels, 0, m_pixels.Length);
}
}
}
internal class AmiMetaData : CmpMetaData
{
public uint MaskWidth;
public uint MaskHeight;
public uint MaskOffset;
public uint MaskLength;
public bool IsMaskCompressed;
}
[Export(typeof(ImageFormat))]
public class AmiFormat : ImageFormat
{
public override string Tag { get { return "AM/MAI"; } }
public override string Description { get { return "MAI image with alpha-channel"; } }
public override uint Signature { get { return 0; } }
public AmiFormat ()
{
Extensions = new string[] { "am", "ami" };
}
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("AmiFormat.Write not implemented");
}
public override ImageMetaData ReadMetaData (Stream stream)
{
if ('A' != stream.ReadByte() || 'M' != stream.ReadByte())
return null;
var header = new byte[0x30];
if (0x2e != stream.Read (header, 2, 0x2e))
return null;
uint size = LittleEndian.ToUInt32 (header, 2);
if (size != stream.Length)
return null;
int am_type = header[0x16];
if (am_type != 2 && am_type != 1 || header[0x18] != 1)
return null;
var info = new AmiMetaData();
info.Width = LittleEndian.ToUInt16 (header, 6);
info.Height = LittleEndian.ToUInt16 (header, 8);
info.MaskWidth = LittleEndian.ToUInt16 (header, 0x0a);
info.MaskHeight = LittleEndian.ToUInt16 (header, 0x0c);
info.Colors = LittleEndian.ToUInt16 (header, 0x12);
info.BPP = header[0x14];
info.IsCompressed = 0 != header[0x15];
info.DataOffset = LittleEndian.ToUInt32 (header, 0x1a);
info.DataLength = LittleEndian.ToUInt32 (header, 0x1e);
info.MaskOffset = LittleEndian.ToUInt32 (header, 0x22);
info.MaskLength = LittleEndian.ToUInt32 (header, 0x26);
info.IsMaskCompressed = 0 != header[0x2a];
if (checked(info.DataLength + info.MaskLength) > size)
return null;
return info;
}
public override ImageData Read (Stream stream, ImageMetaData info)
{
var meta = info as AmiMetaData;
if (null == meta)
throw new ArgumentException ("AmiFormat.Read should be supplied with AmiMetaData", "info");
var reader = new Reader (stream, meta);
reader.Unpack();
return ImageData.Create (info, reader.Format, reader.Palette, reader.Data);
}
internal class Reader
{
private Stream m_input;
private AmiMetaData m_info;
private int m_width;
private int m_height;
private int m_pixel_size;
private byte[] m_output;
private byte[] m_alpha;
private byte[] m_pixels;
public PixelFormat Format { get; private set; }
public BitmapPalette Palette { get; private set; }
public byte[] Data { get { return m_pixels; } }
public Reader (Stream stream, AmiMetaData info)
{
m_input = stream;
m_info = info;
m_width = (int)info.Width;
m_height = (int)info.Height;
m_pixel_size = info.BPP/8;
if (m_pixel_size != 3 && m_pixel_size != 4)
throw new InvalidFormatException ("Invalid color depth");
Format = PixelFormats.Bgra32;
int size = info.IsCompressed ? m_width*m_height*m_pixel_size : (int)info.DataLength;
m_output = new byte[size];
uint mask_size = info.IsMaskCompressed ? info.MaskWidth*info.MaskHeight : info.MaskLength;
m_alpha = new byte[mask_size];
m_pixels = new byte[m_width*m_height*4];
}
public void Unpack ()
{
m_input.Position = m_info.DataOffset;
if (m_info.Colors > 0)
Palette = RleDecoder.ReadPalette (m_input, m_info.Colors, 3);
if (m_info.IsCompressed)
RleDecoder.Unpack (m_input, (int)m_info.DataLength, m_output, m_pixel_size);
else
m_input.Read (m_output, 0, m_output.Length);
m_input.Position = m_info.MaskOffset;
if (m_info.IsMaskCompressed)
RleDecoder.Unpack (m_input, (int)m_info.MaskLength, m_alpha, 1);
else
m_input.Read (m_alpha, 0, m_alpha.Length);
int stride = m_width * m_pixel_size;
for (int y = 0; y < m_height; ++y)
{
int dst_line = y*m_width;
int src_line = (m_height-1-y)*m_width;
for (int x = 0; x < m_width; ++x)
{
m_pixels[(dst_line+x)*4] = m_output[(src_line+x)*m_pixel_size];
m_pixels[(dst_line+x)*4+1] = m_output[(src_line+x)*m_pixel_size+1];
m_pixels[(dst_line+x)*4+2] = m_output[(src_line+x)*m_pixel_size+2];
m_pixels[(dst_line+x)*4+3] = m_alpha[dst_line+x];
}
}
}
}
}
[Export(typeof(ImageFormat))]
public class MaskFormat : ImageFormat
{
public override string Tag { get { return "MSK/MAI"; } }
public override string Description { get { return "MAI indexed image format"; } }
public override uint Signature { get { return 0; } }
public MaskFormat ()
{
Extensions = new string[] { "msk" };
}
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("AmiFormat.Write not implemented");
}
public override ImageMetaData ReadMetaData (Stream stream)
{
using (var input = new ArcView.Reader (stream))
{
uint size = input.ReadUInt32();
if (size != stream.Length)
return null;
uint width = input.ReadUInt32();
uint height = input.ReadUInt32();
if ((width*height + 0x410) != size)
return null;
return new ImageMetaData {
Width = width,
Height = height,
BPP = 8
};
}
}
public override ImageData Read (Stream stream, ImageMetaData info)
{
stream.Position = 0x10;
var palette = RleDecoder.ReadPalette (stream, 0x100, 4);
byte[] pixels = new byte[info.Width*info.Height];
if (pixels.Length != stream.Read (pixels, 0, pixels.Length))
throw new InvalidFormatException();
return ImageData.Create (info, PixelFormats.Indexed8, palette, pixels);
}
}
internal class RleDecoder
{
public static BitmapPalette ReadPalette (Stream input, int colors, int color_size)
{
var palette_data = new byte[colors*color_size];
if (palette_data.Length != input.Read (palette_data, 0, palette_data.Length))
throw new InvalidFormatException();
var palette = new Color[colors];
for (int i = 0; i < palette.Length; ++i)
{
int c = i * color_size;
palette[i] = Color.FromRgb (palette_data[c+2], palette_data[c+1], palette_data[c]);
}
return new BitmapPalette (palette);
}
static public void Unpack (Stream input, int input_size, byte[] output, int pixel_size)
{
int read = 0;
int dst = 0;
while (read < input_size && dst < output.Length)
{
int code = input.ReadByte();
++read;
if (-1 == code)
throw new InvalidFormatException ("Unexpected end of file");
if (0x80 == code)
throw new InvalidFormatException ("Invalid run-length code");
if (code < 0x80)
{
int count = Math.Min (code * pixel_size, output.Length - dst);
if (count != input.Read (output, dst, count))
break;
read += count;
dst += count;
}
else
{
int count = code & 0x7f;
if (pixel_size != input.Read (output, dst, pixel_size))
break;
read += pixel_size;
int src = dst;
dst += pixel_size;
count = Math.Min ((count - 1) * pixel_size, output.Length - dst);
Binary.CopyOverlapped (output, src, dst, count);
dst += count;
}
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
namespace InstallerEditor
{
/// <summary>
/// Summary description for TemplatesEditor.
/// </summary>
public class TemplatesEditor : System.Windows.Forms.Form
{
private SourceGrid2.Grid gridList;
private System.Windows.Forms.Button btCancel;
private System.Windows.Forms.Button btOK;
private System.Windows.Forms.Label label1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public TemplatesEditor()
{
InitializeComponent();
}
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.gridList = new SourceGrid2.Grid();
this.btCancel = new System.Windows.Forms.Button();
this.btOK = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// gridList
//
this.gridList.AccessibleName = "gridList";
this.gridList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.gridList.AutoSizeMinHeight = 10;
this.gridList.AutoSizeMinWidth = 10;
this.gridList.AutoStretchColumnsToFitWidth = false;
this.gridList.AutoStretchRowsToFitHeight = false;
this.gridList.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.gridList.ContextMenuStyle = SourceGrid2.ContextMenuStyle.None;
this.gridList.CustomSort = false;
this.gridList.FocusStyle = SourceGrid2.FocusStyle.None;
this.gridList.GridToolTipActive = true;
this.gridList.Location = new System.Drawing.Point(8, 36);
this.gridList.Name = "gridList";
this.gridList.Size = new System.Drawing.Size(308, 232);
this.gridList.SpecialKeys = ((SourceGrid2.GridSpecialKeys)(((((((((((SourceGrid2.GridSpecialKeys.Ctrl_C | SourceGrid2.GridSpecialKeys.Ctrl_V)
| SourceGrid2.GridSpecialKeys.Ctrl_X)
| SourceGrid2.GridSpecialKeys.Delete)
| SourceGrid2.GridSpecialKeys.Arrows)
| SourceGrid2.GridSpecialKeys.Tab)
| SourceGrid2.GridSpecialKeys.PageDownUp)
| SourceGrid2.GridSpecialKeys.Enter)
| SourceGrid2.GridSpecialKeys.Escape)
| SourceGrid2.GridSpecialKeys.Control)
| SourceGrid2.GridSpecialKeys.Shift)));
this.gridList.TabIndex = 0;
//
// btCancel
//
this.btCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btCancel.Location = new System.Drawing.Point(240, 272);
this.btCancel.Name = "btCancel";
this.btCancel.Size = new System.Drawing.Size(75, 23);
this.btCancel.TabIndex = 1;
this.btCancel.Text = "Cancel";
//
// btOK
//
this.btOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btOK.Location = new System.Drawing.Point(152, 272);
this.btOK.Name = "btOK";
this.btOK.Size = new System.Drawing.Size(75, 23);
this.btOK.TabIndex = 2;
this.btOK.Text = "OK";
this.btOK.Click += new System.EventHandler(this.btOK_Click);
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 4);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(308, 28);
this.label1.TabIndex = 3;
this.label1.Text = "Customize the available list of template files:";
//
// TemplatesEditor
//
this.AcceptButton = this.btOK;
this.AccessibleName = "templatesEditor";
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btCancel;
this.ClientSize = new System.Drawing.Size(324, 299);
this.Controls.Add(this.label1);
this.Controls.Add(this.btOK);
this.Controls.Add(this.btCancel);
this.Controls.Add(this.gridList);
this.Name = "TemplatesEditor";
this.Text = "Customize Templates";
this.Load += new System.EventHandler(this.TemplatesEditor_Load);
this.ResumeLayout(false);
}
#endregion
private void TemplatesEditor_Load(object sender, System.EventArgs e)
{
SourceGrid2.DataModels.EditorTextBoxButton editorBtn = new SourceGrid2.DataModels.EditorTextBoxButton(typeof(string));
editorBtn.AttachEditorControl(gridList.ScrollablePanel);
editorBtn.GetEditorTextBoxTypedButton(gridList.ScrollablePanel).DialogOpen += new EventHandler(TemplatesEditor_DialogOpen);
gridList.ColumnsCount = 1;
for (int r = 0; r < AvailableTemplateFiles.Count; r++)
{
gridList.Rows.Insert(r);
gridList[r, 0] = new SourceGrid2.Cells.Real.Cell(AvailableTemplateFiles[r], editorBtn);
}
for (int r = AvailableTemplateFiles.Count; r < AvailableTemplateFiles.Count + 20; r++)
{
gridList.Rows.Insert(r);
gridList[r, 0] = new SourceGrid2.Cells.Real.Cell("", editorBtn);
}
gridList.AutoSizeMinHeight = gridList.Font.Height;
gridList.AutoStretchColumnsToFitWidth = true;
gridList.StretchColumnsToFitWidth();
}
private void TemplatesEditor_DialogOpen(object sender, EventArgs e)
{
SourceLibrary.Windows.Forms.TextBoxTypedButton txtBtn = (SourceLibrary.Windows.Forms.TextBoxTypedButton)sender;
OpenFileDialog dlg = new OpenFileDialog();
if (txtBtn.Value is String)
dlg.FileName = (string)txtBtn.Value;
dlg.Filter = "Xml Files|*.xml|All Files|*.*";
if (dlg.ShowDialog(this) == DialogResult.OK)
{
txtBtn.Value = dlg.FileName;
}
}
private List<String> m_AvailableTemplateFiles;
private void btOK_Click(object sender, System.EventArgs e)
{
try
{
for (int r = 0; r < gridList.RowsCount; r++)
{
string file = gridList[r, 0].DisplayText;
if (file != null &&
file.Length > 0)
{
file = file.Trim();
if (System.IO.File.Exists(file))
{
}
else
{
MessageBox.Show(this, "File not exist:" + file);
return;
}
}
}
AvailableTemplateFiles.Clear();
for (int r = 0; r < gridList.RowsCount; r++)
{
string file = gridList[r, 0].DisplayText;
if (file != null &&
file.Length > 0)
{
file = file.Trim();
if (System.IO.File.Exists(file))
{
if (AvailableTemplateFiles.Contains(file) == false)
AvailableTemplateFiles.Add(file);
}
else
{
throw new ApplicationException("Invalid file");
}
}
}
DialogResult = DialogResult.OK;
}
catch (Exception err)
{
SourceLibrary.Windows.Forms.ErrorDialog.Show(this, err, "Error");
}
}
public List<String> AvailableTemplateFiles
{
get { return m_AvailableTemplateFiles; }
set { m_AvailableTemplateFiles = value; }
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.