context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Threading;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using Rhino.ServiceBus.Impl;
using Rhino.ServiceBus.Internal;
using Rhino.ServiceBus.MessageModules;
using Rhino.ServiceBus.Msmq;
using Xunit;
namespace Rhino.ServiceBus.Tests
{
public class MessageModuleTests : MsmqTestBase
{
private IWindsorContainer container;
public MessageModuleTests()
{
Module2.Stopped = Module2.Started = false;
container = new WindsorContainer(new XmlInterpreter());
new RhinoServiceBusConfiguration()
.UseCastleWindsor(container)
.AddMessageModule<Module1>()
.AddMessageModule<Module2>()
.Configure();
container.Register(Component.For<BadHandler>());
}
[Fact]
public void Can_specify_modules_to_register_in_the_service_bus()
{
var serviceBus = (DefaultServiceBus)container.Resolve<IServiceBus>();
Assert.Equal(2, serviceBus.Modules.Length);
}
[Fact]
public void Can_specify_modules_in_order_to_be_registered_in_the_service_bus()
{
var serviceBus = (DefaultServiceBus)container.Resolve<IServiceBus>();
Assert.IsType<Module1>(serviceBus.Modules[0]);
Assert.IsType<Module2>(serviceBus.Modules[1]);
}
[Fact]
public void Disabling_queue_init_module()
{
Module2.Stopped = Module2.Started = false;
container = new WindsorContainer(new XmlInterpreter());
new RhinoServiceBusConfiguration()
.AddMessageModule<Module1>()
.AddMessageModule<Module2>()
.DisableQueueAutoCreation()
.UseCastleWindsor(container)
.Configure();
var serviceBus = (DefaultServiceBus)container.Resolve<IServiceBus>();
Assert.IsType<Module1>(serviceBus.Modules[0]);
Assert.IsType<Module2>(serviceBus.Modules[1]);
}
[Fact]
public void When_bus_is_started_modules_will_be_initalized()
{
using(var serviceBus = (DefaultServiceBus)container.Resolve<IServiceBus>())
{
serviceBus.Start();
Assert.True(Module2.Started);
}
}
[Fact]
public void When_bus_is_stopped_modules_will_be_stopped()
{
using (var serviceBus = (DefaultServiceBus)container.Resolve<IServiceBus>())
{
serviceBus.Start();
}
Assert.True(Module2.Stopped);
}
[Fact]
public void Can_register_to_get_message_failure_notification()
{
using (var serviceBus = (DefaultServiceBus)container.Resolve<IServiceBus>())
{
serviceBus.Start();
Module1.ErrorResetEvent = new ManualResetEvent(false);
serviceBus.Send(serviceBus.Endpoint,5);
Module1.ErrorResetEvent.WaitOne(TimeSpan.FromSeconds(30), false);
}
Assert.NotNull(Module1.Exception);
}
[Fact]
public void Can_register_to_get_message_completion_notification_even_on_error()
{
using (var serviceBus = (DefaultServiceBus) container.Resolve<IServiceBus>())
{
serviceBus.Start();
Module1.CompletionResetEvent = new ManualResetEvent(false);
Module1.ErrorResetEvent = new ManualResetEvent(false);
Module1.Completion = false;
serviceBus.Send(serviceBus.Endpoint, 3);
Module1.ErrorResetEvent.WaitOne(TimeSpan.FromSeconds(30), false);
Module1.CompletionResetEvent.WaitOne(TimeSpan.FromSeconds(30), false);
}
Assert.True(Module1.Completion);
}
[Fact]
public void Can_register_to_get_message_completion_notification()
{
using (var serviceBus = (DefaultServiceBus) container.Resolve<IServiceBus>())
{
serviceBus.Start();
Module1.CompletionResetEvent = new ManualResetEvent(false);
Module1.Completion = false;
serviceBus.Send(serviceBus.Endpoint, "hello");
Module1.CompletionResetEvent.WaitOne(TimeSpan.FromSeconds(30), false);
}
Assert.True(Module1.Completion);
}
[Fact]
public void Can_register_to_get_transaction_commit_notification()
{
using (var serviceBus = (DefaultServiceBus)container.Resolve<IServiceBus>())
{
serviceBus.Start();
Module1.TransactionCommitResetEvent = new ManualResetEvent(false);
Module1.TransactionCommit = false;
serviceBus.Send(serviceBus.Endpoint, "transaction");
Module1.TransactionCommitResetEvent.WaitOne(TimeSpan.FromSeconds(30), false);
}
Assert.True(Module1.TransactionCommit);
}
[Fact]
public void Can_register_to_get_transaction_rollback_notification()
{
using (var serviceBus = (DefaultServiceBus)container.Resolve<IServiceBus>())
{
serviceBus.Start();
Module1.TransactionRollbackResetEvent = new ManualResetEvent(false);
Module1.TransactionRollback = false;
serviceBus.Send(serviceBus.Endpoint, 42);
Module1.TransactionRollbackResetEvent.WaitOne(TimeSpan.FromSeconds(30), false);
}
Assert.True(Module1.TransactionRollback);
}
public class Module1 : IMessageModule
{
public static Exception Exception;
public static ManualResetEvent ErrorResetEvent;
public static ManualResetEvent CompletionResetEvent;
public static ManualResetEvent TransactionCommitResetEvent;
public static ManualResetEvent TransactionRollbackResetEvent;
public static bool Completion = true;
public static bool TransactionCommit;
public static bool TransactionRollback;
public void Init(ITransport transport, IServiceBus bus)
{
transport.BeforeMessageTransactionCommit += Transport_BeforeMessageTransactionCommit;
transport.BeforeMessageTransactionRollback += TransportBeforeMessageTransactionRollback;
transport.MessageProcessingFailure+=Transport_OnMessageProcessingFailure;
transport.MessageProcessingCompleted+=Transport_OnMessageProcessingCompleted;
}
private void Transport_BeforeMessageTransactionCommit(CurrentMessageInformation obj)
{
TransactionCommit = true;
TransactionCommitResetEvent.Set();
}
private void TransportBeforeMessageTransactionRollback(CurrentMessageInformation obj)
{
TransactionRollback = true;
TransactionRollbackResetEvent.Set();
}
private static void Transport_OnMessageProcessingCompleted(CurrentMessageInformation t, Exception e)
{
Completion = true;
CompletionResetEvent.Set();
}
private static void Transport_OnMessageProcessingFailure(CurrentMessageInformation t1, Exception t2)
{
Exception = t2;
ErrorResetEvent.Set();
}
public void Stop(ITransport transport, IServiceBus bus)
{
}
}
public class Module2 : IMessageModule
{
public static bool Started, Stopped;
public void Init(ITransport transport, IServiceBus bus)
{
Started = true;
}
public void Stop(ITransport transport, IServiceBus bus)
{
Stopped = true;
}
}
public class BadHandler : ConsumerOf<int>
{
public void Consume(int message)
{
throw new System.NotImplementedException();
}
}
public class SimpleHandler : ConsumerOf<string>
{
public void Consume(string message)
{
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId
{
public partial class SymbolKeyTest : SymbolKeyTestBase
{
#region "Metadata vs. Source"
[Fact]
public void M2SNamedTypeSymbols01()
{
var src1 = @"using System;
public delegate void D(int p1, string p2);
namespace N1.N2
{
public interface I { }
namespace N3
{
public class C
{
public struct S
{
public enum E { Zero, One, Two }
public void M(int n) { Console.WriteLine(n); }
}
}
}
}
";
var src2 = @"using System;
using N1.N2.N3;
public class App : C
{
private event D myEvent;
internal N1.N2.I Prop { get; set; }
protected C.S.E this[int x] { set { } }
public void M(C.S s) { s.M(123); }
}
";
var comp1 = CreateCompilationWithMscorlib(src1);
// Compilation to Compilation
var comp2 = CreateCompilationWithMscorlib(src2, new MetadataReference[] { new CSharpCompilationReference(comp1) });
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType).OrderBy(s => s.Name).ToList();
Assert.Equal(5, originalSymbols.Count);
// ---------------------------
// Metadata symbols
var typesym = comp2.SourceModule.GlobalNamespace.GetTypeMembers("App").FirstOrDefault() as NamedTypeSymbol;
// 'D'
var member01 = (typesym.GetMembers("myEvent").Single() as EventSymbol).Type;
// 'I'
var member02 = (typesym.GetMembers("Prop").Single() as PropertySymbol).Type;
// 'C'
var member03 = typesym.BaseType;
// 'S'
var member04 = (typesym.GetMembers("M").Single() as MethodSymbol).Parameters[0].Type;
// 'E'
var member05 = (typesym.GetMembers(WellKnownMemberNames.Indexer).Single() as PropertySymbol).Type;
ResolveAndVerifySymbol(member03, comp2, originalSymbols[0], comp1, SymbolKeyComparison.CaseSensitive);
ResolveAndVerifySymbol(member01, comp2, originalSymbols[1], comp1, SymbolKeyComparison.CaseSensitive);
ResolveAndVerifySymbol(member05, comp2, originalSymbols[2], comp1, SymbolKeyComparison.CaseSensitive);
ResolveAndVerifySymbol(member02, comp2, originalSymbols[3], comp1, SymbolKeyComparison.CaseSensitive);
ResolveAndVerifySymbol(member04, comp2, originalSymbols[4], comp1, SymbolKeyComparison.CaseSensitive);
}
[WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")]
[Fact]
public void M2SNonTypeMemberSymbols01()
{
var src1 = @"using System;
namespace N1
{
public interface IFoo
{
void M(int p1, int p2);
void M(params short[] ary);
void M(string p1);
void M(ref string p1);
}
public struct S
{
public event Action<S> PublicEvent { add { } remove { } }
public IFoo PublicField;
public string PublicProp { get; set; }
public short this[sbyte p] { get { return p; } }
}
}
";
var src2 = @"using System;
using AN = N1;
public class App
{
static void Main()
{
var obj = new AN.S();
/*<bind0>*/obj.PublicEvent/*</bind0>*/ += EH;
var ifoo = /*<bind1>*/obj.PublicField/*</bind1>*/;
/*<bind3>*/ifoo.M(/*<bind2>*/obj.PublicProp/*</bind2>*/)/*</bind3>*/;
/*<bind5>*/ifoo.M(obj[12], /*<bind4>*/obj[123]/*</bind4>*/)/*</bind5>*/;
}
static void EH(AN.S s) { }
}
";
var comp1 = CreateCompilationWithMscorlib(src1);
// Compilation to Assembly
var comp2 = CreateCompilationWithMscorlib(src2, new MetadataReference[] { comp1.EmitToImageReference() });
// ---------------------------
// Source symbols
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter).ToList();
originalSymbols = originalSymbols.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).Select(s => s).ToList();
Assert.Equal(8, originalSymbols.Count);
// ---------------------------
// Metadata symbols
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp2);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(6, list.Count);
// event
ResolveAndVerifySymbol(list[0], originalSymbols[4], model, comp1, SymbolKeyComparison.CaseSensitive);
// field
ResolveAndVerifySymbol(list[1], originalSymbols[5], model, comp1, SymbolKeyComparison.CaseSensitive);
// prop
ResolveAndVerifySymbol(list[2], originalSymbols[6], model, comp1, SymbolKeyComparison.CaseSensitive);
// index:
ResolveAndVerifySymbol(list[4], originalSymbols[7], model, comp1, SymbolKeyComparison.CaseSensitive);
// M(string p1)
ResolveAndVerifySymbol(list[3], originalSymbols[2], model, comp1, SymbolKeyComparison.CaseSensitive);
// M(params short[] ary)
ResolveAndVerifySymbol(list[5], originalSymbols[1], model, comp1, SymbolKeyComparison.CaseSensitive);
}
#endregion
#region "Metadata vs. Metadata"
[Fact]
public void M2MMultiTargetingMsCorLib01()
{
var src1 = @"using System;
using System.IO;
public class A
{
public FileInfo GetFileInfo(string path)
{
if (File.Exists(path))
{
return new FileInfo(path);
}
return null;
}
public void PrintInfo(Array ary, ref DateTime time)
{
if (ary != null)
Console.WriteLine(ary);
else
Console.WriteLine(""null"");
time = DateTime.Now;
}
}
";
var src2 = @"using System;
class Test
{
static void Main()
{
var a = new A();
var fi = a.GetFileInfo(null);
Console.WriteLine(fi);
var dt = DateTime.Now;
var ary = Array.CreateInstance(typeof(string), 2);
a.PrintInfo(ary, ref dt);
}
}
";
var comp20 = CreateCompilation(src1, new[] { TestReferences.NetFx.v4_0_21006.mscorlib });
// "Compilation 2 Assembly"
var comp40 = CreateCompilationWithMscorlib(src2, new MetadataReference[] { comp20.EmitToImageReference() });
var typeA = comp20.SourceModule.GlobalNamespace.GetTypeMembers("A").Single();
var mem20_1 = typeA.GetMembers("GetFileInfo").Single() as MethodSymbol;
var mem20_2 = typeA.GetMembers("PrintInfo").Single() as MethodSymbol;
// FileInfo
var mtsym20_1 = mem20_1.ReturnType;
Assert.Equal(2, mem20_2.Parameters.Length);
// Array
var mtsym20_2 = mem20_2.Parameters[0].Type;
// ref DateTime
var mtsym20_3 = mem20_2.Parameters[1].Type;
// ====================
var typeTest = comp40.SourceModule.GlobalNamespace.GetTypeMembers("Test").FirstOrDefault();
var mem40 = typeTest.GetMembers("Main").Single() as MethodSymbol;
var list = GetBlockSyntaxList(mem40);
var model = comp40.GetSemanticModel(comp40.SyntaxTrees[0]);
foreach (var body in list)
{
var df = model.AnalyzeDataFlow(body.Statements.First(), body.Statements.Last());
if (df.VariablesDeclared != null)
{
foreach (var local in df.VariablesDeclared)
{
var localType = ((LocalSymbol)local).Type;
if (local.Name == "fi")
{
ResolveAndVerifySymbol(localType, comp40, mtsym20_1, comp20, SymbolKeyComparison.CaseSensitive);
}
else if (local.Name == "ary")
{
ResolveAndVerifySymbol(localType, comp40, mtsym20_2, comp20, SymbolKeyComparison.CaseSensitive);
}
else if (local.Name == "dt")
{
ResolveAndVerifySymbol(localType, comp40, mtsym20_3, comp20, SymbolKeyComparison.CaseSensitive);
}
}
}
}
}
[Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")]
public void M2MMultiTargetingMsCorLib02()
{
var src1 = @"using System;
namespace Mscorlib20
{
public interface IFoo
{
// interface
IDisposable Prop { get; set; }
// class
Exception this[ArgumentException t] { get; }
}
public class CFoo : IFoo
{
// enum
public DayOfWeek PublicField;
// delegate
public event System.Threading.ParameterizedThreadStart PublicEventField;
public IDisposable Prop { get; set; }
public Exception this[ArgumentException t] { get { return t; } }
}
}
";
var src2 = @"using System;
using N20 = Mscorlib20;
class Test
{
public IDisposable M()
{
var obj = new N20::CFoo();
N20.IFoo ifoo = obj;
/*<bind0>*/obj.PublicEventField/*</bind0>*/ += /*<bind1>*/MyEveHandler/*</bind1>*/;
var local = /*<bind2>*/ifoo[null]/*</bind2>*/;
if (/*<bind3>*/obj.PublicField /*</bind3>*/== DayOfWeek.Friday)
{
return /*<bind4>*/(obj as N20.IFoo).Prop/*</bind4>*/;
}
return null;
}
public void MyEveHandler(object o) { }
}
";
var comp20 = CreateCompilation(src1, new[] { TestReferences.NetFx.v4_0_21006.mscorlib });
// "Compilation ref Compilation"
var comp40 = CreateCompilationWithMscorlib(src2, new[] { new CSharpCompilationReference(comp20) });
var originals = GetSourceSymbols(comp20, SymbolCategory.NonTypeMember | SymbolCategory.Parameter);
var originalSymbols = originals.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).ToList();
// IFoo.Prop, CFoo.Prop, Event, Field, IFoo.This, CFoo.This
Assert.Equal(6, originalSymbols.Count);
// ====================
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp40);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(5, list.Count);
// PublicEventField
ResolveAndVerifySymbol(list[0], originalSymbols[2], model, comp20);
// delegate ParameterizedThreadStart
ResolveAndVerifyTypeSymbol(list[0], (originalSymbols[2] as EventSymbol).Type, model, comp20);
// MethodGroup
ResolveAndVerifyTypeSymbol(list[1], (originalSymbols[2] as EventSymbol).Type, model, comp20);
// Indexer
ResolveAndVerifySymbol(list[2], originalSymbols[4], model, comp20);
// class Exception
ResolveAndVerifyTypeSymbol(list[2], (originalSymbols[4] as PropertySymbol).Type, model, comp20);
// PublicField
ResolveAndVerifySymbol(list[3], originalSymbols[3], model, comp20);
// enum DayOfWeek
ResolveAndVerifyTypeSymbol(list[3], (originalSymbols[3] as FieldSymbol).Type, model, comp20);
// Prop
ResolveAndVerifySymbol(list[4], originalSymbols[0], model, comp20);
// interface IDisposable
ResolveAndVerifyTypeSymbol(list[4], (originalSymbols[0] as PropertySymbol).Type, model, comp20);
}
[Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")]
public void M2MMultiTargetingMsCorLib03()
{
var src1 = @"using System;
namespace Mscorlib20
{
public interface IFoo
{
// interface
IDisposable Prop { get; set; }
// class
Exception this[ArgumentException t] { get; }
}
public class CFoo : IFoo
{
// explicit
IDisposable IFoo.Prop { get; set; }
Exception IFoo.this[ArgumentException t] { get { return t; } }
}
}
";
var src2 = @"using System;
using N20 = Mscorlib20;
class Test
{
public IDisposable M()
{
N20.IFoo ifoo = new N20::CFoo();
var local = /*<bind0>*/ifoo[new ArgumentException()]/*</bind0>*/;
return /*<bind1>*/ifoo.Prop/*</bind1>*/;
}
}
";
var comp20 = CreateCompilation(src1, new[] { TestReferences.NetFx.v4_0_21006.mscorlib });
// "Compilation ref Compilation"
var comp40 = CreateCompilationWithMscorlib(src2, new[] { new CSharpCompilationReference(comp20) });
var originals = GetSourceSymbols(comp20, SymbolCategory.NonTypeMember | SymbolCategory.Parameter);
var originalSymbols = originals.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).ToList();
// CFoo.Prop, CFoo.This, IFoo.Prop, IFoo.This
Assert.Equal(4, originalSymbols.Count);
// ====================
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp40);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(2, list.Count);
// Indexer
ResolveAndVerifySymbol(list[0], originalSymbols[3], model, comp20);
// class Exception
ResolveAndVerifyTypeSymbol(list[0], (originalSymbols[3] as PropertySymbol).Type, model, comp20);
// Prop
ResolveAndVerifySymbol(list[1], originalSymbols[2], model, comp20);
// interface IDisposable
ResolveAndVerifyTypeSymbol(list[1], (originalSymbols[2] as PropertySymbol).Type, model, comp20);
}
#endregion
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
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;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// ItemVariantItem
/// </summary>
[DataContract]
public partial class ItemVariantItem : IEquatable<ItemVariantItem>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ItemVariantItem" /> class.
/// </summary>
/// <param name="description">Description.</param>
/// <param name="merchantItemMultimediaOid">Multimedia object identifier.</param>
/// <param name="variantMerchantItemId">Variant item id.</param>
/// <param name="variantMerchantItemOid">Variant item object identifier.</param>
/// <param name="variationOptions">Variation options.</param>
/// <param name="variations">Variations.</param>
public ItemVariantItem(string description = default(string), int? merchantItemMultimediaOid = default(int?), string variantMerchantItemId = default(string), int? variantMerchantItemOid = default(int?), List<string> variationOptions = default(List<string>), List<string> variations = default(List<string>))
{
this.Description = description;
this.MerchantItemMultimediaOid = merchantItemMultimediaOid;
this.VariantMerchantItemId = variantMerchantItemId;
this.VariantMerchantItemOid = variantMerchantItemOid;
this.VariationOptions = variationOptions;
this.Variations = variations;
}
/// <summary>
/// Description
/// </summary>
/// <value>Description</value>
[DataMember(Name="description", EmitDefaultValue=false)]
public string Description { get; set; }
/// <summary>
/// Multimedia object identifier
/// </summary>
/// <value>Multimedia object identifier</value>
[DataMember(Name="merchant_item_multimedia_oid", EmitDefaultValue=false)]
public int? MerchantItemMultimediaOid { get; set; }
/// <summary>
/// Variant item id
/// </summary>
/// <value>Variant item id</value>
[DataMember(Name="variant_merchant_item_id", EmitDefaultValue=false)]
public string VariantMerchantItemId { get; set; }
/// <summary>
/// Variant item object identifier
/// </summary>
/// <value>Variant item object identifier</value>
[DataMember(Name="variant_merchant_item_oid", EmitDefaultValue=false)]
public int? VariantMerchantItemOid { get; set; }
/// <summary>
/// Variation options
/// </summary>
/// <value>Variation options</value>
[DataMember(Name="variation_options", EmitDefaultValue=false)]
public List<string> VariationOptions { get; set; }
/// <summary>
/// Variations
/// </summary>
/// <value>Variations</value>
[DataMember(Name="variations", EmitDefaultValue=false)]
public List<string> Variations { 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 ItemVariantItem {\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" MerchantItemMultimediaOid: ").Append(MerchantItemMultimediaOid).Append("\n");
sb.Append(" VariantMerchantItemId: ").Append(VariantMerchantItemId).Append("\n");
sb.Append(" VariantMerchantItemOid: ").Append(VariantMerchantItemOid).Append("\n");
sb.Append(" VariationOptions: ").Append(VariationOptions).Append("\n");
sb.Append(" Variations: ").Append(Variations).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ItemVariantItem);
}
/// <summary>
/// Returns true if ItemVariantItem instances are equal
/// </summary>
/// <param name="input">Instance of ItemVariantItem to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ItemVariantItem input)
{
if (input == null)
return false;
return
(
this.Description == input.Description ||
(this.Description != null &&
this.Description.Equals(input.Description))
) &&
(
this.MerchantItemMultimediaOid == input.MerchantItemMultimediaOid ||
(this.MerchantItemMultimediaOid != null &&
this.MerchantItemMultimediaOid.Equals(input.MerchantItemMultimediaOid))
) &&
(
this.VariantMerchantItemId == input.VariantMerchantItemId ||
(this.VariantMerchantItemId != null &&
this.VariantMerchantItemId.Equals(input.VariantMerchantItemId))
) &&
(
this.VariantMerchantItemOid == input.VariantMerchantItemOid ||
(this.VariantMerchantItemOid != null &&
this.VariantMerchantItemOid.Equals(input.VariantMerchantItemOid))
) &&
(
this.VariationOptions == input.VariationOptions ||
this.VariationOptions != null &&
this.VariationOptions.SequenceEqual(input.VariationOptions)
) &&
(
this.Variations == input.Variations ||
this.Variations != null &&
this.Variations.SequenceEqual(input.Variations)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Description != null)
hashCode = hashCode * 59 + this.Description.GetHashCode();
if (this.MerchantItemMultimediaOid != null)
hashCode = hashCode * 59 + this.MerchantItemMultimediaOid.GetHashCode();
if (this.VariantMerchantItemId != null)
hashCode = hashCode * 59 + this.VariantMerchantItemId.GetHashCode();
if (this.VariantMerchantItemOid != null)
hashCode = hashCode * 59 + this.VariantMerchantItemOid.GetHashCode();
if (this.VariationOptions != null)
hashCode = hashCode * 59 + this.VariationOptions.GetHashCode();
if (this.Variations != null)
hashCode = hashCode * 59 + this.Variations.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// Description (string) maxLength
if(this.Description != null && this.Description.Length > 512)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Description, length must be less than 512.", new [] { "Description" });
}
yield break;
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.IO;
using System.Linq;
using System.Windows.Input;
using EnvDTE;
using EnvDTE80;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools.Project.Automation;
using TestUtilities;
using TestUtilities.UI;
using Mouse = TestUtilities.UI.Mouse;
using Path = System.IO.Path;
namespace PythonToolsUITests {
public class ProjectHomeTests {
public void LoadRelativeProjects(VisualStudioApp app) {
string fullPath = TestData.GetPath(@"TestData\ProjectHomeProjects.sln");
app.OpenProject(@"TestData\ProjectHomeProjects.sln", expectedProjects: 9);
foreach (var project in app.Dte.Solution.Projects.OfType<Project>()) {
var name = Path.GetFileName(project.FileName);
if (name.StartsWith("ProjectA")) {
// Should have ProgramA.py, Subfolder\ProgramB.py and Subfolder\Subsubfolder\ProgramC.py
var programA = project.ProjectItems.Item("ProgramA.py");
Assert.IsNotNull(programA);
var subfolder = project.ProjectItems.Item("Subfolder");
var programB = subfolder.ProjectItems.Item("ProgramB.py");
Assert.IsNotNull(programB);
var subsubfolder = subfolder.ProjectItems.Item("Subsubfolder");
var programC = subsubfolder.ProjectItems.Item("ProgramC.py");
Assert.IsNotNull(programC);
} else if (name.StartsWith("ProjectB")) {
// Should have ProgramB.py and Subsubfolder\ProgramC.py
var programB = project.ProjectItems.Item("ProgramB.py");
Assert.IsNotNull(programB);
var subsubfolder = project.ProjectItems.Item("Subsubfolder");
var programC = subsubfolder.ProjectItems.Item("ProgramC.py");
Assert.IsNotNull(programC);
} else if (name.StartsWith("ProjectSln")) {
// Should have ProjectHomeProjects\ProgramA.py,
// ProjectHomeProjects\Subfolder\ProgramB.py and
// ProjectHomeProjects\Subfolder\Subsubfolder\ProgramC.py
var projectHome = project.ProjectItems.Item("ProjectHomeProjects");
var programA = projectHome.ProjectItems.Item("ProgramA.py");
Assert.IsNotNull(programA);
var subfolder = projectHome.ProjectItems.Item("Subfolder");
var programB = subfolder.ProjectItems.Item("ProgramB.py");
Assert.IsNotNull(programB);
var subsubfolder = subfolder.ProjectItems.Item("Subsubfolder");
var programC = subsubfolder.ProjectItems.Item("ProgramC.py");
Assert.IsNotNull(programC);
} else {
Assert.Fail("Wrong project file name", name);
}
}
}
public void AddDeleteItem(VisualStudioApp app) {
var sln = app.CopyProjectForTest(@"TestData\ProjectHomeSingleProject.sln");
var slnDir = PathUtils.GetParent(sln);
var project = app.OpenProject(sln);
Assert.AreEqual("ProjectSingle.pyproj", Path.GetFileName(project.FileName));
project.ProjectItems.AddFromTemplate(((Solution2)app.Dte.Solution).GetProjectItemTemplate("PyClass.zip", "pyproj"), "TemplateItem.py");
var newItem = project.ProjectItems.Item("TemplateItem.py");
Assert.IsNotNull(newItem);
Assert.AreEqual(false, project.Saved);
project.Save();
Assert.AreEqual(true, project.Saved);
Assert.IsTrue(File.Exists(Path.Combine(slnDir, "ProjectHomeProjects", "TemplateItem.py")));
newItem.Delete();
Assert.AreEqual(false, project.Saved);
project.Save();
Assert.AreEqual(true, project.Saved);
Assert.IsFalse(File.Exists(Path.Combine(slnDir, "ProjectHomeProjects", "TemplateItem.py")));
}
public void AddDeleteItem2(VisualStudioApp app) {
var sln = app.CopyProjectForTest(@"TestData\ProjectHomeSingleProject.sln");
var slnDir = PathUtils.GetParent(sln);
var project = app.OpenProject(sln);
var folder = project.ProjectItems.Item("Subfolder");
Assert.AreEqual("ProjectSingle.pyproj", Path.GetFileName(project.FileName));
folder.ProjectItems.AddFromTemplate(((Solution2)app.Dte.Solution).GetProjectItemTemplate("PyClass.zip", "pyproj"), "TemplateItem.py");
var newItem = folder.ProjectItems.Item("TemplateItem.py");
Assert.IsNotNull(newItem);
Assert.AreEqual(false, project.Saved);
project.Save();
Assert.AreEqual(true, project.Saved);
Assert.IsTrue(File.Exists(Path.Combine(slnDir, "ProjectHomeProjects", "Subfolder", "TemplateItem.py")));
newItem.Delete();
Assert.AreEqual(false, project.Saved);
project.Save();
Assert.AreEqual(true, project.Saved);
Assert.IsFalse(File.Exists(Path.Combine(slnDir, "ProjectHomeProjects", "Subfolder", "TemplateItem.py")));
}
public void AddDeleteFolder(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\ProjectHomeSingleProject.sln");
Assert.AreEqual("ProjectSingle.pyproj", Path.GetFileName(project.FileName));
project.ProjectItems.AddFolder("NewFolder");
var newFolder = project.ProjectItems.Item("NewFolder");
Assert.IsNotNull(newFolder);
Assert.AreEqual(TestData.GetPath(@"TestData\ProjectHomeProjects\NewFolder\"), newFolder.Properties.Item("FullPath").Value);
newFolder.Delete();
}
public void AddDeleteSubfolder(VisualStudioApp app) {
var project = app.OpenProject(@"TestData\ProjectHomeSingleProject.sln");
var folder = project.ProjectItems.Item("Subfolder");
Assert.AreEqual("ProjectSingle.pyproj", Path.GetFileName(project.FileName));
folder.ProjectItems.AddFolder("NewFolder");
var newFolder = folder.ProjectItems.Item("NewFolder");
Assert.IsNotNull(newFolder);
Assert.AreEqual(TestData.GetPath(@"TestData\ProjectHomeProjects\Subfolder\NewFolder\"), newFolder.Properties.Item("FullPath").Value);
newFolder.Delete();
}
public void SaveProjectAndCheckProjectHome(VisualStudioApp app) {
var sln = app.CopyProjectForTest(@"TestData\HelloWorld.sln");
var slnDir = PathUtils.GetParent(sln);
EnvDTE.Project project;
try {
project = app.OpenProject(sln);
project.SaveAs(Path.Combine(slnDir, "ProjectHomeProjects", "TempFile.pyproj"));
Assert.AreEqual(
PathUtils.TrimEndSeparator(Path.Combine(slnDir, "HelloWorld")),
PathUtils.TrimEndSeparator(((OAProject)project).ProjectNode.ProjectHome)
);
app.Dte.Solution.SaveAs("HelloWorldRelocated.sln");
} finally {
app.Dte.Solution.Close();
GC.Collect();
GC.WaitForPendingFinalizers();
}
project = app.OpenProject(Path.Combine(slnDir, "HelloWorldRelocated.sln"));
Assert.AreEqual("TempFile.pyproj", project.FileName);
Assert.AreEqual(
PathUtils.TrimEndSeparator(Path.Combine(slnDir, "HelloWorld")),
PathUtils.TrimEndSeparator(((OAProject)project).ProjectNode.ProjectHome)
);
}
public void DragDropRelocatedTest(VisualStudioApp app) {
var sln = app.CopyProjectForTest(@"TestData\DragDropRelocatedTest.sln");
var slnDir = PathUtils.GetParent(sln);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "DragDropRelocatedTest"), Path.Combine(slnDir, "DragDropRelocatedTest"));
app.OpenProject(sln);
app.OpenSolutionExplorer();
var window = app.SolutionExplorerTreeView;
var folder = window.FindItem("Solution 'DragDropRelocatedTest' (1 of 1 project)", "DragDropTest", "TestFolder", "SubItem.py");
var point = folder.GetClickablePoint();
Mouse.MoveTo(point);
Mouse.Down(MouseButton.Left);
var projectItem = window.FindItem("Solution 'DragDropRelocatedTest' (1 of 1 project)", "DragDropTest");
point = projectItem.GetClickablePoint();
Mouse.MoveTo(point);
Mouse.Up(MouseButton.Left);
using (var dlg = AutomationDialog.WaitForDialog(app)) {
dlg.OK();
}
Assert.IsNotNull(window.WaitForItem("Solution 'DragDropRelocatedTest' (1 of 1 project)", "DragDropTest", "SubItem.py"));
app.Dte.Solution.Close(true);
// Ensure file was moved and the path was updated correctly.
var project = app.OpenProject(sln);
foreach (var item in project.ProjectItems.OfType<OAFileItem>()) {
Assert.IsTrue(File.Exists((string)item.Properties.Item("FullPath").Value), (string)item.Properties.Item("FullPath").Value);
}
}
public void CutPasteRelocatedTest(VisualStudioApp app) {
var sln = app.CopyProjectForTest(@"TestData\CutPasteRelocatedTest.sln");
var slnDir = PathUtils.GetParent(sln);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "CutPasteRelocatedTest"), Path.Combine(slnDir, "CutPasteRelocatedTest"));
app.OpenProject(sln);
app.OpenSolutionExplorer();
var window = app.SolutionExplorerTreeView;
var folder = window.FindItem("Solution 'CutPasteRelocatedTest' (1 of 1 project)", "CutPasteTest", "TestFolder", "SubItem.py");
AutomationWrapper.Select(folder);
app.ExecuteCommand("Edit.Cut");
var projectItem = window.FindItem("Solution 'CutPasteRelocatedTest' (1 of 1 project)", "CutPasteTest");
AutomationWrapper.Select(projectItem);
app.ExecuteCommand("Edit.Paste");
Assert.IsNotNull(window.WaitForItem("Solution 'CutPasteRelocatedTest' (1 of 1 project)", "CutPasteTest", "SubItem.py"));
app.Dte.Solution.Close(true);
// Ensure file was moved and the path was updated correctly.
var project = app.OpenProject(sln);
foreach (var item in project.ProjectItems.OfType<OAFileItem>()) {
Assert.IsTrue(File.Exists((string)item.Properties.Item("FullPath").Value), (string)item.Properties.Item("FullPath").Value);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using GetSocialSdk.MiniJSON;
using UnityEngine;
namespace GetSocialSdk.Core
{
internal class GetSocialJsonBridge: IGetSocialBridge
{
private IMethodCaller MethodCaller { get; }
public GetSocialJsonBridge(IMethodCaller methodCaller)
{
MethodCaller = methodCaller;
}
public void AddOnInitializedListener(Action action)
{
MethodCaller.RegisterListener("GetSocial.addOnInitializedListener", any => action());
}
public void Init(string appId)
{
CallSync<string>("GetSocial.init", appId);
}
public void Init(Identity identity, Action onSuccess, Action<GetSocialError> onError)
{
CallAsyncVoid("GetSocial.initWithIdentity", GSJson.Serialize(identity), onSuccess, onError);
}
public void Handle(GetSocialAction action)
{
CallSync<string>("GetSocial.handleAction", GSJson.Serialize(action));
}
public bool IsTestDevice()
{
return CallSync<bool>("GetSocial.isTestDevice");
}
public string GetDeviceId()
{
return CallSync<string>("GetSocial.getDeviceId");
}
public string AddOnCurrentUserChangedListener(OnCurrentUserChangedListener listener)
{
Action<CurrentUser> wrapper = some => listener(some);
return MethodCaller.RegisterListener("GetSocial.addOnCurrentUserChangedListener", Json(wrapper));
}
public void RemoveOnCurrentUserChangedListener(string listenerId)
{
CallSync<string>("GetSocial.removeOnCurrentUserChangedListener", listenerId);
}
public CurrentUser GetCurrentUser()
{
return CallSync<CurrentUser>("GetSocial.getCurrentUser");
}
public void SwitchUser(Identity identity, Action success, Action<GetSocialError> failure)
{
CallAsyncVoid("GetSocial.switchUser", GSJson.Serialize(identity), success, failure);
}
public void AddIdentity(Identity identity, Action success, Action<ConflictUser> conflict, Action<GetSocialError> failure)
{
MethodCaller.CallAsync("CurrentUser.addIdentity", GSJson.Serialize(identity), (string result) => {
if (result == null || result.Length == 0) {
success();
} else {
var obj = GSJson.Deserialize(result);
if (obj != null && obj.GetType().IsGenericDictionary())
{
var dictionary = obj as Dictionary<string, object>;
if (dictionary.Count == 1 && dictionary.ContainsKey("result"))
{
success();
} else {
conflict(GSJson.ToObject<ConflictUser>(obj));
}
} else {
conflict(GSJson.ToObject<ConflictUser>(obj));
}
}
}, Json(failure));
}
public void RemoveIdentity(string providerId, Action callback, Action<GetSocialError> failure)
{
CallAsyncVoid("CurrentUser.removeIdentity", providerId, callback, failure);
}
public void ResetUser(Action success, Action<GetSocialError> failure)
{
CallAsyncVoid("GetSocial.resetUser", "", success, failure);
}
public void ResetUserWithoutInit(Action success, Action<GetSocialError> failure)
{
CallAsyncVoid("GetSocial.resetUserWithoutInit", "", success, failure);
}
public void UpdateDetails(UserUpdate userUpdate, Action callback, Action<GetSocialError> failure)
{
CallAsyncVoid("CurrentUser.updateDetails", GSJson.Serialize(userUpdate), callback, failure);
}
public void Refresh(Action callback, Action<GetSocialError> failure)
{
CallAsyncVoid("CurrentUser.refresh", "", callback, failure);
}
public bool SetLanguage(string language)
{
return CallSync<bool>("GetSocial.setLanguage", language);
}
public string GetNativeSdkVersion()
{
// todo
return "";
}
public bool IsInitialized()
{
return CallSync<bool>("GetSocial.isInitialized");
}
public string GetLanguage()
{
return CallSync<string>("GetSocial.getLanguage");
}
public void GetAnnouncements(AnnouncementsQuery query, Action<List<Activity>> onSuccess, Action<GetSocialError> onFailure)
{
CallAsync("Communities.getAnnouncements", GSJson.Serialize(query), onSuccess, onFailure);
}
public void GetActivities(PagingQuery<ActivitiesQuery> query, Action<PagingResult<Activity>> onSuccess, Action<GetSocialError> onFailure)
{
CallAsync("Communities.getActivities", GSJson.Serialize(query), onSuccess, onFailure);
}
public void GetActivity(string id, Action<Activity> onSuccess, Action<GetSocialError> onFailure)
{
CallAsync("Communities.getActivity", id, onSuccess, onFailure);
}
public void PostActivity(ActivityContent content, PostActivityTarget target, Action<Activity> onSuccess, Action<GetSocialError> onFailure)
{
CallAsync("Communities.postActivity", GSJson.Serialize(new PostActivityBody{Target = target, Content = content}), onSuccess, onFailure);
}
public void UpdateActivity(string id, ActivityContent content, Action<Activity> onSuccess, Action<GetSocialError> onFailure)
{
CallAsync("Communities.updateActivity", GSJson.Serialize(new UpdateActivityBody{Target = id, Content = content}), onSuccess, onFailure);
}
public void RemoveActivities(RemoveActivitiesQuery query, Action onSuccess, Action<GetSocialError> onFailure)
{
CallAsyncVoid("Communities.removeActivities", GSJson.Serialize(query), onSuccess, onFailure);
}
public void AddReaction(string reaction, string activityId, Action success, Action<GetSocialError> failure)
{
CallAsyncVoid("Communities.addReaction", GSJson.Serialize(new AddReactionBody{ Reaction = reaction, ActivityId = activityId}), success, failure);
}
public void RemoveReaction(string reaction, string activityId, Action success, Action<GetSocialError> failure)
{
CallAsyncVoid("Communities.removeReaction", GSJson.Serialize(new AddReactionBody{ Reaction = reaction, ActivityId = activityId}), success, failure);
}
public void GetReactions(PagingQuery<ReactionsQuery> query, Action<PagingResult<UserReactions>> onSuccess, Action<GetSocialError> onFailure)
{
CallAsync("Communities.getReactions", GSJson.Serialize(query), onSuccess, onFailure);
}
public void GetTags(TagsQuery query, Action<List<string>> onSuccess, Action<GetSocialError> onFailure)
{
CallAsync("Communities.getTags", GSJson.Serialize(query), onSuccess, onFailure);
}
public void ReportActivity(string activityId, ReportingReason reason, string explanation, Action onSuccess, Action<GetSocialError> onError)
{
CallAsyncVoid("Communities.reportActivity", GSJson.Serialize(new ReportActivityBody{ Id = activityId, Reason = reason, Explanation = explanation}), onSuccess, onError);
}
public void GetUsers(PagingQuery<UsersQuery> query, Action<PagingResult<User>> onSuccess, Action<GetSocialError> onFailure)
{
CallAsync("Communities.getUsers", GSJson.Serialize(query), onSuccess, onFailure);
}
public void GetUsers(UserIdList list, Action<Dictionary<string, User>> onSuccess, Action<GetSocialError> onFailure)
{
CallAsync("Communities.getUsersByIds", GSJson.Serialize(list), onSuccess, onFailure);
}
public void GetUsersCount(UsersQuery query, Action<int> success, Action<GetSocialError> error)
{
CallAsync("Communities.getUsersCount", GSJson.Serialize(query), success, error);
}
public void AddFriends(UserIdList userIds, Action<int> success, Action<GetSocialError> failure)
{
CallAsync("Communities.addFriends", GSJson.Serialize(userIds), success, failure);
}
public void RemoveFriends(UserIdList userIds, Action<int> success, Action<GetSocialError> failure)
{
CallAsync("Communities.removeFriends", GSJson.Serialize(userIds), success, failure);
}
public void GetFriends(PagingQuery<FriendsQuery> query, Action<PagingResult<User>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getFriends", GSJson.Serialize(query), success, failure);
}
public void GetFriendsCount(FriendsQuery query, Action<int> success,
Action<GetSocialError> failure)
{
CallAsync("Communities.getFriendsCount", GSJson.Serialize(query), success, failure);
}
public void AreFriends(UserIdList userIds, Action<Dictionary<string, bool>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.areFriends", GSJson.Serialize(userIds), success, failure);
}
public void IsFriend(UserId userId, Action<bool> success, Action<GetSocialError> failure)
{
CallAsync("Communities.isFriend", GSJson.Serialize(userId), success, failure);
}
public void SetFriends(UserIdList userIds, Action<int> success, Action<GetSocialError> failure)
{
CallAsync("Communities.setFriends", GSJson.Serialize(userIds), success, failure);
}
public void GetFriendsCount(FriendsQuery query, Action<PagingResult<User>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getFriendsCount", GSJson.Serialize(query), success, failure);
}
public void GetSuggestedFriends(SimplePagingQuery query, Action<PagingResult<SuggestedFriend>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getSuggestedFriends", GSJson.Serialize(query), success, failure);
}
public void GetTopic(string topic, Action<Topic> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getTopic", topic, success, failure);
}
public void GetTopics(PagingQuery<TopicsQuery> pagingQuery, Action<PagingResult<Topic>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getTopics", GSJson.Serialize(pagingQuery), success, failure);
}
public void GetTopicsCount(TopicsQuery query, Action<int> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getTopicsCount", GSJson.Serialize(query), success, failure);
}
public void CreateGroup(GroupContent content, Action<Group> success, Action<GetSocialError> failure)
{
CallAsync("Communities.createGroup", GSJson.Serialize(content), success, failure);
}
public void UpdateGroup(string groupId, GroupContent content, Action<Group> success, Action<GetSocialError> failure)
{
CallAsync("Communities.updateGroup", GSJson.Serialize(new UpdateGroupBody { GroupId = groupId, Content = content }), success, failure);
}
public void RemoveGroups(List<string> groupIds, Action success, Action<GetSocialError> failure)
{
CallAsyncVoid("Communities.removeGroups", GSJson.Serialize(groupIds), success, failure);
}
public void GetGroupMembers(PagingQuery<MembersQuery> pagingQuery, Action<PagingResult<GroupMember>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getGroupMembers", GSJson.Serialize(pagingQuery), success, failure);
}
public void GetGroups(PagingQuery<GroupsQuery> pagingQuery, Action<PagingResult<Group>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getGroups", GSJson.Serialize(pagingQuery), success, failure);
}
public void GetGroupsCount(GroupsQuery query, Action<int> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getGroupsCount", GSJson.Serialize(query), success, failure);
}
public void GetGroup(string groupId, Action<Group> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getGroup", (groupId), success, failure);
}
public void UpdateGroupMembers(UpdateGroupMembersQuery query, Action<List<GroupMember>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.updateGroupMembers", GSJson.Serialize(query), success, failure);
}
public void AddGroupMembers(AddGroupMembersQuery query, Action<List<GroupMember>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.addGroupMembers", GSJson.Serialize(query), success, failure);
}
public void JoinGroup(JoinGroupQuery query, Action<GroupMember> success, Action<GetSocialError> failure)
{
CallAsync("Communities.updateGroupMembers", GSJson.Serialize(query.InternalQuery), (List<GroupMember> groupMembers) => {
success(groupMembers.ToArray()[0]);
}, failure);
}
public void RemoveGroupMembers(RemoveGroupMembersQuery query, Action success, Action<GetSocialError> failure)
{
CallAsyncVoid("Communities.removeGroupMembers", GSJson.Serialize(query), success, failure);
}
public void AreGroupMembers(string groupId, UserIdList userIdList, Action<Dictionary<string, Membership>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.areGroupMembers", GSJson.Serialize(new AreGroupMembersBody { GroupId = groupId, UserIdList = userIdList }), success, failure);
}
public void Follow(FollowQuery query, Action<int> success, Action<GetSocialError> failure)
{
CallAsync("Communities.follow", GSJson.Serialize(query), success, failure);
}
public void Unfollow(FollowQuery query, Action<int> success, Action<GetSocialError> failure)
{
CallAsync("Communities.unfollow", GSJson.Serialize(query), success, failure);
}
public void IsFollowing(UserId userId, FollowQuery query, Action<Dictionary<string, bool>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.isFollowing", GSJson.Serialize(new IsFollowingBody { UserId = userId, Query = query }), success, failure);
}
public void GetFollowers(PagingQuery<FollowersQuery> query, Action<PagingResult<User>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getFollowers", GSJson.Serialize(query), success, failure);
}
public void GetFollowersCount(FollowersQuery query, Action<int> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getFollowersCount", GSJson.Serialize(query), success, failure);
}
public void SendChatMessage(ChatMessageContent content, ChatId target, Action<ChatMessage> success, Action<GetSocialError> failure)
{
CallAsync("Communities.sendChatMessage", GSJson.Serialize(new SendChatMessageBody { Content = content, Target = target }), success, failure);
}
public void GetChatMessages(ChatMessagesPagingQuery pagingQuery, Action<ChatMessagesPagingResult> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getChatMessages", GSJson.Serialize(pagingQuery), success, failure);
}
public void GetChats(SimplePagingQuery pagingQuery, Action<PagingResult<Chat>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getChats", GSJson.Serialize(pagingQuery), success, failure);
}
public void GetChat(ChatId chatId, Action<Chat> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getChat", GSJson.Serialize(chatId), success, failure);
}
public void AddVotes(HashSet<string> pollOptionIdSet, string activityId, Action success, Action<GetSocialError> failure)
{
CallAsyncVoid("Communities.addVotes", GSJson.Serialize(new ModifyVotesBody { ActivityId = activityId, PollOptionIds = new List<string>(pollOptionIdSet) }), success, failure);
}
public void SetVotes(HashSet<string> pollOptionIdSet, string activityId, Action onSuccess, Action<GetSocialError> onError)
{
CallAsyncVoid("Communities.setVotes", GSJson.Serialize(new ModifyVotesBody { ActivityId = activityId, PollOptionIds = new List<string>(pollOptionIdSet) }), onSuccess, onError);
}
public void RemoveVotes(HashSet<string> pollOptionIdSet, string activityId, Action onSuccess, Action<GetSocialError> onError)
{
CallAsyncVoid("Communities.removeVotes", GSJson.Serialize(new ModifyVotesBody { ActivityId = activityId, PollOptionIds = new List<string>(pollOptionIdSet) }), onSuccess, onError);
}
public void GetVotes(PagingQuery<VotesQuery> query, Action<PagingResult<UserVotes>> success, Action<GetSocialError> failure)
{
CallAsync("Communities.getVotes", GSJson.Serialize(query), success, failure);
}
#region Invites
public void GetAvailableChannels(Action<List<InviteChannel>> success, Action<GetSocialError> failure)
{
CallAsync("Invites.getAvailableChannels", null, success, failure);
}
public void Send(InviteContent customInviteContent, string channelId, Action success, Action cancel, Action<GetSocialError> failure)
{
CallAsync("Invites.send", GSJson.Serialize(new SendInviteBody { ChannelId = channelId, Content = customInviteContent }), (string result) => {
if ("cancel".Equals(result))
{
cancel();
}
else
{
success();
}
}, failure);
}
public void Create(InviteContent customInviteContent, Action<Invite> success, Action<GetSocialError> failure)
{
CallAsync("Invites.create", GSJson.Serialize(customInviteContent), success, failure);
}
public void CreateLink(Dictionary<string, object> linkParams, Action<string> success, Action<GetSocialError> failure)
{
#if UNITY_IOS
linkParams = ImageToBase64(linkParams, false);
var content = new InviteContent();
content = content.AddLinkParams(linkParams);
CallAsync("Invites.createLink", GSJson.Serialize(content), success, failure);
#else
linkParams = ImageToBase64(linkParams, true);
CallAsync("Invites.createLink", GSJson.Serialize(linkParams), success, failure);
#endif
}
private static Dictionary<string, object> ImageToBase64(Dictionary<string, object> linkParams, bool addSuffix)
{
if (linkParams == null)
{
return null;
}
var result = new Dictionary<string, object>();
foreach (var kv in linkParams)
{
if (kv.Value is Texture2D)
{
if (addSuffix)
{
result[kv.Key + "64"] = (kv.Value as Texture2D).TextureToBase64();
} else
{
result[kv.Key] = (kv.Value as Texture2D).TextureToBase64();
}
} else
{
result[kv.Key] = kv.Value;
}
}
return result;
}
public void GetReferredUsers(PagingQuery<ReferralUsersQuery> query, Action<PagingResult<ReferralUser>> success, Action<GetSocialError> failure)
{
CallAsync("Invites.getReferredUsers", GSJson.Serialize(query), success, failure);
}
public void GetReferrerUsers(PagingQuery<ReferralUsersQuery> query, Action<PagingResult<ReferralUser>> success, Action<GetSocialError> failure)
{
CallAsync("Invites.getReferrerUsers", GSJson.Serialize(query), success, failure);
}
public void SetReferrer(UserId userId, string eventName, Dictionary<string, string> customData, Action success, Action<GetSocialError> failure)
{
CallAsyncVoid("Invites.setReferrer", GSJson.Serialize(new SetReferrerBody { UserId = userId, EventName = eventName, CustomData = customData }), success, failure);
}
public void SetOnReferralDataReceivedListener(Action<ReferralData> listener)
{
Action<ReferralData> wrapper = some => listener(some);
MethodCaller.RegisterListener("Invites.setOnReferralDataReceivedListener", Json(wrapper));
}
#if UNITY_EDITOR
public void TriggerOnReferralDataReceivedListener(ReferralData referralData)
{
// empty
}
#endif
#endregion
#region Promo Codes
public void CreatePromoCode(PromoCodeContent content, Action<PromoCode> success, Action<GetSocialError> failure)
{
CallAsync("PromoCodes.create", GSJson.Serialize(content), success, failure);
}
public void GetPromoCode(string code, Action<PromoCode> success, Action<GetSocialError> failure)
{
CallAsync("PromoCodes.get", code, success, failure);
}
public void ClaimPromoCode(string code, Action<PromoCode> success, Action<GetSocialError> failure)
{
CallAsync("PromoCodes.claim", code, success, failure);
}
#endregion
#region Analytics
public bool TrackPurchase(PurchaseData purchaseData)
{
return CallSync<bool>("Analytics.trackPurchase", GSJson.Serialize(purchaseData));
}
public bool TrackCustomEvent(string eventName, Dictionary<string, string> eventData)
{
return CallSync<bool>("Analytics.trackCustomEvent", GSJson.Serialize(new TrackCustomEventBody { EventName = eventName, EventData = eventData }));
}
#endregion
#region Push notifications
public void GetNotifications(PagingQuery<NotificationsQuery> pagingQuery, Action<PagingResult<Notification>> success, Action<GetSocialError> failure)
{
CallAsync("Notifications.get", GSJson.Serialize(pagingQuery), success, failure);
}
public void CountNotifications(NotificationsQuery query, Action<int> success, Action<GetSocialError> failure) {
CallAsync("Notifications.count", GSJson.Serialize(query), success, failure);
}
public void SetStatus(string newStatus, List<string> notificationIds, Action success, Action<GetSocialError> failure) {
CallAsyncVoid("Notifications.setStatus", GSJson.Serialize(new SetStatusBody { Status = newStatus, NotificationIds = notificationIds }), success, failure);
}
public void SetPushNotificationsEnabled(bool enabled, Action success, Action<GetSocialError> failure) {
CallAsyncVoid("Notifications.setEnabled", GSJson.Serialize(enabled), success, failure);
}
public void ArePushNotificationsEnabled(Action<bool> success, Action<GetSocialError> failure) {
CallAsync("Notifications.areEnabled", "", success, failure);
}
public void Send(NotificationContent content, SendNotificationTarget target, Action success, Action<GetSocialError> failure) {
CallAsyncVoid("Notifications.send", GSJson.Serialize(new SendNotificationBody { Target = target, Content = content }), success, failure) ;
}
public void RegisterDevice() {
CallSync<bool>("Notifications.registerDevice", "");
}
public void SetOnNotificationReceivedListener(Action<Notification> listener) {
MethodCaller.RegisterListener("Notifications.setOnNotificationReceivedListener", Json(listener));
}
public void SetOnNotificationClickedListener(Action<Notification, NotificationContext> listener)
{
Action<NotificationListenerBody> wrapper = body =>
{
listener(body.Notification, body.Context);
};
MethodCaller.RegisterListener("Notifications.setOnNotificationClickedListener", Json(wrapper));
}
public void SetOnTokenReceivedListener(Action<string> listener)
{
MethodCaller.RegisterListener("Notifications.setOnTokenReceivedListener", listener);
}
public void HandleOnStartUnityEvent()
{
MethodCaller.Call("GetSocial.handleOnStartUnityEvent", "");
}
#endregion
private void CallAsync<R>(string method, string body, Action<R> success, Action<GetSocialError> failure)
{
MethodCaller.CallAsync(method, body, Json(success), Json(failure));
}
private void CallAsyncVoid(string method, string body, Action success, Action<GetSocialError> failure)
{
MethodCaller.CallAsync(method, body, any => success(), Json(failure));
}
private static Action<string> Json<T>(Action<T> callback)
{
return s => callback(FromJson<T>(s));
}
public static T FromJson<T>(string json)
{
if (json == null)
{
#if UNITY_2018_1_OR_NEWER
return default;
#else
return default(T);
#endif
}
var obj = GSJson.Deserialize(json);
if (obj != null && obj.GetType().IsGenericDictionary())
{
var dictionary = obj as Dictionary<string, object>;
if (dictionary.Count == 1 && dictionary.ContainsKey("result"))
{
return (T) Convert.ChangeType(dictionary["result"], typeof(T));
}
}
return GSJson.ToObject<T>(obj);
}
private R CallSync<R>(string method, string body = "")
{
return FromJson<R>(MethodCaller.Call(method, body));
}
}
internal interface IMethodCaller
{
string Call(string method, string body);
void CallAsync(string method, string body, Action<string> success, Action<string> failure);
string RegisterListener(string method, Action<string> listener);
}
public class PostActivityBody
{
[JsonSerializationKey("target")]
public PostActivityTarget Target;
[JsonSerializationKey("content")]
public ActivityContent Content;
}
public class UpdateActivityBody
{
[JsonSerializationKey("target")]
public string Target;
[JsonSerializationKey("content")]
public ActivityContent Content;
}
public class AddReactionBody
{
[JsonSerializationKey("reaction")]
public string Reaction;
[JsonSerializationKey("activityId")]
public string ActivityId;
}
public class ModifyVotesBody
{
[JsonSerializationKey("pollOptionIds")]
public List<string> PollOptionIds;
[JsonSerializationKey("activityId")]
public string ActivityId;
}
public class SendNotificationBody
{
[JsonSerializationKey("target")]
public SendNotificationTarget Target;
[JsonSerializationKey("content")]
public NotificationContent Content;
}
public class UpdateGroupBody
{
[JsonSerializationKey("groupId")]
public string GroupId;
[JsonSerializationKey("content")]
public GroupContent Content;
}
public class RemoveGroupMembersBody
{
[JsonSerializationKey("groupId")]
public string GroupId;
[JsonSerializationKey("query")]
public RemoveGroupMembersQuery Query;
}
public class AreGroupMembersBody
{
[JsonSerializationKey("groupId")]
public string GroupId;
[JsonSerializationKey("userIdList")]
public UserIdList UserIdList;
}
public class IsFollowingBody
{
[JsonSerializationKey("userId")]
public UserId UserId;
[JsonSerializationKey("query")]
public FollowQuery Query;
}
public class SendInviteBody
{
[JsonSerializationKey("channelId")]
public string ChannelId;
[JsonSerializationKey("content")]
public InviteContent Content;
}
public class SetReferrerBody
{
[JsonSerializationKey("userId")]
public UserId UserId;
[JsonSerializationKey("eventName")]
public string EventName;
[JsonSerializationKey("customData")]
public Dictionary<string, string> CustomData;
}
public class TrackCustomEventBody
{
[JsonSerializationKey("eventName")]
public string EventName;
[JsonSerializationKey("eventData")]
public Dictionary<string, string> EventData;
}
public class SetStatusBody
{
[JsonSerializationKey("status")]
public string Status;
[JsonSerializationKey("notificationIds")]
public List<string> NotificationIds;
}
public class NotificationListenerBody
{
[JsonSerializationKey("notification")]
public Notification Notification;
[JsonSerializationKey("context")]
public NotificationContext Context;
}
public class ReportActivityBody
{
[JsonSerializationKey("activityId")]
public string Id;
[JsonSerializationKey("reason")]
public ReportingReason Reason;
[JsonSerializationKey("explanation")]
public string Explanation;
}
public class SendChatMessageBody
{
[JsonSerializationKey("target")]
public ChatId Target;
[JsonSerializationKey("content")]
public ChatMessageContent Content;
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// 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.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.8.4. Actual transmission of intercome voice data. COMPLETE
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
[XmlInclude(typeof(OneByteChunk))]
public partial class IntercomSignalPdu : RadioCommunicationsFamilyPdu, IEquatable<IntercomSignalPdu>
{
/// <summary>
/// entity ID
/// </summary>
private EntityID _entityID = new EntityID();
/// <summary>
/// ID of communications device
/// </summary>
private ushort _communicationsDeviceID;
/// <summary>
/// encoding scheme
/// </summary>
private ushort _encodingScheme;
/// <summary>
/// tactical data link type
/// </summary>
private ushort _tdlType;
/// <summary>
/// sample rate
/// </summary>
private uint _sampleRate;
/// <summary>
/// data length
/// </summary>
private ushort _dataLength;
/// <summary>
/// samples
/// </summary>
private ushort _samples;
/// <summary>
/// data bytes
/// </summary>
private byte[] _data;
/// <summary>
/// Initializes a new instance of the <see cref="IntercomSignalPdu"/> class.
/// </summary>
public IntercomSignalPdu()
{
PduType = (byte)31;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(IntercomSignalPdu left, IntercomSignalPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(IntercomSignalPdu left, IntercomSignalPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._entityID.GetMarshalledSize(); // this._entityID
marshalSize += 2; // this._communicationsDeviceID
marshalSize += 2; // this._encodingScheme
marshalSize += 2; // this._tdlType
marshalSize += 4; // this._sampleRate
marshalSize += 2; // this._dataLength
marshalSize += 2; // this._samples
marshalSize += this._data.Length;
return marshalSize;
}
/// <summary>
/// Gets or sets the entity ID
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "entityID")]
public EntityID EntityID
{
get
{
return this._entityID;
}
set
{
this._entityID = value;
}
}
/// <summary>
/// Gets or sets the ID of communications device
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "communicationsDeviceID")]
public ushort CommunicationsDeviceID
{
get
{
return this._communicationsDeviceID;
}
set
{
this._communicationsDeviceID = value;
}
}
/// <summary>
/// Gets or sets the encoding scheme
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "encodingScheme")]
public ushort EncodingScheme
{
get
{
return this._encodingScheme;
}
set
{
this._encodingScheme = value;
}
}
/// <summary>
/// Gets or sets the tactical data link type
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "tdlType")]
public ushort TdlType
{
get
{
return this._tdlType;
}
set
{
this._tdlType = value;
}
}
/// <summary>
/// Gets or sets the sample rate
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "sampleRate")]
public uint SampleRate
{
get
{
return this._sampleRate;
}
set
{
this._sampleRate = value;
}
}
/// <summary>
/// Gets or sets the data length
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getdataLength method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(ushort), ElementName = "dataLength")]
public ushort DataLength
{
get
{
return this._dataLength;
}
set
{
this._dataLength = value;
}
}
/// <summary>
/// Gets or sets the samples
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "samples")]
public ushort Samples
{
get
{
return this._samples;
}
set
{
this._samples = value;
}
}
/// <summary>
/// Gets or sets the data bytes
/// </summary>
[XmlElement(ElementName = "dataList", DataType = "hexBinary")]
public byte[] Data
{
get
{
return this._data;
}
set
{
this._data = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._entityID.Marshal(dos);
dos.WriteUnsignedShort((ushort)this._communicationsDeviceID);
dos.WriteUnsignedShort((ushort)this._encodingScheme);
dos.WriteUnsignedShort((ushort)this._tdlType);
dos.WriteUnsignedInt((uint)this._sampleRate);
dos.WriteUnsignedShort((ushort)this._data.Length);
dos.WriteUnsignedShort((ushort)this._samples);
dos.WriteByte(this._data);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._entityID.Unmarshal(dis);
this._communicationsDeviceID = dis.ReadUnsignedShort();
this._encodingScheme = dis.ReadUnsignedShort();
this._tdlType = dis.ReadUnsignedShort();
this._sampleRate = dis.ReadUnsignedInt();
this._dataLength = dis.ReadUnsignedShort();
this._samples = dis.ReadUnsignedShort();
this._data = dis.ReadByteArray(this._dataLength);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<IntercomSignalPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<entityID>");
this._entityID.Reflection(sb);
sb.AppendLine("</entityID>");
sb.AppendLine("<communicationsDeviceID type=\"ushort\">" + this._communicationsDeviceID.ToString(CultureInfo.InvariantCulture) + "</communicationsDeviceID>");
sb.AppendLine("<encodingScheme type=\"ushort\">" + this._encodingScheme.ToString(CultureInfo.InvariantCulture) + "</encodingScheme>");
sb.AppendLine("<tdlType type=\"ushort\">" + this._tdlType.ToString(CultureInfo.InvariantCulture) + "</tdlType>");
sb.AppendLine("<sampleRate type=\"uint\">" + this._sampleRate.ToString(CultureInfo.InvariantCulture) + "</sampleRate>");
sb.AppendLine("<data type=\"ushort\">" + this._data.Length.ToString(CultureInfo.InvariantCulture) + "</data>");
sb.AppendLine("<samples type=\"ushort\">" + this._samples.ToString(CultureInfo.InvariantCulture) + "</samples>");
sb.AppendLine("<data type=\"byte[]\">");
foreach (byte b in this._data)
{
sb.Append(b.ToString("X2", CultureInfo.InvariantCulture));
}
sb.AppendLine("</data>");
sb.AppendLine("</IntercomSignalPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as IntercomSignalPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(IntercomSignalPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._entityID.Equals(obj._entityID))
{
ivarsEqual = false;
}
if (this._communicationsDeviceID != obj._communicationsDeviceID)
{
ivarsEqual = false;
}
if (this._encodingScheme != obj._encodingScheme)
{
ivarsEqual = false;
}
if (this._tdlType != obj._tdlType)
{
ivarsEqual = false;
}
if (this._sampleRate != obj._sampleRate)
{
ivarsEqual = false;
}
if (this._dataLength != obj._dataLength)
{
ivarsEqual = false;
}
if (this._samples != obj._samples)
{
ivarsEqual = false;
}
if (!this._data.Equals(obj._data))
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._entityID.GetHashCode();
result = GenerateHash(result) ^ this._communicationsDeviceID.GetHashCode();
result = GenerateHash(result) ^ this._encodingScheme.GetHashCode();
result = GenerateHash(result) ^ this._tdlType.GetHashCode();
result = GenerateHash(result) ^ this._sampleRate.GetHashCode();
result = GenerateHash(result) ^ this._dataLength.GetHashCode();
result = GenerateHash(result) ^ this._samples.GetHashCode();
if (this._data.Length > 0)
{
for (int idx = 0; idx < this._data.Length; idx++)
{
result = GenerateHash(result) ^ this._data[idx].GetHashCode();
}
}
return result;
}
}
}
| |
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.interfaces;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
namespace umbraco.editorControls
{
public class DefaultPrevalueEditor : PlaceHolder, IDataPrevalue
{
// UI controls
private TextBox _textbox;
private DropDownList _dropdownlist;
// referenced datatype
private cms.businesslogic.datatype.BaseDataType _datatype;
private BaseDataType _datatypeOld;
private bool _isEnsured = false;
private string _prevalue;
private bool _displayTextBox;
public static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
/// <summary>
/// The default editor for editing the build-in pre values in umbraco
/// </summary>
/// <param name="DataType">The DataType to be parsed</param>
/// <param name="DisplayTextBox">Whether to use the default text box</param>
public DefaultPrevalueEditor(cms.businesslogic.datatype.BaseDataType DataType, bool DisplayTextBox)
{
// state it knows its datatypedefinitionid
_displayTextBox = DisplayTextBox;
_datatype = DataType;
setupChildControls();
}
/// <summary>
/// For backwards compatibility, should be replaced in your extension with the constructor that
/// uses the BaseDataType from the cms.businesslogic.datatype namespace
/// </summary>
/// <param name="DataType">The DataType to be parsed (note: the BaseDataType from editorControls is obsolete)</param>
/// <param name="DisplayTextBox">Whether to use the default text box</param>
public DefaultPrevalueEditor(BaseDataType DataType, bool DisplayTextBox)
{
// state it knows its datatypedefinitionid
_displayTextBox = DisplayTextBox;
_datatypeOld = DataType;
setupChildControls();
}
private void setupChildControls()
{
_dropdownlist = new DropDownList();
_dropdownlist.ID = "dbtype";
_textbox = new TextBox();
_textbox.ID = "prevalues";
_textbox.Visible = _displayTextBox;
// put the childcontrols in context - ensuring that
// the viewstate is persisted etc.
Controls.Add(_textbox);
Controls.Add(_dropdownlist);
_dropdownlist.Items.Add(DBTypes.Date.ToString());
_dropdownlist.Items.Add(DBTypes.Integer.ToString());
_dropdownlist.Items.Add(DBTypes.Ntext.ToString());
_dropdownlist.Items.Add(DBTypes.Nvarchar.ToString());
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!Page.IsPostBack)
{
if (_datatype != null)
_dropdownlist.SelectedValue = _datatype.DBType.ToString();
else
_dropdownlist.SelectedValue = _datatypeOld.DBType.ToString();
_textbox.Text = Prevalue;
}
}
public string Prevalue
{
get
{
ensurePrevalue();
if (_prevalue == null) {
int defId;
if (_datatype != null)
defId = _datatype.DataTypeDefinitionId;
else if (_datatypeOld != null)
defId = _datatypeOld.DataTypeDefinitionId;
else
throw new ArgumentException("Datatype is not initialized");
_prevalue =
SqlHelper.ExecuteScalar<string>("Select [value] from cmsDataTypePreValues where DataTypeNodeId = " + defId);
}
return _prevalue;
}
set
{
int defId;
if (_datatype != null)
defId = _datatype.DataTypeDefinitionId;
else if (_datatypeOld != null)
defId = _datatypeOld.DataTypeDefinitionId;
else
throw new ArgumentException("Datatype is not initialized");
_prevalue = value;
ensurePrevalue();
IParameter[] SqlParams = new IParameter[]
{
SqlHelper.CreateParameter("@value", _textbox.Text),
SqlHelper.CreateParameter("@dtdefid", defId)
};
// update prevalue
SqlHelper.ExecuteNonQuery("update cmsDataTypePreValues set [value] = @value where datatypeNodeId = @dtdefid", SqlParams);
}
}
private void ensurePrevalue()
{
if (!_isEnsured)
{
int defId;
if (_datatype != null)
defId = _datatype.DataTypeDefinitionId;
else if (_datatypeOld != null)
defId = _datatypeOld.DataTypeDefinitionId;
else
throw new ArgumentException("Datatype is not initialized");
bool hasPrevalue = (SqlHelper.ExecuteScalar<int>("select count(id) from cmsDataTypePreValues where dataTypeNodeId = " + defId) > 0);
IParameter[] SqlParams = new IParameter[]
{
SqlHelper.CreateParameter("@value", _textbox.Text),
SqlHelper.CreateParameter("@dtdefid", defId)
};
if (!hasPrevalue)
{
SqlHelper.ExecuteNonQuery("insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (@dtdefid,@value,0,'')",
SqlParams);
}
_isEnsured = true;
}
}
public Control Editor
{
get { return this; }
}
public void Save()
{
// save the prevalue data and get on with you life ;)
if (_datatype != null)
_datatype.DBType = (cms.businesslogic.datatype.DBTypes)Enum.Parse(typeof (cms.businesslogic.datatype.DBTypes), _dropdownlist.SelectedValue, true);
else if (_datatypeOld != null)
_datatypeOld.DBType = (DBTypes)Enum.Parse(typeof (DBTypes), _dropdownlist.SelectedValue, true);
if (_displayTextBox)
{
// If the prevalue editor has an prevalue textbox - save the textbox value as the prevalue
Prevalue = _textbox.Text;
}
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write("<div class='propertyItem'><div class='propertyItemheader'>" + ui.Text("dataBaseDatatype") + "</div>");
_dropdownlist.RenderControl(writer);
writer.Write("<br style='clear: both'/></div>");
if (_displayTextBox) {
writer.Write("<div class='propertyItem'><div class='propertyItemheader'>" + ui.Text("prevalue") + "</div>");
_textbox.RenderControl(writer);
writer.Write("<br style='clear: both'/></div>");
}
/*
writer.WriteLine("<div class='propertyItem'>");
writer.WriteLine("<tr><td>Database datatype</td><td>");
_dropdownlist.RenderControl(writer);
writer.Write("</td></tr>");
if (_displayTextBox)
writer.WriteLine("<tr><td>Prevalue: </td><td>");
_textbox.RenderControl(writer);
writer.WriteLine("</td></tr>");
writer.Write("</div>");
*/
}
public static string GetPrevalueFromId(int Id)
{
return SqlHelper.ExecuteScalar<string>("Select [value] from cmsDataTypePreValues where id = @id",
SqlHelper.CreateParameter("@id", Id));
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009 Oracle. All rights reserved.
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using BerkeleyDB.Internal;
namespace BerkeleyDB {
/// <summary>
/// A class representing a QueueDatabase. The Queue format supports fast
/// access to fixed-length records accessed sequentially or by logical
/// record number.
/// </summary>
public class QueueDatabase : Database {
#region Constructors
private QueueDatabase(DatabaseEnvironment env, uint flags)
: base(env, flags) { }
internal QueueDatabase(BaseDatabase clone) : base(clone) { }
private void Config(QueueDatabaseConfig cfg) {
base.Config(cfg);
/*
* Database.Config calls set_flags, but that doesn't get the Queue
* specific flags. No harm in calling it again.
*/
db.set_flags(cfg.flags);
db.set_re_len(cfg.Length);
if (cfg.padIsSet)
db.set_re_pad(cfg.PadByte);
if (cfg.extentIsSet)
db.set_q_extentsize(cfg.ExtentSize);
}
/// <summary>
/// Instantiate a new QueueDatabase object and open the database
/// represented by <paramref name="Filename"/>.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="Filename"/> is null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe.
/// </para>
/// <para>
/// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation
/// will be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <returns>A new, open database object</returns>
public static QueueDatabase Open(
string Filename, QueueDatabaseConfig cfg) {
return Open(Filename, cfg, null);
}
/// <summary>
/// Instantiate a new QueueDatabase object and open the database
/// represented by <paramref name="Filename"/>.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="Filename"/> is null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe.
/// </para>
/// <para>
/// If <paramref name="txn"/> is null, but
/// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will
/// be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open. Also note that the
/// transaction must be committed before the object is closed.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>A new, open database object</returns>
public static QueueDatabase Open(
string Filename, QueueDatabaseConfig cfg, Transaction txn) {
QueueDatabase ret = new QueueDatabase(cfg.Env, 0);
ret.Config(cfg);
ret.db.open(Transaction.getDB_TXN(txn),
Filename, null, DBTYPE.DB_QUEUE, cfg.openFlags, 0);
ret.isOpen = true;
return ret;
}
#endregion Constructors
#region Properties
/// <summary>
/// The size of the extents used to hold pages in a
/// <see cref="QueueDatabase"/>, specified as a number of pages.
/// </summary>
public uint ExtentSize {
get {
uint ret = 0;
db.get_q_extentsize(ref ret);
return ret;
}
}
/// <summary>
/// If true, modify the operation of <see cref="QueueDatabase.Consume"/>
/// to return key/data pairs in order. That is, they will always return
/// the key/data item from the head of the queue.
/// </summary>
public bool InOrder {
get {
uint flags = 0;
db.get_flags(ref flags);
return (flags & DbConstants.DB_INORDER) != 0;
}
}
/// <summary>
/// The length of records in the database.
/// </summary>
public uint Length {
get {
uint ret = 0;
db.get_re_len(ref ret);
return ret;
}
}
/// <summary>
/// The padding character for short, fixed-length records.
/// </summary>
public int PadByte {
get {
int ret = 0;
db.get_re_pad(ref ret);
return ret;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Append the data item to the end of the database.
/// </summary>
/// <param name="data">The data item to store in the database</param>
/// <returns>The record number allocated to the record</returns>
public uint Append(DatabaseEntry data) {
return Append(data, null);
}
/// <summary>
/// Append the data item to the end of the database.
/// </summary>
/// <remarks>
/// There is a minor behavioral difference between
/// <see cref="RecnoDatabase.Append"/> and
/// <see cref="QueueDatabase.Append"/>. If a transaction enclosing an
/// Append operation aborts, the record number may be reallocated in a
/// subsequent <see cref="RecnoDatabase.Append"/> operation, but it will
/// not be reallocated in a subsequent
/// <see cref="QueueDatabase.Append"/> operation.
/// </remarks>
/// <param name="data">The data item to store in the database</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>The record number allocated to the record</returns>
public uint Append(DatabaseEntry data, Transaction txn) {
DatabaseEntry key = new DatabaseEntry();
Put(key, data, txn, DbConstants.DB_APPEND);
return BitConverter.ToUInt32(key.Data, 0);
}
/// <summary>
/// Return the record number and data from the available record closest
/// to the head of the queue, and delete the record.
/// </summary>
/// <param name="wait">
/// If true and the Queue database is empty, the thread of control will
/// wait until there is data in the queue before returning.
/// </param>
/// <exception cref="LockNotGrantedException">
/// If lock or transaction timeouts have been specified, a
/// <see cref="LockNotGrantedException"/> may be thrown. This failure,
/// by itself, does not require the enclosing transaction be aborted.
/// </exception>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key
/// parameter is the record number and whose Value parameter is the
/// retrieved data.
/// </returns>
public KeyValuePair<uint, DatabaseEntry> Consume(bool wait) {
return Consume(wait, null, null);
}
/// <summary>
/// Return the record number and data from the available record closest
/// to the head of the queue, and delete the record.
/// </summary>
/// <param name="wait">
/// If true and the Queue database is empty, the thread of control will
/// wait until there is data in the queue before returning.
/// </param>
/// <param name="txn">
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <exception cref="LockNotGrantedException">
/// If lock or transaction timeouts have been specified, a
/// <see cref="LockNotGrantedException"/> may be thrown. This failure,
/// by itself, does not require the enclosing transaction be aborted.
/// </exception>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key
/// parameter is the record number and whose Value parameter is the
/// retrieved data.
/// </returns>
public KeyValuePair<uint, DatabaseEntry> Consume(
bool wait, Transaction txn) {
return Consume(wait, txn, null);
}
/// <summary>
/// Return the record number and data from the available record closest
/// to the head of the queue, and delete the record.
/// </summary>
/// <param name="wait">
/// If true and the Queue database is empty, the thread of control will
/// wait until there is data in the queue before returning.
/// </param>
/// <param name="txn">
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="info">The locking behavior to use.</param>
/// <exception cref="LockNotGrantedException">
/// If lock or transaction timeouts have been specified, a
/// <see cref="LockNotGrantedException"/> may be thrown. This failure,
/// by itself, does not require the enclosing transaction be aborted.
/// </exception>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key
/// parameter is the record number and whose Value parameter is the
/// retrieved data.
/// </returns>
public KeyValuePair<uint, DatabaseEntry> Consume(
bool wait, Transaction txn, LockingInfo info) {
KeyValuePair<DatabaseEntry, DatabaseEntry> record;
record = Get(null, null, txn, info,
wait ? DbConstants.DB_CONSUME_WAIT : DbConstants.DB_CONSUME);
return new KeyValuePair<uint, DatabaseEntry>(
BitConverter.ToUInt32(record.Key.Data, 0), record.Value);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public QueueStats FastStats() {
return Stats(null, true, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public QueueStats FastStats(Transaction txn) {
return Stats(txn, true, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <overloads>
/// <para>
/// Among other things, this method makes it possible for applications
/// to request key and record counts without incurring the performance
/// penalty of traversing the entire database.
/// </para>
/// <para>
/// The statistical information is described by the
/// <see cref="BTreeStats"/>, <see cref="HashStats"/>,
/// <see cref="QueueStats"/>, and <see cref="RecnoStats"/> classes.
/// </para>
/// </overloads>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="isoDegree">
/// The level of isolation for database reads.
/// <see cref="Isolation.DEGREE_ONE"/> will be silently ignored for
/// databases which did not specify
/// <see cref="DatabaseConfig.ReadUncommitted"/>.
/// </param>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public QueueStats FastStats(Transaction txn, Isolation isoDegree) {
return Stats(txn, true, isoDegree);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <returns>Database statistical information.</returns>
public QueueStats Stats() {
return Stats(null, false, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>Database statistical information.</returns>
public QueueStats Stats(Transaction txn) {
return Stats(txn, false, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <overloads>
/// The statistical information is described by
/// <see cref="BTreeStats"/>.
/// </overloads>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="isoDegree">
/// The level of isolation for database reads.
/// <see cref="Isolation.DEGREE_ONE"/> will be silently ignored for
/// databases which did not specify
/// <see cref="DatabaseConfig.ReadUncommitted"/>.
/// </param>
/// <returns>Database statistical information.</returns>
public QueueStats Stats(Transaction txn, Isolation isoDegree) {
return Stats(txn, false, isoDegree);
}
private QueueStats Stats(Transaction txn, bool fast, Isolation isoDegree) {
uint flags = 0;
flags |= fast ? DbConstants.DB_FAST_STAT : 0;
switch (isoDegree) {
case Isolation.DEGREE_ONE:
flags |= DbConstants.DB_READ_UNCOMMITTED;
break;
case Isolation.DEGREE_TWO:
flags |= DbConstants.DB_READ_COMMITTED;
break;
}
QueueStatStruct st = db.stat_qam(Transaction.getDB_TXN(txn), flags);
return new QueueStats(st);
}
#endregion Methods
}
}
| |
using Orleans.Persistence.AdoNet.Storage;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Serialization;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Configuration.Overrides;
using Orleans.Runtime.Configuration;
namespace Orleans.Storage
{
/// <summary>
/// Logging codes used by <see cref="AdoNetGrainStorage"/>.
/// </summary>
/// <remarks> These are taken from <em>Orleans.Providers.ProviderErrorCode</em> and <em>Orleans.Providers.AzureProviderErrorCode</em>.</remarks>
internal enum RelationalStorageProviderCodes
{
//These is from Orleans.Providers.ProviderErrorCode and Orleans.Providers.AzureProviderErrorCode.
ProvidersBase = 200000,
RelationalProviderBase = ProvidersBase + 400,
RelationalProviderDeleteError = RelationalProviderBase + 8,
RelationalProviderInitProvider = RelationalProviderBase + 9,
RelationalProviderNoDeserializer = RelationalProviderBase + 10,
RelationalProviderNoStateFound = RelationalProviderBase + 11,
RelationalProviderClearing = RelationalProviderBase + 12,
RelationalProviderCleared = RelationalProviderBase + 13,
RelationalProviderReading = RelationalProviderBase + 14,
RelationalProviderRead = RelationalProviderBase + 15,
RelationalProviderReadError = RelationalProviderBase + 16,
RelationalProviderWriting = RelationalProviderBase + 17,
RelationalProviderWrote = RelationalProviderBase + 18,
RelationalProviderWriteError = RelationalProviderBase + 19
}
public static class AdoNetGrainStorageFactory
{
public static IGrainStorage Create(IServiceProvider services, string name)
{
var optionsMonitor = services.GetRequiredService<IOptionsMonitor<AdoNetGrainStorageOptions>>();
var clusterOptions = services.GetProviderClusterOptions(name);
return ActivatorUtilities.CreateInstance<AdoNetGrainStorage>(services, Options.Create(optionsMonitor.Get(name)), name, clusterOptions);
}
}
/// <summary>
/// A storage provider for writing grain state data to relational storage.
/// </summary>
/// <remarks>
/// <para>
/// Required configuration params: <c>DataConnectionString</c>
/// </para>
/// <para>
/// Optional configuration params:
/// <c>AdoInvariant</c> -- defaults to <c>System.Data.SqlClient</c>
/// <c>UseJsonFormat</c> -- defaults to <c>false</c>
/// <c>UseXmlFormat</c> -- defaults to <c>false</c>
/// <c>UseBinaryFormat</c> -- defaults to <c>true</c>
/// </para>
/// </remarks>
[DebuggerDisplay("Name = {Name}, ConnectionString = {Storage.ConnectionString}")]
public class AdoNetGrainStorage: IGrainStorage, ILifecycleParticipant<ISiloLifecycle>
{
private Serializer serializer;
/// <summary>
/// Tag for BinaryFormatSerializer
/// </summary>
public const string BinaryFormatSerializerTag = "BinaryFormatSerializer";
/// <summary>
/// Tag for JsonFormatSerializer
/// </summary>
public const string JsonFormatSerializerTag = "JsonFormatSerializer";
/// <summary>
/// Tag for XmlFormatSerializer
/// </summary>
public const string XmlFormatSerializerTag = "XmlFormatSerializer";
/// <summary>
/// The Service ID for which this relational provider is used.
/// </summary>
private readonly string serviceId;
private readonly ILogger logger;
/// <summary>
/// The storage used for back-end operations.
/// </summary>
private IRelationalStorage Storage { get; set; }
/// <summary>
/// These chars are delimiters when used to extract a class base type from a class
/// that is either <see cref="Type.AssemblyQualifiedName"/> or <see cref="Type.FullName"/>.
/// <see cref="ExtractBaseClass(string)"/>.
/// </summary>
private static char[] BaseClassExtractionSplitDelimeters { get; } = new[] { '[', ']' };
/// <summary>
/// The default query to initialize this structure from the Orleans database.
/// </summary>
public const string DefaultInitializationQuery = "SELECT QueryKey, QueryText FROM OrleansQuery WHERE QueryKey = 'WriteToStorageKey' OR QueryKey = 'ReadFromStorageKey' OR QueryKey = 'ClearStorageKey'";
/// <summary>
/// The queries currently used. When this is updated, the new queries will take effect immediately.
/// </summary>
public RelationalStorageProviderQueries CurrentOperationalQueries { get; set; }
/// <summary>
/// A strategy to pick a serializer or a deserializer for storage operations. This can be used to:
/// 1) Add a custom serializer or deserializer for use in storage provider operations.
/// 2) In combination with serializer or deserializer to update stored object version.
/// 3) Per-grain storage format selection
/// 4) Switch storage format first by reading using the save format and then writing in the new format.
/// </summary>
public IStorageSerializationPicker StorageSerializationPicker { get; set; }
/// <summary>
/// The hash generator used to hash natural keys, grain ID and grain type to a more narrow index.
/// </summary>
public IStorageHasherPicker HashPicker { get; set; } = new StorageHasherPicker(new[] { new OrleansDefaultHasher() });
private readonly AdoNetGrainStorageOptions options;
private readonly IProviderRuntime providerRuntime;
private readonly string name;
public AdoNetGrainStorage(
ILogger<AdoNetGrainStorage> logger,
IProviderRuntime providerRuntime,
IOptions<AdoNetGrainStorageOptions> options,
IOptions<ClusterOptions> clusterOptions,
string name)
{
this.options = options.Value;
this.providerRuntime = providerRuntime;
this.name = name;
this.logger = logger;
this.serviceId = clusterOptions.Value.ServiceId;
}
public void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe(OptionFormattingUtilities.Name<AdoNetGrainStorage>(this.name), this.options.InitStage, Init, Close);
}
/// <summary>Clear state data function for this storage provider.</summary>
/// <see cref="IGrainStorage.ClearStateAsync(string, GrainReference, IGrainState)"/>.
public async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
//It assumed these parameters are always valid. If not, an exception will be thrown,
//even if not as clear as when using explicitly checked parameters.
var grainId = GrainIdAndExtensionAsString(grainReference);
var baseGrainType = ExtractBaseClass(grainType);
if(logger.IsEnabled(LogLevel.Trace))
{
logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderClearing, LogString("Clearing grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
}
string storageVersion = null;
try
{
var grainIdHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(grainId.GetHashBytes());
var grainTypeHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(Encoding.UTF8.GetBytes(baseGrainType));
var clearRecord = (await Storage.ReadAsync(CurrentOperationalQueries.ClearState, command =>
{
command.AddParameter("GrainIdHash", grainIdHash);
command.AddParameter("GrainIdN0", grainId.N0Key);
command.AddParameter("GrainIdN1", grainId.N1Key);
command.AddParameter("GrainTypeHash", grainTypeHash);
command.AddParameter("GrainTypeString", baseGrainType);
command.AddParameter("GrainIdExtensionString", grainId.StringKey);
command.AddParameter("ServiceId", serviceId);
command.AddParameter("GrainStateVersion", !string.IsNullOrWhiteSpace(grainState.ETag) ? int.Parse(grainState.ETag, CultureInfo.InvariantCulture) : default(int?));
}, (selector, resultSetCount, token) => Task.FromResult(selector.GetValue(0).ToString()), CancellationToken.None).ConfigureAwait(false));
storageVersion = clearRecord.SingleOrDefault();
}
catch(Exception ex)
{
logger.Error((int)RelationalStorageProviderCodes.RelationalProviderDeleteError, LogString("Error clearing grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString(), ex.Message), ex);
throw;
}
const string OperationString = "ClearState";
var inconsistentStateException = CheckVersionInconsistency(OperationString, serviceId, this.name, storageVersion, grainState.ETag, baseGrainType, grainId.ToString());
if(inconsistentStateException != null)
{
throw inconsistentStateException;
}
//No errors found, the version of the state held by the grain can be updated and also the state.
grainState.ETag = storageVersion;
grainState.RecordExists = false;
if(logger.IsEnabled(LogLevel.Trace))
{
logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderCleared, LogString("Cleared grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
}
}
/// <summary> Read state data function for this storage provider.</summary>
/// <see cref="IGrainStorage.ReadStateAsync(string, GrainReference, IGrainState)"/>.
public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
//It assumed these parameters are always valid. If not, an exception will be thrown, even if not as clear
//as with explicitly checked parameters.
var grainId = GrainIdAndExtensionAsString(grainReference);
var baseGrainType = ExtractBaseClass(grainType);
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderReading, LogString("Reading grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
}
try
{
SerializationChoice choice =StorageSerializationPicker.PickDeserializer(serviceId, this.name, baseGrainType, grainReference, grainState, null);
if(choice.Deserializer == null)
{
var errorString = LogString("No deserializer found", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString());
logger.Error((int)RelationalStorageProviderCodes.RelationalProviderNoDeserializer, errorString);
throw new InvalidOperationException(errorString);
}
var commandBehavior = choice.PreferStreaming ? CommandBehavior.SequentialAccess : CommandBehavior.Default;
var grainIdHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(grainId.GetHashBytes());
var grainTypeHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(Encoding.UTF8.GetBytes(baseGrainType));
var readRecords = (await Storage.ReadAsync(CurrentOperationalQueries.ReadFromStorage, (command =>
{
command.AddParameter("GrainIdHash", grainIdHash);
command.AddParameter("GrainIdN0", grainId.N0Key);
command.AddParameter("GrainIdN1", grainId.N1Key);
command.AddParameter("GrainTypeHash", grainTypeHash);
command.AddParameter("GrainTypeString", baseGrainType);
command.AddParameter("GrainIdExtensionString", grainId.StringKey);
command.AddParameter("ServiceId", serviceId);
}), async (selector, resultSetCount, token) =>
{
object storageState = null;
int? version;
if(choice.PreferStreaming)
{
//When streaming via ADO.NET, using CommandBehavior.SequentialAccess, the order of
//the columns on how they are read needs to be exactly this.
const int binaryColumnPositionInSelect = 0;
const int xmlColumnPositionInSelect = 1;
const int jsonColumnPositionInSelect = 2;
var streamSelector = (DbDataReader)selector;
if(!(await streamSelector.IsDBNullAsync(binaryColumnPositionInSelect)))
{
using(var downloadStream = streamSelector.GetStream(binaryColumnPositionInSelect, Storage))
{
storageState = choice.Deserializer.Deserialize(downloadStream, grainState.Type);
}
}
if(!(await streamSelector.IsDBNullAsync(xmlColumnPositionInSelect)))
{
using(var downloadStream = streamSelector.GetTextReader(xmlColumnPositionInSelect))
{
storageState = choice.Deserializer.Deserialize(downloadStream, grainState.Type);
}
}
if(!(await streamSelector.IsDBNullAsync(jsonColumnPositionInSelect)))
{
using(var downloadStream = streamSelector.GetTextReader(jsonColumnPositionInSelect))
{
storageState = choice.Deserializer.Deserialize(downloadStream, grainState.Type);
}
}
version = await streamSelector.GetValueAsync<int?>("Version");
}
else
{
//All but one of these should be null. All will be read and an appropriate deserializer picked.
//NOTE: When streaming will be implemented, it is worthwhile to optimize this so that the defined
//serializer will be picked and then streaming tried according to its tag.
object payload;
payload = selector.GetValueOrDefault<byte[]>("PayloadBinary");
if(payload == null)
{
payload = selector.GetValueOrDefault<string>("PayloadXml");
}
if(payload == null)
{
payload = selector.GetValueOrDefault<string>("PayloadJson");
}
if(payload != null)
{
storageState = choice.Deserializer.Deserialize(payload, grainState.Type);
}
version = selector.GetNullableInt32("Version");
}
return Tuple.Create(storageState, version?.ToString(CultureInfo.InvariantCulture));
}, CancellationToken.None, commandBehavior).ConfigureAwait(false)).SingleOrDefault();
object state = readRecords != null ? readRecords.Item1 : null;
string etag = readRecords != null ? readRecords.Item2 : null;
bool recordExists = readRecords != null;
if(state == null)
{
logger.Info((int)RelationalStorageProviderCodes.RelationalProviderNoStateFound, LogString("Null grain state read (default will be instantiated)", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
state = Activator.CreateInstance(grainState.Type);
}
grainState.State = state;
grainState.ETag = etag;
grainState.RecordExists = recordExists;
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderRead, LogString("Read grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
}
}
catch(Exception ex)
{
logger.Error((int)RelationalStorageProviderCodes.RelationalProviderReadError, LogString("Error reading grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString(), ex.Message), ex);
throw;
}
}
/// <summary> Write state data function for this storage provider.</summary>
/// <see cref="IGrainStorage.WriteStateAsync"/>
public async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
//It assumed these parameters are always valid. If not, an exception will be thrown, even if not as clear
//as with explicitly checked parameters.
var data = grainState.State;
var grainId = GrainIdAndExtensionAsString(grainReference);
var baseGrainType = ExtractBaseClass(grainType);
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderWriting, LogString("Writing grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
}
string storageVersion = null;
try
{
var grainIdHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(grainId.GetHashBytes());
var grainTypeHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(Encoding.UTF8.GetBytes(baseGrainType));
var writeRecord = await Storage.ReadAsync(CurrentOperationalQueries.WriteToStorage, command =>
{
command.AddParameter("GrainIdHash", grainIdHash);
command.AddParameter("GrainIdN0", grainId.N0Key);
command.AddParameter("GrainIdN1", grainId.N1Key);
command.AddParameter("GrainTypeHash", grainTypeHash);
command.AddParameter("GrainTypeString", baseGrainType);
command.AddParameter("GrainIdExtensionString", grainId.StringKey);
command.AddParameter("ServiceId", serviceId);
command.AddParameter("GrainStateVersion", !string.IsNullOrWhiteSpace(grainState.ETag) ? int.Parse(grainState.ETag, CultureInfo.InvariantCulture) : default(int?));
SerializationChoice serializer = StorageSerializationPicker.PickSerializer(serviceId, this.name, baseGrainType, grainReference, grainState);
command.AddParameter("PayloadBinary", (byte[])(serializer.Serializer.Tag == BinaryFormatSerializerTag ? serializer.Serializer.Serialize(data) : null));
command.AddParameter("PayloadJson", (string)(serializer.Serializer.Tag == JsonFormatSerializerTag ? serializer.Serializer.Serialize(data) : null));
command.AddParameter("PayloadXml", (string)(serializer.Serializer.Tag == XmlFormatSerializerTag ? serializer.Serializer.Serialize(data) : null));
}, (selector, resultSetCount, token) =>
{ return Task.FromResult(selector.GetNullableInt32("NewGrainStateVersion").ToString()); }, CancellationToken.None).ConfigureAwait(false);
storageVersion = writeRecord.SingleOrDefault();
}
catch(Exception ex)
{
logger.Error((int)RelationalStorageProviderCodes.RelationalProviderWriteError, LogString("Error writing grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString(), ex.Message), ex);
throw;
}
const string OperationString = "WriteState";
var inconsistentStateException = CheckVersionInconsistency(OperationString, serviceId, this.name, storageVersion, grainState.ETag, baseGrainType, grainId.ToString());
if(inconsistentStateException != null)
{
throw inconsistentStateException;
}
//No errors found, the version of the state held by the grain can be updated.
grainState.ETag = storageVersion;
grainState.RecordExists = true;
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderWrote, LogString("Wrote grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()));
}
}
/// <summary> Initialization function for this storage provider. </summary>
private async Task Init(CancellationToken cancellationToken)
{
this.serializer = providerRuntime.ServiceProvider.GetRequiredService<Serializer>();
//NOTE: StorageSerializationPicker should be defined outside and given as a parameter in constructor or via Init in IProviderConfiguration perhaps.
//Currently this limits one's options to much to the current situation of providing only one serializer for serialization and deserialization
//with no regard to state update or serializer changes. Maybe have this serialized as a JSON in props and read via a key?
StorageSerializationPicker = new DefaultRelationalStoragePicker(this.ConfigureDeserializers(options, providerRuntime), this.ConfigureSerializers(options, providerRuntime));
Storage = RelationalStorage.CreateInstance(options.Invariant, options.ConnectionString);
var queries = await Storage.ReadAsync(DefaultInitializationQuery, command => { }, (selector, resultSetCount, token) =>
{
return Task.FromResult(Tuple.Create(selector.GetValue<string>("QueryKey"), selector.GetValue<string>("QueryText")));
}).ConfigureAwait(false);
CurrentOperationalQueries = new RelationalStorageProviderQueries(
queries.Single(i => i.Item1 == "WriteToStorageKey").Item2,
queries.Single(i => i.Item1 == "ReadFromStorageKey").Item2,
queries.Single(i => i.Item1 == "ClearStorageKey").Item2);
logger.Info(
(int)RelationalStorageProviderCodes.RelationalProviderInitProvider,
$"Initialized storage provider: ServiceId={serviceId} ProviderName={this.name} Invariant={Storage.InvariantName} ConnectionString={ConfigUtilities.RedactConnectionStringInfo(Storage.ConnectionString)}.");
}
/// <summary>
/// Close this provider
/// </summary>
private Task Close(CancellationToken token)
{
return Task.CompletedTask;
}
/// <summary>
/// Checks for version inconsistency as defined in the database scripts.
/// </summary>
/// <param name="serviceId">Service Id.</param>
/// <param name="providerName">The name of this storage provider.</param>
/// <param name="operation">The operation attempted.</param>
/// <param name="storageVersion">The version from storage.</param>
/// <param name="grainVersion">The grain version.</param>
/// <param name="normalizedGrainType">Grain type without generics information.</param>
/// <param name="grainId">The grain ID.</param>
/// <returns>An exception for throwing or <em>null</em> if no violation was detected.</returns>
/// <remarks>This means that the version was not updated in the database or the version storage version was something else than null
/// when the grain version was null, meaning effectively a double activation and save.</remarks>
private static InconsistentStateException CheckVersionInconsistency(string operation, string serviceId, string providerName, string storageVersion, string grainVersion, string normalizedGrainType, string grainId)
{
//If these are the same, it means no row was inserted or updated in the storage.
//Effectively it means the UPDATE or INSERT conditions failed due to ETag violation.
//Also if grainState.ETag storageVersion is null and storage comes back as null,
//it means two grains were activated an the other one succeeded in writing its state.
//
//NOTE: the storage could return also the new and old ETag (Version), but currently it doesn't.
if(storageVersion == grainVersion || storageVersion == string.Empty)
{
//TODO: Note that this error message should be canonical across back-ends.
return new InconsistentStateException($"Version conflict ({operation}): ServiceId={serviceId} ProviderName={providerName} GrainType={normalizedGrainType} GrainId={grainId} ETag={grainVersion}.");
}
return null;
}
/// <summary>
/// Writes a consistent log message from the given parameters.
/// </summary>
/// <param name="operationProlog">A free form prolog information to log.</param>
/// <param name="serviceId">Service Id.</param>
/// <param name="providerName">The name of this storage provider.</param>
/// <param name="version">The grain version.</param>
/// <param name="normalizedGrainType">Grain type without generics information.</param>
/// <param name="grainId">The grain ID.</param>
/// <param name="exceptionMessage">An optional exception message information to log.</param>
/// <returns>A log string to be printed.</returns>
private string LogString(string operationProlog, string serviceId, string providerName, string version, string normalizedGrainType, string grainId, string exceptionMessage = null)
{
const string Exception = " Exception=";
return $"{operationProlog}: ServiceId={serviceId} ProviderName={providerName} GrainType={normalizedGrainType} GrainId={grainId} ETag={version}{(exceptionMessage != null ? Exception + exceptionMessage : string.Empty)}.";
}
/// <summary>
/// Extracts a grain ID as a string and appends the key extension with '#' infix is present.
/// </summary>
/// <param name="grainReference">The reference from which to extract the ID.</param>
/// <returns>The grain ID as a string.</returns>
/// <remarks>This likely should exist in Orleans core in more optimized form.</remarks>
private static AdoGrainKey GrainIdAndExtensionAsString(GrainReference grainReference)
{
//Kudos for https://github.com/tsibelman for the algorithm. See more at https://github.com/dotnet/orleans/issues/1905.
string keyExtension;
AdoGrainKey key;
if(grainReference.IsPrimaryKeyBasedOnLong())
{
key = new AdoGrainKey(grainReference.GetPrimaryKeyLong(out keyExtension), keyExtension);
}
else
{
key = new AdoGrainKey(grainReference.GetPrimaryKey(out keyExtension), keyExtension);
}
return key;
}
/// <summary>
/// Extracts a base class from a string that is either <see cref="Type.AssemblyQualifiedName"/> or
/// <see cref="Type.FullName"/> or returns the one given as a parameter if no type is given.
/// </summary>
/// <param name="typeName">The base class name to give.</param>
/// <returns>The extracted base class or the one given as a parameter if it didn't have a generic part.</returns>
private static string ExtractBaseClass(string typeName)
{
var genericPosition = typeName.IndexOf("`", StringComparison.OrdinalIgnoreCase);
if (genericPosition != -1)
{
//The following relies the generic argument list to be in form as described
//at https://msdn.microsoft.com/en-us/library/w3f99sx1.aspx.
var split = typeName.Split(BaseClassExtractionSplitDelimeters, StringSplitOptions.RemoveEmptyEntries);
var stripped = new Queue<string>(split.Where(i => i.Length > 1 && i[0] != ',').Select(WithoutAssemblyVersion));
return ReformatClassName(stripped);
}
return typeName;
string WithoutAssemblyVersion(string input)
{
var asmNameIndex = input.IndexOf(',');
if (asmNameIndex >= 0)
{
var asmVersionIndex = input.IndexOf(',', asmNameIndex + 1);
if (asmVersionIndex >= 0) return input.Substring(0, asmVersionIndex);
return input.Substring(0, asmNameIndex);
}
return input;
}
string ReformatClassName(Queue<string> segments)
{
var simpleTypeName = segments.Dequeue();
var arity = GetGenericArity(simpleTypeName);
if (arity <= 0) return simpleTypeName;
var args = new List<string>(arity);
for (var i = 0; i < arity; i++)
{
args.Add(ReformatClassName(segments));
}
return $"{simpleTypeName}[{string.Join(",", args.Select(arg => $"[{arg}]"))}]";
}
int GetGenericArity(string input)
{
var arityIndex = input.IndexOf("`", StringComparison.OrdinalIgnoreCase);
if (arityIndex != -1)
{
return int.Parse(input.Substring(arityIndex + 1));
}
return 0;
}
}
private ICollection<IStorageDeserializer> ConfigureDeserializers(AdoNetGrainStorageOptions options, IProviderRuntime providerRuntime)
{
var deserializers = new List<IStorageDeserializer>();
if(options.UseJsonFormat)
{
var jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(providerRuntime.ServiceProvider), options.UseFullAssemblyNames, options.IndentJson, options.TypeNameHandling);
options.ConfigureJsonSerializerSettings?.Invoke(jsonSettings);
deserializers.Add(new OrleansStorageDefaultJsonDeserializer(jsonSettings, JsonFormatSerializerTag));
}
if(options.UseXmlFormat)
{
deserializers.Add(new OrleansStorageDefaultXmlDeserializer(XmlFormatSerializerTag));
}
//if none are set true, configure binary format serializer by default
if(!options.UseXmlFormat && !options.UseJsonFormat)
{
deserializers.Add(new OrleansStorageDefaultBinaryDeserializer(this.serializer, BinaryFormatSerializerTag));
}
return deserializers;
}
private ICollection<IStorageSerializer> ConfigureSerializers(AdoNetGrainStorageOptions options, IProviderRuntime providerRuntime)
{
var serializers = new List<IStorageSerializer>();
if(options.UseJsonFormat)
{
var jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(providerRuntime.ServiceProvider),
options.UseFullAssemblyNames, options.IndentJson, options.TypeNameHandling);
options.ConfigureJsonSerializerSettings?.Invoke(jsonSettings);
serializers.Add(new OrleansStorageDefaultJsonSerializer(jsonSettings, JsonFormatSerializerTag));
}
if(options.UseXmlFormat)
{
serializers.Add(new OrleansStorageDefaultXmlSerializer(XmlFormatSerializerTag));
}
//if none are set true, configure binary format serializer by default
if (!options.UseXmlFormat && !options.UseJsonFormat)
{
serializers.Add(new OrleansStorageDefaultBinarySerializer(this.serializer, BinaryFormatSerializerTag));
}
return serializers;
}
}
}
| |
using ITGlobal.MarkDocs.Format.Impl.Extensions.Cut;
using ITGlobal.MarkDocs.Format.Impl.Metadata;
using ITGlobal.MarkDocs.Source;
using Markdig;
using Markdig.Renderers;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ITGlobal.MarkDocs.Format.Impl
{
/// <summary>
/// A parsed markdown page
/// </summary>
internal sealed class MarkdownPageContent : IPageContent
{
#region nested types
private readonly struct ValidateAnchorQueueItem
{
public ValidateAnchorQueueItem(string pageId, string hash, LinkInline link)
{
PageId = pageId;
Hash = hash;
Link = link;
}
public readonly string PageId;
public readonly string Hash;
public readonly LinkInline Link;
public void Deconstruct(out string pageId, out string hash, out LinkInline link)
{
pageId = PageId;
hash = Hash;
link = Link;
}
}
#endregion
#region fields
private readonly MarkdownDocument _ast;
private readonly MarkdownPipeline _pipeline;
private readonly Queue<ValidateAnchorQueueItem> _validateAnchorsQueue;
private readonly int? _cutBlockIndex;
#endregion
#region .ctor
private MarkdownPageContent(
MarkdownDocument ast,
MarkdownPipeline pipeline,
Queue<ValidateAnchorQueueItem> validateAnchorsQueue,
PageMetadata metadata,
PageAnchors anchors,
int? cutBlockIndex)
{
_ast = ast;
_pipeline = pipeline;
_validateAnchorsQueue = validateAnchorsQueue;
Metadata = metadata;
Anchors = anchors;
_cutBlockIndex = cutBlockIndex;
}
#endregion
#region factory
public static MarkdownPageContent Read(
IPageReadContext ctx,
IMetadataExtractor metadataExtractor,
MarkdownPipeline pipeline,
string markup)
{
using (MarkdownPageReadContext.Use(ctx))
{
// Parse AST
var ast = Markdown.Parse(markup, pipeline);
// Resolve and rewrite URL in links and images
RewriteLinkUrls(ctx, ast, out var validateAnchorsQueue);
// Extract metadata from AST
var metadata = metadataExtractor.Extract(ctx, ast);
var anchors = new PageAnchors(PageAnchorReader.Read(ast));
// Try generate a preview AST
var (cutBlock, cutBlockIndex) = ast
.Select((b, i) => (block: b, index: i))
.FirstOrDefault(_ => _.block is CutBlock);
return new MarkdownPageContent(
ast,
pipeline,
validateAnchorsQueue,
metadata,
anchors,
cutBlock != null ? cutBlockIndex : (int?) null
);
}
}
#endregion
#region properties
public PageMetadata Metadata { get; }
public PageAnchors Anchors { get; }
/// <summary>
/// true if page contains a "cut" separator
/// </summary>
public bool HasPreview => _cutBlockIndex != null;
#endregion
#region url resolution
private static void RewriteLinkUrls(
IPageReadContext ctx,
MarkdownDocument ast,
out Queue<ValidateAnchorQueueItem> validateAnchorsQueue)
{
validateAnchorsQueue = new Queue<ValidateAnchorQueueItem>();
foreach (var link in ast.Descendants().OfType<LinkInline>())
{
if (link.IsRewrittenLink())
{
continue;
}
var (url, anchor) = ctx.ResolveResourceUrl(link.Url, link.Line);
if (url != null)
{
link.Url = url;
link.SetIsRewrittenLink();
}
if (anchor != null)
{
validateAnchorsQueue.Enqueue(new ValidateAnchorQueueItem(ctx.Page.Id, anchor, link));
}
}
}
#endregion
#region rendering
/// <summary>
/// Renders page into HTML
/// </summary>
public string Render(IPageRenderContext ctx)
{
using (MarkdownPageRenderContext.Use(ctx))
{
string html;
using (var writer = new StringWriter())
{
var renderer = new HtmlRenderer(writer);
_pipeline.Setup(renderer);
renderer.Render(_ast);
writer.Flush();
html = writer.ToString();
}
return html;
}
}
/// <summary>
/// Renders page preview into HTML
/// </summary>
public string RenderPreview(IPageRenderContext ctx)
{
if (_cutBlockIndex == null)
{
throw new Exception("This page doesn't have a preview");
}
using (MarkdownPageRenderContext.Use(ctx))
{
string html;
using (var writer = new StringWriter())
{
var renderer = new HtmlRenderer(writer);
_pipeline.Setup(renderer);
for (var i = 0; i < _cutBlockIndex.Value; i++)
{
renderer.Render(_ast[i]);
}
writer.Flush();
html = writer.ToString();
}
return html;
}
}
/// <summary>
/// Runs page content validation
/// </summary>
public void Validate(IPageValidateContext ctx, AssetTree assetTree)
{
while (_validateAnchorsQueue.Count > 0)
{
var (pageId, hash, link) = _validateAnchorsQueue.Dequeue();
ValidateAnchorLink(ctx, assetTree, link, pageId, hash);
}
}
private void ValidateAnchorLink(
IPageValidateContext ctx,
AssetTree assetTree,
LinkInline link,
string url,
string hash)
{
var page = assetTree.TryGetAsset(url) as PageAsset;
if (page == null)
{
ctx.Error($"Invalid hyperlink \"{link.Url}\"", link.Line);
return;
}
if (page.Content.Anchors == null ||
page.Content.Anchors[hash] == null)
{
ctx.Error(
$"Anchor #{hash} doesn't exist on page \"{page.RelativePath}\"",
link.Line
);
}
else if (page.Id == ctx.Page.Id && link.Url != $"#{hash}")
{
var text = link.GetText();
ctx.Warning(
$"Link [{text}]({url}#{hash}) can be replaced with [{text}](#{hash})",
link.Line
);
}
}
#endregion
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// James Driscoll, mailto:[email protected]
// with contributions from Hath1
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: OracleErrorLog.cs 642 2009-06-01 17:41:53Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Data;
using System.Data.OracleClient;
using System.IO;
using System.Text;
using IDictionary = System.Collections.IDictionary;
using System.Collections.Generic;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses Oracle as its backing store.
/// </summary>
public class OracleErrorLog : ErrorLog
{
private readonly string _connectionString;
private readonly string _schemaOwner;
private const int _maxAppNameLength = 60;
private const int _maxSchemaNameLength = 30;
/// <summary>
/// Initializes a new instance of the <see cref="OracleErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public OracleErrorLog(IDictionary config)
{
if (config == null)
throw new ArgumentNullException("config");
string connectionString = ConnectionStringHelper.GetConnectionString(config);
//
// If there is no connection string to use then throw an
// exception to abort construction.
//
if (connectionString.Length == 0)
throw new ApplicationException("Connection string is missing for the Oracle error log.");
_connectionString = connectionString;
//
// Set the application name as this implementation provides
// per-application isolation over a single store.
//
var appName = config.Find("applicationName", string.Empty);
if (appName.Length > _maxAppNameLength)
{
throw new ApplicationException(string.Format(
"Application name is too long. Maximum length allowed is {0} characters.",
_maxAppNameLength.ToString("N0")));
}
ApplicationName = appName;
_schemaOwner = config.Find("schemaOwner", string.Empty);
if(_schemaOwner.Length > _maxSchemaNameLength)
{
throw new ApplicationException(string.Format(
"Oracle schema owner is too long. Maximum length allowed is {0} characters.",
_maxSchemaNameLength.ToString("N0")));
}
if (_schemaOwner.Length > 0)
_schemaOwner = _schemaOwner + ".";
}
/// <summary>
/// Initializes a new instance of the <see cref="OracleErrorLog"/> class
/// to use a specific connection string for connecting to the database.
/// </summary>
public OracleErrorLog(string connectionString)
{
if (connectionString == null)
throw new ArgumentNullException("connectionString");
if (connectionString.Length == 0)
throw new ArgumentException(null, "connectionString");
_connectionString = connectionString;
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "Oracle Error Log"; }
}
/// <summary>
/// Gets the connection string used by the log to connect to the database.
/// </summary>
public virtual string ConnectionString
{
get { return _connectionString; }
}
/// <summary>
/// Logs an error to the database.
/// </summary>
/// <remarks>
/// Use the stored procedure called by this implementation to set a
/// policy on how long errors are kept in the log. The default
/// implementation stores all errors for an indefinite time.
/// </remarks>
public override string Log(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
string errorXml = ErrorXml.EncodeString(error);
Guid id = Guid.NewGuid();
using (OracleConnection connection = new OracleConnection(this.ConnectionString))
using (OracleCommand command = connection.CreateCommand())
{
connection.Open();
using (OracleTransaction transaction = connection.BeginTransaction())
{
// because we are storing the XML data in a NClob, we need to jump through a few hoops!!
// so first we've got to operate within a transaction
command.Transaction = transaction;
// then we need to create a temporary lob on the database server
command.CommandText = "declare xx nclob; begin dbms_lob.createtemporary(xx, false, 0); :tempblob := xx; end;";
command.CommandType = CommandType.Text;
OracleParameterCollection parameters = command.Parameters;
parameters.Add("tempblob", OracleType.NClob).Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
// now we can get a handle to the NClob
OracleLob xmlLob = (OracleLob)parameters[0].Value;
// create a temporary buffer in which to store the XML
byte[] tempbuff = Encoding.Unicode.GetBytes(errorXml);
// and finally we can write to it!
xmlLob.BeginBatch(OracleLobOpenMode.ReadWrite);
xmlLob.Write(tempbuff,0,tempbuff.Length);
xmlLob.EndBatch();
command.CommandText = _schemaOwner + "pkg_elmah$log_error.LogError";
command.CommandType = CommandType.StoredProcedure;
parameters.Clear();
parameters.Add("v_ErrorId", OracleType.NVarChar, 32).Value = id.ToString("N");
parameters.Add("v_Application", OracleType.NVarChar, _maxAppNameLength).Value = ApplicationName;
parameters.Add("v_Host", OracleType.NVarChar, 30).Value = error.HostName;
parameters.Add("v_Type", OracleType.NVarChar, 100).Value = error.Type;
parameters.Add("v_Source", OracleType.NVarChar, 60).Value = error.Source;
parameters.Add("v_Message", OracleType.NVarChar, 500).Value = error.Message;
parameters.Add("v_User", OracleType.NVarChar, 50).Value = error.User;
parameters.Add("v_AllXml", OracleType.NClob).Value = xmlLob;
parameters.Add("v_StatusCode", OracleType.Int32).Value = error.StatusCode;
parameters.Add("v_TimeUtc", OracleType.DateTime).Value = error.Time.ToUniversalTime();
command.ExecuteNonQuery();
transaction.Commit();
}
return id.ToString();
}
}
/// <summary>
/// Returns a page of errors from the databse in descending order
/// of logged time.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
using (OracleConnection connection = new OracleConnection(this.ConnectionString))
using (OracleCommand command = connection.CreateCommand())
{
command.CommandText = _schemaOwner + "pkg_elmah$get_error.GetErrorsXml";
command.CommandType = CommandType.StoredProcedure;
OracleParameterCollection parameters = command.Parameters;
parameters.Add("v_Application", OracleType.NVarChar, _maxAppNameLength).Value = ApplicationName;
parameters.Add("v_PageIndex", OracleType.Int32).Value = pageIndex;
parameters.Add("v_PageSize", OracleType.Int32).Value = pageSize;
parameters.Add("v_TotalCount", OracleType.Int32).Direction = ParameterDirection.Output;
parameters.Add("v_Results", OracleType.Cursor).Direction = ParameterDirection.Output;
connection.Open();
using (OracleDataReader reader = command.ExecuteReader())
{
Debug.Assert(reader != null);
if (errorEntryList != null)
{
while (reader.Read())
{
var id = reader["ErrorId"].ToString();
var guid = new Guid(id);
var error = new Error
{
ApplicationName = reader["Application"].ToString(),
HostName = reader["Host"].ToString(),
Type = reader["Type"].ToString(),
Source = reader["Source"].ToString(),
Message = reader["Message"].ToString(),
User = reader["UserName"].ToString(),
StatusCode = Convert.ToInt32(reader["StatusCode"]),
Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime()
};
errorEntryList.Add(new ErrorLogEntry(this, guid.ToString(), error));
}
}
reader.Close();
}
return (int)command.Parameters["v_TotalCount"].Value;
}
}
/// <summary>
/// Returns the specified error from the database, or null
/// if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
if (id == null)
throw new ArgumentNullException("id");
if (id.Length == 0)
throw new ArgumentException(null, "id");
Guid errorGuid;
try
{
errorGuid = new Guid(id);
}
catch (FormatException e)
{
throw new ArgumentException(e.Message, "id", e);
}
string errorXml;
using (OracleConnection connection = new OracleConnection(this.ConnectionString))
using (OracleCommand command = connection.CreateCommand())
{
command.CommandText = _schemaOwner + "pkg_elmah$get_error.GetErrorXml";
command.CommandType = CommandType.StoredProcedure;
OracleParameterCollection parameters = command.Parameters;
parameters.Add("v_Application", OracleType.NVarChar, _maxAppNameLength).Value = ApplicationName;
parameters.Add("v_ErrorId", OracleType.NVarChar, 32).Value = errorGuid.ToString("N");
parameters.Add("v_AllXml", OracleType.NClob).Direction = ParameterDirection.Output;
connection.Open();
command.ExecuteNonQuery();
OracleLob xmlLob = (OracleLob)command.Parameters["v_AllXml"].Value;
StreamReader streamreader = new StreamReader(xmlLob, Encoding.Unicode);
char[] cbuffer = new char[1000];
int actual;
StringBuilder sb = new StringBuilder();
while((actual = streamreader.Read(cbuffer, 0, cbuffer.Length)) >0)
sb.Append(cbuffer, 0, actual);
errorXml = sb.ToString();
}
if (errorXml == null)
return null;
Error error = ErrorXml.DecodeString(errorXml);
return new ErrorLogEntry(this, id, error);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
public struct MethodDefinition
{
private readonly MetadataReader _reader;
// Workaround: JIT doesn't generate good code for nested structures, so use RowId.
private readonly uint _treatmentAndRowId;
internal MethodDefinition(MetadataReader reader, uint treatmentAndRowId)
{
Debug.Assert(reader != null);
Debug.Assert(treatmentAndRowId != 0);
_reader = reader;
_treatmentAndRowId = treatmentAndRowId;
}
private int RowId
{
get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); }
}
private MethodDefTreatment Treatment
{
get { return (MethodDefTreatment)(_treatmentAndRowId >> TokenTypeIds.RowIdBitCount); }
}
private MethodDefinitionHandle Handle
{
get { return MethodDefinitionHandle.FromRowId(RowId); }
}
public StringHandle Name
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetName(Handle);
}
return GetProjectedName();
}
}
public BlobHandle Signature
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetSignature(Handle);
}
return GetProjectedSignature();
}
}
public int RelativeVirtualAddress
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetRva(Handle);
}
return GetProjectedRelativeVirtualAddress();
}
}
public MethodAttributes Attributes
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetFlags(Handle);
}
return GetProjectedFlags();
}
}
public MethodImplAttributes ImplAttributes
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetImplFlags(Handle);
}
return GetProjectedImplFlags();
}
}
public TypeDefinitionHandle GetDeclaringType()
{
return _reader.GetDeclaringType(Handle);
}
public ParameterHandleCollection GetParameters()
{
return new ParameterHandleCollection(_reader, Handle);
}
public GenericParameterHandleCollection GetGenericParameters()
{
return _reader.GenericParamTable.FindGenericParametersForMethod(Handle);
}
public MethodImport GetImport()
{
int implMapRid = _reader.ImplMapTable.FindImplForMethod(Handle);
if (implMapRid == 0)
{
return default(MethodImport);
}
return _reader.ImplMapTable.GetImport(implMapRid);
}
public CustomAttributeHandleCollection GetCustomAttributes()
{
return new CustomAttributeHandleCollection(_reader, Handle);
}
public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes()
{
return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle);
}
#region Projections
private StringHandle GetProjectedName()
{
if ((Treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.DisposeMethod)
{
return StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.Dispose);
}
return _reader.MethodDefTable.GetName(Handle);
}
private MethodAttributes GetProjectedFlags()
{
MethodAttributes flags = _reader.MethodDefTable.GetFlags(Handle);
MethodDefTreatment treatment = Treatment;
if ((treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.HiddenInterfaceImplementation)
{
flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Private;
}
if ((treatment & MethodDefTreatment.MarkAbstractFlag) != 0)
{
flags |= MethodAttributes.Abstract;
}
if ((treatment & MethodDefTreatment.MarkPublicFlag) != 0)
{
flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public;
}
return flags | MethodAttributes.HideBySig;
}
private MethodImplAttributes GetProjectedImplFlags()
{
MethodImplAttributes flags = _reader.MethodDefTable.GetImplFlags(Handle);
switch (Treatment & MethodDefTreatment.KindMask)
{
case MethodDefTreatment.DelegateMethod:
flags |= MethodImplAttributes.Runtime;
break;
case MethodDefTreatment.DisposeMethod:
case MethodDefTreatment.AttributeMethod:
case MethodDefTreatment.InterfaceMethod:
case MethodDefTreatment.HiddenInterfaceImplementation:
case MethodDefTreatment.Other:
flags |= MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall;
break;
}
return flags;
}
private BlobHandle GetProjectedSignature()
{
return _reader.MethodDefTable.GetSignature(Handle);
}
private int GetProjectedRelativeVirtualAddress()
{
return 0;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
class Program
{
static int Main()
{
TestDictionaryDependencyTracking.Run();
TestStaticBaseLookups.Run();
TestInitThisClass.Run();
TestDelegateFatFunctionPointers.Run();
TestDelegateToCanonMethods.Run();
TestVirtualMethodUseTracking.Run();
TestSlotsInHierarchy.Run();
TestReflectionInvoke.Run();
TestDelegateVirtualMethod.Run();
TestDelegateInterfaceMethod.Run();
TestThreadStaticFieldAccess.Run();
TestConstrainedMethodCalls.Run();
TestInstantiatingUnboxingStubs.Run();
TestMDArrayAddressMethod.Run();
TestNameManglingCollisionRegression.Run();
TestSimpleGVMScenarios.Run();
TestGvmDependencies.Run();
return 100;
}
/// <summary>
/// Tests that we properly track dictionary dependencies of generic methods.
/// (Getting this wrong is a linker failure.)
/// </summary>
class TestDictionaryDependencyTracking
{
static object Gen1<T>()
{
return MakeArray<ClassGen<T>>();
}
static object MakeArray<T>()
{
return new T[0];
}
class Gen<T>
{
public object Frob()
{
return new ValueGen<T[]>();
}
public object Futz()
{
return Gen1<ValueGen<T>>();
}
}
struct ValueGen<T>
{
}
class ClassGen<T>
{
}
public static void Run()
{
new Gen<string>().Frob();
new Gen<object>().Futz();
}
}
/// <summary>
/// Tests static base access.
/// </summary>
class TestStaticBaseLookups
{
class C1 { }
class C2 { }
class C3 { }
class GenHolder<T>
{
public static int IntField;
public static string StringField;
}
class GenAccessor<T>
{
public static string Read()
{
return GenHolder<T>.IntField.ToString() + GenHolder<T>.StringField;
}
public static void SetSimple(int i, string s)
{
GenHolder<T>.IntField = i;
GenHolder<T>.StringField = s;
}
public static void SetComplex<U>(int i, string s)
{
GenHolder<T>.IntField = i;
GenHolder<T>.StringField = s;
GenHolder<U>.IntField = i + 1;
GenHolder<U>.StringField = s + "`";
}
}
public static void Run()
{
GenAccessor<C1>.SetComplex<C2>(42, "Hello");
GenAccessor<C3>.SetSimple(85, "World");
if (GenAccessor<C1>.Read() != "42Hello")
throw new Exception();
if (GenHolder<C2>.IntField != 43 || GenHolder<C2>.StringField != "Hello`")
throw new Exception();
if (GenAccessor<C3>.Read() != "85World")
throw new Exception();
}
}
/// <summary>
/// Tests that we can use a delegate that points to a generic method.
/// </summary>
class TestDelegateFatFunctionPointers
{
struct SmallStruct
{
public int X;
}
struct MediumStruct
{
public int X, Y, Z, W;
}
unsafe struct BigStruct
{
public const int Length = 128;
public fixed byte Bytes[Length];
}
T Generic<T>(object o) where T : class
{
Func<object, T> f = OtherGeneric<T>;
return f(o);
}
T OtherGeneric<T>(object o) where T : class
{
return o as T;
}
delegate void VoidGenericDelegate<T>(ref T x, T val);
void VoidGeneric<T>(ref T x, T val)
{
x = val;
}
SmallStruct SmallStructGeneric<T>(SmallStruct x)
{
return x;
}
MediumStruct MediumStructGeneric<T>(MediumStruct x)
{
return x;
}
BigStruct BigStructGeneric<T>(BigStruct x)
{
return x;
}
public static void Run()
{
var o = new TestDelegateFatFunctionPointers();
string hw = "Hello World";
string roundtrip = o.Generic<string>(hw);
if (roundtrip != hw)
throw new Exception();
{
VoidGenericDelegate<object> f = o.VoidGeneric;
object obj = new object();
object location = null;
f(ref location, obj);
if (location != obj)
throw new Exception();
}
{
Func<SmallStruct, SmallStruct> f = o.SmallStructGeneric<object>;
SmallStruct x = new SmallStruct { X = 12345 };
SmallStruct result = f(x);
if (result.X != x.X)
throw new Exception();
}
{
Func<MediumStruct, MediumStruct> f = o.MediumStructGeneric<object>;
MediumStruct x = new MediumStruct { X = 12, Y = 34, Z = 56, W = 78 };
MediumStruct result = f(x);
if (result.X != x.X || result.Y != x.Y || result.Z != x.Z || result.W != x.W)
throw new Exception();
}
unsafe
{
Func<BigStruct, BigStruct> f = o.BigStructGeneric<object>;
BigStruct x = new BigStruct();
for (int i = 0; i < BigStruct.Length; i++)
x.Bytes[i] = (byte)(i * 2);
BigStruct result = f(x);
for (int i = 0; i < BigStruct.Length; i++)
if (x.Bytes[i] != result.Bytes[i])
throw new Exception();
}
}
}
class TestDelegateToCanonMethods
{
class Foo
{
public readonly int Value;
public Foo(int value)
{
Value = value;
}
public override string ToString()
{
return Value.ToString();
}
}
class Bar
{
public readonly int Value;
public Bar(int value)
{
Value = value;
}
public override string ToString()
{
return Value.ToString();
}
}
class GenClass<T>
{
public readonly T X;
public GenClass(T x)
{
X = x;
}
public string MakeString()
{
// Use a constructed type that is not used elsewhere
return typeof(T[,]).GetElementType().Name + ": " + X.ToString();
}
public string MakeGenString<U>()
{
// Use a constructed type that is not used elsewhere
return typeof(T[,,]).GetElementType().Name + ", " +
typeof(U[,,,]).GetElementType().Name + ": " + X.ToString();
}
}
struct GenStruct<T>
{
public readonly T X;
public GenStruct(T x)
{
X = x;
}
public string MakeString()
{
// Use a constructed type that is not used elsewhere
return typeof(T[,]).GetElementType().Name + ": " + X.ToString();
}
public string MakeGenString<U>()
{
// Use a constructed type that is not used elsewhere
return typeof(T[,,]).GetElementType().Name + ", " +
typeof(U[,,,]).GetElementType().Name + ": " + X.ToString();
}
}
public static void Run()
{
// Delegate to a shared nongeneric reference type instance method
{
GenClass<Foo> g = new GenClass<Foo>(new Foo(42));
Func<string> f = g.MakeString;
if (f() != "Foo: 42")
throw new Exception();
}
// Delegate to a unshared nongeneric reference type instance method
{
GenClass<int> g = new GenClass<int>(85);
Func<string> f = g.MakeString;
if (f() != "Int32: 85")
throw new Exception();
}
// Delegate to a shared generic reference type instance method
{
GenClass<Foo> g = new GenClass<Foo>(new Foo(42));
Func<string> f = g.MakeGenString<Foo>;
if (f() != "Foo, Foo: 42")
throw new Exception();
}
// Delegate to a unshared generic reference type instance method
{
GenClass<int> g = new GenClass<int>(85);
Func<string> f = g.MakeGenString<int>;
if (f() != "Int32, Int32: 85")
throw new Exception();
}
// Delegate to a shared nongeneric value type instance method
/*{
GenStruct<Bar> g = new GenStruct<Bar>(new Bar(42));
Func<string> f = g.MakeString;
if (f() != "Bar: 42")
throw new Exception();
}*/
// Delegate to a unshared nongeneric value type instance method
{
GenStruct<int> g = new GenStruct<int>(85);
Func<string> f = g.MakeString;
if (f() != "Int32: 85")
throw new Exception();
}
// Delegate to a shared generic value type instance method
/*{
GenStruct<Bar> g = new GenStruct<Bar>(new Bar(42));
Func<string> f = g.MakeGenString<Bar>;
if (f() != "Bar, Bar: 42")
throw new Exception();
}*/
// Delegate to a unshared generic value type instance method
{
GenStruct<int> g = new GenStruct<int>(85);
Func<string> f = g.MakeGenString<int>;
if (f() != "Int32, Int32: 85")
throw new Exception();
}
}
}
class TestDelegateVirtualMethod
{
static void Generic<T>()
{
Base<T> o = new Derived<T>();
Func<string> f = o.Do;
if (f() != "Derived")
throw new Exception();
o = new Base<T>();
f = o.Do;
if (f() != "Base")
throw new Exception();
}
public static void Run()
{
Generic<string>();
}
class Base<T>
{
public virtual string Do() => "Base";
}
class Derived<T> : Base<T>
{
public override string Do() => "Derived";
}
}
class TestDelegateInterfaceMethod
{
static void Generic<T>()
{
IFoo<T> o = new Foo<T>();
Func<string> f = o.Do;
if (f() != "Foo")
throw new Exception();
}
public static void Run()
{
Generic<string>();
}
interface IFoo<T>
{
string Do();
}
class Foo<T> : IFoo<T>
{
public string Do() => "Foo";
}
}
/// <summary>
/// Tests RyuJIT's initThisClass.
/// </summary>
class TestInitThisClass
{
class Gen1<T> where T : class
{
static string s_str1;
static string s_str2;
static Gen1()
{
s_str1 = ("Hello" as T) as string;
s_str2 = ("World" as T) as string;
}
public static string Get1()
{
return (s_str1 as T) as string;
}
public static string Get2<U>()
{
return (s_str2 as T) as string;
}
}
class Gen2<T> where T : class
{
public static string GetFromClassParam()
{
return (Gen1<T>.Get1() as T) as string;
}
public static string GetFromMethodParam()
{
return (Gen1<T>.Get2<T>() as T) as string;
}
}
class NonGeneric
{
public static readonly string Message;
static NonGeneric()
{
Message = "Hi there";
}
public static string Get<T>(object o)
{
if (o is T[])
return Message;
return null;
}
}
public static void Run()
{
if (Gen2<string>.GetFromClassParam() != "Hello")
throw new Exception();
if (Gen2<string>.GetFromMethodParam() != "World")
throw new Exception();
if (NonGeneric.Get<object>(new object[0]) != "Hi there")
throw new Exception();
}
}
/// <summary>
/// Tests that lazily built vtables for canonically equivalent types have the same shape.
/// </summary>
class TestVirtualMethodUseTracking
{
class C1 { }
class C2 { }
class Base<T> where T : class
{
public virtual T As(object o)
{
return o as T;
}
}
class Derived<T> : Base<T> where T : class
{
public T AsToo(object o)
{
return o as T;
}
}
public static void Run()
{
C1 c1 = new C1();
if (new Derived<C1>().As(c1) != c1)
throw new Exception();
C2 c2 = new C2();
if (new Derived<C2>().AsToo(c2) != c2)
throw new Exception();
}
}
/// <summary>
/// Makes sure that during the base slot computation for types such as
/// Derived<__Canon> (where the base type ends up being Base<__Canon, string>),
/// the lazy vtable slot computation works.
/// </summary>
class TestSlotsInHierarchy
{
class Base<T, U>
{
public virtual int Do()
{
return 42;
}
}
class Derived<T> : Base<T, string> where T : class
{
public T Cast(object v)
{
return v as T;
}
}
public static void Run()
{
var derived = new Derived<string>();
var derivedAsBase = (Base<string, string>)derived;
if (derivedAsBase.Do() != 42)
throw new Exception();
if (derived.Cast("Hello") != "Hello")
throw new Exception();
}
}
class TestReflectionInvoke
{
struct Foo<T>
{
public int Value;
[MethodImpl(MethodImplOptions.NoInlining)]
public bool SetAndCheck<U>(int value, U check)
{
Value = value;
return check != null && typeof(T) == typeof(U);
}
}
public static void Run()
{
if (String.Empty.Length > 0)
{
// Make sure we compile this method body.
var tmp = new Foo<string>();
tmp.SetAndCheck<string>(0, null);
}
object o = new Foo<string>();
{
MethodInfo mi = typeof(Foo<string>).GetTypeInfo().GetDeclaredMethod("SetAndCheck").MakeGenericMethod(typeof(string));
if (!(bool)mi.Invoke(o, new object[] { 123, "hello" }))
throw new Exception();
var foo = (Foo<string>)o;
if (foo.Value != 123)
throw new Exception();
if ((bool)mi.Invoke(o, new object[] { 123, null }))
throw new Exception();
}
// Uncomment when we have the type loader to buld invoke stub dictionaries.
/*{
MethodInfo mi = typeof(Foo<string>).GetTypeInfo().GetDeclaredMethod("SetAndCheck").MakeGenericMethod(typeof(object));
if ((bool)mi.Invoke(o, new object[] { 123, new object() }))
throw new Exception();
}*/
}
}
class TestThreadStaticFieldAccess
{
class TypeWithThreadStaticField<T>
{
[ThreadStatic]
public static int X;
[MethodImpl(MethodImplOptions.NoInlining)]
public static int Read()
{
return X;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Write(int x)
{
X = x;
}
}
class BeforeFieldInitType<T>
{
[ThreadStatic]
public static int X = 1985;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static int ReadFromBeforeFieldInitType<T>()
{
return BeforeFieldInitType<T>.X;
}
public static void Run()
{
// This will set the field to a value from non-shared code
TypeWithThreadStaticField<object>.X = 42;
// Now read the value from shared code
if (TypeWithThreadStaticField<object>.Read() != 42)
throw new Exception();
// Set the value from shared code
TypeWithThreadStaticField<string>.Write(112);
// Now read the value from non-shared code
if (TypeWithThreadStaticField<string>.X != 112)
throw new Exception();
// Check that the storage locations for string and object instantiations differ
if (TypeWithThreadStaticField<object>.Read() != 42)
throw new Exception();
// Make sure we run the cctor
if (ReadFromBeforeFieldInitType<object>() != 1985)
throw new Exception();
}
}
class TestConstrainedMethodCalls
{
interface IFoo<T>
{
void Frob();
}
struct Foo<T> : IFoo<T>
{
public int FrobbedValue;
public void Frob()
{
FrobbedValue = 12345;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void DoFrob<T, U>(ref T t) where T : IFoo<U>
{
// Perform a constrained interface call from shared code.
// This should have been resolved to a direct call at compile time.
t.Frob();
}
public static void Run()
{
var foo = new Foo<object>();
DoFrob<Foo<object>, object>(ref foo);
// If the FrobbedValue doesn't change when we frob, we must have done box+interface call.
if (foo.FrobbedValue != 12345)
throw new Exception();
}
}
class TestInstantiatingUnboxingStubs
{
static volatile IFoo s_foo;
interface IFoo
{
bool IsInst(object o);
void Set(int value);
}
struct Foo<T> : IFoo
{
public int Value;
public bool IsInst(object o)
{
return o is T;
}
public void Set(int value)
{
Value = value;
}
}
public static void Run()
{
s_foo = new Foo<string>();
// Make sure the instantiation argument is properly passed
if (!s_foo.IsInst("ab"))
throw new Exception();
if (s_foo.IsInst(new object()))
throw new Exception();
// Make sure the byref to 'this' is properly passed
s_foo.Set(42);
var foo = (Foo<string>)s_foo;
if (foo.Value != 42)
throw new Exception();
}
}
class TestMDArrayAddressMethod
{
[MethodImpl(MethodImplOptions.NoInlining)]
private static void PassByRef(ref object x)
{
x = new Object();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void DoGen<T>(object[,] arr)
{
// Here, the array type is known statically at the time of compilation
PassByRef(ref arr[0, 0]);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void PassByRef2<T>(ref T x)
{
x = default(T);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void DoGen2<T>(T[,] arr)
{
// Here, the array type needs to be looked up from the dictionary
PassByRef2<T>(ref arr[0, 0]);
}
public static void Run()
{
int exceptionsSeen = 0;
try
{
DoGen<object>(new string[1, 1]);
}
catch (ArrayTypeMismatchException)
{
exceptionsSeen++;
}
DoGen<object>(new object[1, 1]);
try
{
DoGen2<object>(new string[1, 1]);
}
catch (ArrayTypeMismatchException)
{
exceptionsSeen++;
}
DoGen2<object>(new object[1, 1]);
if (exceptionsSeen != 2)
throw new Exception();
}
}
//
// Regression test for issue https://github.com/dotnet/corert/issues/1964
//
class TestNameManglingCollisionRegression
{
class Gen1<T>
{
public Gen1(T t) {}
}
public static void Run()
{
Gen1<object[]>[] g1 = new Gen1<object[]>[1];
g1[0] = new Gen1<object[]>(new object[] {new object[1]});
Gen1<object[][]> g2 = new Gen1<object[][]>(new object[1][]);
}
}
class TestSimpleGVMScenarios
{
interface IFoo<out U>
{
string IMethod1<T>(T t1, T t2);
}
class Base : IFoo<string>, IFoo<int>
{
public virtual string GMethod1<T>(T t1, T t2) { return "Base.GMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
public virtual string IMethod1<T>(T t1, T t2) { return "Base.IMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
}
class Derived : Base, IFoo<string>, IFoo<int>
{
public override string GMethod1<T>(T t1, T t2) { return "Derived.GMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
string IFoo<string>.IMethod1<T>(T t1, T t2) { return "Derived.IFoo<string>.IMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
}
class SuperDerived : Derived, IFoo<string>, IFoo<int>
{
string IFoo<int>.IMethod1<T>(T t1, T t2) { return "SuperDerived.IFoo<int>.IMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
}
class GenBase<A> : IFoo<string>, IFoo<int>
{
public virtual string GMethod1<T>(T t1, T t2) { return "GenBase<" + typeof(A) + ">.GMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
public virtual string IMethod1<T>(T t1, T t2) { return "GenBase<" + typeof(A) + ">.IMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
}
class GenDerived<A> : GenBase<A>, IFoo<string>, IFoo<int>
{
public override string GMethod1<T>(T t1, T t2) { return "GenDerived<" + typeof(A) + ">.GMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
string IFoo<string>.IMethod1<T>(T t1, T t2) { return "GenDerived<" + typeof(A) + ">.IFoo<string>.IMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
}
class GenSuperDerived<A> : GenDerived<A>, IFoo<string>, IFoo<int>
{
string IFoo<int>.IMethod1<T>(T t1, T t2) { return "GenSuperDerived<" + typeof(A) + ">.IFoo<int>.IMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
}
struct MyStruct1 : IFoo<string>, IFoo<int>
{
string IFoo<string>.IMethod1<T>(T t1, T t2) { return "MyStruct1.IFoo<string>.IMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
string IFoo<int>.IMethod1<T>(T t1, T t2) { return "MyStruct1.IFoo<int>.IMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
}
struct MyStruct2 : IFoo<string>, IFoo<int>
{
string IFoo<string>.IMethod1<T>(T t1, T t2) { return "MyStruct2.IFoo<string>.IMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
public string IMethod1<T>(T t1, T t2) { return "MyStruct2.IMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
}
struct MyStruct3 : IFoo<string>, IFoo<int>
{
string IFoo<int>.IMethod1<T>(T t1, T t2) { return "MyStruct3.IFoo<int>.IMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
public string IMethod1<T>(T t1, T t2) { return "MyStruct3.IMethod1<" + typeof(T) + ">(" + t1 + "," + t2 + ")"; }
}
static string s_GMethod1;
static string s_IFooString;
static string s_IFooObject;
static string s_IFooInt;
static int s_NumErrors = 0;
private static void TestWithStruct(IFoo<string> ifooStr, IFoo<object> ifooObj, IFoo<int> ifooInt)
{
var res = ifooStr.IMethod1<int>(1, 2);
WriteLineWithVerification(res, s_IFooString);
res = ifooObj.IMethod1<int>(3, 4);
WriteLineWithVerification(res, s_IFooObject);
res = ifooInt.IMethod1<int>(5, 6);
WriteLineWithVerification(res, s_IFooInt);
}
private static void TestWithClass(object o)
{
Base b = o as Base;
var res = b.GMethod1<int>(1, 2);
WriteLineWithVerification(res, s_GMethod1);
IFoo<string> ifoo1 = o as IFoo<string>;
res = ifoo1.IMethod1<int>(3, 4);
WriteLineWithVerification(res, s_IFooString);
IFoo<object> ifoo2 = o as IFoo<object>;
res = ifoo2.IMethod1<int>(5, 6);
WriteLineWithVerification(res, s_IFooObject);
IFoo<int> ifoo3 = o as IFoo<int>;
res = ifoo3.IMethod1<int>(7, 8);
WriteLineWithVerification(res, s_IFooInt);
}
private static void TestWithGenClass<T>(object o)
{
GenBase<T> b = o as GenBase<T>;
var res = b.GMethod1<int>(1, 2);
WriteLineWithVerification(res, s_GMethod1);
IFoo<string> ifoo1 = o as IFoo<string>;
res = ifoo1.IMethod1<int>(3, 4);
WriteLineWithVerification(res, s_IFooString);
IFoo<object> ifoo2 = o as IFoo<object>;
res = ifoo2.IMethod1<int>(5, 6);
WriteLineWithVerification(res, s_IFooObject);
IFoo<int> ifoo3 = o as IFoo<int>;
res = ifoo3.IMethod1<int>(7, 8);
WriteLineWithVerification(res, s_IFooInt);
}
private static void WriteLineWithVerification(string actual, string expected)
{
if (actual != expected)
{
Console.WriteLine("ACTUAL : " + actual);
Console.WriteLine("EXPECTED : " + expected);
s_NumErrors++;
}
else
{
Console.WriteLine(actual);
}
}
public static void Run()
{
{
s_GMethod1 = "Base.GMethod1<System.Int32>(1,2)";
s_IFooString = "Base.IMethod1<System.Int32>(3,4)";
s_IFooObject = "Base.IMethod1<System.Int32>(5,6)";
s_IFooInt = "Base.IMethod1<System.Int32>(7,8)";
TestWithClass(new Base());
Console.WriteLine("====================");
s_GMethod1 = "Derived.GMethod1<System.Int32>(1,2)";
s_IFooString = "Derived.IFoo<string>.IMethod1<System.Int32>(3,4)";
s_IFooObject = "Derived.IFoo<string>.IMethod1<System.Int32>(5,6)";
s_IFooInt = "Base.IMethod1<System.Int32>(7,8)";
TestWithClass(new Derived());
Console.WriteLine("====================");
s_GMethod1 = "Derived.GMethod1<System.Int32>(1,2)";
s_IFooString = "Derived.IFoo<string>.IMethod1<System.Int32>(3,4)";
s_IFooObject = "Derived.IFoo<string>.IMethod1<System.Int32>(5,6)";
s_IFooInt = "SuperDerived.IFoo<int>.IMethod1<System.Int32>(7,8)";
TestWithClass(new SuperDerived());
Console.WriteLine("====================");
}
{
s_GMethod1 = "GenBase<System.Byte>.GMethod1<System.Int32>(1,2)";
s_IFooString = "GenBase<System.Byte>.IMethod1<System.Int32>(3,4)";
s_IFooObject = "GenBase<System.Byte>.IMethod1<System.Int32>(5,6)";
s_IFooInt = "GenBase<System.Byte>.IMethod1<System.Int32>(7,8)";
TestWithGenClass<byte>(new GenBase<byte>());
Console.WriteLine("====================");
s_GMethod1 = "GenDerived<System.Byte>.GMethod1<System.Int32>(1,2)";
s_IFooString = "GenDerived<System.Byte>.IFoo<string>.IMethod1<System.Int32>(3,4)";
s_IFooObject = "GenDerived<System.Byte>.IFoo<string>.IMethod1<System.Int32>(5,6)";
s_IFooInt = "GenBase<System.Byte>.IMethod1<System.Int32>(7,8)";
TestWithGenClass<byte>(new GenDerived<byte>());
Console.WriteLine("====================");
s_GMethod1 = "GenDerived<System.String>.GMethod1<System.Int32>(1,2)";
s_IFooString = "GenDerived<System.String>.IFoo<string>.IMethod1<System.Int32>(3,4)";
s_IFooObject = "GenDerived<System.String>.IFoo<string>.IMethod1<System.Int32>(5,6)";
s_IFooInt = "GenBase<System.String>.IMethod1<System.Int32>(7,8)";
TestWithGenClass<String>(new GenDerived<String>());
Console.WriteLine("====================");
s_GMethod1 = "GenDerived<System.Byte>.GMethod1<System.Int32>(1,2)";
s_IFooString = "GenDerived<System.Byte>.IFoo<string>.IMethod1<System.Int32>(3,4)";
s_IFooObject = "GenDerived<System.Byte>.IFoo<string>.IMethod1<System.Int32>(5,6)";
s_IFooInt = "GenSuperDerived<System.Byte>.IFoo<int>.IMethod1<System.Int32>(7,8)";
TestWithGenClass<byte>(new GenSuperDerived<byte>());
Console.WriteLine("====================");
}
{
s_IFooString = "MyStruct1.IFoo<string>.IMethod1<System.Int32>(1,2)";
s_IFooObject = "MyStruct1.IFoo<string>.IMethod1<System.Int32>(3,4)";
s_IFooInt = "MyStruct1.IFoo<int>.IMethod1<System.Int32>(5,6)";
TestWithStruct(new MyStruct1(), new MyStruct1(), new MyStruct1());
Console.WriteLine("====================");
s_IFooString = "MyStruct2.IFoo<string>.IMethod1<System.Int32>(1,2)";
s_IFooObject = "MyStruct2.IFoo<string>.IMethod1<System.Int32>(3,4)";
s_IFooInt = "MyStruct2.IMethod1<System.Int32>(5,6)";
TestWithStruct(new MyStruct2(), new MyStruct2(), new MyStruct2());
Console.WriteLine("====================");
s_IFooString = "MyStruct3.IMethod1<System.Int32>(1,2)";
s_IFooObject = "MyStruct3.IMethod1<System.Int32>(3,4)";
s_IFooInt = "MyStruct3.IFoo<int>.IMethod1<System.Int32>(5,6)";
TestWithStruct(new MyStruct3(), new MyStruct3(), new MyStruct3());
Console.WriteLine("====================");
}
if (s_NumErrors != 0)
throw new Exception();
}
}
class TestGvmDependencies
{
class Atom { }
class Foo
{
public virtual object Frob<T>()
{
return new T[0, 0];
}
}
class Bar : Foo
{
public override object Frob<T>()
{
return new T[0, 0, 0];
}
}
public static void Run()
{
{
Foo x = new Foo();
x.Frob<Atom>();
}
{
Foo x = new Bar();
x.Frob<Atom>();
}
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Timers;
using System.Threading.Tasks;
using log4net;
using log4net.Config;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Grid.Framework;
using OpenSim.Grid.MessagingServer.Modules;
using System.Threading;
namespace OpenSim.Grid.MessagingServer
{
/// <summary>
/// </summary>
public class OpenMessage_Main : BaseOpenSimServer, IGridServiceCore
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private MessageServerConfig Cfg;
private MessageService msgsvc;
private MessageRegionModule m_regionModule;
private InterMessageUserServerModule m_userServerModule;
private UserDataBaseService m_userDataBaseService;
private ManualResetEvent Terminating = new ManualResetEvent(false);
private InWorldz.RemoteAdmin.RemoteAdmin m_radmin;
public static void Main(string[] args)
{
// Please note that if you are changing something in this function you should check to see if you need to change the other server's Main functions as well.
// Under any circumstance other than an explicit exit the exit code should be 1.
Environment.ExitCode = 1;
ServicePointManager.DefaultConnectionLimit = 12;
// Add the arguments supplied when running the application to the configuration
var configSource = new ArgvConfigSource(args);
configSource.Alias.AddAlias("On", true);
configSource.Alias.AddAlias("Off", false);
configSource.Alias.AddAlias("True", true);
configSource.Alias.AddAlias("False", false);
configSource.Alias.AddAlias("Yes", true);
configSource.Alias.AddAlias("No", false);
configSource.AddSwitch("Startup", "background");
configSource.AddSwitch("Startup", "pidfile");
m_log.Info("[SERVER]: Launching MessagingServer...");
var pidFile = new PIDFileManager(configSource.Configs["Startup"].GetString("pidfile", string.Empty));
XmlConfigurator.Configure();
OpenMessage_Main messageserver = new OpenMessage_Main();
pidFile.SetStatus(PIDFileManager.Status.Starting);
messageserver.Startup();
pidFile.SetStatus(PIDFileManager.Status.Running);
messageserver.Work(configSource.Configs["Startup"].GetBoolean("background", false));
}
public OpenMessage_Main()
{
m_console = new LocalConsole("Messaging");
MainConsole.Instance = m_console;
}
private void Work(bool background)
{
if (background)
{
Terminating.WaitOne();
Terminating.Close();
}
else
{
m_console.Notice("Enter help for a list of commands\n");
while (true)
{
m_console.Prompt();
}
}
}
private void registerWithUserServer()
{
retry:
if (m_userServerModule.registerWithUserServer())
{
m_log.Info("[SERVER]: Starting HTTP process");
m_httpServer = new BaseHttpServer(Cfg.HttpPort, null);
m_httpServer.AddXmlRPCHandler("login_to_simulator", msgsvc.UserLoggedOn);
m_httpServer.AddXmlRPCHandler("logout_of_simulator", msgsvc.UserLoggedOff);
m_httpServer.AddXmlRPCHandler("get_presence_info_bulk", msgsvc.GetPresenceInfoBulk);
m_httpServer.AddXmlRPCHandler("process_region_shutdown", msgsvc.ProcessRegionShutdown);
m_httpServer.AddXmlRPCHandler("agent_location", msgsvc.AgentLocation);
m_httpServer.AddXmlRPCHandler("agent_leaving", msgsvc.AgentLeaving);
m_httpServer.AddXmlRPCHandler("region_startup", m_regionModule.RegionStartup);
m_httpServer.AddXmlRPCHandler("region_shutdown", m_regionModule.RegionShutdown);
// New Style
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("login_to_simulator"), msgsvc.UserLoggedOn));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("logout_of_simulator"), msgsvc.UserLoggedOff));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("get_presence_info_bulk"), msgsvc.GetPresenceInfoBulk));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("process_region_shutdown"), msgsvc.ProcessRegionShutdown));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("agent_location"), msgsvc.AgentLocation));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("agent_leaving"), msgsvc.AgentLeaving));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("region_startup"), m_regionModule.RegionStartup));
m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("region_shutdown"), m_regionModule.RegionShutdown));
m_radmin = new InWorldz.RemoteAdmin.RemoteAdmin(Cfg.SSLPublicCertFile);
m_radmin.AddCommand("MessagingService", "Shutdown", MessagingServerShutdownHandler);
m_radmin.AddHandler(m_httpServer);
m_httpServer.Start();
m_log.Info("[SERVER]: Userserver registration was successful");
}
else
{
m_log.Error("[STARTUP]: Unable to connect to User Server, retrying in 5 seconds");
System.Threading.Thread.Sleep(5000);
goto retry;
}
}
public object MessagingServerShutdownHandler(IList args, IPEndPoint remoteClient)
{
m_radmin.CheckSessionValid(new UUID((string)args[0]));
try
{
int delay = (int)args[1];
string message;
if (delay > 0)
message = "Server is going down in " + delay.ToString() + " second(s).";
else
message = "Server is going down now.";
m_log.DebugFormat("[RADMIN] Shutdown: {0}", message);
// Perform shutdown
if (delay > 0)
System.Threading.Thread.Sleep(delay * 1000);
// Do this on a new thread so the actual shutdown call returns successfully.
Task.Factory.StartNew(Shutdown);
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN] Shutdown: failed: {0}", e.Message);
m_log.DebugFormat("[RADMIN] Shutdown: failed: {0}", e.ToString());
throw;
}
m_log.Info("[RADMIN]: Shutdown Administrator Request complete");
return true;
}
private void deregisterFromUserServer()
{
m_userServerModule.deregisterWithUserServer();
if (m_httpServer != null)
{
// try a completely fresh registration, with fresh handlers, too
m_httpServer.Stop();
m_httpServer = null;
}
m_console.Notice("[SERVER]: Deregistered from userserver.");
}
protected override void StartupSpecific()
{
Cfg = new MessageServerConfig("MESSAGING SERVER", (Path.Combine(Util.configDir(), "MessagingServer_Config.xml")));
m_userDataBaseService = new UserDataBaseService();
m_userDataBaseService.AddPlugin(Cfg.DatabaseProvider, Cfg.DatabaseConnect);
//Register the database access service so modules can fetch it
// RegisterInterface<UserDataBaseService>(m_userDataBaseService);
m_userServerModule = new InterMessageUserServerModule(Cfg, this);
m_userServerModule.Initialize();
msgsvc = new MessageService(Cfg, this, m_userDataBaseService);
msgsvc.Initialize();
m_regionModule = new MessageRegionModule(Cfg, this);
m_regionModule.Initialize();
registerWithUserServer();
m_userServerModule.PostInitialize();
msgsvc.PostInitialize();
m_regionModule.PostInitialize();
m_log.Info("[SERVER]: Messageserver 0.5 - Startup complete");
base.StartupSpecific();
m_console.Commands.AddCommand("messageserver", false, "clear cache",
"clear cache",
"Clear presence cache", HandleClearCache);
m_console.Commands.AddCommand("messageserver", false, "register",
"register",
"Re-register with user server(s)", HandleRegister);
}
private void HandleClearCache(string module, string[] cmd)
{
int entries = m_regionModule.ClearRegionCache();
m_console.Notice("Region cache cleared! Cleared " +
entries.ToString() + " entries");
}
private void HandleRegister(string module, string[] cmd)
{
deregisterFromUserServer();
registerWithUserServer();
}
public override void ShutdownSpecific()
{
Terminating.Set();
m_userServerModule.deregisterWithUserServer();
}
#region IUGAIMCore
protected Dictionary<Type, object> m_moduleInterfaces = new Dictionary<Type, object>();
/// <summary>
/// Register an Module interface.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="iface"></param>
public void RegisterInterface<T>(T iface)
{
lock (m_moduleInterfaces)
{
if (!m_moduleInterfaces.ContainsKey(typeof(T)))
{
m_moduleInterfaces.Add(typeof(T), iface);
}
}
}
public bool TryGet<T>(out T iface)
{
if (m_moduleInterfaces.ContainsKey(typeof(T)))
{
iface = (T)m_moduleInterfaces[typeof(T)];
return true;
}
iface = default(T);
return false;
}
public T Get<T>()
{
return (T)m_moduleInterfaces[typeof(T)];
}
public BaseHttpServer GetHttpServer()
{
return m_httpServer;
}
#endregion
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Graph.RBAC.Version1_6
{
using Microsoft.Azure;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AzureOperationResponse = Microsoft.Rest.Azure.AzureOperationResponse;
/// <summary>
/// ApplicationsOperations operations.
/// </summary>
public partial interface IApplicationsOperations
{
/// <summary>
/// Create a new application.
/// </summary>
/// <param name='parameters'>
/// The parameters for creating an application.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Application>> CreateWithHttpMessagesAsync(ApplicationCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists applications by filter parameters.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Application>>> ListWithHttpMessagesAsync(ODataQuery<Application> odataQuery = default(ODataQuery<Application>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete an application.
/// </summary>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get an application by object ID.
/// </summary>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Application>> GetWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update an existing application.
/// </summary>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='parameters'>
/// Parameters to update an existing application.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> PatchWithHttpMessagesAsync(string applicationObjectId, ApplicationUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the keyCredentials associated with an application.
/// </summary>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<KeyCredential>>> ListKeyCredentialsWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update the keyCredentials associated with an application.
/// </summary>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='parameters'>
/// Parameters to update the keyCredentials of an existing application.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> UpdateKeyCredentialsWithHttpMessagesAsync(string applicationObjectId, KeyCredentialsUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the passwordCredentials associated with an application.
/// </summary>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<PasswordCredential>>> ListPasswordCredentialsWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update passwordCredentials associated with an application.
/// </summary>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='parameters'>
/// Parameters to update passwordCredentials of an existing
/// application.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> UpdatePasswordCredentialsWithHttpMessagesAsync(string applicationObjectId, PasswordCredentialsUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a list of applications from the current tenant.
/// </summary>
/// <param name='nextLink'>
/// Next link for the list operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Application>>> ListNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
public static partial class BitConverter
{
public static readonly bool IsLittleEndian;
public static long DoubleToInt64Bits(double value) { return default(long); }
public static byte[] GetBytes(bool value) { return default(byte[]); }
public static byte[] GetBytes(char value) { return default(byte[]); }
public static byte[] GetBytes(double value) { return default(byte[]); }
public static byte[] GetBytes(short value) { return default(byte[]); }
public static byte[] GetBytes(int value) { return default(byte[]); }
public static byte[] GetBytes(long value) { return default(byte[]); }
public static byte[] GetBytes(float value) { return default(byte[]); }
[System.CLSCompliantAttribute(false)]
public static byte[] GetBytes(ushort value) { return default(byte[]); }
[System.CLSCompliantAttribute(false)]
public static byte[] GetBytes(uint value) { return default(byte[]); }
[System.CLSCompliantAttribute(false)]
public static byte[] GetBytes(ulong value) { return default(byte[]); }
public static double Int64BitsToDouble(long value) { return default(double); }
public static bool ToBoolean(byte[] value, int startIndex) { return default(bool); }
public static char ToChar(byte[] value, int startIndex) { return default(char); }
public static double ToDouble(byte[] value, int startIndex) { return default(double); }
public static short ToInt16(byte[] value, int startIndex) { return default(short); }
public static int ToInt32(byte[] value, int startIndex) { return default(int); }
public static long ToInt64(byte[] value, int startIndex) { return default(long); }
public static float ToSingle(byte[] value, int startIndex) { return default(float); }
public static string ToString(byte[] value) { return default(string); }
public static string ToString(byte[] value, int startIndex) { return default(string); }
public static string ToString(byte[] value, int startIndex, int length) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(byte[] value, int startIndex) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(byte[] value, int startIndex) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(byte[] value, int startIndex) { return default(ulong); }
}
public static partial class Convert
{
public static object ChangeType(object value, System.Type conversionType) { return default(object); }
public static object ChangeType(object value, System.Type conversionType, System.IFormatProvider provider) { return default(object); }
public static object ChangeType(object value, System.TypeCode typeCode, System.IFormatProvider provider) { return default(object); }
public static byte[] FromBase64CharArray(char[] inArray, int offset, int length) { return default(byte[]); }
public static byte[] FromBase64String(string s) { return default(byte[]); }
public static System.TypeCode GetTypeCode(object value) { return default(System.TypeCode); }
public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut) { return default(int); }
public static string ToBase64String(byte[] inArray) { return default(string); }
public static string ToBase64String(byte[] inArray, int offset, int length) { return default(string); }
public static bool ToBoolean(bool value) { return default(bool); }
public static bool ToBoolean(byte value) { return default(bool); }
public static bool ToBoolean(decimal value) { return default(bool); }
public static bool ToBoolean(double value) { return default(bool); }
public static bool ToBoolean(short value) { return default(bool); }
public static bool ToBoolean(int value) { return default(bool); }
public static bool ToBoolean(long value) { return default(bool); }
public static bool ToBoolean(object value) { return default(bool); }
public static bool ToBoolean(object value, System.IFormatProvider provider) { return default(bool); }
[System.CLSCompliantAttribute(false)]
public static bool ToBoolean(sbyte value) { return default(bool); }
public static bool ToBoolean(float value) { return default(bool); }
public static bool ToBoolean(string value) { return default(bool); }
public static bool ToBoolean(string value, System.IFormatProvider provider) { return default(bool); }
[System.CLSCompliantAttribute(false)]
public static bool ToBoolean(ushort value) { return default(bool); }
[System.CLSCompliantAttribute(false)]
public static bool ToBoolean(uint value) { return default(bool); }
[System.CLSCompliantAttribute(false)]
public static bool ToBoolean(ulong value) { return default(bool); }
public static byte ToByte(bool value) { return default(byte); }
public static byte ToByte(byte value) { return default(byte); }
public static byte ToByte(char value) { return default(byte); }
public static byte ToByte(decimal value) { return default(byte); }
public static byte ToByte(double value) { return default(byte); }
public static byte ToByte(short value) { return default(byte); }
public static byte ToByte(int value) { return default(byte); }
public static byte ToByte(long value) { return default(byte); }
public static byte ToByte(object value) { return default(byte); }
public static byte ToByte(object value, System.IFormatProvider provider) { return default(byte); }
[System.CLSCompliantAttribute(false)]
public static byte ToByte(sbyte value) { return default(byte); }
public static byte ToByte(float value) { return default(byte); }
public static byte ToByte(string value) { return default(byte); }
public static byte ToByte(string value, System.IFormatProvider provider) { return default(byte); }
public static byte ToByte(string value, int fromBase) { return default(byte); }
[System.CLSCompliantAttribute(false)]
public static byte ToByte(ushort value) { return default(byte); }
[System.CLSCompliantAttribute(false)]
public static byte ToByte(uint value) { return default(byte); }
[System.CLSCompliantAttribute(false)]
public static byte ToByte(ulong value) { return default(byte); }
public static char ToChar(byte value) { return default(char); }
public static char ToChar(short value) { return default(char); }
public static char ToChar(int value) { return default(char); }
public static char ToChar(long value) { return default(char); }
public static char ToChar(object value) { return default(char); }
public static char ToChar(object value, System.IFormatProvider provider) { return default(char); }
[System.CLSCompliantAttribute(false)]
public static char ToChar(sbyte value) { return default(char); }
public static char ToChar(string value) { return default(char); }
public static char ToChar(string value, System.IFormatProvider provider) { return default(char); }
[System.CLSCompliantAttribute(false)]
public static char ToChar(ushort value) { return default(char); }
[System.CLSCompliantAttribute(false)]
public static char ToChar(uint value) { return default(char); }
[System.CLSCompliantAttribute(false)]
public static char ToChar(ulong value) { return default(char); }
public static System.DateTime ToDateTime(object value) { return default(System.DateTime); }
public static System.DateTime ToDateTime(object value, System.IFormatProvider provider) { return default(System.DateTime); }
public static System.DateTime ToDateTime(string value) { return default(System.DateTime); }
public static System.DateTime ToDateTime(string value, System.IFormatProvider provider) { return default(System.DateTime); }
public static decimal ToDecimal(bool value) { return default(decimal); }
public static decimal ToDecimal(byte value) { return default(decimal); }
public static decimal ToDecimal(decimal value) { return default(decimal); }
public static decimal ToDecimal(double value) { return default(decimal); }
public static decimal ToDecimal(short value) { return default(decimal); }
public static decimal ToDecimal(int value) { return default(decimal); }
public static decimal ToDecimal(long value) { return default(decimal); }
public static decimal ToDecimal(object value) { return default(decimal); }
public static decimal ToDecimal(object value, System.IFormatProvider provider) { return default(decimal); }
[System.CLSCompliantAttribute(false)]
public static decimal ToDecimal(sbyte value) { return default(decimal); }
public static decimal ToDecimal(float value) { return default(decimal); }
public static decimal ToDecimal(string value) { return default(decimal); }
public static decimal ToDecimal(string value, System.IFormatProvider provider) { return default(decimal); }
[System.CLSCompliantAttribute(false)]
public static decimal ToDecimal(ushort value) { return default(decimal); }
[System.CLSCompliantAttribute(false)]
public static decimal ToDecimal(uint value) { return default(decimal); }
[System.CLSCompliantAttribute(false)]
public static decimal ToDecimal(ulong value) { return default(decimal); }
public static double ToDouble(bool value) { return default(double); }
public static double ToDouble(byte value) { return default(double); }
public static double ToDouble(decimal value) { return default(double); }
public static double ToDouble(double value) { return default(double); }
public static double ToDouble(short value) { return default(double); }
public static double ToDouble(int value) { return default(double); }
public static double ToDouble(long value) { return default(double); }
public static double ToDouble(object value) { return default(double); }
public static double ToDouble(object value, System.IFormatProvider provider) { return default(double); }
[System.CLSCompliantAttribute(false)]
public static double ToDouble(sbyte value) { return default(double); }
public static double ToDouble(float value) { return default(double); }
public static double ToDouble(string value) { return default(double); }
public static double ToDouble(string value, System.IFormatProvider provider) { return default(double); }
[System.CLSCompliantAttribute(false)]
public static double ToDouble(ushort value) { return default(double); }
[System.CLSCompliantAttribute(false)]
public static double ToDouble(uint value) { return default(double); }
[System.CLSCompliantAttribute(false)]
public static double ToDouble(ulong value) { return default(double); }
public static short ToInt16(bool value) { return default(short); }
public static short ToInt16(byte value) { return default(short); }
public static short ToInt16(char value) { return default(short); }
public static short ToInt16(decimal value) { return default(short); }
public static short ToInt16(double value) { return default(short); }
public static short ToInt16(short value) { return default(short); }
public static short ToInt16(int value) { return default(short); }
public static short ToInt16(long value) { return default(short); }
public static short ToInt16(object value) { return default(short); }
public static short ToInt16(object value, System.IFormatProvider provider) { return default(short); }
[System.CLSCompliantAttribute(false)]
public static short ToInt16(sbyte value) { return default(short); }
public static short ToInt16(float value) { return default(short); }
public static short ToInt16(string value) { return default(short); }
public static short ToInt16(string value, System.IFormatProvider provider) { return default(short); }
public static short ToInt16(string value, int fromBase) { return default(short); }
[System.CLSCompliantAttribute(false)]
public static short ToInt16(ushort value) { return default(short); }
[System.CLSCompliantAttribute(false)]
public static short ToInt16(uint value) { return default(short); }
[System.CLSCompliantAttribute(false)]
public static short ToInt16(ulong value) { return default(short); }
public static int ToInt32(bool value) { return default(int); }
public static int ToInt32(byte value) { return default(int); }
public static int ToInt32(char value) { return default(int); }
public static int ToInt32(decimal value) { return default(int); }
public static int ToInt32(double value) { return default(int); }
public static int ToInt32(short value) { return default(int); }
public static int ToInt32(int value) { return default(int); }
public static int ToInt32(long value) { return default(int); }
public static int ToInt32(object value) { return default(int); }
public static int ToInt32(object value, System.IFormatProvider provider) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int ToInt32(sbyte value) { return default(int); }
public static int ToInt32(float value) { return default(int); }
public static int ToInt32(string value) { return default(int); }
public static int ToInt32(string value, System.IFormatProvider provider) { return default(int); }
public static int ToInt32(string value, int fromBase) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int ToInt32(ushort value) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int ToInt32(uint value) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int ToInt32(ulong value) { return default(int); }
public static long ToInt64(bool value) { return default(long); }
public static long ToInt64(byte value) { return default(long); }
public static long ToInt64(char value) { return default(long); }
public static long ToInt64(decimal value) { return default(long); }
public static long ToInt64(double value) { return default(long); }
public static long ToInt64(short value) { return default(long); }
public static long ToInt64(int value) { return default(long); }
public static long ToInt64(long value) { return default(long); }
public static long ToInt64(object value) { return default(long); }
public static long ToInt64(object value, System.IFormatProvider provider) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static long ToInt64(sbyte value) { return default(long); }
public static long ToInt64(float value) { return default(long); }
public static long ToInt64(string value) { return default(long); }
public static long ToInt64(string value, System.IFormatProvider provider) { return default(long); }
public static long ToInt64(string value, int fromBase) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static long ToInt64(ushort value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static long ToInt64(uint value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static long ToInt64(ulong value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(bool value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(byte value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(char value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(decimal value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(double value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(short value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(int value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(long value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(object value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(object value, System.IFormatProvider provider) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(sbyte value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(float value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string value, System.IFormatProvider provider) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string value, int fromBase) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(ushort value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(uint value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(ulong value) { return default(sbyte); }
public static float ToSingle(bool value) { return default(float); }
public static float ToSingle(byte value) { return default(float); }
public static float ToSingle(decimal value) { return default(float); }
public static float ToSingle(double value) { return default(float); }
public static float ToSingle(short value) { return default(float); }
public static float ToSingle(int value) { return default(float); }
public static float ToSingle(long value) { return default(float); }
public static float ToSingle(object value) { return default(float); }
public static float ToSingle(object value, System.IFormatProvider provider) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static float ToSingle(sbyte value) { return default(float); }
public static float ToSingle(float value) { return default(float); }
public static float ToSingle(string value) { return default(float); }
public static float ToSingle(string value, System.IFormatProvider provider) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static float ToSingle(ushort value) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static float ToSingle(uint value) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static float ToSingle(ulong value) { return default(float); }
public static string ToString(bool value) { return default(string); }
public static string ToString(bool value, System.IFormatProvider provider) { return default(string); }
public static string ToString(byte value) { return default(string); }
public static string ToString(byte value, System.IFormatProvider provider) { return default(string); }
public static string ToString(byte value, int toBase) { return default(string); }
public static string ToString(char value) { return default(string); }
public static string ToString(char value, System.IFormatProvider provider) { return default(string); }
public static string ToString(System.DateTime value) { return default(string); }
public static string ToString(System.DateTime value, System.IFormatProvider provider) { return default(string); }
public static string ToString(decimal value) { return default(string); }
public static string ToString(decimal value, System.IFormatProvider provider) { return default(string); }
public static string ToString(double value) { return default(string); }
public static string ToString(double value, System.IFormatProvider provider) { return default(string); }
public static string ToString(short value) { return default(string); }
public static string ToString(short value, System.IFormatProvider provider) { return default(string); }
public static string ToString(short value, int toBase) { return default(string); }
public static string ToString(int value) { return default(string); }
public static string ToString(int value, System.IFormatProvider provider) { return default(string); }
public static string ToString(int value, int toBase) { return default(string); }
public static string ToString(long value) { return default(string); }
public static string ToString(long value, System.IFormatProvider provider) { return default(string); }
public static string ToString(long value, int toBase) { return default(string); }
public static string ToString(object value) { return default(string); }
public static string ToString(object value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(sbyte value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(sbyte value, System.IFormatProvider provider) { return default(string); }
public static string ToString(float value) { return default(string); }
public static string ToString(float value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ushort value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ushort value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(uint value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(uint value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ulong value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ulong value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(bool value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(byte value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(char value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(decimal value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(double value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(short value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(int value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(long value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(object value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(object value, System.IFormatProvider provider) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(sbyte value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(float value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(string value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(string value, System.IFormatProvider provider) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(string value, int fromBase) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(ushort value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(uint value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(ulong value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(bool value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(byte value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(char value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(decimal value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(double value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(short value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(int value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(long value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(object value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(object value, System.IFormatProvider provider) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(sbyte value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(float value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(string value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(string value, System.IFormatProvider provider) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(string value, int fromBase) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(ushort value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(uint value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(ulong value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(bool value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(byte value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(char value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(decimal value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(double value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(short value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(int value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(long value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(object value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(object value, System.IFormatProvider provider) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(sbyte value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(float value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(string value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(string value, System.IFormatProvider provider) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(string value, int fromBase) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(ushort value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(uint value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(ulong value) { return default(ulong); }
}
public static partial class Environment
{
public static int CurrentManagedThreadId { get { return default(int); } }
public static bool HasShutdownStarted { get { return default(bool); } }
public static string NewLine { get { return default(string); } }
public static int ProcessorCount { get { return default(int); } }
public static string StackTrace { get { return default(string); } }
public static int TickCount { get { return default(int); } }
public static string ExpandEnvironmentVariables(string name) { return default(string); }
[System.Security.SecurityCriticalAttribute]
public static void FailFast(string message) { }
[System.Security.SecurityCriticalAttribute]
public static void FailFast(string message, System.Exception exception) { }
public static string GetEnvironmentVariable(string variable) { return default(string); }
public static System.Collections.IDictionary GetEnvironmentVariables() { return default(System.Collections.IDictionary); }
public static void SetEnvironmentVariable(string variable, string value) { }
}
public static partial class Math
{
public static decimal Abs(decimal value) { return default(decimal); }
public static double Abs(double value) { return default(double); }
public static short Abs(short value) { return default(short); }
public static int Abs(int value) { return default(int); }
public static long Abs(long value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte Abs(sbyte value) { return default(sbyte); }
public static float Abs(float value) { return default(float); }
public static double Acos(double d) { return default(double); }
public static double Asin(double d) { return default(double); }
public static double Atan(double d) { return default(double); }
public static double Atan2(double y, double x) { return default(double); }
public static decimal Ceiling(decimal d) { return default(decimal); }
public static double Ceiling(double a) { return default(double); }
public static double Cos(double d) { return default(double); }
public static double Cosh(double value) { return default(double); }
public static double Exp(double d) { return default(double); }
public static decimal Floor(decimal d) { return default(decimal); }
public static double Floor(double d) { return default(double); }
public static double IEEERemainder(double x, double y) { return default(double); }
public static double Log(double d) { return default(double); }
public static double Log(double a, double newBase) { return default(double); }
public static double Log10(double d) { return default(double); }
public static byte Max(byte val1, byte val2) { return default(byte); }
public static decimal Max(decimal val1, decimal val2) { return default(decimal); }
public static double Max(double val1, double val2) { return default(double); }
public static short Max(short val1, short val2) { return default(short); }
public static int Max(int val1, int val2) { return default(int); }
public static long Max(long val1, long val2) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte Max(sbyte val1, sbyte val2) { return default(sbyte); }
public static float Max(float val1, float val2) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static ushort Max(ushort val1, ushort val2) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint Max(uint val1, uint val2) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong Max(ulong val1, ulong val2) { return default(ulong); }
public static byte Min(byte val1, byte val2) { return default(byte); }
public static decimal Min(decimal val1, decimal val2) { return default(decimal); }
public static double Min(double val1, double val2) { return default(double); }
public static short Min(short val1, short val2) { return default(short); }
public static int Min(int val1, int val2) { return default(int); }
public static long Min(long val1, long val2) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte Min(sbyte val1, sbyte val2) { return default(sbyte); }
public static float Min(float val1, float val2) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static ushort Min(ushort val1, ushort val2) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint Min(uint val1, uint val2) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong Min(ulong val1, ulong val2) { return default(ulong); }
public static double Pow(double x, double y) { return default(double); }
public static decimal Round(decimal d) { return default(decimal); }
public static decimal Round(decimal d, int decimals) { return default(decimal); }
public static decimal Round(decimal d, int decimals, System.MidpointRounding mode) { return default(decimal); }
public static decimal Round(decimal d, System.MidpointRounding mode) { return default(decimal); }
public static double Round(double a) { return default(double); }
public static double Round(double value, int digits) { return default(double); }
public static double Round(double value, int digits, System.MidpointRounding mode) { return default(double); }
public static double Round(double value, System.MidpointRounding mode) { return default(double); }
public static int Sign(decimal value) { return default(int); }
public static int Sign(double value) { return default(int); }
public static int Sign(short value) { return default(int); }
public static int Sign(int value) { return default(int); }
public static int Sign(long value) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int Sign(sbyte value) { return default(int); }
public static int Sign(float value) { return default(int); }
public static double Sin(double a) { return default(double); }
public static double Sinh(double value) { return default(double); }
public static double Sqrt(double d) { return default(double); }
public static double Tan(double a) { return default(double); }
public static double Tanh(double value) { return default(double); }
public static decimal Truncate(decimal d) { return default(decimal); }
public static double Truncate(double d) { return default(double); }
}
public enum MidpointRounding
{
AwayFromZero = 1,
ToEven = 0,
}
public partial class Progress<T> : System.IProgress<T>
{
public Progress() { }
public Progress(System.Action<T> handler) { }
public event System.EventHandler<T> ProgressChanged { add { } remove { } }
protected virtual void OnReport(T value) { }
void System.IProgress<T>.Report(T value) { }
}
public partial class Random
{
public Random() { }
public Random(int Seed) { }
public virtual int Next() { return default(int); }
public virtual int Next(int maxValue) { return default(int); }
public virtual int Next(int minValue, int maxValue) { return default(int); }
public virtual void NextBytes(byte[] buffer) { }
public virtual double NextDouble() { return default(double); }
protected virtual double Sample() { return default(double); }
}
public abstract partial class StringComparer : System.Collections.Generic.IComparer<string>, System.Collections.Generic.IEqualityComparer<string>, System.Collections.IComparer, System.Collections.IEqualityComparer
{
protected StringComparer() { }
public static System.StringComparer CurrentCulture { get { return default(System.StringComparer); } }
public static System.StringComparer CurrentCultureIgnoreCase { get { return default(System.StringComparer); } }
public static System.StringComparer Ordinal { get { return default(System.StringComparer); } }
public static System.StringComparer OrdinalIgnoreCase { get { return default(System.StringComparer); } }
public abstract int Compare(string x, string y);
public abstract bool Equals(string x, string y);
public abstract int GetHashCode(string obj);
int System.Collections.IComparer.Compare(object x, object y) { return default(int); }
bool System.Collections.IEqualityComparer.Equals(object x, object y) { return default(bool); }
int System.Collections.IEqualityComparer.GetHashCode(object obj) { return default(int); }
}
public partial class UriBuilder
{
public UriBuilder() { }
public UriBuilder(string uri) { }
public UriBuilder(string schemeName, string hostName) { }
public UriBuilder(string scheme, string host, int portNumber) { }
public UriBuilder(string scheme, string host, int port, string pathValue) { }
public UriBuilder(string scheme, string host, int port, string path, string extraValue) { }
public UriBuilder(System.Uri uri) { }
public string Fragment { get { return default(string); } set { } }
public string Host { get { return default(string); } set { } }
public string Password { get { return default(string); } set { } }
public string Path { get { return default(string); } set { } }
public int Port { get { return default(int); } set { } }
public string Query { get { return default(string); } set { } }
public string Scheme { get { return default(string); } set { } }
public System.Uri Uri { get { return default(System.Uri); } }
public string UserName { get { return default(string); } set { } }
public override bool Equals(object rparam) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override string ToString() { return default(string); }
}
}
namespace System.Diagnostics
{
public partial class Stopwatch
{
public static readonly long Frequency;
public static readonly bool IsHighResolution;
public Stopwatch() { }
public System.TimeSpan Elapsed { get { return default(System.TimeSpan); } }
public long ElapsedMilliseconds { get { return default(long); } }
public long ElapsedTicks { get { return default(long); } }
public bool IsRunning { get { return default(bool); } }
public static long GetTimestamp() { return default(long); }
public void Reset() { }
public void Restart() { }
public void Start() { }
public static System.Diagnostics.Stopwatch StartNew() { return default(System.Diagnostics.Stopwatch); }
public void Stop() { }
}
}
namespace System.IO
{
public static partial class Path
{
public static readonly char AltDirectorySeparatorChar;
public static readonly char DirectorySeparatorChar;
public static readonly char PathSeparator;
public static readonly char VolumeSeparatorChar;
public static string ChangeExtension(string path, string extension) { return default(string); }
public static string Combine(string path1, string path2) { return default(string); }
public static string Combine(string path1, string path2, string path3) { return default(string); }
public static string Combine(params string[] paths) { return default(string); }
public static string GetDirectoryName(string path) { return default(string); }
public static string GetExtension(string path) { return default(string); }
public static string GetFileName(string path) { return default(string); }
public static string GetFileNameWithoutExtension(string path) { return default(string); }
public static string GetFullPath(string path) { return default(string); }
public static char[] GetInvalidFileNameChars() { return default(char[]); }
public static char[] GetInvalidPathChars() { return default(char[]); }
public static string GetPathRoot(string path) { return default(string); }
public static string GetRandomFileName() { return default(string); }
public static string GetTempFileName() { return default(string); }
public static string GetTempPath() { return default(string); }
public static bool HasExtension(string path) { return default(bool); }
public static bool IsPathRooted(string path) { return default(bool); }
}
}
namespace System.Net
{
public static partial class WebUtility
{
public static string HtmlDecode(string value) { return default(string); }
public static string HtmlEncode(string value) { return default(string); }
public static string UrlDecode(string encodedValue) { return default(string); }
public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count) { return default(byte[]); }
public static string UrlEncode(string value) { return default(string); }
public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count) { return default(byte[]); }
}
}
namespace System.Runtime.Versioning
{
public sealed partial class FrameworkName : System.IEquatable<System.Runtime.Versioning.FrameworkName>
{
public FrameworkName(string frameworkName) { }
public FrameworkName(string identifier, System.Version version) { }
public FrameworkName(string identifier, System.Version version, string profile) { }
public string FullName { get { return default(string); } }
public string Identifier { get { return default(string); } }
public string Profile { get { return default(string); } }
public System.Version Version { get { return default(System.Version); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Runtime.Versioning.FrameworkName other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Runtime.Versioning.FrameworkName left, System.Runtime.Versioning.FrameworkName right) { return default(bool); }
public static bool operator !=(System.Runtime.Versioning.FrameworkName left, System.Runtime.Versioning.FrameworkName right) { return default(bool); }
public override string ToString() { return default(string); }
}
}
| |
/***************************************************************************
* DiscUsageDisplay.cs
*
* Copyright (C) 2006 Novell, Inc.
* Written by Aaron Bockover <[email protected]>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using Gtk;
using Cairo;
using Hyena.Gui;
namespace Banshee.Widgets
{
public class DiscUsageDisplay : Gtk.DrawingArea
{
private static Color bound_color_a = new Cairo.Color(1, 0x66 / (double)0xff, 0x00);
private static Color bound_color_b = new Cairo.Color(1, 0xcc / (double)0xff, 0x00, 0.3);
private static Color disc_color_a = new Cairo.Color(1, 1, 1);
private static Color disc_color_b = new Cairo.Color(0.95, 0.95, 0.95);
private static Color red_color = new Cairo.Color(0xcc / (double)0xff, 0, 0, 0.5);
private RadialGradient bg_gradient;
private RadialGradient fg_gradient_full;
private RadialGradient fg_gradient;
private RadialGradient bound_gradient;
private Color fill_color_a;
private Color fill_color_b;
private Color fill_color_c;
private Color stroke_color;
private Color inner_stroke_color;
private Color text_color;
private Color text_bg_color;
private const double a1 = 3 * Math.PI / 2;
private double x, y, radius, a2, base_line_width;
private long capacity;
private long usage;
public DiscUsageDisplay()
{
AppPaintable = true;
}
protected override void OnStyleSet(Gtk.Style style)
{
fill_color_a = CairoExtensions.GdkColorToCairoColor(Style.Background(StateType.Selected));
fill_color_b = CairoExtensions.GdkColorToCairoColor(Style.Foreground(StateType.Selected));
fill_color_c = CairoExtensions.GdkColorToCairoColor(Style.Background(StateType.Normal));
stroke_color = CairoExtensions.GdkColorToCairoColor(Style.Foreground(StateType.Normal), 0.6);
inner_stroke_color = CairoExtensions.GdkColorToCairoColor(Style.Foreground(StateType.Normal), 0.4);
text_color = CairoExtensions.GdkColorToCairoColor(Style.Foreground(StateType.Normal), 0.8);
text_bg_color = CairoExtensions.GdkColorToCairoColor(Style.Background(StateType.Normal), 0.6);
}
protected override void OnSizeAllocated(Gdk.Rectangle rect)
{
x = rect.Width / 2.0;
y = rect.Height / 2.0;
radius = Math.Min(rect.Width / 2, rect.Height / 2) - 5;
base_line_width = Math.Sqrt(radius) * 0.2;
bg_gradient = new RadialGradient(x, y, 0, x, y, radius);
bg_gradient.AddColorStop(0, disc_color_a);
bg_gradient.AddColorStop(1, disc_color_b);
fg_gradient = new RadialGradient(x, y, 0, x, y, radius * 2);
fg_gradient.AddColorStop(0, fill_color_a);
fg_gradient.AddColorStop(1, fill_color_b);
fg_gradient_full = new RadialGradient(x, y, 0, x, y, radius);
fg_gradient_full.AddColorStop(0, disc_color_b);
fg_gradient_full.AddColorStop(1, red_color);
bound_gradient = new RadialGradient(x, y, 0, x, y, radius * 2);
bound_gradient.AddColorStop(0, bound_color_a);
bound_gradient.AddColorStop(1, bound_color_b);
base.OnSizeAllocated(rect);
}
protected override bool OnExposeEvent(Gdk.EventExpose evnt)
{
if(!IsRealized) {
return false;
}
Cairo.Context cr = Gdk.CairoHelper.Create(GdkWindow);
foreach(Gdk.Rectangle rect in evnt.Region.GetRectangles()) {
cr.Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
cr.Clip();
Draw(cr);
}
CairoExtensions.DisposeContext (cr);
return false;
}
private void Draw(Cairo.Context cr)
{
cr.Antialias = Antialias.Subpixel;
cr.LineWidth = base_line_width / 1.5;
cr.Arc(x, y, radius, 0, 2 * Math.PI);
cr.Pattern = bg_gradient;
cr.Fill();
/*cr.LineTo(x, y);
cr.Arc(x, y, radius, a1 + 2 * Math.PI * 0.92, a1);
cr.LineTo(x, y);
cr.Pattern = bound_gradient;
cr.Fill();
cr.Stroke();*/
if(Capacity > 0) {
if(Fraction < 1.0) {
cr.LineTo(x, y);
cr.Arc(x, y, radius, a1, a2);
cr.LineTo(x, y);
} else {
cr.Arc(x, y, radius, 0, 2 * Math.PI);
}
cr.Pattern = Fraction >= 1.0 ? fg_gradient_full : fg_gradient;
cr.FillPreserve();
cr.Color = stroke_color;
cr.Stroke();
}
cr.Arc(x, y, radius / 2.75, 0, 2 * Math.PI);
cr.Color = fill_color_c;
cr.FillPreserve();
cr.Color = new Cairo.Color(1, 1, 1, 0.75);
cr.FillPreserve();
cr.LineWidth = base_line_width / 1.5;
cr.Color = stroke_color;
cr.Stroke();
cr.Arc(x, y, radius / 5.5, 0, 2 * Math.PI);
cr.Color = fill_color_c;
cr.FillPreserve();
cr.LineWidth = base_line_width / 2;
cr.Color = inner_stroke_color;
cr.Stroke();
cr.Arc(x, y, radius, 0, 2 * Math.PI);
cr.Stroke();
if(Capacity <= 0) {
// this sucks balls
cr.Rectangle(0, 0, Allocation.Width, Allocation.Height);
cr.Color = text_bg_color;
cr.FillPreserve();
cr.SelectFontFace("Sans", FontSlant.Normal, FontWeight.Bold);
cr.Color = text_color;
cr.SetFontSize(Allocation.Width * 0.2);
DrawText(cr, Mono.Unix.Catalog.GetString("Insert\nDisc"), 3);
}
}
private void DrawText(Cairo.Context cr, string text, double lineSpacing)
{
string [] lines = text.Split('\n');
double [] cuml_heights = new double[lines.Length];
double y_start = 0.0;
for(int i = 0; i < lines.Length; i++) {
TextExtents extents = cr.TextExtents(lines[i]);
double height = extents.Height + (i > 0 ? lineSpacing : 0);
cuml_heights[i] = i > 0 ? cuml_heights[i - 1] + height : height;
}
y_start = (Allocation.Height / 2) - (cuml_heights[cuml_heights.Length - 1] / 2);
for(int i = 0; i < lines.Length; i++) {
TextExtents extents = cr.TextExtents(lines[i]);
double x = (Allocation.Width / 2) - (extents.Width / 2);
double y = y_start + cuml_heights[i];
cr.MoveTo(x, y);
cr.ShowText(lines[i]);
}
}
private void CalculateA2()
{
a2 = a1 + 2 * Math.PI * Fraction;
}
private double Fraction {
get { return (double)Usage / (double)Capacity; }
}
public long Capacity {
get { return capacity; }
set {
capacity = value;
CalculateA2();
QueueDraw();
}
}
public long Usage {
get { return usage; }
set {
usage = value;
CalculateA2();
QueueDraw();
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Xunit;
#if AVALONIA_SKIA
namespace Avalonia.Skia.RenderTests
#else
namespace Avalonia.Direct2D1.RenderTests.Controls
#endif
{
public class BorderTests : TestBase
{
public BorderTests()
: base(@"Controls\Border")
{
}
[Fact]
public async Task Border_1px_Border()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(1),
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_2px_Border()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Uniform_CornerRadius()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
CornerRadius = new CornerRadius(16),
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_NonUniform_CornerRadius()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
CornerRadius = new CornerRadius(16, 4, 7, 10),
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Fill()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
Background = Brushes.Red,
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Brush_Offsets_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new Border
{
Background = Brushes.Red,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Padding_Offsets_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Padding = new Thickness(2),
Child = new Border
{
Background = Brushes.Red,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Margin_Offsets_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new Border
{
Background = Brushes.Red,
Margin = new Thickness(2),
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Centers_Content_Horizontally()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Center,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Centers_Content_Vertically()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
VerticalAlignment = VerticalAlignment.Center,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Stretches_Content_Horizontally()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Stretch,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Stretches_Content_Vertically()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
VerticalAlignment = VerticalAlignment.Stretch,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Left_Aligns_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Left,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Right_Aligns_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Right,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Top_Aligns_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
VerticalAlignment = VerticalAlignment.Top,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Bottom_Aligns_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = "Segoe UI",
FontSize = 12,
VerticalAlignment = VerticalAlignment.Bottom,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Nested_Rotate()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
Background = Brushes.Coral,
Width = 100,
Height = 100,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Child = new Border
{
Margin = new Thickness(25),
Background = Brushes.Chocolate,
},
RenderTransform = new RotateTransform(45),
}
};
await RenderToFile(target);
CompareImages();
}
}
}
| |
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2009 the Open Toolkit library.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Diagnostics;
namespace OpenTK.Platform
{
using Graphics;
using Input;
sealed class Factory : IPlatformFactory2
{
private bool disposed;
static Factory()
{
Toolkit.Init();
}
public Factory()
{
// Ensure we are correctly initialized.
Toolkit.Init();
// Create regular platform backend
#if SDL2
if (Configuration.RunningOnSdl2)
{
Default = new SDL2.Sdl2Factory();
}
#endif
#if WIN32
else if (Configuration.RunningOnWindows)
{
Default = new Windows.WinFactory();
}
#endif
#if CARBON
else if (Configuration.RunningOnMacOS)
{
Default = new MacOS.MacOSFactory();
}
#endif
#if X11
else if (Configuration.RunningOnX11)
{
Default = new X11.X11Factory();
}
else if (Configuration.RunningOnLinux)
{
Default = new Linux.LinuxFactory();
}
#endif
if (Default == null)
{
Default = new UnsupportedPlatform();
}
// Create embedded platform backend for EGL / OpenGL ES.
// Todo: we could probably delay this until the embedded
// factory is actually accessed. This might improve startup
// times slightly.
if (Configuration.RunningOnSdl2)
{
// SDL supports both EGL and desktop backends
// using the same API.
Embedded = Default;
}
#if IPHONE
else if (Configuration.RunningOnIOS)
{
Embedded = new iPhoneOS.iPhoneFactory();
}
#else
else if (Egl.Egl.IsSupported)
{
if (Configuration.RunningOnLinux)
{
Embedded = Default;
}
#if X11
else if (Configuration.RunningOnX11)
{
Embedded = new Egl.EglX11PlatformFactory();
}
#endif
#if WIN32
else if (Configuration.RunningOnWindows)
{
Embedded = new Egl.EglWinPlatformFactory();
}
#endif
#if CARBON
else if (Configuration.RunningOnMacOS)
{
Embedded = new Egl.EglMacPlatformFactory();
}
#endif
#if ANDROID
else if (Configuration.RunningOnAndroid) Embedded = new Android.AndroidFactory();
#endif
else
{
Embedded = new UnsupportedPlatform();
}
#if ANDROID
Angle = new UnsupportedPlatform();
#else
Angle = new Egl.EglAnglePlatformFactory(Embedded);
#endif
}
#endif
else
{
Embedded = new UnsupportedPlatform();
Angle = Embedded;
}
if (Default is UnsupportedPlatform && !(Embedded is UnsupportedPlatform))
{
Default = Embedded;
}
}
public static IPlatformFactory2 Default { get; private set; }
public static IPlatformFactory2 Embedded { get; private set; }
public static IPlatformFactory2 Angle { get; private set; }
public INativeWindow CreateNativeWindow(int x, int y, int width, int height, string title,
GraphicsMode mode, GameWindowFlags options, DisplayDevice device)
{
return Default.CreateNativeWindow(x, y, width, height, title, mode, options, device);
}
public IDisplayDeviceDriver CreateDisplayDeviceDriver()
{
return Default.CreateDisplayDeviceDriver();
}
public IGraphicsContext CreateGLContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
{
return Default.CreateGLContext(mode, window, shareContext, directRendering, major, minor, flags);
}
public IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
{
return Default.CreateGLContext(handle, window, shareContext, directRendering, major, minor, flags);
}
public GraphicsContext.GetCurrentContextDelegate CreateGetCurrentGraphicsContext()
{
return Default.CreateGetCurrentGraphicsContext();
}
public IKeyboardDriver2 CreateKeyboardDriver()
{
return Default.CreateKeyboardDriver();
}
public IMouseDriver2 CreateMouseDriver()
{
return Default.CreateMouseDriver();
}
public IGamePadDriver CreateGamePadDriver()
{
return Default.CreateGamePadDriver();
}
public IJoystickDriver2 CreateJoystickDriver()
{
return Default.CreateJoystickDriver();
}
public void RegisterResource(IDisposable resource)
{
Default.RegisterResource(resource);
}
private class UnsupportedPlatform : PlatformFactoryBase
{
private static readonly string error_string = "Please, refer to http://www.opentk.com for more information.";
public override INativeWindow CreateNativeWindow(int x, int y, int width, int height, string title, GraphicsMode mode, GameWindowFlags options, DisplayDevice device)
{
throw new PlatformNotSupportedException(error_string);
}
public override IDisplayDeviceDriver CreateDisplayDeviceDriver()
{
throw new PlatformNotSupportedException(error_string);
}
public override IGraphicsContext CreateGLContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
{
throw new PlatformNotSupportedException(error_string);
}
public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
{
throw new PlatformNotSupportedException(error_string);
}
public override GraphicsContext.GetCurrentContextDelegate CreateGetCurrentGraphicsContext()
{
throw new PlatformNotSupportedException(error_string);
}
public override IKeyboardDriver2 CreateKeyboardDriver()
{
throw new PlatformNotSupportedException(error_string);
}
public override IMouseDriver2 CreateMouseDriver()
{
throw new PlatformNotSupportedException(error_string);
}
public override IJoystickDriver2 CreateJoystickDriver()
{
throw new PlatformNotSupportedException(error_string);
}
}
private void Dispose(bool manual)
{
if (!disposed)
{
if (manual)
{
Default.Dispose();
if (Embedded != Default)
{
Embedded.Dispose();
}
}
else
{
Debug.Print("{0} leaked, did you forget to call Dispose()?", GetType());
}
disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Factory()
{
Dispose(false);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Net;
using System.Security.Principal;
using System.DirectoryServices;
namespace System.DirectoryServices.AccountManagement
{
internal partial class SAMStoreCtx : StoreCtx
{
private DirectoryEntry _ctxBase;
private object _ctxBaseLock = new object(); // when mutating ctxBase
private bool _ownCtxBase; // if true, we "own" ctxBase and must Dispose of it when we're done
private bool _disposed = false;
internal NetCred Credentials { get { return _credentials; } }
private NetCred _credentials = null;
internal AuthenticationTypes AuthTypes { get { return _authTypes; } }
private AuthenticationTypes _authTypes;
private ContextOptions _contextOptions;
static SAMStoreCtx()
{
//
// Load the *PropertyMappingTableByProperty and *PropertyMappingTableByWinNT tables
//
s_userPropertyMappingTableByProperty = new Hashtable();
s_userPropertyMappingTableByWinNT = new Hashtable();
s_groupPropertyMappingTableByProperty = new Hashtable();
s_groupPropertyMappingTableByWinNT = new Hashtable();
s_computerPropertyMappingTableByProperty = new Hashtable();
s_computerPropertyMappingTableByWinNT = new Hashtable();
s_validPropertyMap = new Dictionary<string, ObjectMask>();
s_maskMap = new Dictionary<Type, ObjectMask>();
s_maskMap.Add(typeof(UserPrincipal), ObjectMask.User);
s_maskMap.Add(typeof(ComputerPrincipal), ObjectMask.Computer);
s_maskMap.Add(typeof(GroupPrincipal), ObjectMask.Group);
s_maskMap.Add(typeof(Principal), ObjectMask.Principal);
for (int i = 0; i < s_propertyMappingTableRaw.GetLength(0); i++)
{
string propertyName = s_propertyMappingTableRaw[i, 0] as string;
Type principalType = s_propertyMappingTableRaw[i, 1] as Type;
string winNTAttribute = s_propertyMappingTableRaw[i, 2] as string;
FromWinNTConverterDelegate fromWinNT = s_propertyMappingTableRaw[i, 3] as FromWinNTConverterDelegate;
ToWinNTConverterDelegate toWinNT = s_propertyMappingTableRaw[i, 4] as ToWinNTConverterDelegate;
Debug.Assert(propertyName != null);
Debug.Assert((winNTAttribute != null && fromWinNT != null) || (fromWinNT == null));
Debug.Assert(principalType == typeof(Principal) || principalType.IsSubclassOf(typeof(Principal)));
// Build the table entry. The same entry will be used in both tables.
// Once constructed, the table entries are treated as read-only, so there's
// no danger in sharing the entries between tables.
PropertyMappingTableEntry propertyEntry = new PropertyMappingTableEntry();
propertyEntry.propertyName = propertyName;
propertyEntry.suggestedWinNTPropertyName = winNTAttribute;
propertyEntry.winNTToPapiConverter = fromWinNT;
propertyEntry.papiToWinNTConverter = toWinNT;
// Add it to the appropriate tables
List<Hashtable> byPropertyTables = new List<Hashtable>();
List<Hashtable> byWinNTTables = new List<Hashtable>();
ObjectMask BitMask = 0;
if (principalType == typeof(UserPrincipal))
{
byPropertyTables.Add(s_userPropertyMappingTableByProperty);
byWinNTTables.Add(s_userPropertyMappingTableByWinNT);
BitMask = ObjectMask.User;
}
else if (principalType == typeof(ComputerPrincipal))
{
byPropertyTables.Add(s_computerPropertyMappingTableByProperty);
byWinNTTables.Add(s_computerPropertyMappingTableByWinNT);
BitMask = ObjectMask.Computer;
}
else if (principalType == typeof(GroupPrincipal))
{
byPropertyTables.Add(s_groupPropertyMappingTableByProperty);
byWinNTTables.Add(s_groupPropertyMappingTableByWinNT);
BitMask = ObjectMask.Group;
}
else
{
Debug.Assert(principalType == typeof(Principal));
byPropertyTables.Add(s_userPropertyMappingTableByProperty);
byPropertyTables.Add(s_computerPropertyMappingTableByProperty);
byPropertyTables.Add(s_groupPropertyMappingTableByProperty);
byWinNTTables.Add(s_userPropertyMappingTableByWinNT);
byWinNTTables.Add(s_computerPropertyMappingTableByWinNT);
byWinNTTables.Add(s_groupPropertyMappingTableByWinNT);
BitMask = ObjectMask.Principal;
}
if ((winNTAttribute == null) || (winNTAttribute == "*******"))
{
BitMask = ObjectMask.None;
}
ObjectMask currentMask;
if (s_validPropertyMap.TryGetValue(propertyName, out currentMask))
{
s_validPropertyMap[propertyName] = currentMask | BitMask;
}
else
{
s_validPropertyMap.Add(propertyName, BitMask);
}
// *PropertyMappingTableByProperty
// If toWinNT is null, there's no PAPI->WinNT mapping for this property
// (it's probably read-only, e.g., "LastLogon").
// if (toWinNT != null)
// {
foreach (Hashtable propertyMappingTableByProperty in byPropertyTables)
{
if (propertyMappingTableByProperty[propertyName] == null)
propertyMappingTableByProperty[propertyName] = new ArrayList();
((ArrayList)propertyMappingTableByProperty[propertyName]).Add(propertyEntry);
}
// }
// *PropertyMappingTableByWinNT
// If fromLdap is null, there's no direct WinNT->PAPI mapping for this property.
// It's probably a property that requires custom handling, such as an IdentityClaim.
if (fromWinNT != null)
{
string winNTAttributeLower = winNTAttribute.ToLower(CultureInfo.InvariantCulture);
foreach (Hashtable propertyMappingTableByWinNT in byWinNTTables)
{
if (propertyMappingTableByWinNT[winNTAttributeLower] == null)
propertyMappingTableByWinNT[winNTAttributeLower] = new ArrayList();
((ArrayList)propertyMappingTableByWinNT[winNTAttributeLower]).Add(propertyEntry);
}
}
}
}
// Throws exception if ctxBase is not a computer object
public SAMStoreCtx(DirectoryEntry ctxBase, bool ownCtxBase, string username, string password, ContextOptions options)
{
Debug.Assert(ctxBase != null);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Constructing SAMStoreCtx for {0}", ctxBase.Path);
Debug.Assert(SAMUtils.IsOfObjectClass(ctxBase, "Computer"));
_ctxBase = ctxBase;
_ownCtxBase = ownCtxBase;
if (username != null && password != null)
_credentials = new NetCred(username, password);
_contextOptions = options;
_authTypes = SDSUtils.MapOptionsToAuthTypes(options);
}
public override void Dispose()
{
try
{
if (!_disposed)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Dispose: disposing, ownCtxBase={0}", _ownCtxBase);
if (_ownCtxBase)
_ctxBase.Dispose();
_disposed = true;
}
}
finally
{
base.Dispose();
}
}
//
// StoreCtx information
//
// Retrieves the Path (ADsPath) of the object used as the base of the StoreCtx
internal override string BasePath
{
get
{
Debug.Assert(_ctxBase != null);
return _ctxBase.Path;
}
}
//
// CRUD
//
// Used to perform the specified operation on the Principal. They also make any needed security subsystem
// calls to obtain digitial signatures.
//
// Insert() and Update() must check to make sure no properties not supported by this StoreCtx
// have been set, prior to persisting the Principal.
internal override void Insert(Principal p)
{
Debug.Assert(p.unpersisted == true);
Debug.Assert(p.fakePrincipal == false);
try
{
// Insert the principal into the store
SDSUtils.InsertPrincipal(
p,
this,
new SDSUtils.GroupMembershipUpdater(UpdateGroupMembership),
_credentials,
_authTypes,
false // handled in PushChangesToNative
);
// Load in all the initial values from the store
((DirectoryEntry)p.UnderlyingObject).RefreshCache();
// Load in the StoreKey
Debug.Assert(p.Key == null); // since it was previously unpersisted
Debug.Assert(p.UnderlyingObject != null); // since we just persisted it
Debug.Assert(p.UnderlyingObject is DirectoryEntry);
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
// We just created a principal, so it should have an objectSid
Debug.Assert((de.Properties["objectSid"] != null) && (de.Properties["objectSid"].Count == 1));
SAMStoreKey key = new SAMStoreKey(
this.MachineFlatName,
(byte[])de.Properties["objectSid"].Value
);
p.Key = key;
// Reset the change tracking
p.ResetAllChangeStatus();
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Insert: new SID is ", Utils.ByteArrayToString((byte[])de.Properties["objectSid"].Value));
}
catch (System.Runtime.InteropServices.COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
internal override void Update(Principal p)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Update");
Debug.Assert(p.fakePrincipal == false);
Debug.Assert(p.unpersisted == false);
Debug.Assert(p.UnderlyingObject != null);
Debug.Assert(p.UnderlyingObject is DirectoryEntry);
try
{
// Commit the properties
SDSUtils.ApplyChangesToDirectory(
p,
this,
new SDSUtils.GroupMembershipUpdater(UpdateGroupMembership),
_credentials,
_authTypes
);
// Reset the change tracking
p.ResetAllChangeStatus();
}
catch (System.Runtime.InteropServices.COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
internal override void Delete(Principal p)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Delete");
Debug.Assert(p.fakePrincipal == false);
// Principal.Delete() shouldn't be calling us on an unpersisted Principal.
Debug.Assert(p.unpersisted == false);
Debug.Assert(p.UnderlyingObject != null);
Debug.Assert(p.UnderlyingObject is DirectoryEntry);
try
{
SDSUtils.DeleteDirectoryEntry((DirectoryEntry)p.UnderlyingObject);
}
catch (System.Runtime.InteropServices.COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
internal override bool AccessCheck(Principal p, PrincipalAccessMask targetPermission)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "AccessCheck " + targetPermission.ToString());
switch (targetPermission)
{
case PrincipalAccessMask.ChangePassword:
PropertyValueCollection values = ((DirectoryEntry)p.GetUnderlyingObject()).Properties["UserFlags"];
if (values.Count != 0)
{
Debug.Assert(values.Count == 1);
Debug.Assert(values[0] is int);
return (SDSUtils.StatusFromAccountControl((int)values[0], PropertyNames.PwdInfoCannotChangePassword));
}
Debug.Fail("SAMStoreCtx.AccessCheck: user entry has an empty UserFlags value");
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "AccessCheck Unable to read userAccountControl");
break;
default:
Debug.Fail("SAMStoreCtx.AccessCheck: Fell off end looking for " + targetPermission.ToString());
break;
}
return false;
}
internal override void Move(StoreCtx originalStore, Principal p)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Move");
}
//
// Special operations: the Principal classes delegate their implementation of many of the
// special methods to their underlying StoreCtx
//
// methods for manipulating accounts
/// <summary>
/// This method sets the default user account control bits for the new principal
/// being created in this account store.
/// </summary>
/// <param name="p"> Principal to set the user account control bits for </param>
internal override void InitializeUserAccountControl(AuthenticablePrincipal p)
{
Debug.Assert(p != null);
Debug.Assert(p.fakePrincipal == false);
Debug.Assert(p.unpersisted == true); // should only ever be called for new principals
// set the userAccountControl bits on the underlying directory entry
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Debug.Assert(de != null);
Type principalType = p.GetType();
if ((principalType == typeof(UserPrincipal)) || (principalType.IsSubclassOf(typeof(UserPrincipal))))
{
de.Properties["userFlags"].Value = SDSUtils.SAM_DefaultUAC;
}
}
internal override bool IsLockedOut(AuthenticablePrincipal p)
{
Debug.Assert(p.fakePrincipal == false);
Debug.Assert(p.unpersisted == false);
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Debug.Assert(de != null);
try
{
de.RefreshCache();
return (bool)de.InvokeGet("IsAccountLocked");
}
catch (System.Reflection.TargetInvocationException e)
{
if (e.InnerException is System.Runtime.InteropServices.COMException)
{
throw (ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e.InnerException));
}
throw;
}
}
internal override void UnlockAccount(AuthenticablePrincipal p)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UnlockAccount");
Debug.Assert(p.fakePrincipal == false);
Debug.Assert(p.unpersisted == false);
// Computer accounts are never locked out, so nothing to do
if (p is ComputerPrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UnlockAccount: computer acct, skipping");
return;
}
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Debug.Assert(de != null);
// After setting the property, we need to commit the change to the store.
// We do it in a copy of de, so that we don't inadvertently commit any other
// pending changes in de.
DirectoryEntry copyOfDe = null;
try
{
copyOfDe = SDSUtils.BuildDirectoryEntry(de.Path, _credentials, _authTypes);
Debug.Assert(copyOfDe != null);
copyOfDe.InvokeSet("IsAccountLocked", new object[] { false });
copyOfDe.CommitChanges();
}
catch (System.Runtime.InteropServices.COMException e)
{
// ADSI threw an exception trying to write the change
GlobalDebug.WriteLineIf(GlobalDebug.Error, "SAMStoreCtx", "UnlockAccount: caught COMException, message={0}", e.Message);
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
finally
{
if (copyOfDe != null)
copyOfDe.Dispose();
}
}
// methods for manipulating passwords
internal override void SetPassword(AuthenticablePrincipal p, string newPassword)
{
Debug.Assert(p.fakePrincipal == false);
Debug.Assert(p is UserPrincipal || p is ComputerPrincipal);
// Shouldn't be being called if this is the case
Debug.Assert(p.unpersisted == false);
// ********** In SAM, computer accounts don't have a set password method
if (p is ComputerPrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "SetPassword: computer acct, can't reset");
throw new InvalidOperationException(SR.SAMStoreCtxNoComputerPasswordSet);
}
Debug.Assert(p != null);
Debug.Assert(newPassword != null); // but it could be an empty string
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Debug.Assert(de != null);
SDSUtils.SetPassword(de, newPassword);
}
internal override void ChangePassword(AuthenticablePrincipal p, string oldPassword, string newPassword)
{
Debug.Assert(p.fakePrincipal == false);
Debug.Assert(p is UserPrincipal || p is ComputerPrincipal);
// Shouldn't be being called if this is the case
Debug.Assert(p.unpersisted == false);
// ********** In SAM, computer accounts don't have a change password method
if (p is ComputerPrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ChangePassword: computer acct, can't change");
throw new InvalidOperationException(SR.SAMStoreCtxNoComputerPasswordSet);
}
Debug.Assert(p != null);
Debug.Assert(newPassword != null); // but it could be an empty string
Debug.Assert(oldPassword != null); // but it could be an empty string
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Debug.Assert(de != null);
SDSUtils.ChangePassword(de, oldPassword, newPassword);
}
internal override void ExpirePassword(AuthenticablePrincipal p)
{
Debug.Assert(p.fakePrincipal == false);
// ********** In SAM, computer accounts don't have a password-expired property
if (p is ComputerPrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ExpirePassword: computer acct, can't expire");
throw new InvalidOperationException(SR.SAMStoreCtxNoComputerPasswordExpire);
}
WriteAttribute(p, "PasswordExpired", 1);
}
internal override void UnexpirePassword(AuthenticablePrincipal p)
{
Debug.Assert(p.fakePrincipal == false);
// ********** In SAM, computer accounts don't have a password-expired property
if (p is ComputerPrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "UnexpirePassword: computer acct, can't unexpire");
throw new InvalidOperationException(SR.SAMStoreCtxNoComputerPasswordExpire);
}
WriteAttribute(p, "PasswordExpired", 0);
}
private void WriteAttribute(AuthenticablePrincipal p, string attribute, int value)
{
Debug.Assert(p is UserPrincipal || p is ComputerPrincipal);
Debug.Assert(p != null);
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
SDSUtils.WriteAttribute(de.Path, attribute, value, _credentials, _authTypes);
}
//
// the various FindBy* methods
//
internal override ResultSet FindByLockoutTime(
DateTime dt, MatchType matchType, Type principalType)
{
throw new NotSupportedException(SR.StoreNotSupportMethod);
}
internal override ResultSet FindByBadPasswordAttempt(
DateTime dt, MatchType matchType, Type principalType)
{
throw new NotSupportedException(SR.StoreNotSupportMethod);
}
internal override ResultSet FindByLogonTime(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(FindByDateMatcher.DateProperty.LogonTime, matchType, dt, principalType);
}
internal override ResultSet FindByPasswordSetTime(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(FindByDateMatcher.DateProperty.PasswordSetTime, matchType, dt, principalType);
}
internal override ResultSet FindByExpirationTime(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(FindByDateMatcher.DateProperty.AccountExpirationTime, matchType, dt, principalType);
}
private ResultSet FindByDate(
FindByDateMatcher.DateProperty property,
MatchType matchType,
DateTime value,
Type principalType
)
{
// We use the same SAMQuery set that we use for query-by-example, but with a different
// SAMMatcher class to perform the date-range filter.
// Get the entries we'll iterate over. Write access to Children is controlled through the
// ctxBaseLock, but we don't want to have to hold that lock while we're iterating over all
// the child entries. So we have to clone the ctxBase --- not ideal, but it prevents
// multithreading issues.
DirectoryEntries entries = SDSUtils.BuildDirectoryEntry(_ctxBase.Path, _credentials, _authTypes).Children;
Debug.Assert(entries != null);
// The SAMQuerySet will use this to restrict the types of DirectoryEntry objects returned.
List<string> schemaTypes = GetSchemaFilter(principalType);
// Create the ResultSet that will perform the client-side filtering
SAMQuerySet resultSet = new SAMQuerySet(
schemaTypes,
entries,
_ctxBase,
-1, // no size limit
this,
new FindByDateMatcher(property, matchType, value));
return resultSet;
}
// Get groups of which p is a direct member
internal override ResultSet GetGroupsMemberOf(Principal p)
{
// Enforced by the methods that call us
Debug.Assert(p.unpersisted == false);
if (!p.fakePrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf: is real principal");
// No nested groups or computers as members of groups in SAM
if (!(p is UserPrincipal))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf: not a user, returning empty set");
return new EmptySet();
}
Debug.Assert(p.UnderlyingObject != null);
DirectoryEntry userDE = (DirectoryEntry)p.UnderlyingObject;
UnsafeNativeMethods.IADsMembers iadsMembers = (UnsafeNativeMethods.IADsMembers)userDE.Invoke("Groups");
ResultSet resultSet = new SAMGroupsSet(iadsMembers, this, _ctxBase);
return resultSet;
}
else
{
// ADSI's IADsGroups doesn't work for fake principals like NT AUTHORITY\NETWORK SERVICE
// We use the same SAMQuery set that we use for query-by-example, but with a different
// SAMMatcher class to match groups which contain the specified principal as a member
// Get the entries we'll iterate over. Write access to Children is controlled through the
// ctxBaseLock, but we don't want to have to hold that lock while we're iterating over all
// the child entries. So we have to clone the ctxBase --- not ideal, but it prevents
// multithreading issues.
DirectoryEntries entries = SDSUtils.BuildDirectoryEntry(_ctxBase.Path, _credentials, _authTypes).Children;
Debug.Assert(entries != null);
// The SAMQuerySet will use this to restrict the types of DirectoryEntry objects returned.
List<string> schemaTypes = GetSchemaFilter(typeof(GroupPrincipal));
SecurityIdentifier principalSid = p.Sid;
byte[] SidB = new byte[principalSid.BinaryLength];
principalSid.GetBinaryForm(SidB, 0);
if (principalSid == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOf: bad SID IC");
throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery);
}
// Create the ResultSet that will perform the client-side filtering
SAMQuerySet resultSet = new SAMQuerySet(
schemaTypes,
entries,
_ctxBase,
-1, // no size limit
this,
new GroupMemberMatcher(SidB));
return resultSet;
}
}
// Get groups from this ctx which contain a principal corresponding to foreignPrincipal
// (which is a principal from foreignContext)
internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreCtx foreignContext)
{
// If it's a fake principal, we don't need to do any of the lookup to find a local representation.
// We'll skip straight to GetGroupsMemberOf(Principal), which will lookup the groups to which it belongs via its SID.
if (foreignPrincipal.fakePrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf(ctx): is fake principal");
return GetGroupsMemberOf(foreignPrincipal);
}
// Get the Principal's SID, so we can look it up by SID in our store
SecurityIdentifier Sid = foreignPrincipal.Sid;
if (Sid == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOf(ctx): no SID IC");
throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery);
}
// In SAM, only users can be member of SAM groups (no nested groups)
UserPrincipal u = UserPrincipal.FindByIdentity(this.OwningContext, IdentityType.Sid, Sid.ToString());
// If no corresponding principal exists in this store, then by definition the principal isn't
// a member of any groups in this store.
if (u == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf(ctx): no corresponding user, returning empty set");
return new EmptySet();
}
// Now that we got the principal in our store, enumerating its group membership can be handled the
// usual way.
return GetGroupsMemberOf(u);
}
// Get groups of which p is a member, using AuthZ S4U APIs for recursive membership
internal override ResultSet GetGroupsMemberOfAZ(Principal p)
{
// Enforced by the methods that call us
Debug.Assert(p.unpersisted == false);
Debug.Assert(p is UserPrincipal);
// Get the user SID that AuthZ will use.
SecurityIdentifier Sid = p.Sid;
if (Sid == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOfAZ: no SID IC");
throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery);
}
byte[] Sidb = new byte[Sid.BinaryLength];
Sid.GetBinaryForm(Sidb, 0);
if (Sidb == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOfAZ: Bad SID IC");
throw new ArgumentException(SR.StoreCtxSecurityIdentityClaimBadFormat);
}
try
{
return new AuthZSet(Sidb, _credentials, _contextOptions, this.MachineFlatName, this, _ctxBase);
}
catch (System.Runtime.InteropServices.COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
// Get members of group g
internal override BookmarkableResultSet GetGroupMembership(GroupPrincipal g, bool recursive)
{
// Enforced by the methods that call us
Debug.Assert(g.unpersisted == false);
// Fake groups are a member of other groups, but they themselves have no members
// (they don't even exist in the store)
if (g.fakePrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupMembership: is fake principal, returning empty set");
return new EmptySet();
}
Debug.Assert(g.UnderlyingObject != null);
DirectoryEntry groupDE = (DirectoryEntry)g.UnderlyingObject;
UnsafeNativeMethods.IADsGroup iADsGroup = (UnsafeNativeMethods.IADsGroup)groupDE.NativeObject;
BookmarkableResultSet resultSet = new SAMMembersSet(groupDE.Path, iADsGroup, recursive, this, _ctxBase);
return resultSet;
}
// Is p a member of g in the store?
internal override bool SupportsNativeMembershipTest { get { return false; } }
internal override bool IsMemberOfInStore(GroupPrincipal g, Principal p)
{
Debug.Fail("SAMStoreCtx.IsMemberOfInStore: Shouldn't be here.");
return false;
}
// Can a Clear() operation be performed on the specified group? If not, also returns
// a string containing a human-readable explanation of why not, suitable for use in an exception.
internal override bool CanGroupBeCleared(GroupPrincipal g, out string explanationForFailure)
{
// Always true for this type of StoreCtx
explanationForFailure = null;
return true;
}
// Can the given member be removed from the specified group? If not, also returns
// a string containing a human-readable explanation of why not, suitable for use in an exception.
internal override bool CanGroupMemberBeRemoved(GroupPrincipal g, Principal member, out string explanationForFailure)
{
// Always true for this type of StoreCtx
explanationForFailure = null;
return true;
}
//
// Cross-store support
//
// Given a native store object that represents a "foreign" principal (e.g., a FPO object in this store that
// represents a pointer to another store), maps that representation to the other store's StoreCtx and returns
// a Principal from that other StoreCtx. The implementation of this method is highly dependent on the
// details of the particular store, and must have knowledge not only of this StoreCtx, but also of how to
// interact with other StoreCtxs to fulfill the request.
//
// This method is typically used by ResultSet implementations, when they're iterating over a collection
// (e.g., of group membership) and encounter an entry that represents a foreign principal.
internal override Principal ResolveCrossStoreRefToPrincipal(object o)
{
Debug.Assert(o is DirectoryEntry);
// Get the SID of the foreign principal
DirectoryEntry foreignDE = (DirectoryEntry)o;
if (foreignDE.Properties["objectSid"].Count == 0)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: no objectSid found");
throw new PrincipalOperationException(SR.SAMStoreCtxCantRetrieveObjectSidForCrossStore);
}
Debug.Assert(foreignDE.Properties["objectSid"].Count == 1);
byte[] sid = (byte[])foreignDE.Properties["objectSid"].Value;
// Ask the OS to resolve the SID to its target.
int accountUsage = 0;
string name;
string domainName;
int err = Utils.LookupSid(this.MachineUserSuppliedName, _credentials, sid, out name, out domainName, out accountUsage);
if (err != 0)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn,
"SAMStoreCtx",
"ResolveCrossStoreRefToPrincipal: LookupSid failed, err={0}, server={1}",
err,
this.MachineUserSuppliedName);
throw new PrincipalOperationException(
SR.Format(SR.SAMStoreCtxCantResolveSidForCrossStore, err));
}
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"SAMStoreCtx",
"ResolveCrossStoreRefToPrincipal: LookupSid found {0} in {1}",
name,
domainName);
// Since this is SAM, the remote principal must be an AD principal.
// Build a PrincipalContext for the store which owns the principal
// Use the ad default options so we turn sign and seal back on.
#if USE_CTX_CACHE
PrincipalContext remoteCtx = SDSCache.Domain.GetContext(domainName, _credentials, DefaultContextOptions.ADDefaultContextOption);
#else
PrincipalContext remoteCtx = new PrincipalContext(
ContextType.Domain,
domainName,
null,
(this.credentials != null ? credentials.UserName : null),
(this.credentials != null ? credentials.Password : null),
DefaultContextOptions.ADDefaultContextOption);
#endif
SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0);
Principal p = remoteCtx.QueryCtx.FindPrincipalByIdentRef(
typeof(Principal),
UrnScheme.SidScheme,
sidObj.ToString(),
DateTime.UtcNow);
if (p != null)
return p;
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: no matching principal");
throw new PrincipalOperationException(SR.SAMStoreCtxFailedFindCrossStoreTarget);
}
}
//
// Data Validation
//
// Returns true if AccountInfo is supported for the specified principal, false otherwise.
// Used when an application tries to access the AccountInfo property of a newly-inserted
// (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed.
internal override bool SupportsAccounts(AuthenticablePrincipal p)
{
// Fake principals do not have store objects, so they certainly don't have stored account info.
if (p.fakePrincipal)
return false;
// Both Computer and User support accounts.
return true;
}
// Returns the set of credential types supported by this store for the specified principal.
// Used when an application tries to access the PasswordInfo property of a newly-inserted
// (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed.
// Also used to implement AuthenticablePrincipal.SupportedCredentialTypes.
internal override CredentialTypes SupportedCredTypes(AuthenticablePrincipal p)
{
// Fake principals do not have store objects, so they certainly don't have stored creds.
if (p.fakePrincipal)
return (CredentialTypes)0;
CredentialTypes supportedTypes = CredentialTypes.Password;
// Longhorn SAM supports certificate-based authentication
if (this.IsLSAM)
supportedTypes |= CredentialTypes.Certificate;
return supportedTypes;
}
//
// Construct a fake Principal to represent a well-known SID like
// "\Everyone" or "NT AUTHORITY\NETWORK SERVICE"
//
internal override Principal ConstructFakePrincipalFromSID(byte[] sid)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"SAMStoreCtx",
"ConstructFakePrincipalFromSID: sid={0}, machine={1}",
Utils.ByteArrayToString(sid),
this.MachineFlatName);
Principal p = Utils.ConstructFakePrincipalFromSID(
sid,
this.OwningContext,
this.MachineUserSuppliedName,
_credentials,
this.MachineUserSuppliedName);
// Assign it a StoreKey
SAMStoreKey key = new SAMStoreKey(this.MachineFlatName, sid);
p.Key = key;
return p;
}
//
// Private data
//
private bool IsLSAM // IsLonghornSAM (also called MSAM or LH-SAM)
{
get
{
if (!_isLSAM.HasValue)
{
lock (_computerInfoLock)
{
if (!_isLSAM.HasValue)
LoadComputerInfo();
}
}
Debug.Assert(_isLSAM.HasValue);
return _isLSAM.Value;
}
}
internal string MachineUserSuppliedName
{
get
{
if (_machineUserSuppliedName == null)
{
lock (_computerInfoLock)
{
if (_machineUserSuppliedName == null)
LoadComputerInfo();
}
}
Debug.Assert(_machineUserSuppliedName != null);
return _machineUserSuppliedName;
}
}
internal string MachineFlatName
{
get
{
if (_machineFlatName == null)
{
lock (_computerInfoLock)
{
if (_machineFlatName == null)
LoadComputerInfo();
}
}
Debug.Assert(_machineFlatName != null);
return _machineFlatName;
}
}
private object _computerInfoLock = new object();
private Nullable<bool> _isLSAM = null;
private string _machineUserSuppliedName = null;
private string _machineFlatName = null;
// computerInfoLock must be held coming in here
private void LoadComputerInfo()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo");
Debug.Assert(_ctxBase != null);
Debug.Assert(SAMUtils.IsOfObjectClass(_ctxBase, "Computer"));
//
// Target OS version
//
int versionMajor;
int versionMinor;
if (!SAMUtils.GetOSVersion(_ctxBase, out versionMajor, out versionMinor))
{
throw new PrincipalOperationException(SR.SAMStoreCtxUnableToRetrieveVersion);
}
Debug.Assert(versionMajor > 0);
Debug.Assert(versionMinor >= 0);
if (versionMajor >= 6) // 6.0 == Longhorn
_isLSAM = true;
else
_isLSAM = false;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo: ver={0}.{1}", versionMajor, versionMinor);
//
// Machine user-supplied name
//
// This ADSI property stores the machine name as supplied by the user in the ADsPath.
// It could be a flat name or a DNS name.
if (_ctxBase.Properties["Name"].Count > 0)
{
Debug.Assert(_ctxBase.Properties["Name"].Count == 1);
_machineUserSuppliedName = (string)_ctxBase.Properties["Name"].Value;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo: machineUserSuppliedName={0}", _machineUserSuppliedName);
}
else
{
throw new PrincipalOperationException(SR.SAMStoreCtxUnableToRetrieveMachineName);
}
//
// Machine flat name
//
IntPtr buffer = IntPtr.Zero;
try
{
// This function takes in a flat or DNS name, and returns the flat name of the computer
int err = UnsafeNativeMethods.NetWkstaGetInfo(_machineUserSuppliedName, 100, ref buffer);
if (err == 0)
{
UnsafeNativeMethods.WKSTA_INFO_100 wkstaInfo =
(UnsafeNativeMethods.WKSTA_INFO_100)Marshal.PtrToStructure(buffer, typeof(UnsafeNativeMethods.WKSTA_INFO_100));
_machineFlatName = wkstaInfo.wki100_computername;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo: machineFlatName={0}", _machineFlatName);
}
else
{
throw new PrincipalOperationException(
SR.Format(
SR.SAMStoreCtxUnableToRetrieveFlatMachineName,
err));
}
}
finally
{
if (buffer != IntPtr.Zero)
UnsafeNativeMethods.NetApiBufferFree(buffer);
}
}
internal override bool IsValidProperty(Principal p, string propertyName)
{
ObjectMask value = ObjectMask.None;
if (s_validPropertyMap.TryGetValue(propertyName, out value))
{
return ((s_maskMap[p.GetType()] & value) > 0 ? true : false);
}
else
{
Debug.Fail("Property not found");
return false;
}
}
}
}
// #endif // PAPI_REGSAM
| |
// Copyright 2016 Applied Geographics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web.UI.HtmlControls;
public partial class Admin_CheckConfiguration : CustomStyledPage
{
private const int ColumnCount = 5;
protected void cmdRecheck_Click(object sender, EventArgs e)
{
ViewState["Step"] = 0;
}
protected void Page_PreRender(object sender, EventArgs e)
{
if (ViewState["Step"] == null || (int)ViewState["Step"] == 0)
{
labMessage.InnerText = "Analyzing configuration, please wait ...";
cmdRecheck.Visible = false;
tblReport.Visible = false;
string script = "$('body').find('*').css('cursor', 'wait'); document.forms[0].submit();";
ClientScript.RegisterStartupScript(typeof(Admin_CheckConfiguration), "start", script, true);
ViewState["Step"] = 1;
}
else
{
cmdRecheck.Visible = true;
tblReport.Visible = true;
tblReport.Rows.Clear();
LayoutColumns();
Configuration config = Configuration.GetCurrent();
config.CascadeDeactivated();
config.RemoveDeactivated();
config.ValidateConfiguration();
int errorCount = WriteSettingsBlock(config);
errorCount += WriteReportBlock(config.Application, "ApplicationID", null);
errorCount += WriteReportBlock(config.ApplicationMapTab, "ApplicationID", "MapTabID");
errorCount += WriteReportBlock(config.ApplicationMarkupCategory, "ApplicationID", "CategoryID");
errorCount += WriteReportBlock(config.ApplicationPrintTemplate, "ApplicationID", "TemplateID");
errorCount += WriteReportBlock(config.Connection, "ConnectionID", null);
errorCount += WriteReportBlock(config.DataTab, "DataTabID", "LayerID");
errorCount += WriteReportBlock(config.Layer, "LayerID", null);
errorCount += WriteReportBlock(config.LayerFunction, "LayerID", "FunctionName");
errorCount += WriteReportBlock(config.LayerProximity, "LayerID", "ProximityID");
errorCount += WriteReportBlock(config.Level, "LevelID", "ZoneLevelID");
errorCount += WriteReportBlock(config.MapTab, "MapTabID", null);
errorCount += WriteReportBlock(config.MapTabLayer, "MapTabID", "LayerID");
errorCount += WriteReportBlock(config.MapTabTileGroup, "MapTabID", "TileGroupID");
errorCount += WriteReportBlock(config.MarkupCategory, "CategoryID", null);
errorCount += WriteReportBlock(config.PrintTemplate, "TemplateID", null);
errorCount += WriteReportBlock(config.PrintTemplateContent, "TemplateID", "SequenceNo");
errorCount += WriteReportBlock(config.Proximity, "ProximityID", null);
errorCount += WriteReportBlock(config.Query, "QueryID", "LayerID");
errorCount += WriteReportBlock(config.Search, "SearchID", "LayerID");
errorCount += WriteReportBlock(config.SearchInputField, "FieldID", "SearchID");
errorCount += WriteReportBlock(config.TileGroup, "TileGroupID", null);
errorCount += WriteReportBlock(config.TileLayer, "TileLayerID", null);
errorCount += WriteReportBlock(config.Zone, "ZoneID", "ZoneLevelID");
errorCount += WriteReportBlock(config.ZoneLevel, "ZoneLevelID", null);
errorCount += WriteReportBlock(config.ZoneLevelCombo, "ZoneID,LevelID", "ZoneLevelID");
labMessage.InnerText = errorCount == 0 ? "No errors found" : errorCount == 1 ? "1 error found" : String.Format("{0} errors found", errorCount);
IAdminMasterPage master = (IAdminMasterPage)Master;
if (master.ReloadRequested)
{
config.RemoveValidationErrors();
master.ReloadConfiguration(config);
}
}
}
private string CheckColor(Color color)
{
return color.IsEmpty ? "Not set or not a valid HTML color specification" : null;
}
private string CheckGreaterThanZero(int value)
{
return value == Int32.MinValue ? "Not set" : value <= 0 ? "Must be greater than 0" : null;
}
private string CheckGreaterThanZero(double value)
{
return Double.IsNaN(value) ? "Not set" : value <= 0 ? "Must be greater than 0.0" : null;
}
private string CheckInRange(double value, double minValue, double maxValue)
{
return Double.IsNaN(value) ? "Not set" : value < minValue || maxValue < value ? String.Format("Must be between {0:0.0} and {1:0.0}", minValue, maxValue) : null;
}
private string CheckInValues(string value, List<String> validValues)
{
if (String.IsNullOrEmpty(value))
{
return "Not set";
}
if (!validValues.Contains(value))
{
validValues = validValues.Select(o => String.Format("\"{0}\"", o)).ToList();
return "Must be " + String.Join(", ", validValues.Take(validValues.Count - 1).ToArray()) + " or " + validValues[validValues.Count - 1];
}
return null;
}
private string CheckIsSet(int value)
{
return value == Int32.MinValue ? "Not set" : null;
}
private string CheckIsSet(double value)
{
return Double.IsNaN(value) ? "Not set" : null;
}
private void LayoutColumns()
{
HtmlTableRow tr = new HtmlTableRow();
tr.Attributes["class"] = "ReportLayout";
tblReport.Rows.Add(tr);
HtmlTableCell td = new HtmlTableCell();
tr.Cells.Add(td);
td.Width = "20px";
td.Height = "0px";
td = new HtmlTableCell();
tr.Cells.Add(td);
td.Width = "120px";
td.Height = "0px";
td = new HtmlTableCell();
tr.Cells.Add(td);
td.Width = "120px";
td.Height = "0px";
td = new HtmlTableCell();
tr.Cells.Add(td);
td.Width = "50px";
td.Height = "0px";
td = new HtmlTableCell();
tr.Cells.Add(td);
td.Width = "500px";
td.Height = "0px";
}
private int WriteSettingsBlock(Configuration config)
{
AppSettings appSettings = config.AppSettings;
List<String> name = new List<String>();
List<String> message = new List<String>();
// check AdminEmail
name.Add("AdminEmail");
message.Add(appSettings.AdminEmail == null ? "Not set" : null);
// check DefaultApplication
name.Add("DefaultApplication");
bool hasApplication = !String.IsNullOrEmpty(appSettings.DefaultApplication) && config.Application.Any(o => String.Compare(o.ApplicationID, appSettings.DefaultApplication, true) == 0);
message.Add(!hasApplication ? "Not set to a valid application ID" : null);
// check FullExtent
name.Add("FullExtent");
message.Add(appSettings.DefaultFullExtent == null ? "Not set or incorrectly specified, must be four comma-separated numbers" : null);
// check projections
name.Add("MapProjection");
message.Add(appSettings.MapCoordinateSystem == null ? "Not set or incorrectly specified, must be a Proj4 string" : null);
name.Add("MeasureProjection");
message.Add(appSettings.MeasureCoordinateSystem == null ? "Not set or incorrectly specified, must be a Proj4 string" : null);
int errorCount = message.Where(o => o != null).Count();
// write header
HtmlTableRow tr = new HtmlTableRow();
tblReport.Rows.Add(tr);
tr.Attributes["class"] = errorCount == 0 ? "ReportHeader Closed" : "ReportHeader Opened";
HtmlTableCell td = new HtmlTableCell();
tr.Cells.Add(td);
td.ColSpan = 3;
td.Attributes["unselectable"] = "on";
td.InnerText = WebConfigSettings.ConfigurationTablePrefix + "Setting";
td = new HtmlTableCell();
tr.Cells.Add(td);
td.ColSpan = 2;
td.Attributes["unselectable"] = "on";
if (errorCount > 0)
{
td.InnerText = String.Format("{0} {1}", errorCount, errorCount == 1 ? "error" : "errors");
}
// report on settings
for (int i = 0; i < name.Count; ++i)
{
tr = new HtmlTableRow();
tblReport.Rows.Add(tr);
tr.Attributes["class"] = "ReportRow";
if (errorCount == 0)
{
tr.Style["display"] = "none";
}
td = new HtmlTableCell();
tr.Cells.Add(td);
td = new HtmlTableCell();
tr.Cells.Add(td);
td.VAlign = "top";
td.InnerText = name[i];
td = new HtmlTableCell();
tr.Cells.Add(td);
td = new HtmlTableCell();
tr.Cells.Add(td);
td.VAlign = "top";
td.InnerText = String.IsNullOrEmpty(message[i]) ? "OK" : "invalid";
td = new HtmlTableCell();
tr.Cells.Add(td);
td.VAlign = "top";
if (!String.IsNullOrEmpty(message[i]))
{
td.InnerText = message[i];
}
}
tr = new HtmlTableRow();
tblReport.Rows.Add(tr);
tr.Attributes["class"] = "ReportSpacer";
td = new HtmlTableCell();
tr.Cells.Add(td);
td.ColSpan = ColumnCount;
td.Height = "6px";
return errorCount;
}
private int WriteReportBlock(DataTable table, string idColumns, string linkColumn)
{
string sortOrder = idColumns;
if (linkColumn != null)
{
sortOrder += ", " + linkColumn;
}
DataRow[] row = table.Select("", sortOrder);
int errorCount = row.Count(o => !o.IsNull("ValidationError"));
HtmlTableRow tr = new HtmlTableRow();
tblReport.Rows.Add(tr);
tr.Attributes["class"] = errorCount == 0 ? "ReportHeader Closed" : "ReportHeader Opened";
HtmlTableCell td = new HtmlTableCell();
tr.Cells.Add(td);
td.ColSpan = 3;
td.InnerText = WebConfigSettings.ConfigurationTablePrefix + table.TableName;
td = new HtmlTableCell();
tr.Cells.Add(td);
td.ColSpan = 2;
if (row.Length == 0)
{
td.InnerText = "(no rows)";
}
else if (errorCount > 0)
{
td.InnerText += String.Format("{0} {1}", errorCount, errorCount == 1 ? "error" : "errors");
}
for (int i = 0; i < row.Length; ++i)
{
tr = new HtmlTableRow();
tblReport.Rows.Add(tr);
tr.Attributes["class"] = "ReportRow";
if (errorCount == 0)
{
tr.Style["display"] = "none";
}
td = new HtmlTableCell();
tr.Cells.Add(td);
td.Align = "right";
td.VAlign = "top";
td.InnerText = (i + 1).ToString();
td = new HtmlTableCell();
tr.Cells.Add(td);
td.VAlign = "top";
string[] idColumn = idColumns.Split(',');
td.InnerText = row[i][idColumn[0]].ToString();
for (int j = 1; j < idColumn.Length; ++j)
{
td.InnerText += ", " + row[i][idColumn[j]].ToString();
}
td = new HtmlTableCell();
tr.Cells.Add(td);
td.VAlign = "top";
if (linkColumn != null)
{
td.InnerText = row[i][linkColumn].ToString();
}
td = new HtmlTableCell();
tr.Cells.Add(td);
td.VAlign = "top";
td.InnerText = row[i].IsNull("ValidationError") ? "OK" : "invalid";
td = new HtmlTableCell();
tr.Cells.Add(td);
td.VAlign = "top";
if (!row[i].IsNull("ValidationError"))
{
td.InnerText = row[i]["ValidationError"].ToString();
}
}
tr = new HtmlTableRow();
tblReport.Rows.Add(tr);
tr.Attributes["class"] = "ReportSpacer";
td = new HtmlTableCell();
tr.Cells.Add(td);
td.ColSpan = ColumnCount;
td.Height = "6px";
return errorCount;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using FieldInvertState = Lucene.Net.Index.FieldInvertState;
using Term = Lucene.Net.Index.Term;
using SmallFloat = Lucene.Net.Util.SmallFloat;
using IDFExplanation = Lucene.Net.Search.Explanation.IDFExplanation;
namespace Lucene.Net.Search
{
/// <summary>Expert: Scoring API.
/// <p/>Subclasses implement search scoring.
///
/// <p/>The score of query <code>q</code> for document <code>d</code> correlates to the
/// cosine-distance or dot-product between document and query vectors in a
/// <a href="http://en.wikipedia.org/wiki/Vector_Space_Model">
/// Vector Space Model (VSM) of Information Retrieval</a>.
/// A document whose vector is closer to the query vector in that model is scored higher.
///
/// The score is computed as follows:
///
/// <p/>
/// <table cellpadding="1" cellspacing="0" border="1" align="center">
/// <tr><td>
/// <table cellpadding="1" cellspacing="0" border="0" align="center">
/// <tr>
/// <td valign="middle" align="right" rowspan="1">
/// score(q,d)   =  
/// <A HREF="#formula_coord">coord(q,d)</A>  · 
/// <A HREF="#formula_queryNorm">queryNorm(q)</A>  · 
/// </td>
/// <td valign="bottom" align="center" rowspan="1">
/// <big><big><big>∑</big></big></big>
/// </td>
/// <td valign="middle" align="right" rowspan="1">
/// <big><big>(</big></big>
/// <A HREF="#formula_tf">tf(t in d)</A>  · 
/// <A HREF="#formula_idf">idf(t)</A><sup>2</sup>  · 
/// <A HREF="#formula_termBoost">t.getBoost()</A> · 
/// <A HREF="#formula_norm">norm(t,d)</A>
/// <big><big>)</big></big>
/// </td>
/// </tr>
/// <tr valigh="top">
/// <td></td>
/// <td align="center"><small>t in q</small></td>
/// <td></td>
/// </tr>
/// </table>
/// </td></tr>
/// </table>
///
/// <p/> where
/// <ol>
/// <li>
/// <A NAME="formula_tf"></A>
/// <b>tf(t in d)</b>
/// correlates to the term's <i>frequency</i>,
/// defined as the number of times term <i>t</i> appears in the currently scored document <i>d</i>.
/// Documents that have more occurrences of a given term receive a higher score.
/// The default computation for <i>tf(t in d)</i> in
/// {@link Lucene.Net.Search.DefaultSimilarity#Tf(float) DefaultSimilarity} is:
///
/// <br/> <br/>
/// <table cellpadding="2" cellspacing="2" border="0" align="center">
/// <tr>
/// <td valign="middle" align="right" rowspan="1">
/// {@link Lucene.Net.Search.DefaultSimilarity#Tf(float) tf(t in d)}   =  
/// </td>
/// <td valign="top" align="center" rowspan="1">
/// frequency<sup><big>½</big></sup>
/// </td>
/// </tr>
/// </table>
/// <br/> <br/>
/// </li>
///
/// <li>
/// <A NAME="formula_idf"></A>
/// <b>idf(t)</b> stands for Inverse Document Frequency. This value
/// correlates to the inverse of <i>docFreq</i>
/// (the number of documents in which the term <i>t</i> appears).
/// This means rarer terms give higher contribution to the total score.
/// The default computation for <i>idf(t)</i> in
/// {@link Lucene.Net.Search.DefaultSimilarity#Idf(int, int) DefaultSimilarity} is:
///
/// <br/> <br/>
/// <table cellpadding="2" cellspacing="2" border="0" align="center">
/// <tr>
/// <td valign="middle" align="right">
/// {@link Lucene.Net.Search.DefaultSimilarity#Idf(int, int) idf(t)}  =  
/// </td>
/// <td valign="middle" align="center">
/// 1 + log <big>(</big>
/// </td>
/// <td valign="middle" align="center">
/// <table>
/// <tr><td align="center"><small>numDocs</small></td></tr>
/// <tr><td align="center">–––––––––</td></tr>
/// <tr><td align="center"><small>docFreq+1</small></td></tr>
/// </table>
/// </td>
/// <td valign="middle" align="center">
/// <big>)</big>
/// </td>
/// </tr>
/// </table>
/// <br/> <br/>
/// </li>
///
/// <li>
/// <A NAME="formula_coord"></A>
/// <b>coord(q,d)</b>
/// is a score factor based on how many of the query terms are found in the specified document.
/// Typically, a document that contains more of the query's terms will receive a higher score
/// than another document with fewer query terms.
/// This is a search time factor computed in
/// {@link #Coord(int, int) coord(q,d)}
/// by the Similarity in effect at search time.
/// <br/> <br/>
/// </li>
///
/// <li><b>
/// <A NAME="formula_queryNorm"></A>
/// queryNorm(q)
/// </b>
/// is a normalizing factor used to make scores between queries comparable.
/// This factor does not affect document ranking (since all ranked documents are multiplied by the same factor),
/// but rather just attempts to make scores from different queries (or even different indexes) comparable.
/// This is a search time factor computed by the Similarity in effect at search time.
///
/// The default computation in
/// {@link Lucene.Net.Search.DefaultSimilarity#QueryNorm(float) DefaultSimilarity}
/// is:
/// <br/> <br/>
/// <table cellpadding="1" cellspacing="0" border="0" align="center">
/// <tr>
/// <td valign="middle" align="right" rowspan="1">
/// queryNorm(q)   =  
/// {@link Lucene.Net.Search.DefaultSimilarity#QueryNorm(float) queryNorm(sumOfSquaredWeights)}
///   =  
/// </td>
/// <td valign="middle" align="center" rowspan="1">
/// <table>
/// <tr><td align="center"><big>1</big></td></tr>
/// <tr><td align="center"><big>
/// ––––––––––––––
/// </big></td></tr>
/// <tr><td align="center">sumOfSquaredWeights<sup><big>½</big></sup></td></tr>
/// </table>
/// </td>
/// </tr>
/// </table>
/// <br/> <br/>
///
/// The sum of squared weights (of the query terms) is
/// computed by the query {@link Lucene.Net.Search.Weight} object.
/// For example, a {@link Lucene.Net.Search.BooleanQuery boolean query}
/// computes this value as:
///
/// <br/> <br/>
/// <table cellpadding="1" cellspacing="0" border="0" align="center">
/// <tr>
/// <td valign="middle" align="right" rowspan="1">
/// {@link Lucene.Net.Search.Weight#SumOfSquaredWeights() sumOfSquaredWeights}   =  
/// {@link Lucene.Net.Search.Query#GetBoost() q.getBoost()} <sup><big>2</big></sup>
///  · 
/// </td>
/// <td valign="bottom" align="center" rowspan="1">
/// <big><big><big>∑</big></big></big>
/// </td>
/// <td valign="middle" align="right" rowspan="1">
/// <big><big>(</big></big>
/// <A HREF="#formula_idf">idf(t)</A>  · 
/// <A HREF="#formula_termBoost">t.getBoost()</A>
/// <big><big>) <sup>2</sup> </big></big>
/// </td>
/// </tr>
/// <tr valigh="top">
/// <td></td>
/// <td align="center"><small>t in q</small></td>
/// <td></td>
/// </tr>
/// </table>
/// <br/> <br/>
///
/// </li>
///
/// <li>
/// <A NAME="formula_termBoost"></A>
/// <b>t.getBoost()</b>
/// is a search time boost of term <i>t</i> in the query <i>q</i> as
/// specified in the query text
/// (see <A HREF="../../../../../../queryparsersyntax.html#Boosting a Term">query syntax</A>),
/// or as set by application calls to
/// {@link Lucene.Net.Search.Query#SetBoost(float) setBoost()}.
/// Notice that there is really no direct API for accessing a boost of one term in a multi term query,
/// but rather multi terms are represented in a query as multi
/// {@link Lucene.Net.Search.TermQuery TermQuery} objects,
/// and so the boost of a term in the query is accessible by calling the sub-query
/// {@link Lucene.Net.Search.Query#GetBoost() getBoost()}.
/// <br/> <br/>
/// </li>
///
/// <li>
/// <A NAME="formula_norm"></A>
/// <b>norm(t,d)</b> encapsulates a few (indexing time) boost and length factors:
///
/// <ul>
/// <li><b>Document boost</b> - set by calling
/// {@link Lucene.Net.Documents.Document#SetBoost(float) doc.setBoost()}
/// before adding the document to the index.
/// </li>
/// <li><b>Field boost</b> - set by calling
/// {@link Lucene.Net.Documents.Fieldable#SetBoost(float) field.setBoost()}
/// before adding the field to a document.
/// </li>
/// <li>{@link #LengthNorm(String, int) <b>lengthNorm</b>(field)} - computed
/// when the document is added to the index in accordance with the number of tokens
/// of this field in the document, so that shorter fields contribute more to the score.
/// LengthNorm is computed by the Similarity class in effect at indexing.
/// </li>
/// </ul>
///
/// <p/>
/// When a document is added to the index, all the above factors are multiplied.
/// If the document has multiple fields with the same name, all their boosts are multiplied together:
///
/// <br/> <br/>
/// <table cellpadding="1" cellspacing="0" border="0" align="center">
/// <tr>
/// <td valign="middle" align="right" rowspan="1">
/// norm(t,d)   =  
/// {@link Lucene.Net.Documents.Document#GetBoost() doc.getBoost()}
///  · 
/// {@link #LengthNorm(String, int) lengthNorm(field)}
///  · 
/// </td>
/// <td valign="bottom" align="center" rowspan="1">
/// <big><big><big>∏</big></big></big>
/// </td>
/// <td valign="middle" align="right" rowspan="1">
/// {@link Lucene.Net.Documents.Fieldable#GetBoost() f.getBoost}()
/// </td>
/// </tr>
/// <tr valigh="top">
/// <td></td>
/// <td align="center"><small>field <i><b>f</b></i> in <i>d</i> named as <i><b>t</b></i></small></td>
/// <td></td>
/// </tr>
/// </table>
/// <br/> <br/>
/// However the resulted <i>norm</i> value is {@link #EncodeNorm(float) encoded} as a single byte
/// before being stored.
/// At search time, the norm byte value is read from the index
/// {@link Lucene.Net.Store.Directory directory} and
/// {@link #DecodeNorm(byte) decoded} back to a float <i>norm</i> value.
/// This encoding/decoding, while reducing index size, comes with the price of
/// precision loss - it is not guaranteed that decode(encode(x)) = x.
/// For instance, decode(encode(0.89)) = 0.75.
/// Also notice that search time is too late to modify this <i>norm</i> part of scoring, e.g. by
/// using a different {@link Similarity} for search.
/// <br/> <br/>
/// </li>
/// </ol>
///
/// </summary>
/// <seealso cref="SetDefault(Similarity)">
/// </seealso>
/// <seealso cref="Lucene.Net.Index.IndexWriter.SetSimilarity(Similarity)">
/// </seealso>
/// <seealso cref="Searcher.SetSimilarity(Similarity)">
/// </seealso>
[Serializable]
public abstract class Similarity
{
public Similarity()
{
InitBlock();
}
[Serializable]
private class AnonymousClassIDFExplanation:IDFExplanation
{
public AnonymousClassIDFExplanation(float idf, Similarity enclosingInstance)
{
InitBlock(idf, enclosingInstance);
}
private void InitBlock(float idf, Similarity enclosingInstance)
{
this.idf = idf;
this.enclosingInstance = enclosingInstance;
}
private float idf;
private Similarity enclosingInstance;
public Similarity Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
//@Override
public override float GetIdf()
{
return idf;
}
//@Override
public override System.String Explain()
{
return "Inexplicable";
}
}
[Serializable]
private class AnonymousClassIDFExplanation1:IDFExplanation
{
public AnonymousClassIDFExplanation1(int df, int max, float idf, Similarity enclosingInstance)
{
InitBlock(df, max, idf, enclosingInstance);
}
private void InitBlock(int df, int max, float idf, Similarity enclosingInstance)
{
this.df = df;
this.max = max;
this.idf = idf;
this.enclosingInstance = enclosingInstance;
}
private int df;
private int max;
private float idf;
private Similarity enclosingInstance;
public Similarity Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
//@Override
public override System.String Explain()
{
return "idf(docFreq=" + df + ", maxDocs=" + max + ")";
}
//@Override
public override float GetIdf()
{
return idf;
}
}
[Serializable]
private class AnonymousClassIDFExplanation2:IDFExplanation
{
public AnonymousClassIDFExplanation2(float idf, Similarity enclosingInstance)
{
InitBlock(idf, enclosingInstance);
}
private void InitBlock(float idf, Similarity enclosingInstance)
{
this.idf = idf;
this.enclosingInstance = enclosingInstance;
}
private float idf;
private Similarity enclosingInstance;
public Similarity Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
//@Override
public override float GetIdf()
{
return idf;
}
//@Override
public override System.String Explain()
{
return "Inexplicable";
}
}
[Serializable]
private class AnonymousClassIDFExplanation3:IDFExplanation
{
public AnonymousClassIDFExplanation3(float fIdf, System.Text.StringBuilder exp, Similarity enclosingInstance)
{
InitBlock(fIdf, exp, enclosingInstance);
}
private void InitBlock(float fIdf, System.Text.StringBuilder exp, Similarity enclosingInstance)
{
this.fIdf = fIdf;
this.exp = exp;
this.enclosingInstance = enclosingInstance;
}
private float fIdf;
private System.Text.StringBuilder exp;
private Similarity enclosingInstance;
public Similarity Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
//@Override
public override float GetIdf()
{
return fIdf;
}
//@Override
public override System.String Explain()
{
return exp.ToString();
}
}
private void InitBlock()
{
SupportedMethods = GetSupportedMethods(this.GetType());
}
public const int NO_DOC_ID_PROVIDED = - 1;
/// <summary>Set the default Similarity implementation used by indexing and search
/// code.
///
/// </summary>
/// <seealso cref="Searcher.SetSimilarity(Similarity)">
/// </seealso>
/// <seealso cref="Lucene.Net.Index.IndexWriter.SetSimilarity(Similarity)">
/// </seealso>
public static void SetDefault(Similarity similarity)
{
Similarity.defaultImpl = similarity;
}
/// <summary>Return the default Similarity implementation used by indexing and search
/// code.
///
/// <p/>This is initially an instance of {@link DefaultSimilarity}.
///
/// </summary>
/// <seealso cref="Searcher.SetSimilarity(Similarity)">
/// </seealso>
/// <seealso cref="Lucene.Net.Index.IndexWriter.SetSimilarity(Similarity)">
/// </seealso>
public static Similarity GetDefault()
{
return Similarity.defaultImpl;
}
/// <summary>Cache of decoded bytes. </summary>
private static readonly float[] NORM_TABLE = new float[256];
/// <summary>Decodes a normalization factor stored in an index.</summary>
/// <seealso cref="EncodeNorm(float)">
/// </seealso>
public static float DecodeNorm(byte b)
{
return NORM_TABLE[b & 0xFF]; // & 0xFF maps negative bytes to positive above 127
}
/// <summary>Returns a table for decoding normalization bytes.</summary>
/// <seealso cref="EncodeNorm(float)">
/// </seealso>
public static float[] GetNormDecoder()
{
return NORM_TABLE;
}
/// <summary> Compute the normalization value for a field, given the accumulated
/// state of term processing for this field (see {@link FieldInvertState}).
///
/// <p/>Implementations should calculate a float value based on the field
/// state and then return that value.
///
/// <p/>For backward compatibility this method by default calls
/// {@link #LengthNorm(String, int)} passing
/// {@link FieldInvertState#GetLength()} as the second argument, and
/// then multiplies this value by {@link FieldInvertState#GetBoost()}.<p/>
///
/// <p/><b>WARNING</b>: This API is new and experimental and may
/// suddenly change.<p/>
///
/// </summary>
/// <param name="field">field name
/// </param>
/// <param name="state">current processing state for this field
/// </param>
/// <returns> the calculated float norm
/// </returns>
public virtual float ComputeNorm(System.String field, FieldInvertState state)
{
return (float) (state.GetBoost() * LengthNorm(field, state.GetLength()));
}
/// <summary>Computes the normalization value for a field given the total number of
/// terms contained in a field. These values, together with field boosts, are
/// stored in an index and multipled into scores for hits on each field by the
/// search code.
///
/// <p/>Matches in longer fields are less precise, so implementations of this
/// method usually return smaller values when <code>numTokens</code> is large,
/// and larger values when <code>numTokens</code> is small.
///
/// <p/>Note that the return values are computed under
/// {@link Lucene.Net.Index.IndexWriter#AddDocument(Lucene.Net.Documents.Document)}
/// and then stored using
/// {@link #EncodeNorm(float)}.
/// Thus they have limited precision, and documents
/// must be re-indexed if this method is altered.
///
/// </summary>
/// <param name="fieldName">the name of the field
/// </param>
/// <param name="numTokens">the total number of tokens contained in fields named
/// <i>fieldName</i> of <i>doc</i>.
/// </param>
/// <returns> a normalization factor for hits on this field of this document
///
/// </returns>
/// <seealso cref="Lucene.Net.Documents.Field.SetBoost(float)">
/// </seealso>
public abstract float LengthNorm(System.String fieldName, int numTokens);
/// <summary>Computes the normalization value for a query given the sum of the squared
/// weights of each of the query terms. This value is then multipled into the
/// weight of each query term.
///
/// <p/>This does not affect ranking, but rather just attempts to make scores
/// from different queries comparable.
///
/// </summary>
/// <param name="sumOfSquaredWeights">the sum of the squares of query term weights
/// </param>
/// <returns> a normalization factor for query weights
/// </returns>
public abstract float QueryNorm(float sumOfSquaredWeights);
/// <summary>Encodes a normalization factor for storage in an index.
///
/// <p/>The encoding uses a three-bit mantissa, a five-bit exponent, and
/// the zero-exponent point at 15, thus
/// representing values from around 7x10^9 to 2x10^-9 with about one
/// significant decimal digit of accuracy. Zero is also represented.
/// Negative numbers are rounded up to zero. Values too large to represent
/// are rounded down to the largest representable value. Positive values too
/// small to represent are rounded up to the smallest positive representable
/// value.
///
/// </summary>
/// <seealso cref="Lucene.Net.Documents.Field.SetBoost(float)">
/// </seealso>
/// <seealso cref="Lucene.Net.Util.SmallFloat">
/// </seealso>
public static byte EncodeNorm(float f)
{
return (byte) SmallFloat.FloatToByte315(f);
}
/// <summary>Computes a score factor based on a term or phrase's frequency in a
/// document. This value is multiplied by the {@link #Idf(Term, Searcher)}
/// factor for each term in the query and these products are then summed to
/// form the initial score for a document.
///
/// <p/>Terms and phrases repeated in a document indicate the topic of the
/// document, so implementations of this method usually return larger values
/// when <code>freq</code> is large, and smaller values when <code>freq</code>
/// is small.
///
/// <p/>The default implementation calls {@link #Tf(float)}.
///
/// </summary>
/// <param name="freq">the frequency of a term within a document
/// </param>
/// <returns> a score factor based on a term's within-document frequency
/// </returns>
public virtual float Tf(int freq)
{
return Tf((float) freq);
}
/// <summary>Computes the amount of a sloppy phrase match, based on an edit distance.
/// This value is summed for each sloppy phrase match in a document to form
/// the frequency that is passed to {@link #Tf(float)}.
///
/// <p/>A phrase match with a small edit distance to a document passage more
/// closely matches the document, so implementations of this method usually
/// return larger values when the edit distance is small and smaller values
/// when it is large.
///
/// </summary>
/// <seealso cref="PhraseQuery.SetSlop(int)">
/// </seealso>
/// <param name="distance">the edit distance of this sloppy phrase match
/// </param>
/// <returns> the frequency increment for this match
/// </returns>
public abstract float SloppyFreq(int distance);
/// <summary>Computes a score factor based on a term or phrase's frequency in a
/// document. This value is multiplied by the {@link #Idf(Term, Searcher)}
/// factor for each term in the query and these products are then summed to
/// form the initial score for a document.
///
/// <p/>Terms and phrases repeated in a document indicate the topic of the
/// document, so implementations of this method usually return larger values
/// when <code>freq</code> is large, and smaller values when <code>freq</code>
/// is small.
///
/// </summary>
/// <param name="freq">the frequency of a term within a document
/// </param>
/// <returns> a score factor based on a term's within-document frequency
/// </returns>
public abstract float Tf(float freq);
/// <summary>Computes a score factor for a simple term.
///
/// <p/>The default implementation is:<pre>
/// return idf(searcher.docFreq(term), searcher.maxDoc());
/// </pre>
///
/// Note that {@link Searcher#MaxDoc()} is used instead of
/// {@link Lucene.Net.Index.IndexReader#NumDocs()} because it is proportional to
/// {@link Searcher#DocFreq(Term)} , i.e., when one is inaccurate,
/// so is the other, and in the same direction.
///
/// </summary>
/// <param name="term">the term in question
/// </param>
/// <param name="searcher">the document collection being searched
/// </param>
/// <returns> a score factor for the term
/// </returns>
/// <deprecated> see {@link #IdfExplain(Term, Searcher)}
/// </deprecated>
[Obsolete("see IdfExplain(Term, Searcher)")]
public virtual float Idf(Term term, Searcher searcher)
{
return Idf(searcher.DocFreq(term), searcher.MaxDoc());
}
/// <summary> Computes a score factor for a simple term and returns an explanation
/// for that score factor.
///
/// <p/>
/// The default implementation uses:
///
/// <pre>
/// idf(searcher.docFreq(term), searcher.maxDoc());
/// </pre>
///
/// Note that {@link Searcher#MaxDoc()} is used instead of
/// {@link Lucene.Net.Index.IndexReader#NumDocs()} because it is
/// proportional to {@link Searcher#DocFreq(Term)} , i.e., when one is
/// inaccurate, so is the other, and in the same direction.
///
/// </summary>
/// <param name="term">the term in question
/// </param>
/// <param name="searcher">the document collection being searched
/// </param>
/// <returns> an IDFExplain object that includes both an idf score factor
/// and an explanation for the term.
/// </returns>
/// <throws> IOException </throws>
public virtual IDFExplanation IdfExplain(Term term, Searcher searcher)
{
if (SupportedMethods.overridesTermIDF)
{
float idf = Idf(term, searcher);
return new AnonymousClassIDFExplanation(idf, this);
}
int df = searcher.DocFreq(term);
int max = searcher.MaxDoc();
float idf2 = Idf(df, max);
return new AnonymousClassIDFExplanation1(df, max, idf2, this);
}
/// <summary>Computes a score factor for a phrase.
///
/// <p/>The default implementation sums the {@link #Idf(Term,Searcher)} factor
/// for each term in the phrase.
///
/// </summary>
/// <param name="terms">the terms in the phrase
/// </param>
/// <param name="searcher">the document collection being searched
/// </param>
/// <returns> idf score factor
/// </returns>
/// <deprecated> see {@link #idfExplain(Collection, Searcher)}
/// </deprecated>
[Obsolete("see IdfExplain(Collection, Searcher)")]
public virtual float Idf(System.Collections.ICollection terms, Searcher searcher)
{
float idf = 0.0f;
System.Collections.IEnumerator i = terms.GetEnumerator();
while (i.MoveNext())
{
idf += Idf((Term) i.Current, searcher);
}
return idf;
}
/// <summary> Computes a score factor for a phrase.
///
/// <p/>
/// The default implementation sums the idf factor for
/// each term in the phrase.
///
/// </summary>
/// <param name="terms">the terms in the phrase
/// </param>
/// <param name="searcher">the document collection being searched
/// </param>
/// <returns> an IDFExplain object that includes both an idf
/// score factor for the phrase and an explanation
/// for each term.
/// </returns>
/// <throws> IOException </throws>
public virtual IDFExplanation idfExplain(System.Collections.ICollection terms, Searcher searcher)
{
if (SupportedMethods.overridesCollectionIDF)
{
float idf = Idf(terms, searcher);
return new AnonymousClassIDFExplanation2(idf, this);
}
int max = searcher.MaxDoc();
float idf2 = 0.0f;
System.Text.StringBuilder exp = new System.Text.StringBuilder();
foreach (Term term in terms)
{
int df = searcher.DocFreq(term);
idf2 += Idf(df, max);
exp.Append(" ");
exp.Append(term.Text());
exp.Append("=");
exp.Append(df);
}
float fIdf = idf2;
return new AnonymousClassIDFExplanation3(fIdf, exp, this);
}
/// <summary>Computes a score factor based on a term's document frequency (the number
/// of documents which contain the term). This value is multiplied by the
/// {@link #Tf(int)} factor for each term in the query and these products are
/// then summed to form the initial score for a document.
///
/// <p/>Terms that occur in fewer documents are better indicators of topic, so
/// implementations of this method usually return larger values for rare terms,
/// and smaller values for common terms.
///
/// </summary>
/// <param name="docFreq">the number of documents which contain the term
/// </param>
/// <param name="numDocs">the total number of documents in the collection
/// </param>
/// <returns> a score factor based on the term's document frequency
/// </returns>
public abstract float Idf(int docFreq, int numDocs);
/// <summary>Computes a score factor based on the fraction of all query terms that a
/// document contains. This value is multiplied into scores.
///
/// <p/>The presence of a large portion of the query terms indicates a better
/// match with the query, so implementations of this method usually return
/// larger values when the ratio between these parameters is large and smaller
/// values when the ratio between them is small.
///
/// </summary>
/// <param name="overlap">the number of query terms matched in the document
/// </param>
/// <param name="maxOverlap">the total number of terms in the query
/// </param>
/// <returns> a score factor based on term overlap with the query
/// </returns>
public abstract float Coord(int overlap, int maxOverlap);
/// <summary> Calculate a scoring factor based on the data in the payload. Overriding implementations
/// are responsible for interpreting what is in the payload. Lucene makes no assumptions about
/// what is in the byte array.
/// <p/>
/// The default implementation returns 1.
///
/// </summary>
/// <param name="fieldName">The fieldName of the term this payload belongs to
/// </param>
/// <param name="payload">The payload byte array to be scored
/// </param>
/// <param name="offset">The offset into the payload array
/// </param>
/// <param name="length">The length in the array
/// </param>
/// <returns> An implementation dependent float to be used as a scoring factor
///
/// </returns>
/// <deprecated> See {@link #ScorePayload(int, String, int, int, byte[], int, int)}
/// </deprecated>
//TODO: When removing this, set the default value below to return 1.
[Obsolete("See ScorePayload(int, String, int, int, byte[], int, int)")]
public virtual float ScorePayload(System.String fieldName, byte[] payload, int offset, int length)
{
//Do nothing
return 1;
}
/// <summary> Calculate a scoring factor based on the data in the payload. Overriding implementations
/// are responsible for interpreting what is in the payload. Lucene makes no assumptions about
/// what is in the byte array.
/// <p/>
/// The default implementation returns 1.
///
/// </summary>
/// <param name="docId">The docId currently being scored. If this value is {@link #NO_DOC_ID_PROVIDED}, then it should be assumed that the PayloadQuery implementation does not provide document information
/// </param>
/// <param name="fieldName">The fieldName of the term this payload belongs to
/// </param>
/// <param name="start">The start position of the payload
/// </param>
/// <param name="end">The end position of the payload
/// </param>
/// <param name="payload">The payload byte array to be scored
/// </param>
/// <param name="offset">The offset into the payload array
/// </param>
/// <param name="length">The length in the array
/// </param>
/// <returns> An implementation dependent float to be used as a scoring factor
///
/// </returns>
public virtual float ScorePayload(int docId, System.String fieldName, int start, int end, byte[] payload, int offset, int length)
{
//TODO: When removing the deprecated scorePayload above, set this to return 1
return ScorePayload(fieldName, payload, offset, length);
}
/// <deprecated> Remove this when old API is removed!
/// </deprecated>
[Obsolete("Remove this when old API is removed! ")]
private MethodSupport SupportedMethods;
/// <deprecated> Remove this when old API is removed!
/// </deprecated>
[Obsolete("Remove this when old API is removed! ")]
[Serializable]
private sealed class MethodSupport
{
internal bool overridesCollectionIDF;
internal bool overridesTermIDF;
internal MethodSupport(System.Type clazz)
{
overridesCollectionIDF = IsMethodOverridden(clazz, "Idf", C_IDF_METHOD_PARAMS);
overridesTermIDF = IsMethodOverridden(clazz, "Idf", T_IDF_METHOD_PARAMS);
}
private static bool IsMethodOverridden(System.Type clazz, System.String name, System.Type[] params_Renamed)
{
try
{
return clazz.GetMethod(name, (params_Renamed == null)?new System.Type[0]:(System.Type[]) params_Renamed).DeclaringType != typeof(Similarity);
}
catch (System.MethodAccessException e)
{
// should not happen
throw new System.SystemException(e.Message, e);
}
}
/// <deprecated> Remove this when old API is removed!
/// </deprecated>
[Obsolete("Remove this when old API is removed! ")]
private static readonly System.Type[] T_IDF_METHOD_PARAMS = new System.Type[]{typeof(Term), typeof(Searcher)};
/// <deprecated> Remove this when old API is removed!
/// </deprecated>
[Obsolete("Remove this when old API is removed! ")]
private static readonly System.Type[] C_IDF_METHOD_PARAMS = new System.Type[]{typeof(System.Collections.ICollection), typeof(Searcher)};
}
/// <deprecated> Remove this when old API is removed!
/// </deprecated>
[Obsolete("Remove this when old API is removed! ")]
private static readonly System.Collections.Hashtable knownMethodSupport = new System.Collections.Hashtable();
// {{Aroush-2.9 Port issue, need to mimic java's IdentityHashMap
/*
* From Java docs:
* This class implements the Map interface with a hash table, using
* reference-equality in place of object-equality when comparing keys
* (and values). In other words, in an IdentityHashMap, two keys k1 and k2
* are considered equal if and only if (k1==k2). (In normal Map
* implementations (like HashMap) two keys k1 and k2 are considered
* equal if and only if (k1==null ? k2==null : k1.equals(k2)).)
*/
// Aroush-2.9}}
/// <deprecated> Remove this when old API is removed!
/// </deprecated>
[Obsolete("Remove this when old API is removed! ")]
private static MethodSupport GetSupportedMethods(System.Type clazz)
{
MethodSupport supportedMethods;
lock (knownMethodSupport)
{
supportedMethods = (MethodSupport) knownMethodSupport[clazz];
if (supportedMethods == null)
{
knownMethodSupport.Add(clazz, supportedMethods = new MethodSupport(clazz));
}
}
return supportedMethods;
}
/// <summary>The Similarity implementation used by default.
/// TODO: move back to top when old API is removed!
///
/// </summary>
private static Similarity defaultImpl = new DefaultSimilarity();
static Similarity()
{
{
for (int i = 0; i < 256; i++)
NORM_TABLE[i] = SmallFloat.Byte315ToFloat((byte) i);
}
}
}
}
| |
using Util = Saklient.Util;
using Client = Saklient.Cloud.Client;
using Resource = Saklient.Cloud.Resources.Resource;
using QueryParams = Saklient.Cloud.Models.QueryParams;
using SaklientException = Saklient.Errors.SaklientException;
namespace Saklient.Cloud.Models
{
/// <summary>
///
/// </summary>
public class Model
{
internal Client _Client;
internal Client Get_client()
{
return this._Client;
}
public Client Client
{
get { return this.Get_client(); }
}
internal QueryParams _Query;
internal QueryParams Get_query()
{
return this._Query;
}
public QueryParams Query
{
get { return this.Get_query(); }
}
internal long? _Total;
internal long? Get_total()
{
return this._Total;
}
public long? Total
{
get { return this.Get_total(); }
}
internal long? _Count;
internal long? Get_count()
{
return this._Count;
}
public long? Count
{
get { return this.Get_count(); }
}
internal virtual string _ApiPath()
{
return null;
}
internal virtual string _RootKey()
{
return null;
}
internal virtual string _RootKeyM()
{
return null;
}
internal virtual string _ClassName()
{
return null;
}
/// <summary>
/// <param name="client" />
/// </summary>
public Model(Client client)
{
this._Client = client;
this._Reset();
}
internal Model _Offset(long offset)
{
this._Query.Begin = offset;
return this;
}
internal Model _Limit(long count)
{
this._Query.Count = count;
return this;
}
internal Model _Sort(string column, bool reverse=false)
{
string op = reverse ? "-" : "";
(this._Query.Sort as System.Collections.IList).Add(op + column);
return this;
}
internal Model _FilterBy(string key, object value, bool multiple=false)
{
object filter = this._Query.Filter;
if (multiple) {
if (!(filter as System.Collections.Generic.Dictionary<string, object>).ContainsKey(key)) {
(filter as System.Collections.Generic.Dictionary<string, object>)[key] = new System.Collections.Generic.List<object> { };
}
System.Collections.Generic.List<object> values = ((System.Collections.Generic.List<object>)((filter as System.Collections.Generic.Dictionary<string, object>)[key]));
(values as System.Collections.IList).Add(value);
}
else {
if ((filter as System.Collections.Generic.Dictionary<string, object>).ContainsKey(key)) {
throw new SaklientException("filter_duplicated", "The same filter key can be specified only once (by calling the same method 'withFooBar')");
}
(filter as System.Collections.Generic.Dictionary<string, object>)[key] = value;
}
return this;
}
internal Model _Reset()
{
this._Query = new QueryParams();
this._Total = 0;
this._Count = 0;
return this;
}
internal virtual Resource _CreateResourceImpl(object obj, bool wrapped=false)
{
return null;
}
internal Resource _Create()
{
return this._CreateResourceImpl(null);
}
internal Resource _GetById(string id)
{
object query = this._Query.Build();
this._Reset();
object result = this._Client.Request("GET", this._ApiPath() + "/" + Util.UrlEncode(id), query);
this._Total = 1;
this._Count = 1;
return this._CreateResourceImpl(result, true);
}
internal System.Collections.Generic.List<Resource> _Find()
{
object query = this._Query.Build();
this._Reset();
object result = this._Client.Request("GET", this._ApiPath(), query);
this._Total = System.Convert.ToInt64((result as System.Collections.Generic.Dictionary<string, object>)["Total"]);
this._Count = System.Convert.ToInt64((result as System.Collections.Generic.Dictionary<string, object>)["Count"]);
System.Collections.Generic.List<Resource> data = new System.Collections.Generic.List<Resource> { };
System.Collections.Generic.List<object> records = ((System.Collections.Generic.List<object>)((result as System.Collections.Generic.Dictionary<string, object>)[this._RootKeyM()]));
for (int __it1=0; __it1 < (records as System.Collections.IList).Count; __it1++) {
var record = records[__it1];
(data as System.Collections.IList).Add(this._CreateResourceImpl(record));
}
return ((System.Collections.Generic.List<Resource>)(data));
}
internal Resource _FindOne()
{
object query = this._Query.Build();
this._Reset();
object result = this._Client.Request("GET", this._ApiPath(), query);
this._Total = System.Convert.ToInt64((result as System.Collections.Generic.Dictionary<string, object>)["Total"]);
this._Count = System.Convert.ToInt64((result as System.Collections.Generic.Dictionary<string, object>)["Count"]);
if (this._Total == 0) {
return null;
}
System.Collections.Generic.List<object> records = ((System.Collections.Generic.List<object>)((result as System.Collections.Generic.Dictionary<string, object>)[this._RootKeyM()]));
return this._CreateResourceImpl(records[System.Convert.ToInt32(0)]);
}
internal Model _WithNameLike(string name)
{
return this._FilterBy("Name", name);
}
internal Model _WithTag(string tag)
{
return this._FilterBy("Tags.Name", new System.Collections.Generic.List<object> { tag });
}
internal Model _WithTags(System.Collections.Generic.List<string> tags)
{
return this._FilterBy("Tags.Name", new System.Collections.Generic.List<object> { tags });
}
internal Model _WithTagDnf(System.Collections.Generic.List<System.Collections.Generic.List<string>> dnf)
{
return this._FilterBy("Tags.Name", dnf);
}
internal Model _SortByName(bool reverse=false)
{
return this._Sort("Name", reverse);
}
}
}
| |
using System;
using System.Collections.Specialized;
using Skybrud.Social.Google.Analytics.Objects;
using Skybrud.Social.Google.OAuth;
namespace Skybrud.Social.Google.Analytics {
public class AnalyticsRawEndpoint {
protected const string ManagementUrl = "https://www.googleapis.com/analytics/v3/management/";
public GoogleOAuthClient Client { get; private set; }
internal AnalyticsRawEndpoint(GoogleOAuthClient client) {
Client = client;
}
#region Accounts
public string GetAccounts() {
return SocialUtils.DoHttpGetRequestAndGetBodyAsString("https://www.googleapis.com/analytics/v3/management/accounts", new NameValueCollection {
{"access_token", Client.AccessToken}
});
}
#endregion
#region Web properties
public string GetWebProperties(int maxResults = 0, int startIndex = 0) {
return GetWebProperties("~all", maxResults, startIndex);
}
public string GetWebProperties(AnalyticsAccount account, int maxResults = 0, int startIndex = 0) {
return GetWebProperties(account.Id, maxResults, startIndex);
}
public string GetWebProperties(string accountId, int maxResults = 0, int startIndex = 0) {
NameValueCollection query = new NameValueCollection();
if (maxResults > 0) query.Add("max-results", maxResults + "");
if (startIndex > 0) query.Add("start-index", startIndex + "");
query.Add("access_token", Client.AccessToken);
return SocialUtils.DoHttpGetRequestAndGetBodyAsString("https://www.googleapis.com/analytics/v3/management/accounts/" + accountId + "/webproperties", query);
}
#endregion
#region Profiles
/// <summary>
/// Gets a view (profile) to which the user has access.
/// </summary>
/// <param name="accountId">Account ID to retrieve the goal for.</param>
/// <param name="webPropertyId">Web property ID to retrieve the goal for.</param>
/// <param name="profileId">View (Profile) ID to retrieve the goal for.</param>
public string GetProfile(string accountId, string webPropertyId, string profileId) {
// Construct the URL
string url = String.Format(
"{0}accounts/{1}/webproperties/{2}/profiles/{3}",
ManagementUrl,
accountId,
webPropertyId,
profileId
);
// Make the call to the API
return Client.DoAuthenticatedGetRequest(url);
}
/// <summary>
/// Gets a list of all profiles the user has access to.
/// </summary>
/// <param name="maxResults">The maximum number of views (profiles) to include in this response.</param>
/// <param name="startIndex">An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.</param>
public string GetProfiles(int maxResults = 0, int startIndex = 0) {
return GetProfiles("~all", "~all", maxResults, startIndex);
}
/// <summary>
/// Gets a list of all profiles for the specified account. The result will profiles of all web properties of the account.
/// </summary>
/// <param name="account">The parent account.</param>
/// <param name="maxResults">The maximum number of views (profiles) to include in this response.</param>
/// <param name="startIndex">An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.</param>
public string GetProfiles(AnalyticsAccount account, int maxResults = 0, int startIndex = 0) {
return GetProfiles(account.Id, "~all", maxResults, startIndex);
}
/// <summary>
/// Gets a list of profiles for the specified web property.
/// </summary>
/// <param name="property">The parent web propaerty.</param>
/// <param name="maxResults">The maximum number of views (profiles) to include in this response.</param>
/// <param name="startIndex">An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.</param>
public string GetProfiles(AnalyticsWebProperty property, int maxResults = 0, int startIndex = 0) {
return GetProfiles(property.AccountId, property.Id, maxResults, startIndex);
}
/// <summary>
/// Gets a list of profiles for the specified account.
/// </summary>
/// <param name="accountId">Account ID for the view (profiles) to retrieve. Can either be a specific account ID or '~all', which refers to all the accounts to which the user has access.</param>
/// <param name="maxResults">The maximum number of views (profiles) to include in this response.</param>
/// <param name="startIndex">An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.</param>
public string GetProfiles(string accountId, int maxResults = 0, int startIndex = 0) {
return GetProfiles(accountId, "~all", maxResults, startIndex);
}
/// <summary>
/// Gets a list of profiles for the specified account and web property.
/// </summary>
/// <param name="accountId">Account ID for the view (profiles) to retrieve. Can either be a specific account ID or '~all', which refers to all the accounts to which the user has access.</param>
/// <param name="webPropertyId">Web property ID for the views (profiles) to retrieve. Can either be a specific web property ID or '~all', which refers to all the web properties to which the user has access.</param>
/// <param name="maxResults">The maximum number of views (profiles) to include in this response.</param>
/// <param name="startIndex">An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.</param>
public string GetProfiles(string accountId, string webPropertyId, int maxResults = 0, int startIndex = 0) {
// Construct the query string
NameValueCollection query = new NameValueCollection();
if (maxResults > 0) query.Add("max-results", maxResults + "");
if (startIndex > 0) query.Add("start-index", startIndex + "");
// Construct the URL
string url = String.Format(
"{0}accounts/" + accountId + "/webproperties/" + webPropertyId + "/profiles",
ManagementUrl,
accountId,
webPropertyId
);
// Make the call to the API
return Client.DoAuthenticatedGetRequest(url, query);
}
#endregion
#region Data
public string GetData(AnalyticsProfile profile, DateTime startDate, DateTime endDate, string[] metrics, string[] dimensions) {
return GetData(profile.Id, startDate, endDate, metrics, dimensions);
}
public string GetData(string profileId, DateTime startDate, DateTime endDate, string[] metrics, string[] dimensions) {
return GetData(profileId, new AnalyticsDataOptions {
StartDate = startDate,
EndDate = endDate,
Metrics = metrics,
Dimensions = dimensions
});
}
public string GetData(AnalyticsProfile profile, DateTime startDate, DateTime endDate, AnalyticsMetricCollection metrics, AnalyticsDimensionCollection dimensions) {
return GetData(profile.Id, startDate, endDate, metrics, dimensions);
}
public string GetData(string profileId, DateTime startDate, DateTime endDate, AnalyticsMetricCollection metrics, AnalyticsDimensionCollection dimensions) {
return GetData(profileId, new AnalyticsDataOptions {
StartDate = startDate,
EndDate = endDate,
Metrics = metrics,
Dimensions = dimensions
});
}
public string GetData(AnalyticsProfile profile, AnalyticsDataOptions options) {
return GetData(profile.Id, options);
}
public string GetData(string profileId, AnalyticsDataOptions options) {
// Validate arguments
if (options == null) throw new ArgumentNullException("options");
// Generate the name value collection
NameValueCollection query = options.ToNameValueCollection(profileId, Client.AccessToken);
// Make the call to the API
return SocialUtils.DoHttpGetRequestAndGetBodyAsString("https://www.googleapis.com/analytics/v3/data/ga", query);
}
#endregion
#region Realtime data
/// <summary>
/// Gets the realtime data from the specified profile and metrics.
/// </summary>
/// <param name="profile">The Analytics profile to gather realtime data from.</param>
/// <param name="metrics">The metrics collection of what data to return.</param>
public string GetRealtimeData(AnalyticsProfile profile, AnalyticsMetricCollection metrics) {
return GetRealtimeData(profile.Id, metrics);
}
/// <summary>
/// Gets the realtime data from the specified profile, metrics and dimensions.
/// </summary>
/// <param name="profile">The Analytics profile to gather realtime data from.</param>
/// <param name="metrics">The metrics collection of what data to return.</param>
/// <param name="dimensions">The dimensions collection of what data to return.</param>
public string GetRealtimeData(AnalyticsProfile profile, AnalyticsMetricCollection metrics, AnalyticsDimensionCollection dimensions) {
return GetRealtimeData(profile.Id, metrics, dimensions);
}
/// <summary>
/// Gets the realtime data from the specified profile and options.
/// </summary>
/// <param name="profile">The Analytics profile to gather realtime data from.</param>
/// <param name="options">The options specifying the query.</param>
public string GetRealtimeData(AnalyticsProfile profile, AnalyticsRealtimeDataOptions options) {
return GetRealtimeData(profile.Id, options);
}
/// <summary>
/// Gets the realtime data from the specified profile and metrics.
/// </summary>
/// <param name="profileId">The ID of the Analytics profile.</param>
/// <param name="metrics">The metrics collection of what data to return.</param>
public string GetRealtimeData(string profileId, AnalyticsMetricCollection metrics) {
return GetRealtimeData(profileId, new AnalyticsRealtimeDataOptions {
Metrics = metrics
});
}
/// <summary>
/// Gets the realtime data from the specified profile and metrics.
/// </summary>
/// <param name="profileId">The ID of the Analytics profile.</param>
/// <param name="metrics">The metrics collection of what data to return.</param>
/// <param name="dimensions">The dimensions collection of what data to return.</param>
public string GetRealtimeData(string profileId, AnalyticsMetricCollection metrics, AnalyticsDimensionCollection dimensions) {
return GetRealtimeData(profileId, new AnalyticsRealtimeDataOptions {
Metrics = metrics,
Dimensions = dimensions
});
}
/// <summary>
/// Gets the realtime data from the specified profile and options.
/// </summary>
/// <param name="profileId">The ID of the Analytics profile.</param>
/// <param name="options">The options specifying the query.</param>
public string GetRealtimeData(string profileId, AnalyticsRealtimeDataOptions options) {
// Validate arguments
if (options == null) throw new ArgumentNullException("options");
// Generate the name value collection
NameValueCollection query = options.ToNameValueCollection(profileId, Client.AccessToken);
// Make the call to the API
return SocialUtils.DoHttpGetRequestAndGetBodyAsString("https://www.googleapis.com/analytics/v3/data/realtime", query);
}
#endregion
}
}
| |
// This source file is based on mock4net by Alexandre Victoor which is licensed under the Apache 2.0 License.
// For more details see 'mock4net/LICENSE.txt' and 'mock4net/readme.md' in this project root.
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.ResponseProviders;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
using Stef.Validation;
namespace WireMock.Server
{
/// <summary>
/// The respond with a provider.
/// </summary>
internal class RespondWithAProvider : IRespondWithAProvider
{
private int _priority;
private string _title;
private string _path;
private string _executionConditionState;
private string _nextState;
private string _scenario;
private int _timesInSameState = 1;
private readonly RegistrationCallback _registrationCallback;
private readonly IRequestMatcher _requestMatcher;
private readonly IWireMockServerSettings _settings;
private readonly bool _saveToFile;
public Guid Guid { get; private set; } = Guid.NewGuid();
public IWebhook[] Webhooks { get; private set; }
public ITimeSettings TimeSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="RespondWithAProvider"/> class.
/// </summary>
/// <param name="registrationCallback">The registration callback.</param>
/// <param name="requestMatcher">The request matcher.</param>
/// <param name="settings">The WireMockServerSettings.</param>
/// <param name="saveToFile">Optional boolean to indicate if this mapping should be saved as static mapping file.</param>
public RespondWithAProvider(RegistrationCallback registrationCallback, IRequestMatcher requestMatcher, IWireMockServerSettings settings, bool saveToFile = false)
{
_registrationCallback = registrationCallback;
_requestMatcher = requestMatcher;
_settings = settings;
_saveToFile = saveToFile;
}
/// <summary>
/// The respond with.
/// </summary>
/// <param name="provider">The provider.</param>
public void RespondWith(IResponseProvider provider)
{
_registrationCallback(new Mapping(Guid, _title, _path, _settings, _requestMatcher, provider, _priority, _scenario, _executionConditionState, _nextState, _timesInSameState, Webhooks, TimeSettings), _saveToFile);
}
/// <see cref="IRespondWithAProvider.WithGuid(string)"/>
public IRespondWithAProvider WithGuid(string guid)
{
return WithGuid(Guid.Parse(guid));
}
/// <see cref="IRespondWithAProvider.WithGuid(Guid)"/>
public IRespondWithAProvider WithGuid(Guid guid)
{
Guid = guid;
return this;
}
/// <see cref="IRespondWithAProvider.WithTitle"/>
public IRespondWithAProvider WithTitle(string title)
{
_title = title;
return this;
}
/// <see cref="IRespondWithAProvider.WithPath"/>
public IRespondWithAProvider WithPath(string path)
{
_path = path;
return this;
}
/// <see cref="IRespondWithAProvider.AtPriority"/>
public IRespondWithAProvider AtPriority(int priority)
{
_priority = priority;
return this;
}
/// <see cref="IRespondWithAProvider.InScenario(string)"/>
public IRespondWithAProvider InScenario(string scenario)
{
_scenario = scenario;
return this;
}
/// <see cref="IRespondWithAProvider.InScenario(int)"/>
public IRespondWithAProvider InScenario(int scenario)
{
return InScenario(scenario.ToString());
}
/// <see cref="IRespondWithAProvider.WhenStateIs(string)"/>
public IRespondWithAProvider WhenStateIs(string state)
{
if (string.IsNullOrEmpty(_scenario))
{
throw new NotSupportedException("Unable to set state condition when no scenario is defined.");
}
_executionConditionState = state;
return this;
}
/// <see cref="IRespondWithAProvider.WhenStateIs(int)"/>
public IRespondWithAProvider WhenStateIs(int state)
{
return WhenStateIs(state.ToString());
}
/// <see cref="IRespondWithAProvider.WillSetStateTo(string, int?)"/>
public IRespondWithAProvider WillSetStateTo(string state, int? times = 1)
{
if (string.IsNullOrEmpty(_scenario))
{
throw new NotSupportedException("Unable to set next state when no scenario is defined.");
}
_nextState = state;
_timesInSameState = times ?? 1;
return this;
}
/// <see cref="IRespondWithAProvider.WillSetStateTo(int, int?)"/>
public IRespondWithAProvider WillSetStateTo(int state, int? times = 1)
{
return WillSetStateTo(state.ToString(), times);
}
/// <inheritdoc />
public IRespondWithAProvider WithTimeSettings(ITimeSettings timeSettings)
{
Guard.NotNull(timeSettings, nameof(timeSettings));
TimeSettings = timeSettings;
return this;
}
/// <see cref="IRespondWithAProvider.WithWebhook(IWebhook[])"/>
public IRespondWithAProvider WithWebhook(params IWebhook[] webhooks)
{
Guard.HasNoNulls(webhooks, nameof(webhooks));
Webhooks = webhooks;
return this;
}
/// <see cref="IRespondWithAProvider.WithWebhook(string, string, IDictionary{string, WireMockList{string}}, string, bool, TransformerType)"/>
public IRespondWithAProvider WithWebhook(
[NotNull] string url,
[CanBeNull] string method = "post",
[CanBeNull] IDictionary<string, WireMockList<string>> headers = null,
[CanBeNull] string body = null,
bool useTransformer = true,
TransformerType transformerType = TransformerType.Handlebars)
{
Webhooks = new[] { InitWebhook(url, method, headers, useTransformer, transformerType) };
if (body != null)
{
Webhooks[0].Request.BodyData = new BodyData
{
BodyAsString = body,
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
};
}
return this;
}
/// <see cref="IRespondWithAProvider.WithWebhook(string, string, IDictionary{string, WireMockList{string}}, object, bool, TransformerType)"/>
public IRespondWithAProvider WithWebhook(
[NotNull] string url,
[CanBeNull] string method = "post",
[CanBeNull] IDictionary<string, WireMockList<string>> headers = null,
[CanBeNull] object body = null,
bool useTransformer = true,
TransformerType transformerType = TransformerType.Handlebars)
{
Webhooks = new[] { InitWebhook(url, method, headers, useTransformer, transformerType) };
if (body != null)
{
Webhooks[0].Request.BodyData = new BodyData
{
BodyAsJson = body,
DetectedBodyType = BodyType.Json,
DetectedBodyTypeFromContentType = BodyType.Json
};
}
return this;
}
private static IWebhook InitWebhook(
string url,
string method,
IDictionary<string, WireMockList<string>> headers,
bool useTransformer,
TransformerType transformerType)
{
return new Webhook
{
Request = new WebhookRequest
{
Url = url,
Method = method ?? "post",
Headers = headers,
UseTransformer = useTransformer,
TransformerType = transformerType
}
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Journalist.Collections;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Serilog;
namespace Journalist.WindowsAzure.Storage.Tables
{
public class TableBatchOperationAdapter : IBatchOperation
{
private const int MAX_OPERATIONS_COUNT = 100;
private static readonly ILogger s_logger = Log.ForContext<TableBatchOperationAdapter>();
private readonly Func<TableBatchOperation, Task<IList<TableResult>>> m_executeBatchAsync;
private readonly Func<TableBatchOperation, IList<TableResult>> m_executeBatchSync;
private readonly TableBatchOperation m_batch;
private readonly ITableEntityConverter m_tableEntityConverter;
public TableBatchOperationAdapter(
Func<TableBatchOperation, Task<IList<TableResult>>> executeBatchAsync,
Func<TableBatchOperation, IList<TableResult>> executeBatchSync,
ITableEntityConverter tableEntityConverter)
{
Require.NotNull(executeBatchAsync, "executeBatchAsync");
Require.NotNull(executeBatchSync, "executeBatchSync");
Require.NotNull(tableEntityConverter, "tableEntityConverter");
m_executeBatchAsync = executeBatchAsync;
m_executeBatchSync = executeBatchSync;
m_tableEntityConverter = tableEntityConverter;
m_batch = new TableBatchOperation();
}
public void Insert(string partitionKey, string rowKey, string propertyName, object propertyValue)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(rowKey, "rowKey");
Require.NotEmpty(propertyName, "propertyName");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(propertyName, propertyValue);
entity.PartitionKey = partitionKey;
entity.RowKey = rowKey;
m_batch.Insert(entity);
}
public void Insert(string partitionKey, string rowKey, IReadOnlyDictionary<string, object> properties)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(rowKey, "rowKey");
Require.NotNull(properties, "properties");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(properties);
entity.PartitionKey = partitionKey;
entity.RowKey = rowKey;
m_batch.Insert(entity);
}
public void Insert(string partitionKey, string propertyName, object propertyValue)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(propertyName, "propertyName");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(propertyName, propertyValue);
entity.PartitionKey = partitionKey;
entity.RowKey = string.Empty;
m_batch.Insert(entity);
}
public void Insert(string partitionKey, IReadOnlyDictionary<string, object> properties)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotNull(properties, "properties");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(properties);
entity.PartitionKey = partitionKey;
entity.RowKey = string.Empty;
m_batch.Insert(entity);
}
public void Merge(string partitionKey, string rowKey, string etag, string propertyName, object propertyValue)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(rowKey, "rowKey");
Require.NotEmpty(etag, "etag");
Require.NotEmpty(propertyName, "propertyName");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(propertyName, propertyValue);
entity.PartitionKey = partitionKey;
entity.RowKey = rowKey;
entity.ETag = etag;
m_batch.Merge(entity);
}
public void Merge(string partitionKey, string rowKey, string etag, IReadOnlyDictionary<string, object> properties)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(rowKey, "rowKey");
Require.NotEmpty(etag, "etag");
Require.NotNull(properties, "properties");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(properties);
entity.PartitionKey = partitionKey;
entity.RowKey = rowKey;
entity.ETag = etag;
m_batch.Merge(entity);
}
public void Merge(string partitionKey, string etag, string propertyName, object propertyValue)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(etag, "etag");
Require.NotEmpty(propertyName, "propertyName");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(propertyName, propertyValue);
entity.PartitionKey = partitionKey;
entity.RowKey = string.Empty;
entity.ETag = etag;
m_batch.Merge(entity);
}
public void Merge(string partitionKey, string etag, IReadOnlyDictionary<string, object> properties)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(etag, "etag");
Require.NotNull(properties, "properties");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(properties);
entity.PartitionKey = partitionKey;
entity.RowKey = string.Empty;
entity.ETag = etag;
m_batch.Merge(entity);
}
public void Replace(string partitionKey, string rowKey, string etag, string propertyName, object propertyValue)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(rowKey, "rowKey");
Require.NotEmpty(etag, "etag");
Require.NotEmpty(propertyName, "propertyName");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(propertyName, propertyValue);
entity.PartitionKey = partitionKey;
entity.RowKey = rowKey;
entity.ETag = etag;
m_batch.Replace(entity);
}
public void Replace(string partitionKey, string rowKey, string etag, IReadOnlyDictionary<string, object> properties)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(rowKey, "rowKey");
Require.NotEmpty(etag, "etag");
Require.NotNull(properties, "properties");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(properties);
entity.PartitionKey = partitionKey;
entity.RowKey = rowKey;
entity.ETag = etag;
m_batch.Replace(entity);
}
public void Replace(string partitionKey, string etag, string propertyName, object propertyValue)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(etag, "etag");
Require.NotEmpty(propertyName, "propertyName");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(propertyName, propertyValue);
entity.PartitionKey = partitionKey;
entity.RowKey = string.Empty;
entity.ETag = etag;
m_batch.Replace(entity);
}
public void Replace(string partitionKey, string etag, IReadOnlyDictionary<string, object> properties)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(etag, "etag");
Require.NotNull(properties, "properties");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(properties);
entity.PartitionKey = partitionKey;
entity.RowKey = string.Empty;
entity.ETag = etag;
m_batch.Replace(entity);
}
public void InsertOrReplace(string partitionKey, string rowKey, string propertyName, object propertyValue)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(rowKey, "rowKey");
Require.NotEmpty(propertyName, "propertyName");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(propertyName, propertyValue);
entity.PartitionKey = partitionKey;
entity.RowKey = rowKey;
m_batch.InsertOrReplace(entity);
}
public void InsertOrReplace(string partitionKey, string rowKey, IReadOnlyDictionary<string, object> properties)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(rowKey, "rowKey");
Require.NotNull(properties, "properties");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(properties);
entity.PartitionKey = partitionKey;
entity.RowKey = rowKey;
m_batch.InsertOrReplace(entity);
}
public void InsertOrReplace(string partitionKey, string propertyName, object propertyValue)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(propertyName, "propertyName");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(propertyName, propertyValue);
entity.PartitionKey = partitionKey;
entity.RowKey = string.Empty;
m_batch.InsertOrReplace(entity);
}
public void InsertOrReplace(string partitionKey, IReadOnlyDictionary<string, object> properties)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotNull(properties, "properties");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(properties);
entity.PartitionKey = partitionKey;
entity.RowKey = string.Empty;
m_batch.InsertOrReplace(entity);
}
public void InsertOrMerge(string partitionKey, string rowKey, string propertyName, object propertyValue)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(rowKey, "rowKey");
Require.NotEmpty(propertyName, "propertyName");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(propertyName, propertyValue);
entity.PartitionKey = partitionKey;
entity.RowKey = rowKey;
m_batch.InsertOrMerge(entity);
}
public void InsertOrMerge(string partitionKey, string rowKey, IReadOnlyDictionary<string, object> properties)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(rowKey, "rowKey");
Require.NotNull(properties, "properties");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(properties);
entity.PartitionKey = partitionKey;
entity.RowKey = rowKey;
m_batch.InsertOrMerge(entity);
}
public void InsertOrMerge(string partitionKey, string propertyName, object propertyValue)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(propertyName, "propertyName");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(propertyName, propertyValue);
entity.PartitionKey = partitionKey;
entity.RowKey = string.Empty;
m_batch.InsertOrMerge(entity);
}
public void InsertOrMerge(string partitionKey, IReadOnlyDictionary<string, object> properties)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotNull(properties, "properties");
AssertBatchSizeIsNotExceeded();
var entity = m_tableEntityConverter.CreateDynamicTableEntityFromProperties(properties);
entity.PartitionKey = partitionKey;
entity.RowKey = string.Empty;
m_batch.InsertOrMerge(entity);
}
public void Delete(string partitionKey, string rowKey, string etag)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotEmpty(rowKey, "rowKey");
Require.NotNull(etag, "etag");
AssertBatchSizeIsNotExceeded();
var entity = new DynamicTableEntity
{
PartitionKey = partitionKey,
RowKey = rowKey,
ETag = etag
};
m_batch.Delete(entity);
}
public void Delete(string partitionKey, string etag)
{
Require.NotEmpty(partitionKey, "partitionKey");
Require.NotNull(etag, "etag");
AssertBatchSizeIsNotExceeded();
var entity = new DynamicTableEntity
{
PartitionKey = partitionKey,
RowKey = string.Empty,
ETag = etag
};
m_batch.Delete(entity);
}
public async Task<IReadOnlyList<OperationResult>> ExecuteAsync()
{
try
{
var tableResult = await m_executeBatchAsync(m_batch);
return ParseOperationResult(tableResult);
}
catch (StorageException exception) when (exception.RequestInformation.ExtendedErrorInformation != null)
{
s_logger.Verbose(
exception,
"Execution of batch operation failed. Request information: {@RequestInformation}.",
exception.RequestInformation);
throw new BatchOperationException(
operationBatchNumber: ExtractOperationNumber(exception.RequestInformation.ExtendedErrorInformation),
statusCode: (HttpStatusCode)exception.RequestInformation.HttpStatusCode,
operationErrorCode: exception.RequestInformation.ExtendedErrorInformation.ErrorCode,
inner: exception);
}
}
public IReadOnlyList<OperationResult> Execute()
{
try
{
var tableResult = m_executeBatchSync(m_batch);
return ParseOperationResult(tableResult);
}
catch (StorageException exception) when (exception.RequestInformation.ExtendedErrorInformation != null)
{
s_logger.Verbose(
exception,
"Execution of batch operation failed. Request information: {@RequestInformation}.",
exception.RequestInformation);
throw new BatchOperationException(
operationBatchNumber: ExtractOperationNumber(exception.RequestInformation.ExtendedErrorInformation),
statusCode: (HttpStatusCode)exception.RequestInformation.HttpStatusCode,
operationErrorCode: exception.RequestInformation.ExtendedErrorInformation.ErrorCode,
inner: exception);
}
}
private static int ExtractOperationNumber(StorageExtendedErrorInformation information)
{
var errorInfo = information.ErrorMessage.Split("\n".YieldArray(), StringSplitOptions.RemoveEmptyEntries);
var operationInfo = errorInfo[0].Split(':'.YieldArray(), StringSplitOptions.RemoveEmptyEntries);
int operationNumber;
int.TryParse(operationInfo[0], out operationNumber);
return operationNumber;
}
private static List<OperationResult> ParseOperationResult(IList<TableResult> tableResult)
{
var result = new List<OperationResult>(tableResult.Count);
result.AddRange(tableResult.Select(r => new OperationResult(r.Etag ?? string.Empty, (HttpStatusCode)r.HttpStatusCode)));
return result;
}
private void AssertBatchSizeIsNotExceeded()
{
if ((OperationsCount + 1) > MAX_OPERATIONS_COUNT)
{
throw new InvalidOperationException("Max batch size was exceeded.");
}
}
public int OperationsCount
{
get { return m_batch.Count; }
}
public bool IsMaximumOperationsCountWasReached
{
get { return m_batch.Count == MAX_OPERATIONS_COUNT; }
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedImagesClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetImageRequest request = new GetImageRequest
{
Image = "image225a8078",
Project = "projectaa6ff846",
};
Image expectedResponse = new Image
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
LicenseCodes =
{
-3549522739643304114L,
},
SourceImage = "source_image5e9c0c38",
SourceImageId = "source_image_id954b5e55",
GuestOsFeatures =
{
new GuestOsFeature(),
},
SourceSnapshotId = "source_snapshot_id008ab5dd",
SourceSnapshot = "source_snapshot1fcf3da1",
LabelFingerprint = "label_fingerprint06ccff3a",
Status = Image.Types.Status.Ready,
ShieldedInstanceInitialState = new InitialStateConfig(),
SourceSnapshotEncryptionKey = new CustomerEncryptionKey(),
DiskSizeGb = 7103353205508136450L,
StorageLocations =
{
"storage_locationse772402d",
},
Family = "family0bda3f0d",
Licenses =
{
"licensesd1cc2f9d",
},
ImageEncryptionKey = new CustomerEncryptionKey(),
ArchiveSizeBytes = -1817962760933329403L,
SourceImageEncryptionKey = new CustomerEncryptionKey(),
Description = "description2cf9da67",
SourceDisk = "source_disk0eec086f",
SourceType = Image.Types.SourceType.UndefinedSourceType,
SourceDiskId = "source_disk_id020f9fb8",
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RawDisk = new RawDisk(),
Deprecated = new DeprecationStatus(),
SourceDiskEncryptionKey = new CustomerEncryptionKey(),
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Image response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetImageRequest request = new GetImageRequest
{
Image = "image225a8078",
Project = "projectaa6ff846",
};
Image expectedResponse = new Image
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
LicenseCodes =
{
-3549522739643304114L,
},
SourceImage = "source_image5e9c0c38",
SourceImageId = "source_image_id954b5e55",
GuestOsFeatures =
{
new GuestOsFeature(),
},
SourceSnapshotId = "source_snapshot_id008ab5dd",
SourceSnapshot = "source_snapshot1fcf3da1",
LabelFingerprint = "label_fingerprint06ccff3a",
Status = Image.Types.Status.Ready,
ShieldedInstanceInitialState = new InitialStateConfig(),
SourceSnapshotEncryptionKey = new CustomerEncryptionKey(),
DiskSizeGb = 7103353205508136450L,
StorageLocations =
{
"storage_locationse772402d",
},
Family = "family0bda3f0d",
Licenses =
{
"licensesd1cc2f9d",
},
ImageEncryptionKey = new CustomerEncryptionKey(),
ArchiveSizeBytes = -1817962760933329403L,
SourceImageEncryptionKey = new CustomerEncryptionKey(),
Description = "description2cf9da67",
SourceDisk = "source_disk0eec086f",
SourceType = Image.Types.SourceType.UndefinedSourceType,
SourceDiskId = "source_disk_id020f9fb8",
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RawDisk = new RawDisk(),
Deprecated = new DeprecationStatus(),
SourceDiskEncryptionKey = new CustomerEncryptionKey(),
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Image>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Image responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Image responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetImageRequest request = new GetImageRequest
{
Image = "image225a8078",
Project = "projectaa6ff846",
};
Image expectedResponse = new Image
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
LicenseCodes =
{
-3549522739643304114L,
},
SourceImage = "source_image5e9c0c38",
SourceImageId = "source_image_id954b5e55",
GuestOsFeatures =
{
new GuestOsFeature(),
},
SourceSnapshotId = "source_snapshot_id008ab5dd",
SourceSnapshot = "source_snapshot1fcf3da1",
LabelFingerprint = "label_fingerprint06ccff3a",
Status = Image.Types.Status.Ready,
ShieldedInstanceInitialState = new InitialStateConfig(),
SourceSnapshotEncryptionKey = new CustomerEncryptionKey(),
DiskSizeGb = 7103353205508136450L,
StorageLocations =
{
"storage_locationse772402d",
},
Family = "family0bda3f0d",
Licenses =
{
"licensesd1cc2f9d",
},
ImageEncryptionKey = new CustomerEncryptionKey(),
ArchiveSizeBytes = -1817962760933329403L,
SourceImageEncryptionKey = new CustomerEncryptionKey(),
Description = "description2cf9da67",
SourceDisk = "source_disk0eec086f",
SourceType = Image.Types.SourceType.UndefinedSourceType,
SourceDiskId = "source_disk_id020f9fb8",
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RawDisk = new RawDisk(),
Deprecated = new DeprecationStatus(),
SourceDiskEncryptionKey = new CustomerEncryptionKey(),
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Image response = client.Get(request.Project, request.Image);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetImageRequest request = new GetImageRequest
{
Image = "image225a8078",
Project = "projectaa6ff846",
};
Image expectedResponse = new Image
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
LicenseCodes =
{
-3549522739643304114L,
},
SourceImage = "source_image5e9c0c38",
SourceImageId = "source_image_id954b5e55",
GuestOsFeatures =
{
new GuestOsFeature(),
},
SourceSnapshotId = "source_snapshot_id008ab5dd",
SourceSnapshot = "source_snapshot1fcf3da1",
LabelFingerprint = "label_fingerprint06ccff3a",
Status = Image.Types.Status.Ready,
ShieldedInstanceInitialState = new InitialStateConfig(),
SourceSnapshotEncryptionKey = new CustomerEncryptionKey(),
DiskSizeGb = 7103353205508136450L,
StorageLocations =
{
"storage_locationse772402d",
},
Family = "family0bda3f0d",
Licenses =
{
"licensesd1cc2f9d",
},
ImageEncryptionKey = new CustomerEncryptionKey(),
ArchiveSizeBytes = -1817962760933329403L,
SourceImageEncryptionKey = new CustomerEncryptionKey(),
Description = "description2cf9da67",
SourceDisk = "source_disk0eec086f",
SourceType = Image.Types.SourceType.UndefinedSourceType,
SourceDiskId = "source_disk_id020f9fb8",
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RawDisk = new RawDisk(),
Deprecated = new DeprecationStatus(),
SourceDiskEncryptionKey = new CustomerEncryptionKey(),
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Image>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Image responseCallSettings = await client.GetAsync(request.Project, request.Image, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Image responseCancellationToken = await client.GetAsync(request.Project, request.Image, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFromFamilyRequestObject()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFromFamilyImageRequest request = new GetFromFamilyImageRequest
{
Project = "projectaa6ff846",
Family = "family0bda3f0d",
};
Image expectedResponse = new Image
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
LicenseCodes =
{
-3549522739643304114L,
},
SourceImage = "source_image5e9c0c38",
SourceImageId = "source_image_id954b5e55",
GuestOsFeatures =
{
new GuestOsFeature(),
},
SourceSnapshotId = "source_snapshot_id008ab5dd",
SourceSnapshot = "source_snapshot1fcf3da1",
LabelFingerprint = "label_fingerprint06ccff3a",
Status = Image.Types.Status.Ready,
ShieldedInstanceInitialState = new InitialStateConfig(),
SourceSnapshotEncryptionKey = new CustomerEncryptionKey(),
DiskSizeGb = 7103353205508136450L,
StorageLocations =
{
"storage_locationse772402d",
},
Family = "family0bda3f0d",
Licenses =
{
"licensesd1cc2f9d",
},
ImageEncryptionKey = new CustomerEncryptionKey(),
ArchiveSizeBytes = -1817962760933329403L,
SourceImageEncryptionKey = new CustomerEncryptionKey(),
Description = "description2cf9da67",
SourceDisk = "source_disk0eec086f",
SourceType = Image.Types.SourceType.UndefinedSourceType,
SourceDiskId = "source_disk_id020f9fb8",
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RawDisk = new RawDisk(),
Deprecated = new DeprecationStatus(),
SourceDiskEncryptionKey = new CustomerEncryptionKey(),
};
mockGrpcClient.Setup(x => x.GetFromFamily(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Image response = client.GetFromFamily(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFromFamilyRequestObjectAsync()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFromFamilyImageRequest request = new GetFromFamilyImageRequest
{
Project = "projectaa6ff846",
Family = "family0bda3f0d",
};
Image expectedResponse = new Image
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
LicenseCodes =
{
-3549522739643304114L,
},
SourceImage = "source_image5e9c0c38",
SourceImageId = "source_image_id954b5e55",
GuestOsFeatures =
{
new GuestOsFeature(),
},
SourceSnapshotId = "source_snapshot_id008ab5dd",
SourceSnapshot = "source_snapshot1fcf3da1",
LabelFingerprint = "label_fingerprint06ccff3a",
Status = Image.Types.Status.Ready,
ShieldedInstanceInitialState = new InitialStateConfig(),
SourceSnapshotEncryptionKey = new CustomerEncryptionKey(),
DiskSizeGb = 7103353205508136450L,
StorageLocations =
{
"storage_locationse772402d",
},
Family = "family0bda3f0d",
Licenses =
{
"licensesd1cc2f9d",
},
ImageEncryptionKey = new CustomerEncryptionKey(),
ArchiveSizeBytes = -1817962760933329403L,
SourceImageEncryptionKey = new CustomerEncryptionKey(),
Description = "description2cf9da67",
SourceDisk = "source_disk0eec086f",
SourceType = Image.Types.SourceType.UndefinedSourceType,
SourceDiskId = "source_disk_id020f9fb8",
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RawDisk = new RawDisk(),
Deprecated = new DeprecationStatus(),
SourceDiskEncryptionKey = new CustomerEncryptionKey(),
};
mockGrpcClient.Setup(x => x.GetFromFamilyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Image>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Image responseCallSettings = await client.GetFromFamilyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Image responseCancellationToken = await client.GetFromFamilyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFromFamily()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFromFamilyImageRequest request = new GetFromFamilyImageRequest
{
Project = "projectaa6ff846",
Family = "family0bda3f0d",
};
Image expectedResponse = new Image
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
LicenseCodes =
{
-3549522739643304114L,
},
SourceImage = "source_image5e9c0c38",
SourceImageId = "source_image_id954b5e55",
GuestOsFeatures =
{
new GuestOsFeature(),
},
SourceSnapshotId = "source_snapshot_id008ab5dd",
SourceSnapshot = "source_snapshot1fcf3da1",
LabelFingerprint = "label_fingerprint06ccff3a",
Status = Image.Types.Status.Ready,
ShieldedInstanceInitialState = new InitialStateConfig(),
SourceSnapshotEncryptionKey = new CustomerEncryptionKey(),
DiskSizeGb = 7103353205508136450L,
StorageLocations =
{
"storage_locationse772402d",
},
Family = "family0bda3f0d",
Licenses =
{
"licensesd1cc2f9d",
},
ImageEncryptionKey = new CustomerEncryptionKey(),
ArchiveSizeBytes = -1817962760933329403L,
SourceImageEncryptionKey = new CustomerEncryptionKey(),
Description = "description2cf9da67",
SourceDisk = "source_disk0eec086f",
SourceType = Image.Types.SourceType.UndefinedSourceType,
SourceDiskId = "source_disk_id020f9fb8",
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RawDisk = new RawDisk(),
Deprecated = new DeprecationStatus(),
SourceDiskEncryptionKey = new CustomerEncryptionKey(),
};
mockGrpcClient.Setup(x => x.GetFromFamily(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Image response = client.GetFromFamily(request.Project, request.Family);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFromFamilyAsync()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFromFamilyImageRequest request = new GetFromFamilyImageRequest
{
Project = "projectaa6ff846",
Family = "family0bda3f0d",
};
Image expectedResponse = new Image
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
LicenseCodes =
{
-3549522739643304114L,
},
SourceImage = "source_image5e9c0c38",
SourceImageId = "source_image_id954b5e55",
GuestOsFeatures =
{
new GuestOsFeature(),
},
SourceSnapshotId = "source_snapshot_id008ab5dd",
SourceSnapshot = "source_snapshot1fcf3da1",
LabelFingerprint = "label_fingerprint06ccff3a",
Status = Image.Types.Status.Ready,
ShieldedInstanceInitialState = new InitialStateConfig(),
SourceSnapshotEncryptionKey = new CustomerEncryptionKey(),
DiskSizeGb = 7103353205508136450L,
StorageLocations =
{
"storage_locationse772402d",
},
Family = "family0bda3f0d",
Licenses =
{
"licensesd1cc2f9d",
},
ImageEncryptionKey = new CustomerEncryptionKey(),
ArchiveSizeBytes = -1817962760933329403L,
SourceImageEncryptionKey = new CustomerEncryptionKey(),
Description = "description2cf9da67",
SourceDisk = "source_disk0eec086f",
SourceType = Image.Types.SourceType.UndefinedSourceType,
SourceDiskId = "source_disk_id020f9fb8",
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RawDisk = new RawDisk(),
Deprecated = new DeprecationStatus(),
SourceDiskEncryptionKey = new CustomerEncryptionKey(),
};
mockGrpcClient.Setup(x => x.GetFromFamilyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Image>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Image responseCallSettings = await client.GetFromFamilyAsync(request.Project, request.Family, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Image responseCancellationToken = await client.GetFromFamilyAsync(request.Project, request.Family, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyImageRequest request = new GetIamPolicyImageRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
OptionsRequestedPolicyVersion = -1471234741,
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyImageRequest request = new GetIamPolicyImageRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
OptionsRequestedPolicyVersion = -1471234741,
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicy()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyImageRequest request = new GetIamPolicyImageRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request.Project, request.Resource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyAsync()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyImageRequest request = new GetIamPolicyImageRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Resource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyImageRequest request = new SetIamPolicyImageRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
GlobalSetPolicyRequestResource = new GlobalSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyImageRequest request = new SetIamPolicyImageRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
GlobalSetPolicyRequestResource = new GlobalSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicy()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyImageRequest request = new SetIamPolicyImageRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
GlobalSetPolicyRequestResource = new GlobalSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request.Project, request.Resource, request.GlobalSetPolicyRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyAsync()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyImageRequest request = new SetIamPolicyImageRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
GlobalSetPolicyRequestResource = new GlobalSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Resource, request.GlobalSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Resource, request.GlobalSetPolicyRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsImageRequest request = new TestIamPermissionsImageRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsImageRequest request = new TestIamPermissionsImageRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissions()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsImageRequest request = new TestIamPermissionsImageRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Resource, request.TestPermissionsRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsAsync()
{
moq::Mock<Images.ImagesClient> mockGrpcClient = new moq::Mock<Images.ImagesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsImageRequest request = new TestIamPermissionsImageRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ImagesClient client = new ImagesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
/*
Copyright (c) 2013 Ant Micro <www.antmicro.com>
Authors:
* Mateusz Holenko ([email protected])
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using AntShell.Helpers;
namespace AntShell.Terminal
{
public class NavigableTerminalEmulator : BasicTerminalEmulator
{
private const int MAX_HEIGHT = 9999;
private const int MAX_WIDTH = 9999;
private SequenceValidator validator;
private Queue<char> sequenceQueue;
public ITerminalHandler Handler { get; set; }
private VirtualCursor vcursor;
private List<int> WrappedLines;
private int CurrentLine;
private int LinesScrolled;
private bool onceAgain;
private bool clearScreen = false;
private bool forceVirtualCursor = false;
public NavigableTerminalEmulator(IOProvider io, bool forceVCursor = false) : base(io)
{
validator = new SequenceValidator();
sequenceQueue = new Queue<char>();
forceVirtualCursor = forceVCursor;
WrappedLines = new List<int>();
vcursor = new VirtualCursor();
ControlSequences();
}
public void Start(bool clearScreen)
{
this.clearScreen = clearScreen;
if(clearScreen)
{
ClearScreen();
ResetCursor();
}
ResetColors();
}
private void ControlSequences()
{
validator.Add(ControlSequenceType.LeftArrow, (char)SequenceElement.ESC, (char)SequenceElement.CSI, 'D');
validator.Add(ControlSequenceType.RightArrow, (char)SequenceElement.ESC, (char)SequenceElement.CSI, 'C');
validator.Add(ControlSequenceType.UpArrow, (char)SequenceElement.ESC, (char)SequenceElement.CSI, 'A');
validator.Add(ControlSequenceType.DownArrow, (char)SequenceElement.ESC, (char)SequenceElement.CSI, 'B');
validator.Add(ControlSequenceType.LeftArrow, (char)SequenceElement.ESC, 'O', 'D');
validator.Add(ControlSequenceType.RightArrow, (char)SequenceElement.ESC, 'O', 'C');
validator.Add(ControlSequenceType.UpArrow, (char)SequenceElement.ESC, 'O', 'A');
validator.Add(ControlSequenceType.DownArrow, (char)SequenceElement.ESC, 'O', 'B');
validator.Add(ControlSequenceType.CtrlLeftArrow, (char)SequenceElement.ESC, (char)SequenceElement.CSI, '1', ';', '5', 'D');
validator.Add(ControlSequenceType.CtrlRightArrow, (char)SequenceElement.ESC, (char)SequenceElement.CSI, '1', ';', '5', 'C');
validator.Add(ControlSequenceType.Delete, (char)SequenceElement.ESC, (char)SequenceElement.CSI, '3', '~');
validator.Add(ControlSequenceType.Home, (char)SequenceElement.ESC, (char)SequenceElement.CSI, '1', '~');
validator.Add(ControlSequenceType.Home, (char)SequenceElement.ESC, 'O', 'H');
validator.Add(ControlSequenceType.Home, (char)SequenceElement.ESC, (char)SequenceElement.CSI, 'H');
validator.Add(ControlSequenceType.End, (char)SequenceElement.ESC, (char)SequenceElement.CSI, '4', '~');
validator.Add(ControlSequenceType.End, (char)SequenceElement.ESC, 'O', 'F');
validator.Add(ControlSequenceType.End, (char)SequenceElement.ESC, (char)SequenceElement.CSI, 'F');
validator.Add(ControlSequenceType.Esc, (char)SequenceElement.ESC, (char)SequenceElement.ESC);
validator.Add(new ControlSequence(ControlSequenceType.Ctrl, 'k'), (char)11);
validator.Add(new ControlSequence(ControlSequenceType.Ctrl, 'r'), (char)18);
validator.Add(new ControlSequence(ControlSequenceType.Ctrl, 'w'), (char)23);
validator.Add(new ControlSequence(ControlSequenceType.Ctrl, 'c'), (char)3);
validator.Add(ControlSequenceType.Tab, '\t');
validator.Add(ControlSequenceType.Backspace, (char)127);
validator.Add(ControlSequenceType.Backspace, (char)8);
validator.Add(ControlSequenceType.Enter, '\r');
validator.Add(ControlSequenceType.Enter, '\n');
validator.Add(ControlSequenceType.Ignore, (char)12);
validator.Add((ControlSequenceGenerator)((s, l) =>
{
var str = new string(s.ToArray());
var trimmed = str.Substring(2, str.Length - 3);
var splitted = trimmed.Split(';');
return new ControlSequence(ControlSequenceType.CursorPosition, new Position(int.Parse(splitted[1]), int.Parse(splitted[0])));
}),
(char)SequenceElement.ESC, (char)SequenceElement.CSI, (char)SequenceElement.INTEGER, ';', (char)SequenceElement.INTEGER, 'R');
}
#region Input handling
public void Stop()
{
if(clearScreen)
{
ClearScreen();
CursorToColumn(1);
CursorUp(MAX_HEIGHT);
}
ResetColors();
onceAgain = false;
InputOutput.CancelGet();
InputOutput.Dispose();
}
public void Run(bool stopOnError = false)
{
onceAgain = true;
while(onceAgain)
{
var input = GetNextInput();
if(input == null)
{
if(stopOnError)
{
break;
}
continue;
}
HandleInput(input);
}
}
public object GetNextInput()
{
while(true)
{
var b = InputOutput.GetNextChar();
if(b == null)
{
return null;
}
if(sequenceQueue.Count == 0)
{
if(b == (char)SequenceElement.ESC)
{
sequenceQueue.Enqueue(b.Value);
continue;
}
// try special control sequence
ControlSequence cs;
var result = validator.Check(new [] { b.Value }, out cs);
if(result == SequenceValidationResult.SequenceFound)
{
return cs;
}
// so it must be normal character
return b.Value;
}
else
{
sequenceQueue.Enqueue(b.Value);
ControlSequence cs;
var validationResult = validator.Check(sequenceQueue.ToArray(), out cs);
if(cs == null)
{
if(validationResult == SequenceValidationResult.SequenceNotFound)
{
sequenceQueue.Clear();
}
}
else
{
sequenceQueue.Clear();
return cs;
}
}
}
}
private void HandleInput(object input)
{
if(input == null)
{
return;
}
var inputAsControlSequence = input as ControlSequence;
if(input is char)
{
Handler.HandleCharacter((char)input);
}
else if(inputAsControlSequence != null)
{
Handler.HandleControlSequence((ControlSequence)input);
}
}
#endregion
private void OnScreenScroll()
{
LinesScrolled++;
}
private void OnLineWrapped()
{
WrappedLines.Add(vcursor.MaxPosition.X + 1);
CurrentLine++;
}
#region Writers
internal int Write(string text, ConsoleColor? color = null)
{
var result = 0;
if(text != null)
{
ColorChangerWrapper(color, () =>
{
foreach(var c in text)
{
result += WriteChar(c) ? 1 : 0;
}
});
}
return result;
}
public void Write(char c, ConsoleColor? color = null)
{
ColorChangerWrapper(color, () => WriteChar(c));
}
public void WriteNoMove(string text, int skip = 0, ConsoleColor? color = null)
{
if(text != null)
{
var ep = vcursor.RealPosition;
var currline = CurrentLine;
HideCursor();
CursorForward(skip);
var count = Write(text, color);
CursorBackward(count + skip);
ShowCursor();
vcursor.RealPosition = ep;
CurrentLine = currline;
}
}
public void WriteRaw(char c, ConsoleColor? color = null)
{
ColorChangerWrapper(color, () => InputOutput.Write(c));
}
public void WriteRaw(byte[] bs, ConsoleColor? color = null)
{
ColorChangerWrapper(color, () =>
{
foreach(var b in bs)
{
InputOutput.Write(b);
}
}
);
}
public void WriteRaw(string text, ConsoleColor? color = null)
{
if(text != null)
{
ColorChangerWrapper(color, () =>
{
foreach(var b in text)
{
InputOutput.Write(b);
}
}
);
}
}
private void ColorChangerWrapper(ConsoleColor? color, Action action)
{
if(color.HasValue)
{
SetColor(color.Value);
}
action();
if(color.HasValue)
{
ResetColors();
}
}
private bool InEscapeMode = false;
private bool WriteChar(char c)
{
InputOutput.Write(c);
if(c == (byte)SequenceElement.ESC) // to eliminate control sequences, mostly color change
{
InEscapeMode = true;
}
if(!InEscapeMode) // if the char changed cursor position by one; check for color steering codes
{
if(c == '\r')
{
vcursor.RealPosition.X = 1;
}
else if(c == '\n')
{
var scrolled = !vcursor.MoveDown();
if(scrolled)
{
OnScreenScroll();
}
}
else
{
var result = vcursor.MoveForward();
if(vcursor.IsCursorOutOfLine && !vcursor.IsCursorOutOfScreen)
{
CursorDown();
CursorToColumn(1);
}
if(result == VirtualCursorMoveResult.LineWrapped)
{
OnLineWrapped();
}
if(result == VirtualCursorMoveResult.ScreenScrolled)
{
OnLineWrapped();
OnScreenScroll();
}
}
return true;
}
else
{
if(c == 'm')
{
InEscapeMode = false;
}
}
return false;
}
#endregion
#region Cursor movement
public void CursorUp(int n = 1, bool recalculateEstimatedPosition = true)
{
if(n > 0)
{
SendCSI();
if(n > 1)
{
SendControlSequence(n.ToString());
}
SendControlSequence((byte)'A');
if(recalculateEstimatedPosition)
{
vcursor.MoveUp(n);
}
}
}
public void CursorDown(int n = 1, bool recalculateEstimatedPosition = true)
{
if(n > 0)
{
SendCSI();
if(n > 1)
{
SendControlSequence(n.ToString());
}
SendControlSequence((byte)'B');
if(recalculateEstimatedPosition)
{
vcursor.MoveDown(n);
}
}
}
public void CursorForward(int n = 1)
{
if(n > 0)
{
var move = vcursor.CalculateMoveForward(n);
CursorDown(move.Y);
n = Math.Abs(move.X);
if(n != 0)
{
SendCSI();
}
if(n > 1)
{
SendControlSequence(n.ToString());
}
if(move.X > 0)
{
SendControlSequence((byte)'C');
vcursor.MoveForward(n, true);
}
else if(move.X < 0)
{
SendControlSequence((byte)'D');
vcursor.MoveBackward(n);
}
CurrentLine = vcursor.RealPosition.X == 1 ? CurrentLine - (move.Y - 1) : CurrentLine - move.Y;
if(vcursor.IsCursorOutOfScreen)
{
ScrollDown();
}
}
}
public void CursorBackward(int n = 1)
{
if(n > 0)
{
var vb = (vcursor.RealPosition.X == 1);
var move = vcursor.CalculateMoveBackward(n);
CurrentLine = Math.Max(0, CurrentLine + (vb ? move.Y + 1 : move.Y));
CursorUp(-move.Y);
n = Math.Abs(move.X);
if(n != 0)
{
SendCSI();
}
if(n > 1)
{
SendControlSequence(n.ToString());
}
if(move.X < 0)
{
SendControlSequence((byte)'D');
vcursor.MoveBackward(n);
}
else if(move.X > 0)
{
SendControlSequence((byte)'C');
vcursor.MoveForward(n, false);
}
}
}
public void CursorToColumn(int n, bool recalculateEstimatedPosition = true)
{
SendCSI();
SendControlSequence(n.ToString());
SendControlSequence((byte)'G');
if(recalculateEstimatedPosition)
{
vcursor.SetX(n);
}
}
public void NewLine()
{
Write("\n\r");
CurrentLine = 0;
WrappedLines.Clear();
}
#endregion
#region Erase
public void ClearLine()
{
SendCSI((byte)'2', (byte)'K');
CursorToColumn(0);
var count = vcursor.MaxReachedPosition.Y - vcursor.RealPosition.Y;
CursorDown(count);
for(int i = count; i > 0; i--)
{
SendCSI((byte)'2', (byte)'K'); // clear line
CursorUp();
if(WrappedLines.Count - i >= 0)
{
WrappedLines.RemoveAt(WrappedLines.Count - i);
}
}
CurrentLine = 0;
vcursor.MaxReachedPosition.X = vcursor.RealPosition.X;
vcursor.MaxReachedPosition.Y = vcursor.RealPosition.Y;
}
public void ClearToTheEndOfLine()
{
var count = vcursor.MaxReachedPosition.Y - vcursor.RealPosition.Y;
CursorDown(count);
for(int i = count; i > 0; i--)
{
SendCSI((byte)'2', (byte)'K'); // clear line
CursorUp();
if(WrappedLines.Count > 0 && WrappedLines.Count - i > 0)
{
WrappedLines.RemoveAt(WrappedLines.Count - i);
}
}
SendCSI((byte)'K');
vcursor.MaxReachedPosition.X = vcursor.RealPosition.X;
vcursor.MaxReachedPosition.Y = vcursor.RealPosition.Y;
}
public void ClearDown()
{
SendCSI((byte)'J');
}
#endregion
#region Display
public void ResetColors()
{
if(PlainMode)
{
return;
}
SendCSI((byte)'0', (byte)'m'); // reset colors
}
public void Calibrate()
{
if(forceVirtualCursor)
{
vcursor.Calibrate(new Position(0, 0), new Position(MAX_WIDTH, MAX_HEIGHT));
}
else
{
vcursor.Calibrate(GetCursorPosition(), GetSize());
}
}
public void ScrollDown()
{
SendControlSequence((byte)SequenceElement.ESC, (byte)'D');
}
private Position savedPosition;
private int scrollCount;
public void SaveCursor()
{
savedPosition = vcursor.RealPosition.Clone();
scrollCount = LinesScrolled;
SendCSI((byte)'s');
}
public void RestoreCursor()
{
SendCSI((byte)'u');
vcursor.RealPosition = savedPosition.Clone();
var scrolled = LinesScrolled - scrollCount;
CursorUp(scrolled);
}
public void HideCursor()
{
SendCSI();
SendControlSequence("?25l");
}
public void ShowCursor()
{
SendCSI();
SendControlSequence("?25h");
}
public void SetColor(ConsoleColor color)
{
if(PlainMode)
{
return;
}
switch(color)
{
case ConsoleColor.Black:
SendCSI((byte)SequenceElement.SEM, (byte)'0', (byte)'3', (byte)'0', (byte)'m');
break;
case ConsoleColor.Red:
SendCSI((byte)SequenceElement.SEM, (byte)'0', (byte)'3', (byte)'1', (byte)'m');
break;
case ConsoleColor.Green:
SendCSI((byte)SequenceElement.SEM, (byte)'0', (byte)'3', (byte)'2', (byte)'m');
break;
case ConsoleColor.Yellow:
SendCSI((byte)SequenceElement.SEM, (byte)'0', (byte)'3', (byte)'3', (byte)'m');
break;
case ConsoleColor.Blue:
SendCSI((byte)SequenceElement.SEM, (byte)'0', (byte)'3', (byte)'4', (byte)'m');
break;
case ConsoleColor.Magenta:
SendCSI((byte)SequenceElement.SEM, (byte)'0', (byte)'3', (byte)'5', (byte)'m');
break;
case ConsoleColor.Cyan:
SendCSI((byte)SequenceElement.SEM, (byte)'0', (byte)'3', (byte)'6', (byte)'m');
break;
case ConsoleColor.Gray:
SendCSI((byte)SequenceElement.SEM, (byte)'0', (byte)'3', (byte)'7', (byte)'m');
break;
case ConsoleColor.DarkGray:
SendCSI((byte)'3', (byte)'0', (byte)SequenceElement.SEM, (byte)'1', (byte)'m');
break;
case ConsoleColor.DarkRed:
SendCSI((byte)'3', (byte)'1', (byte)SequenceElement.SEM, (byte)'1', (byte)'m');
break;
case ConsoleColor.DarkGreen:
SendCSI((byte)'3', (byte)'2', (byte)SequenceElement.SEM, (byte)'1', (byte)'m');
break;
case ConsoleColor.DarkYellow:
SendCSI((byte)'3', (byte)'3', (byte)SequenceElement.SEM, (byte)'1', (byte)'m');
break;
case ConsoleColor.DarkBlue:
SendCSI((byte)'3', (byte)'4', (byte)SequenceElement.SEM, (byte)'1', (byte)'m');
break;
case ConsoleColor.DarkMagenta:
SendCSI((byte)'3', (byte)'5', (byte)SequenceElement.SEM, (byte)'1', (byte)'m');
break;
case ConsoleColor.DarkCyan:
SendCSI((byte)'3', (byte)'6', (byte)SequenceElement.SEM, (byte)'1', (byte)'m');
break;
case ConsoleColor.White:
SendCSI((byte)'3', (byte)'7', (byte)SequenceElement.SEM, (byte)'1', (byte)'m');
break;
}
}
public Position GetSize()
{
HideCursor();
SaveCursor();
CursorToColumn(MAX_WIDTH, false);
CursorDown(MAX_HEIGHT, false);
var result = GetCursorPosition();
RestoreCursor();
ShowCursor();
return result;
}
public Position GetCursorPosition()
{
if(forceVirtualCursor)
{
return vcursor.RealPosition.Clone();
}
var unusedCharacters = new List<char>();
ControlSequence cs;
while(true)
{
var localBuffer = new List<char>();
SendCSI();
SendControlSequence("6n");
while(true)
{
var currentChar = InputOutput.GetNextChar();
if(currentChar == null)
{
foreach(var uc in unusedCharacters)
{
InputOutput.Inject(uc);
}
// the output is closed - there will be no more data
return new Position(0, 0);
}
localBuffer.Add(currentChar.Value);
var validationResult = validator.Check(localBuffer, out cs);
switch(validationResult)
{
case SequenceValidationResult.PrefixFound:
continue;
case SequenceValidationResult.SequenceFound:
if(cs.Type == ControlSequenceType.CursorPosition)
{
foreach(var uc in unusedCharacters)
{
InputOutput.Inject(uc);
}
return cs.Argument as Position;
}
break;
}
unusedCharacters.AddRange(localBuffer);
localBuffer.Clear();
}
}
}
#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.
namespace System.Buffers.Text
{
public static partial class Utf8Parser
{
/// <summary>
/// Parses a Guid at the start of a Utf8 string.
/// </summary>
/// <param name="text">The Utf8 string to parse</param>
/// <param name="value">Receives the parsed value</param>
/// <param name="bytesConsumed">On a successful parse, receives the length in bytes of the substring that was parsed </param>
/// <param name="standardFormat">Expected format of the Utf8 string</param>
/// <returns>
/// true for success. "bytesConsumed" contains the length in bytes of the substring that was parsed.
/// false if the string was not syntactically valid or an overflow or underflow occurred. "bytesConsumed" is set to 0.
/// </returns>
/// <remarks>
/// Formats supported:
/// D (default) nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn
/// B {nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn}
/// P (nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn)
/// N nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
/// </remarks>
/// <exceptions>
/// <cref>System.FormatException</cref> if the format is not valid for this data type.
/// </exceptions>
public static bool TryParse(ReadOnlySpan<byte> text, out Guid value, out int bytesConsumed, char standardFormat = default)
{
switch (standardFormat)
{
case default(char):
case 'D':
return TryParseGuidCore(text, false, ' ', ' ', out value, out bytesConsumed);
case 'B':
return TryParseGuidCore(text, true, '{', '}', out value, out bytesConsumed);
case 'P':
return TryParseGuidCore(text, true, '(', ')', out value, out bytesConsumed);
case 'N':
return TryParseGuidN(text, out value, out bytesConsumed);
default:
return ThrowHelper.TryParseThrowFormatException(out value, out bytesConsumed);
}
}
// nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn (not very Guid-like, but the format is what it is...)
private static bool TryParseGuidN(ReadOnlySpan<byte> text, out Guid value, out int bytesConsumed)
{
if (text.Length < 32)
{
value = default;
bytesConsumed = 0;
return false;
}
int justConsumed;
if (!TryParseUInt32X(text.Slice(0, 8), out uint i1, out justConsumed) || justConsumed != 8)
{
value = default;
bytesConsumed = 0;
return false; // 8 digits
}
if (!TryParseUInt16X(text.Slice(8, 4), out ushort i2, out justConsumed) || justConsumed != 4)
{
value = default;
bytesConsumed = 0;
return false; // next 4 digits
}
if (!TryParseUInt16X(text.Slice(12, 4), out ushort i3, out justConsumed) || justConsumed != 4)
{
value = default;
bytesConsumed = 0;
return false; // next 4 digits
}
if (!TryParseUInt16X(text.Slice(16, 4), out ushort i4, out justConsumed) || justConsumed != 4)
{
value = default;
bytesConsumed = 0;
return false; // next 4 digits
}
if (!TryParseUInt64X(text.Slice(20), out ulong i5, out justConsumed) || justConsumed != 12)
{
value = default;
bytesConsumed = 0;
return false; // next 4 digits
}
bytesConsumed = 32;
value = new Guid((int)i1, (short)i2, (short)i3, (byte)(i4 >> 8), (byte)i4,
(byte)(i5 >> 40), (byte)(i5 >> 32), (byte)(i5 >> 24), (byte)(i5 >> 16), (byte)(i5 >> 8), (byte)i5);
return true;
}
// {8-4-4-4-12}, where number is the number of hex digits, and {/} are ends.
private static bool TryParseGuidCore(ReadOnlySpan<byte> text, bool ends, char begin, char end, out Guid value, out int bytesConsumed)
{
int expectedCodingUnits = 36 + (ends ? 2 : 0); // 32 hex digits + 4 delimiters + 2 optional ends
if (text.Length < expectedCodingUnits)
{
value = default;
bytesConsumed = 0;
return false;
}
if (ends)
{
if (text[0] != begin)
{
value = default;
bytesConsumed = 0;
return false;
}
text = text.Slice(1); // skip begining
}
int justConsumed;
if (!TryParseUInt32X(text, out uint i1, out justConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (justConsumed != 8)
{
value = default;
bytesConsumed = 0;
return false; // 8 digits
}
if (text[justConsumed] != '-')
{
value = default;
bytesConsumed = 0;
return false;
}
text = text.Slice(9); // justConsumed + 1 for delimiter
if (!TryParseUInt16X(text, out ushort i2, out justConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (justConsumed != 4)
{
value = default;
bytesConsumed = 0;
return false; // 4 digits
}
if (text[justConsumed] != '-')
{
value = default;
bytesConsumed = 0;
return false;
}
text = text.Slice(5); // justConsumed + 1 for delimiter
if (!TryParseUInt16X(text, out ushort i3, out justConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (justConsumed != 4)
{
value = default;
bytesConsumed = 0;
return false; // 4 digits
}
if (text[justConsumed] != '-')
{
value = default;
bytesConsumed = 0;
return false;
}
text = text.Slice(5); // justConsumed + 1 for delimiter
if (!TryParseUInt16X(text, out ushort i4, out justConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (justConsumed != 4)
{
value = default;
bytesConsumed = 0;
return false; // 4 digits
}
if (text[justConsumed] != '-')
{
value = default;
bytesConsumed = 0;
return false;
}
text = text.Slice(5);// justConsumed + 1 for delimiter
if (!TryParseUInt64X(text, out ulong i5, out justConsumed))
{
value = default;
bytesConsumed = 0;
return false;
}
if (justConsumed != 12)
{
value = default;
bytesConsumed = 0;
return false; // 12 digits
}
if (ends && text[justConsumed] != end)
{
value = default;
bytesConsumed = 0;
return false;
}
bytesConsumed = expectedCodingUnits;
value = new Guid((int)i1, (short)i2, (short)i3, (byte)(i4 >> 8), (byte)i4,
(byte)(i5 >> 40), (byte)(i5 >> 32), (byte)(i5 >> 24), (byte)(i5 >> 16), (byte)(i5 >> 8), (byte)i5);
return true;
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Utilities;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Date;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.X509.Extension;
namespace Org.BouncyCastle.X509
{
/**
* The following extensions are listed in RFC 2459 as relevant to CRLs
*
* Authority Key Identifier
* Issuer Alternative Name
* CRL Number
* Delta CRL Indicator (critical)
* Issuing Distribution Point (critical)
*/
public class X509Crl
: X509ExtensionBase
// TODO Add interface Crl?
{
private readonly CertificateList c;
private readonly string sigAlgName;
private readonly byte[] sigAlgParams;
private readonly bool isIndirect;
public X509Crl(
CertificateList c)
{
this.c = c;
try
{
this.sigAlgName = X509SignatureUtilities.GetSignatureName(c.SignatureAlgorithm);
if (c.SignatureAlgorithm.Parameters != null)
{
this.sigAlgParams = ((Asn1Encodable)c.SignatureAlgorithm.Parameters).GetDerEncoded();
}
else
{
this.sigAlgParams = null;
}
this.isIndirect = IsIndirectCrl;
}
catch (Exception e)
{
throw new CrlException("CRL contents invalid: " + e);
}
}
protected override X509Extensions GetX509Extensions()
{
return Version == 2
? c.TbsCertList.Extensions
: null;
}
public virtual byte[] GetEncoded()
{
try
{
return c.GetDerEncoded();
}
catch (Exception e)
{
throw new CrlException(e.ToString());
}
}
public virtual void Verify(
AsymmetricKeyParameter publicKey)
{
if (!c.SignatureAlgorithm.Equals(c.TbsCertList.Signature))
{
throw new CrlException("Signature algorithm on CertificateList does not match TbsCertList.");
}
ISigner sig = SignerUtilities.GetSigner(SigAlgName);
sig.Init(false, publicKey);
byte[] encoded = this.GetTbsCertList();
sig.BlockUpdate(encoded, 0, encoded.Length);
if (!sig.VerifySignature(this.GetSignature()))
{
throw new SignatureException("CRL does not verify with supplied public key.");
}
}
public virtual int Version
{
get { return c.Version; }
}
public virtual X509Name IssuerDN
{
get { return c.Issuer; }
}
public virtual DateTime ThisUpdate
{
get { return c.ThisUpdate.ToDateTime(); }
}
public virtual DateTimeObject NextUpdate
{
get
{
return c.NextUpdate == null
? null
: new DateTimeObject(c.NextUpdate.ToDateTime());
}
}
private ISet LoadCrlEntries()
{
ISet entrySet = new HashSet();
IEnumerable certs = c.GetRevokedCertificateEnumeration();
X509Name previousCertificateIssuer = IssuerDN;
foreach (CrlEntry entry in certs)
{
X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer);
entrySet.Add(crlEntry);
previousCertificateIssuer = crlEntry.GetCertificateIssuer();
}
return entrySet;
}
public virtual X509CrlEntry GetRevokedCertificate(
BigInteger serialNumber)
{
IEnumerable certs = c.GetRevokedCertificateEnumeration();
X509Name previousCertificateIssuer = IssuerDN;
foreach (CrlEntry entry in certs)
{
X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer);
if (serialNumber.Equals(entry.UserCertificate.Value))
{
return crlEntry;
}
previousCertificateIssuer = crlEntry.GetCertificateIssuer();
}
return null;
}
public virtual ISet GetRevokedCertificates()
{
ISet entrySet = LoadCrlEntries();
if (entrySet.Count > 0)
{
return entrySet; // TODO? Collections.unmodifiableSet(entrySet);
}
return null;
}
public virtual byte[] GetTbsCertList()
{
try
{
return c.TbsCertList.GetDerEncoded();
}
catch (Exception e)
{
throw new CrlException(e.ToString());
}
}
public virtual byte[] GetSignature()
{
return c.Signature.GetBytes();
}
public virtual string SigAlgName
{
get { return sigAlgName; }
}
public virtual string SigAlgOid
{
get { return c.SignatureAlgorithm.ObjectID.Id; }
}
public virtual byte[] GetSigAlgParams()
{
return Arrays.Clone(sigAlgParams);
}
public override bool Equals(
object obj)
{
if (obj == this)
return true;
X509Crl other = obj as X509Crl;
if (other == null)
return false;
return c.Equals(other.c);
// NB: May prefer this implementation of Equals if more than one certificate implementation in play
//return Arrays.AreEqual(this.GetEncoded(), other.GetEncoded());
}
public override int GetHashCode()
{
return c.GetHashCode();
}
/**
* Returns a string representation of this CRL.
*
* @return a string representation of this CRL.
*/
public override string ToString()
{
StringBuilder buf = new StringBuilder();
string nl = Platform.NewLine;
buf.Append(" Version: ").Append(this.Version).Append(nl);
buf.Append(" IssuerDN: ").Append(this.IssuerDN).Append(nl);
buf.Append(" This update: ").Append(this.ThisUpdate).Append(nl);
buf.Append(" Next update: ").Append(this.NextUpdate).Append(nl);
buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(nl);
byte[] sig = this.GetSignature();
buf.Append(" Signature: ");
buf.Append(AsHexString(sig, 0, 20)).Append(nl);
for (int i = 20; i < sig.Length; i += 20)
{
int count = System.Math.Min(20, sig.Length - i);
buf.Append(" ");
buf.Append(AsHexString(sig, i, count)).Append(nl);
}
X509Extensions extensions = c.TbsCertList.Extensions;
if (extensions != null)
{
IEnumerator e = extensions.ExtensionOids.GetEnumerator();
if (e.MoveNext())
{
buf.Append(" Extensions: ").Append(nl);
}
do
{
DerObjectIdentifier oid = (DerObjectIdentifier) e.Current;
X509Extension ext = extensions.GetExtension(oid);
if (ext.Value != null)
{
Asn1Object asn1Value = X509ExtensionUtilities.FromExtensionValue(ext.Value);
buf.Append(" critical(").Append(ext.IsCritical).Append(") ");
try
{
if (oid.Equals(X509Extensions.CrlNumber))
{
buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).Append(nl);
}
else if (oid.Equals(X509Extensions.DeltaCrlIndicator))
{
buf.Append(
"Base CRL: "
+ new CrlNumber(DerInteger.GetInstance(
asn1Value).PositiveValue))
.Append(nl);
}
else if (oid.Equals(X509Extensions.IssuingDistributionPoint))
{
buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl);
}
else if (oid.Equals(X509Extensions.CrlDistributionPoints))
{
buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl);
}
else if (oid.Equals(X509Extensions.FreshestCrl))
{
buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl);
}
else
{
buf.Append(oid.Id);
buf.Append(" value = ").Append(
Asn1Dump.DumpAsString(asn1Value))
.Append(nl);
}
}
catch (Exception)
{
buf.Append(oid.Id);
buf.Append(" value = ").Append("*****").Append(nl);
}
}
else
{
buf.Append(nl);
}
}
while (e.MoveNext());
}
ISet certSet = GetRevokedCertificates();
if (certSet != null)
{
foreach (X509CrlEntry entry in certSet)
{
buf.Append(entry);
buf.Append(nl);
}
}
return buf.ToString();
}
/**
* Checks whether the given certificate is on this CRL.
*
* @param cert the certificate to check for.
* @return true if the given certificate is on this CRL,
* false otherwise.
*/
// public bool IsRevoked(
// Certificate cert)
// {
// if (!cert.getType().Equals("X.509"))
// {
// throw new RuntimeException("X.509 CRL used with non X.509 Cert");
// }
public virtual bool IsRevoked(
X509Certificate cert)
{
CrlEntry[] certs = c.GetRevokedCertificates();
if (certs != null)
{
// BigInteger serial = ((X509Certificate)cert).SerialNumber;
BigInteger serial = cert.SerialNumber;
for (int i = 0; i < certs.Length; i++)
{
if (certs[i].UserCertificate.Value.Equals(serial))
{
return true;
}
}
}
return false;
}
protected virtual bool IsIndirectCrl
{
get
{
Asn1OctetString idp = GetExtensionValue(X509Extensions.IssuingDistributionPoint);
bool isIndirect = false;
try
{
if (idp != null)
{
isIndirect = IssuingDistributionPoint.GetInstance(
X509ExtensionUtilities.FromExtensionValue(idp)).IsIndirectCrl;
}
}
catch (Exception e)
{
// TODO
// throw new ExtCrlException("Exception reading IssuingDistributionPoint", e);
throw new CrlException("Exception reading IssuingDistributionPoint" + e);
}
return isIndirect;
}
}
private static string AsHexString(
byte[] bytes,
int index,
int count)
{
byte[] hex = Hex.Encode(bytes, index, count);
return Encoding.ASCII.GetString(hex, 0, hex.Length);
}
}
}
| |
//
// Sidebar.cs
//
// Author:
// Ruben Vermeersch <[email protected]>
//
// Copyright (C) 2008-2010 Novell, Inc.
// Copyright (C) 2008-2010 Ruben Vermeersch
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using FSpot.Core;
using FSpot.Extensions;
using FSpot.Settings;
using Gtk;
using Mono.Unix;
namespace FSpot.Widgets
{
// Decides which sidebar page should be shown for each context. Implemented
// using the Strategy pattern, to make it swappable easily, in case the
// default MRUSidebarContextSwitchStrategy is not sufficiently usable.
public interface ISidebarContextSwitchStrategy
{
string PageForContext (ViewContext context);
void SwitchedToPage (ViewContext context, string name);
}
// Implements a Most Recently Used switching strategy. The last page you used
// for a given context is used.
public class MRUSidebarContextSwitchStrategy : ISidebarContextSwitchStrategy
{
public const string PREF_PREFIX = Preferences.APP_FSPOT + "ui/sidebar";
string PrefKeyForContext (ViewContext context)
{
return string.Format ("{0}/{1}", PREF_PREFIX, context);
}
public string PageForContext (ViewContext context)
{
string name = Preferences.Get<string> (PrefKeyForContext (context));
if (name == null)
name = DefaultForContext (context);
return name;
}
public void SwitchedToPage (ViewContext context, string name)
{
Preferences.Set (PrefKeyForContext (context), name);
}
string DefaultForContext (ViewContext context)
{
if (context == ViewContext.Edit)
return Catalog.GetString ("Edit");
// Don't care otherwise, Tags sounds reasonable
return Catalog.GetString ("Tags");
}
}
public class Sidebar : VBox {
HBox button_box;
public Notebook Notebook { get; private set; }
MenuButton choose_button;
EventBox eventBox;
Menu choose_menu;
List<string> menu_list;
List<string> image_list;
public event EventHandler CloseRequested;
// Selection change events, sidebar pages can subscribed to this.
public event IBrowsableCollectionChangedHandler SelectionChanged;
public event IBrowsableCollectionItemsChangedHandler SelectionItemsChanged;
// The photos selected.
public IBrowsableCollection Selection { get; private set; }
public event EventHandler ContextChanged;
public event EventHandler PageSwitched;
ViewContext view_context = ViewContext.Unknown;
public ViewContext Context {
get { return view_context; }
set {
view_context = value;
ContextChanged?.Invoke (this, null);
}
}
readonly ISidebarContextSwitchStrategy ContextSwitchStrategy;
public Sidebar ()
{
ContextSwitchStrategy = new MRUSidebarContextSwitchStrategy ();
ContextChanged += HandleContextChanged;
button_box = new HBox ();
PackStart (button_box, false, false, 0);
Notebook = new Notebook ();
Notebook.ShowTabs = false;
Notebook.ShowBorder = false;
PackStart (Notebook, true, true, 0);
var button = new Button ();
button.Image = new Image ("gtk-close", Gtk.IconSize.Button);
button.Relief = ReliefStyle.None;
button.Pressed += HandleCloseButtonPressed;
button_box.PackEnd (button, false, true, 0);
choose_button = new MenuButton ();
choose_button.Relief = ReliefStyle.None;
eventBox = new EventBox ();
eventBox.Add (choose_button);
button_box.PackStart (eventBox, true, true, 0);
choose_menu = new Menu ();
choose_button.Menu = choose_menu;
menu_list = new List<string> ();
image_list = new List<string> ();
}
void HandleContextChanged (object sender, EventArgs args)
{
// Make sure the ViewModeCondition is set correctly.
if (Context == ViewContext.Single)
ViewModeCondition.Mode = FSpot.Extensions.ViewMode.Single;
else if (Context == ViewContext.Library || Context == ViewContext.Edit)
ViewModeCondition.Mode = FSpot.Extensions.ViewMode.Library;
else
ViewModeCondition.Mode = FSpot.Extensions.ViewMode.Unknown;
string name = ContextSwitchStrategy.PageForContext (Context);
SwitchTo (name);
}
void HandleCanSelectChanged (object sender, EventArgs args)
{
//Log.Debug ("Can select changed for {0} to {1}", sender, (sender as SidebarPage).CanSelect);
}
public void AppendPage (Widget widget, string label, string icon_name)
{
AppendPage (new SidebarPage (widget, label, icon_name));
}
public void AppendPage (SidebarPage page)
{
page.Sidebar = this;
page.CanSelectChanged += HandleCanSelectChanged;
string label = page.Label;
string icon_name = page.IconName;
Notebook.AppendPage (page.SidebarWidget, new Label (label));
page.SidebarWidget.Show ();
MenuItem item;
if (icon_name == null)
item = new MenuItem (label);
else {
item = new ImageMenuItem (label);
(item as ImageMenuItem).Image = new Image ();
((item as ImageMenuItem).Image as Image).IconName = icon_name;
}
item.Activated += HandleItemClicked;
choose_menu.Append (item);
item.Show ();
if (Notebook.Children.Length == 1) {
choose_button.Label = label;
choose_button.Image.IconName = icon_name;
}
menu_list.Add (label);
image_list.Add (icon_name);
}
public void HandleMainWindowViewModeChanged (object o, EventArgs args)
{
MainWindow.ModeType mode = App.Instance.Organizer.ViewMode;
if (mode == MainWindow.ModeType.IconView)
Context = ViewContext.Library;
else if (mode == MainWindow.ModeType.PhotoView)
Context = ViewContext.Edit;
}
public void HandleItemClicked (object o, EventArgs args)
{
string name = ((o as MenuItem).Child as Label).Text;
SwitchTo (name);
ContextSwitchStrategy.SwitchedToPage (Context, name);
}
public void HandleCloseButtonPressed (object sender, EventArgs args)
{
CloseRequested?.Invoke (this, args);
}
public void SwitchTo (int n)
{
if (n >= Notebook.Children.Length) {
n = 0;
}
Notebook.CurrentPage = n;
choose_button.Label = menu_list [n];
choose_button.Image.IconName = image_list [n];
PageSwitched?.Invoke (this, EventArgs.Empty);
}
public int CurrentPage
{
get { return Notebook.CurrentPage; }
}
public void SwitchTo (string name)
{
if (menu_list.Contains (name))
SwitchTo (menu_list.IndexOf (name));
}
public bool IsActive (SidebarPage page)
{
return (Notebook.GetNthPage (Notebook.CurrentPage) == page.SidebarWidget);
}
public void HandleSelectionChanged (IBrowsableCollection collection) {
Selection = collection;
// Proxy selection change to the subscribed sidebar pages.
if (SelectionChanged != null)
SelectionChanged (collection);
}
// Proxy selection item changes to the subscribed sidebar pages.
public void HandleSelectionItemsChanged (IBrowsableCollection collection, BrowsableEventArgs args) {
if (SelectionItemsChanged != null)
SelectionItemsChanged (collection, args);
}
}
}
| |
using NUnit.Framework;
using Sendwithus;
using System;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
namespace SendwithusTest
{
/// <summary>
/// Class to test the sendwithus Drip Campaign API
/// </summary>
[TestFixture]
public class DripCampaignTest
{
private const string DEFAULT_CAMPAIGN_ID = "dc_VXKGx85NmwHnRv9FZv88TW";
private const string INVALID_CAMPAIGN_ID = "invalid_campaign_id";
private const string DEFAULT_SENDER_EMAIL_ADDRESS = "[email protected]";
private const string DEFAULT_REPLY_TO_EMAIL_ADDRESS = "[email protected]";
private const string DEFAULT_RECIPIENT_EMAIL_ADDRESS = "[email protected]";
private const string DEFAULT_CC_EMAIL_ADDRESS_1 = "[email protected]";
private const string DEFAULT_CC_EMAIL_ADDRESS_2 = "[email protected]";
private const string DEFAULT_BCC_EMAIL_ADDRESS_1 = "[email protected]";
private const string DEFAULT_BCC_EMAIL_ADDRESS_2 = "[email protected]";
private const string DEFAULT_EMAIL_NAME = "Chuck Norris";
private const string DEFAULT_SENDER_NAME = "Matt Damon";
private const string DEFAULT_TAG_1 = "tag1";
private const string DEFAULT_TAG_2 = "tag2";
private const string DEFAULT_TAG_3 = "tag3";
private const string DEFAULT_VERSION_NAME = "New Version";
private const string DEFAULT_LOCALE = "en-US";
private const string DEFAULT_ESP_ACCOUNT_ID = "esp_pmUQQ7aRUhWYUrfeJqwPwB";
/// <summary>
/// Sets the API
/// </summary>
[SetUp]
public void InitializeUnitTesting()
{
// Set the API key
SendwithusClient.ApiKey = SendwithusClientTest.API_KEY_TEST;
}
/// <summary>
/// Tests the API call POST /drip_campaigns/(drip_campaign_id)/activate
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestActivateDripCampaignAsyncWithMinimumParameters()
{
Trace.WriteLine(String.Format("POST /drip_campaigns/{0}/activate with minimum parameters",DEFAULT_CAMPAIGN_ID));
// Build the drip campaign object
var recipient = new EmailRecipient(DEFAULT_RECIPIENT_EMAIL_ADDRESS);
var dripCampaign = new DripCampaign(recipient);
// Make the API call
try
{
var dripCampaignResponse = await dripCampaign.ActivateAsync(DEFAULT_CAMPAIGN_ID);
// Validate the response
SendwithusClientTest.ValidateResponse(dripCampaignResponse);
}
catch (AggregateException exception)
{
Assert.Fail(exception.ToString());
}
}
/// <summary>
/// Tests the API call POST /drip_campaigns/(drip_campaign_id)/activate
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestActivateDripCampaignAsyncWithAllParameters()
{
Trace.WriteLine(String.Format("POST /drip_campaigns/{0}/activate with all parameters", DEFAULT_CAMPAIGN_ID));
// Build the drip campaign object
var recipient = new EmailRecipient(DEFAULT_RECIPIENT_EMAIL_ADDRESS, DEFAULT_EMAIL_NAME);
var dripCampaign = new DripCampaign(recipient);
dripCampaign.cc.Add(new EmailRecipient(DEFAULT_CC_EMAIL_ADDRESS_1, DEFAULT_EMAIL_NAME));
dripCampaign.cc.Add(new EmailRecipient(DEFAULT_CC_EMAIL_ADDRESS_2, DEFAULT_EMAIL_NAME));
dripCampaign.bcc.Add(new EmailRecipient(DEFAULT_BCC_EMAIL_ADDRESS_1, DEFAULT_EMAIL_NAME));
dripCampaign.bcc.Add(new EmailRecipient(DEFAULT_BCC_EMAIL_ADDRESS_2, DEFAULT_EMAIL_NAME));
dripCampaign.sender.address = DEFAULT_SENDER_EMAIL_ADDRESS;
dripCampaign.sender.name = DEFAULT_SENDER_NAME;
dripCampaign.sender.reply_to = DEFAULT_REPLY_TO_EMAIL_ADDRESS;
dripCampaign.tags.Add(DEFAULT_TAG_1);
dripCampaign.tags.Add(DEFAULT_TAG_2);
dripCampaign.tags.Add(DEFAULT_TAG_3);
dripCampaign.locale = DEFAULT_LOCALE;
dripCampaign.esp_account = DEFAULT_ESP_ACCOUNT_ID;
dripCampaign.email_data.Add("amount", "$12.00");
// Make the API call
try
{
var dripCampaignResponse = await dripCampaign.ActivateAsync(DEFAULT_CAMPAIGN_ID);
// Validate the response
SendwithusClientTest.ValidateResponse(dripCampaignResponse);
}
catch (AggregateException exception)
{
Assert.Fail(exception.ToString());
}
}
/// <summary>
/// Tests the API call POST /drip_campaigns/(drip_campaign_id)/activate with invalid campaign ID
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestActivateDripCampaignWithInvalidParameters()
{
Trace.WriteLine(String.Format("POST /drip_campaigns/{0}/activate with invalid campaign ID", INVALID_CAMPAIGN_ID));
// Build the drip campaign object
var recipient = new EmailRecipient(DEFAULT_RECIPIENT_EMAIL_ADDRESS);
var dripCampaign = new DripCampaign(recipient);
// Make the API call
try {
var response = await dripCampaign.ActivateAsync(INVALID_CAMPAIGN_ID);
}
catch (AggregateException exception)
{
// Make sure the response was HTTP 400 Bad Request
SendwithusClientTest.ValidateException(exception, HttpStatusCode.BadRequest);
}
}
/// <summary>
/// Tests the API call POST /drip_campaigns/(drip_campaign_id)/deactivate
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestDeactivateFromDripCampaignAsync()
{
Trace.WriteLine(String.Format("POST /drip_campaigns/{0}/deactivate", DEFAULT_CAMPAIGN_ID));
// Make the API call
try
{
var dripCampaignResponse = await DripCampaign.DeactivateFromCampaignAsync(DEFAULT_CAMPAIGN_ID, DEFAULT_RECIPIENT_EMAIL_ADDRESS);
// Validate the response
SendwithusClientTest.ValidateResponse(dripCampaignResponse);
}
catch (AggregateException exception)
{
Assert.Fail(exception.ToString());
}
}
/// <summary>
/// Tests the API call POST /drip_campaigns/(drip_campaign_id)/deactivate
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestDeactivateFromAllDripCampaignsAsync()
{
Trace.WriteLine(String.Format("POST /drip_campaigns/{0}/deactivate", DEFAULT_CAMPAIGN_ID));
// Make the API call
try
{
var dripCampaignDeactivateResponse = await DripCampaign.DeactivateFromAllCampaignsAsync(DEFAULT_RECIPIENT_EMAIL_ADDRESS);
// Validate the response
SendwithusClientTest.ValidateResponse(dripCampaignDeactivateResponse);
}
catch (AggregateException exception)
{
Assert.Fail(exception.ToString());
}
}
/// <summary>
/// Tests the API call GET /drip_campaigns
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestGetDripCampaignsAsync()
{
Trace.WriteLine("GET /drip_campaigns");
// Make the API call
try
{
var dripCampaignDetails = await DripCampaign.GetDripCampaignsAsync();
// Validate the response
SendwithusClientTest.ValidateResponse(dripCampaignDetails);
}
catch (AggregateException exception)
{
Assert.Fail(exception.ToString());
}
}
/// <summary>
/// Tests the API call GET /drip_campaigns/(drip_campaign_id)
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestGetDripCampaignAsync()
{
Trace.WriteLine(String.Format("GET /drip_campaigns/{0}",DEFAULT_CAMPAIGN_ID));
// Make the API call
try
{
var response = await DripCampaign.GetDripCampaignAsync(DEFAULT_CAMPAIGN_ID);
// Validate the response
SendwithusClientTest.ValidateResponse(response);
}
catch (AggregateException exception)
{
Assert.Fail(exception.ToString());
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
////////////////////////////////////////////////////////////////////////////
//
// Class: StringInfo
//
// 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.
//
// Date: March 31, 1999
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
[System.Runtime.InteropServices.ComVisible(true)]
public class StringInfo
{
private String m_str;
private int[] m_indexes;
// Legacy constructor
public StringInfo() : this("") { }
// Primary, useful constructor
public StringInfo(String value)
{
this.String = value;
}
[System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals(Object value)
{
StringInfo that = value as StringInfo;
if (that != null)
{
return (this.m_str.Equals(that.m_str));
}
return (false);
}
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetHashCode()
{
return this.m_str.GetHashCode();
}
// Our zero-based array of index values into the string. Initialize if
// our private array is not yet, in fact, initialized.
private int[] Indexes
{
get
{
if ((null == this.m_indexes) && (0 < this.String.Length))
{
this.m_indexes = StringInfo.ParseCombiningCharacters(this.String);
}
return (this.m_indexes);
}
}
public String String
{
get
{
return (this.m_str);
}
set
{
if (null == value)
{
throw new ArgumentNullException("String",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
this.m_str = value;
this.m_indexes = null;
}
}
public int LengthInTextElements
{
get
{
if (null == this.Indexes)
{
// Indexes not initialized, so assume length zero
return (0);
}
return (this.Indexes.Length);
}
}
public static String GetNextTextElement(String str)
{
return (GetNextTextElement(str, 0));
}
////////////////////////////////////////////////////////////////////////
//
// Get the code point count of the current text element.
//
// A combining class is defined as:
// A character/surrogate that has the following Unicode category:
// * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT)
// * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA)
// * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE)
//
// In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as:
//
// 1. If a character/surrogate is in the following category, it is a text element.
// It can NOT further combine with characters in the combinging class to form a text element.
// * one of the Unicode category in the combinging class
// * UnicodeCategory.Format
// * UnicodeCateogry.Control
// * UnicodeCategory.OtherNotAssigned
// 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element.
//
// Return:
// The length of the current text element
//
// Parameters:
// String str
// index The starting index
// len The total length of str (to define the upper boundary)
// ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element.
// currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element.
//
////////////////////////////////////////////////////////////////////////
internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
return (currentCharCount);
}
// Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
int nextCharCount;
UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
if (CharUnicodeInfo.IsCombiningCategory(ucNext))
{
// The next element is a combining class.
// Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
// not a format character, and not a control character).
if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
|| (ucCurrent == UnicodeCategory.Format)
|| (ucCurrent == UnicodeCategory.Control)
|| (ucCurrent == UnicodeCategory.OtherNotAssigned)
|| (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
{
// Will fall thru and return the currentCharCount
}
else
{
int startIndex = index; // Remember the current index.
// We have a valid base characters, and we have a character (or surrogate) that is combining.
// Check if there are more combining characters to follow.
// Check if the next character is a nonspacing character.
index += currentCharCount + nextCharCount;
while (index < len)
{
ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
if (!CharUnicodeInfo.IsCombiningCategory(ucNext))
{
ucCurrent = ucNext;
currentCharCount = nextCharCount;
break;
}
index += nextCharCount;
}
return (index - startIndex);
}
}
// The return value will be the currentCharCount.
int ret = currentCharCount;
ucCurrent = ucNext;
// Update currentCharCount.
currentCharCount = nextCharCount;
return (ret);
}
// Returns the str containing the next text element in str starting at
// index index. If index is not supplied, then it will start at the beginning
// of str. It recognizes a base character plus one or more combining
// characters or a properly formed surrogate pair as a text element. See also
// the ParseCombiningCharacters() and the ParseSurrogates() methods.
public static String GetNextTextElement(String str, int index)
{
//
// Validate parameters.
//
if (str == null)
{
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || index >= len)
{
if (index == len)
{
return (String.Empty);
}
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
}
int charLen;
UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen)));
}
public static TextElementEnumerator GetTextElementEnumerator(String str)
{
return (GetTextElementEnumerator(str, 0));
}
public static TextElementEnumerator GetTextElementEnumerator(String str, int index)
{
//
// Validate parameters.
//
if (str == null)
{
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || (index > len))
{
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
}
return (new TextElementEnumerator(str, index, len));
}
/*
* Returns the indices of each base character or properly formed surrogate pair
* within the str. It recognizes a base character plus one or more combining
* characters or a properly formed surrogate pair as a text element and returns
* the index of the base character or high surrogate. Each index is the
* beginning of a text element within a str. The length of each element is
* easily computed as the difference between successive indices. The length of
* the array will always be less than or equal to the length of the str. For
* example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would
* return the indices: 0, 2, 4.
*/
public static int[] ParseCombiningCharacters(String str)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
int len = str.Length;
int[] result = new int[len];
if (len == 0)
{
return (result);
}
int resultCount = 0;
int i = 0;
int currentCharLen;
UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
while (i < len)
{
result[resultCount++] = i;
i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
}
if (resultCount < len)
{
int[] returnArray = new int[resultCount];
Array.Copy(result, returnArray, resultCount);
return (returnArray);
}
return (result);
}
}
}
| |
//
// Copyright 2010, Novell, Inc.
// Copyright 2011, 2012 Xamarin 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.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
using MonoMac.CoreFoundation;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public enum NSStringEncoding : uint {
ASCIIStringEncoding = 1,
NEXTSTEP = 2,
JapaneseEUC = 3,
UTF8 = 4,
ISOLatin1 = 5,
Symbol = 6,
NonLossyASCII = 7,
ShiftJIS = 8,
ISOLatin2 = 9,
Unicode = 10,
WindowsCP1251 = 11,
WindowsCP1252 = 12,
WindowsCP1253 = 13,
WindowsCP1254 = 14,
WindowsCP1250 = 15,
ISO2022JP = 21,
MacOSRoman = 30,
UTF16BigEndian = 0x90000100,
UTF16LittleEndian = 0x94000100,
UTF32 = 0x8c000100,
UTF32BigEndian = 0x98000100,
UTF32LittleEndian = 0x9c000100,
};
public enum NSStringCompareOptions : uint {
CaseInsensitiveSearch = 1,
LiteralSearch = 2,
BackwardsSearch = 4,
AnchoredSearch = 8,
NumericSearch = 64,
DiacriticInsensitiveSearch = 128,
WidthInsensitiveSearch = 256,
ForcedOrderingSearch = 512,
RegularExpressionSearch = 1024
}
#if GENERATOR && !MONOMAC
[Register ("NSString")]
#endif
public partial class NSString : NSObject {
static IntPtr selUTF8String = Selector.sel_registerName ("UTF8String");
static IntPtr selInitWithUTF8String = Selector.sel_registerName ("initWithUTF8String:");
static IntPtr selInitWithCharactersLength = Selector.sel_registerName ("initWithCharacters:length:");
#if COREBUILD
static IntPtr class_ptr = Class.GetHandle ("NSString");
#endif
#if GENERATOR && !MONOMAC
public NSString (IntPtr handle) : base (handle) {
}
#endif
public static IntPtr CreateNative (string str)
{
if (str == null)
return IntPtr.Zero;
unsafe {
fixed (char *ptrFirstChar = str){
var handle = Messaging.intptr_objc_msgSend (class_ptr, Selector.Alloc);
handle = Messaging.intptr_objc_msgsend_intptr_int (handle, selInitWithCharactersLength, (IntPtr) ptrFirstChar, str.Length);
return handle;
}
}
}
public static void ReleaseNative (IntPtr handle)
{
if (handle == IntPtr.Zero)
return;
Messaging.void_objc_msgSend (handle, Selector.Release);
}
#if false
public NSString (string str) {
if (str == null)
throw new ArgumentNullException ("str");
IntPtr bytes = Marshal.StringToHGlobalAuto (str);
Handle = (IntPtr) Messaging.intptr_objc_msgSend_intptr (Handle, selInitWithUTF8String, bytes);
Marshal.FreeHGlobal (bytes);
}
#else
public NSString (string str) {
if (str == null)
throw new ArgumentNullException ("str");
unsafe {
fixed (char *ptrFirstChar = str){
Handle = Messaging.intptr_objc_msgsend_intptr_int (Handle, selInitWithCharactersLength, (IntPtr) ptrFirstChar, str.Length);
}
}
}
#endif
public unsafe override string ToString ()
{
if (Handle == IntPtr.Zero)
return null;
return FromHandle (Handle);
}
public static implicit operator string (NSString str)
{
if (((object) str) == null)
return null;
return str.ToString ();
}
public static explicit operator NSString (string str)
{
if (str == null)
return null;
return new NSString (str);
}
public unsafe static string FromHandle (IntPtr usrhandle)
{
if (usrhandle == IntPtr.Zero)
return null;
return Marshal.PtrToStringAuto (Messaging.intptr_objc_msgSend (usrhandle, selUTF8String));
}
public static bool Equals (NSString a, NSString b)
{
if ((a as object) == (b as object))
return true;
if (((object) a) == null || ((object) b) == null)
return false;
if (a.Handle == b.Handle)
return true;
#if GENERATOR || COREBUILD
return a.ToString ().Equals (b.ToString ());
#else
return a.IsEqualTo (b.Handle);
#endif
}
public static bool operator == (NSString a, NSString b)
{
return Equals (a, b);
}
public static bool operator != (NSString a, NSString b)
{
return !Equals (a, b);
}
public override bool Equals (Object obj)
{
return Equals (this, obj as NSString);
}
public override int GetHashCode ()
{
return (int) this.Handle;
}
#if !MONOMAC && !COREBUILD
[Obsolete ("Use the version with a `ref float actualFontSize`")]
public System.Drawing.SizeF DrawString (System.Drawing.PointF point, float width, MonoTouch.UIKit.UIFont font, float minFontSize, float actualFontSize, MonoTouch.UIKit.UILineBreakMode breakMode, MonoTouch.UIKit.UIBaselineAdjustment adjustment)
{
float temp = actualFontSize;
return DrawString (point, width, font, minFontSize, ref temp, breakMode, adjustment);
}
#endif
}
}
| |
using System;
using System.Runtime.Serialization;
using Microsoft.Xna.Framework;
namespace RectangleFLib
{
[DataContract]
public struct RectangleF : IEquatable<RectangleF>
{
#region Private Fields
private static RectangleF emptyRectangle = new RectangleF();
#endregion Private Fields
#region Public Fields
[DataMember]
public float X;
[DataMember]
public float Y;
[DataMember]
public float Width;
[DataMember]
public float Height;
#endregion Public Fields
#region Public Properties
public static RectangleF Empty
{
get { return emptyRectangle; }
}
public float Left
{
get { return this.X; }
}
public float Right
{
get { return (this.X + this.Width); }
}
public float Top
{
get { return this.Y; }
}
public float Bottom
{
get { return (this.Y + this.Height); }
}
#endregion Public Properties
#region Constructors
public RectangleF(float x, float y, float width, float height)
{
this.X = x;
this.Y = y;
this.Width = width;
this.Height = height;
}
#endregion Constructors
#region Public Methods
public static bool operator ==(RectangleF a, RectangleF b)
{
return ((a.X == b.X) && (a.Y == b.Y) && (a.Width == b.Width) && (a.Height == b.Height));
}
public bool Contains(int x, int y)
{
return ((((this.X <= x) && (x < (this.X + this.Width))) && (this.Y <= y)) && (y < (this.Y + this.Height)));
}
public bool Contains(float x, float y)
{
return ((((this.X <= x) && (x < (this.X + this.Width))) && (this.Y <= y)) && (y < (this.Y + this.Height)));
}
public bool Contains(Point value)
{
return ((((this.X <= value.X) && (value.X < (this.X + this.Width))) && (this.Y <= value.Y)) && (value.Y < (this.Y + this.Height)));
}
public bool Contains(Vector2 value)
{
return ((((this.X <= value.X) && (value.X < (this.X + this.Width))) && (this.Y <= value.Y)) && (value.Y < (this.Y + this.Height)));
}
public bool Contains(RectangleF value)
{
return ((((this.X <= value.X) && ((value.X + value.Width) <= (this.X + this.Width))) && (this.Y <= value.Y)) && ((value.Y + value.Height) <= (this.Y + this.Height)));
}
public static bool operator !=(RectangleF a, RectangleF b)
{
return !(a == b);
}
public void Offset(Vector2 offset)
{
X += offset.X;
Y += offset.Y;
}
public void Offset(int offsetX, int offsetY)
{
X += offsetX;
Y += offsetY;
}
public Vector2 Location
{
get
{
return new Vector2(this.X, this.Y);
}
set
{
X = value.X;
Y = value.Y;
}
}
public Vector2 Center
{
get
{
return new Vector2(this.X + (this.Width / 2), this.Y + (this.Height / 2));
}
}
public void Inflate(float horizontalValue, float verticalValue)
{
X -= horizontalValue;
Y -= verticalValue;
Width += horizontalValue * 2;
Height += verticalValue * 2;
}
public bool IsEmpty
{
get
{
return ((((this.Width == 0) && (this.Height == 0)) && (this.X == 0)) && (this.Y == 0));
}
}
public bool Equals(RectangleF other)
{
return this == other;
}
public override bool Equals(object obj)
{
return (obj is RectangleF) ? this == ((RectangleF)obj) : false;
}
public override string ToString()
{
return string.Format("{{X:{0} Y:{1} Width:{2} Height:{3}}}", X, Y, Width, Height);
}
public override int GetHashCode()
{
return (int)(this.X * this.Y * this.Width * this.Height);
}
public bool Intersects(RectangleF value)
{
return value.Left <= Right &&
Left <= value.Right &&
value.Top <= Bottom &&
Top <= value.Bottom;
}
public void Intersects(ref RectangleF value, out bool result)
{
result = value.Left <= Right &&
Left <= value.Right &&
value.Top <= Bottom &&
Top <= value.Bottom;
}
public static RectangleF Intersect(RectangleF value1, RectangleF value2)
{
RectangleF rectangle;
Intersect(ref value1, ref value2, out rectangle);
return rectangle;
}
public static void Intersect(ref RectangleF value1, ref RectangleF value2, out RectangleF result)
{
if (value1.Intersects(value2))
{
float right_side = Math.Min(value1.X + value1.Width, value2.X + value2.Width);
float left_side = Math.Max(value1.X, value2.X);
float top_side = Math.Max(value1.Y, value2.Y);
float bottom_side = Math.Min(value1.Y + value1.Height, value2.Y + value2.Height);
result = new RectangleF(left_side, top_side, right_side - left_side, bottom_side - top_side);
}
else
{
result = new RectangleF(0, 0, 0, 0);
}
}
public static RectangleF Union(RectangleF value1, RectangleF value2)
{
float x = Math.Min(value1.X, value2.X);
float y = Math.Min(value1.Y, value2.Y);
return new RectangleF(x, y,
Math.Max(value1.Right, value2.Right) - x,
Math.Max(value1.Bottom, value2.Bottom) - y);
}
public static void Union(ref RectangleF value1, ref RectangleF value2, out RectangleF result)
{
result.X = Math.Min(value1.X, value2.X);
result.Y = Math.Min(value1.Y, value2.Y);
result.Width = Math.Max(value1.Right, value2.Right) - result.X;
result.Height = Math.Max(value1.Bottom, value2.Bottom) - result.Y;
}
public RectangleF(Rectangle value) //constructor
{
X = value.X;
Y = value.Y;
Width = value.Width;
Height = value.Height;
}
public static implicit operator Microsoft.Xna.Framework.Rectangle(RectangleF b) // explicit RectangleF to Rectangle conversion operator
{
Rectangle d = new Rectangle((int)b.X, (int)b.Y, (int)b.Width, (int)b.Height);
return d;
}
#endregion Public Methods
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
namespace Core
{
public class CBO
{
public static List<PropertyInfo> GetPropertyInfo(Type objType)
{
var objProperties = (List<PropertyInfo>) DataCache.GetCache(objType.FullName);
if (objProperties == null)
{
objProperties = new List<PropertyInfo>();
foreach (PropertyInfo tempLoopVar_objProperty in objType.GetProperties())
{
objProperties.Add(tempLoopVar_objProperty);
}
objProperties.TrimExcess();
DataCache.SetCache(objType.FullName, objProperties);
}
return objProperties;
}
private static int[] GetOrdinals(List<PropertyInfo> objProperties, IDataReader dr)
{
var arrOrdinals = new int[objProperties.Count];
if (dr != null)
{
int count = objProperties.Count - 1;
for (int i = 0; i <= count; i++)
{
arrOrdinals[i] = -1;
try
{
arrOrdinals[i] = dr.GetOrdinal(objProperties[i].Name);
}
catch // property does not exist in datareader
{
}
}
}
return arrOrdinals;
}
private static object CreateObject(Type objType, IDataReader dr, List<PropertyInfo> objProperties,
int[] arrOrdinals)
{
object objObject = Activator.CreateInstance(objType);
int count = objProperties.Count - 1;
for (int i = 0; i <= count; i++)
{
if (objProperties[i].CanWrite)
{
if (arrOrdinals[i] != -1)
{
if (Convert.IsDBNull(dr.GetValue(arrOrdinals[i])))
{
objProperties[i].SetValue(objObject, Null.SetNull(objProperties[i]), null);
}
else
{
try
{
objProperties[i].SetValue(objObject, dr.GetValue(arrOrdinals[i]), null);
}
catch
{
try
{
Type pType = objProperties[i].PropertyType;
if (pType.BaseType.Equals(typeof (Enum)))
{
objProperties[i].SetValue(objObject,
Enum.ToObject(pType, dr.GetValue(arrOrdinals[i])),
null);
}
else
{
objProperties[i].SetValue(objObject,
Convert.ChangeType(dr.GetValue(arrOrdinals[i]), pType),
null);
}
}
catch
{
// property does not exist in datareader
objProperties[i].SetValue(objObject, Null.SetNull(objProperties[i]), null);
}
}
}
}
}
}
return objObject;
}
public static object FillObject(IDataReader dr, Type objType)
{
object objFillObject;
List<PropertyInfo> objProperties = GetPropertyInfo(objType);
int[] arrOrdinals = GetOrdinals(objProperties, dr);
if (dr != null && dr.Read())
{
objFillObject = CreateObject(objType, dr, objProperties, arrOrdinals);
}
else
{
objFillObject = null;
}
if (dr != null)
{
dr.Close();
}
return objFillObject;
}
public static ArrayList FillCollection(IDataReader dr, Type objType)
{
var objFillCollection = new ArrayList();
if (dr == null)
return objFillCollection;
object objFillObject;
List<PropertyInfo> objProperties = GetPropertyInfo(objType);
int[] arrOrdinals = GetOrdinals(objProperties, dr);
while (dr.Read())
{
objFillObject = CreateObject(objType, dr, objProperties, arrOrdinals);
objFillCollection.Add(objFillObject);
}
if (dr != null)
{
dr.Close();
}
return objFillCollection;
}
public static IList FillCollection(IDataReader dr, Type objType, IList objToFill)
{
if (dr == null)
return objToFill;
object objFillObject;
List<PropertyInfo> objProperties = GetPropertyInfo(objType);
int[] arrOrdinals = GetOrdinals(objProperties, dr);
while (dr.Read())
{
objFillObject = CreateObject(objType, dr, objProperties, arrOrdinals);
objToFill.Add(objFillObject);
}
if (dr != null)
{
dr.Close();
}
return objToFill;
}
private static T CreateObject<T>(IDataReader dr, List<PropertyInfo> objProperties, int[] arrOrdinals)
where T : class, new()
{
var objObject = new T();
int count = objProperties.Count - 1;
for (int i = 0; i <= count; i++)
{
if (objProperties[i].CanWrite)
{
if (arrOrdinals[i] != -1)
{
if (Convert.IsDBNull(dr.GetValue(arrOrdinals[i])))
{
objProperties[i].SetValue(objObject, Null.SetNull(objProperties[i]), null);
}
else
{
try
{
objProperties[i].SetValue(objObject, dr.GetValue(arrOrdinals[i]), null);
}
catch
{
try
{
Type pType = objProperties[i].PropertyType;
if (pType.BaseType.Equals(typeof (Enum)))
{
objProperties[i].SetValue(objObject,
Enum.ToObject(pType, dr.GetValue(arrOrdinals[i])),
null);
}
else
{
objProperties[i].SetValue(objObject,
Convert.ChangeType(dr.GetValue(arrOrdinals[i]), pType),
null);
}
}
catch
{
// property does not exist in datareader
objProperties[i].SetValue(objObject, Null.SetNull(objProperties[i]), null);
}
}
}
}
}
}
return objObject;
}
public static T FillObject<T>(IDataReader dr) where T : class, new()
{
var objFillObject = new T();
List<PropertyInfo> objProperties = GetPropertyInfo(typeof (T));
int[] arrOrdinals = GetOrdinals(objProperties, dr);
if (dr != null && dr.Read())
{
objFillObject = CreateObject<T>(dr, objProperties, arrOrdinals);
}
else
{
objFillObject = null;
}
if (dr != null)
{
dr.Close();
}
return objFillObject;
}
public static C FillCollection<T, C>(IDataReader dr)
where T : class, new()
where C : ICollection<T>, new()
{
var objFillCollection = new C();
if (dr == null)
return objFillCollection;
T objFillObject;
List<PropertyInfo> objProperties = GetPropertyInfo(typeof (T));
int[] arrOrdinals = GetOrdinals(objProperties, dr);
while (dr.Read())
{
objFillObject = CreateObject<T>(dr, objProperties, arrOrdinals);
objFillCollection.Add(objFillObject);
}
if (dr != null)
{
dr.Close();
}
return objFillCollection;
}
public static List<T> FillCollection<T>(IDataReader dr) where T : class, new()
{
return FillCollection<T, List<T>>(dr);
}
public static IList<T> FillCollection<T>(IDataReader dr, IList<T> objToFill) where T : class, new()
{
if (dr == null)
return objToFill;
T objFillObject;
List<PropertyInfo> objProperties = GetPropertyInfo(typeof (T));
int[] arrOrdinals = GetOrdinals(objProperties, dr);
while (dr.Read())
{
objFillObject = CreateObject<T>(dr, objProperties, arrOrdinals);
objToFill.Add(objFillObject);
}
if (dr != null)
{
dr.Close();
}
return objToFill;
}
public static object InitializeObject(object objObject, Type objType)
{
List<PropertyInfo> objProperties = GetPropertyInfo(objType);
int count = objProperties.Count - 1;
for (int i = 0; i <= count; i++)
{
if (objProperties[i].CanWrite)
{
objProperties[i].SetValue(objObject, Null.SetNull(objProperties[i]), null);
}
}
return objObject;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using fyiReporting.RDL;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Text;
using System.Xml;
using System.Globalization;
using System.Drawing;
namespace fyiReporting.RDL
{
///<summary>
/// Renders a report to HTML. All positioning is handled via tables.
///</summary>
internal class RenderHtmlTable: IPresent
{
Report r; // report
// Stack<string> _Container; // container for body/list/rectangle/ ...
StringWriter tw; // temporary location where the output is going
IStreamGen _sg; // stream generater
Hashtable _styles; // hash table of styles we've generated
int cssId=1; // ID for css when names are usable or available
bool bScriptToggle=false; // need to generate toggle javascript in header
bool bScriptTableSort=false; // need to generate table sort javascript in header
Bitmap _bm=null; // bm and
Graphics _g=null; // g are needed when calculating string heights
bool _Asp=false; // denotes ASP.NET compatible HTML; e.g. no <html>, <body>
// separate JavaScript and CSS
string _Prefix=""; // prefix to generating all HTML names (e.g. css, ...
string _CSS; // when ASP we put the CSS into a string
string _JavaScript; // as well as any required javascript
int _SkipMatrixCols=0; // # of matrix columns to skip
public RenderHtmlTable(Report rep, IStreamGen sg)
{
r = rep;
_sg = sg; // We need this in future
tw = new StringWriter(); // will hold the bulk of the HTML until we generate
// final file
_styles = new Hashtable();
}
//Replaced from forum, User: Aulofee http://www.fyireporting.com/forum/viewtopic.php?t=793
//~RenderHtmlTable()
public void Dispose()
{
// These should already be cleaned up; but in case of an unexpected error
// these still need to be disposed of
if (_bm != null)
_bm.Dispose();
if (_g != null)
_g.Dispose();
}
public Report Report()
{
return r;
}
public bool Asp
{
get {return _Asp;}
set {_Asp = value;}
}
public string JavaScript
{
get {return _JavaScript;}
}
public string CSS
{
get {return _CSS;}
}
public string Prefix
{
get {return _Prefix;}
set
{
_Prefix = value==null? "": value;
if (_Prefix.Length > 0 &&
_Prefix[0] == '_')
_Prefix = "a" + _Prefix; // not perfect but underscores as first letter don't work
}
}
public bool IsPagingNeeded()
{
return false;
}
public void Start()
{
// Create three tables that represent how each top level report item (e.g. those not in a table
// or matrix) will be positioned.
return;
}
string FixupRelativeName(string relativeName)
{
if (_sg is OneFileStreamGen)
{
if (relativeName[0] == Path.DirectorySeparatorChar || relativeName[0] == Path.AltDirectorySeparatorChar)
relativeName = relativeName.Substring(1);
}
else if (relativeName[0] != Path.DirectorySeparatorChar)
relativeName = Path.DirectorySeparatorChar + relativeName;
return relativeName;
}
// puts the JavaScript into the header
private void ScriptGenerate(TextWriter ftw)
{
if (bScriptToggle || bScriptTableSort)
{
ftw.WriteLine("<script language=\"javascript\">");
}
if (bScriptToggle)
{
ftw.WriteLine("var dname='';");
ftw.WriteLine(@"function hideShow(node, hideCount, showID) {
if (navigator.appName.toLowerCase().indexOf('netscape') > -1)
dname = 'table-row';
else
dname = 'block';
var tNode;
for (var ci=0;ci<node.childNodes.length;ci++) {
if (node.childNodes[ci].tagName && node.childNodes[ci].tagName.toLowerCase() == 'img') tNode = node.childNodes[ci];
}
var rows = findObject(showID);
if (rows[0].style.display == dname) {hideRows(rows, hideCount); tNode.src='plus.gif';}
else {
tNode.src='minus.gif';
for (var i = 0; i < rows.length; i++) {
rows[i].style.display = dname;
}
}
}
function hideRows(rows, count) {
var row;
if (navigator.appName.toLowerCase().indexOf('netscape') > -1)
{
for (var r=0; r < rows.length; r++) {
row = rows[r];
row.style.display = 'none';
var imgs = row.getElementsByTagName('img');
for (var ci=0;ci<imgs.length;ci++) {
if (imgs[ci].className == 'toggle') {
imgs[ci].src='plus.gif';
}
}
}
return;
}
if (rows.tagName == 'TR')
row = rows;
else
row = rows[0];
while (count > 0) {
row.style.display = 'none';
var imgs = row.getElementsByTagName('img');
for (var ci=0;ci<imgs.length;ci++) {
if (imgs[ci].className == 'toggle') {
imgs[ci].src='plus.gif';
}
}
row = row.nextSibling;
count--;
}
}
function findObject(id) {
if (navigator.appName.toLowerCase().indexOf('netscape') > -1)
{
var a = new Array();
var count=0;
for (var i=0; i < document.all.length; i++)
{
if (document.all[i].id == id)
a[count++] = document.all[i];
}
return a;
}
else
{
var o = document.all[id];
if (o.tagName == 'TR')
{
var a = new Array();
a[0] = o;
return a;
}
return o;
}
}
");
}
if (bScriptTableSort)
{
ftw.WriteLine("var SORT_INDEX;");
ftw.WriteLine("var SORT_DIR;");
ftw.WriteLine("function sort_getInnerText(element) {");
ftw.WriteLine(" if (typeof element == 'string') return element;");
ftw.WriteLine(" if (typeof element == 'undefined') return element;");
ftw.WriteLine(" if (element.innerText) return element.innerText;");
ftw.WriteLine(" var s = '';");
ftw.WriteLine(" var cn = element.childNodes;");
ftw.WriteLine(" for (var i = 0; i < cn.length; i++) {");
ftw.WriteLine(" switch (cn[i].nodeType) {");
ftw.WriteLine(" case 1:"); // element node
ftw.WriteLine(" s += sort_getInnerText(cn[i]);");
ftw.WriteLine(" break;");
ftw.WriteLine(" case 3:"); // text node
ftw.WriteLine(" s += cn[i].nodeValue;");
ftw.WriteLine(" break;");
ftw.WriteLine(" }");
ftw.WriteLine(" }");
ftw.WriteLine(" return s;");
ftw.WriteLine("}");
ftw.WriteLine("function sort_table(node, sortfn, header_rows, footer_rows) {");
ftw.WriteLine(" var arrowNode;"); // arrow node
ftw.WriteLine(" for (var ci=0;ci<node.childNodes.length;ci++) {");
ftw.WriteLine(" if (node.childNodes[ci].tagName && node.childNodes[ci].tagName.toLowerCase() == 'span') arrowNode = node.childNodes[ci];");
ftw.WriteLine(" }");
ftw.WriteLine(" var td = node.parentNode;");
ftw.WriteLine(" SORT_INDEX = td.cellIndex;"); // need to remember SORT_INDEX in compare function
ftw.WriteLine(" var table = sort_getTable(td);");
ftw.WriteLine(" var sortnext;");
ftw.WriteLine(" if (arrowNode.getAttribute('sortdir') == 'down') {");
ftw.WriteLine(" arrow = ' ↑';");
ftw.WriteLine(" SORT_DIR = -1;"); // descending SORT_DIR in compare function
ftw.WriteLine(" sortnext = 'up';");
ftw.WriteLine(" } else {");
ftw.WriteLine(" arrow = ' ↓';");
ftw.WriteLine(" SORT_DIR = 1;"); // ascending SORT_DIR in compare function
ftw.WriteLine(" sortnext = 'down';");
ftw.WriteLine(" }");
ftw.WriteLine(" var newRows = new Array();");
ftw.WriteLine(" for (j=header_rows;j<table.rows.length-footer_rows;j++) { newRows[j-header_rows] = table.rows[j]; }");
ftw.WriteLine(" newRows.sort(sortfn);");
// We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
ftw.WriteLine(" for (i=0;i<newRows.length;i++) {table.tBodies[0].appendChild(newRows[i]);}");
// Reset all arrows and directions for next time
ftw.WriteLine(" var spans = document.getElementsByTagName('span');");
ftw.WriteLine(" for (var ci=0;ci<spans.length;ci++) {");
ftw.WriteLine(" if (spans[ci].className == 'sortarrow') {");
// in the same table as us?
ftw.WriteLine(" if (sort_getTable(spans[ci]) == sort_getTable(node)) {");
ftw.WriteLine(" spans[ci].innerHTML = ' ';");
ftw.WriteLine(" spans[ci].setAttribute('sortdir','up');");
ftw.WriteLine(" }");
ftw.WriteLine(" }");
ftw.WriteLine(" }");
ftw.WriteLine(" arrowNode.innerHTML = arrow;");
ftw.WriteLine(" arrowNode.setAttribute('sortdir',sortnext);");
ftw.WriteLine("}");
ftw.WriteLine("function sort_getTable(el) {");
ftw.WriteLine(" if (el == null) return null;");
ftw.WriteLine(" else if (el.nodeType == 1 && el.tagName.toLowerCase() == 'table')");
ftw.WriteLine(" return el;");
ftw.WriteLine(" else");
ftw.WriteLine(" return sort_getTable(el.parentNode);");
ftw.WriteLine("}");
ftw.WriteLine("function sort_cmp_date(c1,c2) {");
ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]);");
ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]);");
ftw.WriteLine(" dt1 = new Date(t1);");
ftw.WriteLine(" dt2 = new Date(t2);");
ftw.WriteLine(" if (dt1==dt2) return 0;");
ftw.WriteLine(" if (dt1<dt2) return -SORT_DIR;");
ftw.WriteLine(" return SORT_DIR;");
ftw.WriteLine("}");
// numeric - removes any extraneous formating characters before parsing
ftw.WriteLine("function sort_cmp_number(c1,c2) {");
ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]).replace(/[^0-9.]/g,'');");
ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]).replace(/[^0-9.]/g,'');");
ftw.WriteLine(" n1 = parseFloat(t1);");
ftw.WriteLine(" n2 = parseFloat(t2);");
ftw.WriteLine(" if (isNaN(n1)) n1 = Number.MAX_VALUE");
ftw.WriteLine(" if (isNaN(n2)) n2 = Number.MAX_VALUE");
ftw.WriteLine(" return (n1 - n2)*SORT_DIR;");
ftw.WriteLine("}");
// For string we first do a case insensitive comparison;
// when equal we then do a case sensitive comparison
ftw.WriteLine("function sort_cmp_string(c1,c2) {");
ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]).toLowerCase();");
ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]).toLowerCase();");
ftw.WriteLine(" if (t1==t2) return sort_cmp_casesensitive(c1,c2);");
ftw.WriteLine(" if (t1<t2) return -SORT_DIR;");
ftw.WriteLine(" return SORT_DIR;");
ftw.WriteLine("}");
ftw.WriteLine("function sort_cmp_casesensitive(c1,c2) {");
ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]);");
ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]);");
ftw.WriteLine(" if (t1==t2) return 0;");
ftw.WriteLine(" if (t2<t2) return -SORT_DIR;");
ftw.WriteLine(" return SORT_DIR;");
ftw.WriteLine("}");
}
if (bScriptToggle || bScriptTableSort)
{
ftw.WriteLine("</script>");
}
return;
}
// handle the Action tag
private string Action(Action a, Row r, string t, string tooltip)
{
if (a == null)
return t;
string result = t;
if (a.Hyperlink != null)
{ // Handle a hyperlink
string url = a.HyperLinkValue(this.r, r);
if (tooltip == null)
result = String.Format("<a target=\"_top\" href=\"{0}\">{1}</a>", url, t);
else
result = String.Format("<a target=\"_top\" href=\"{0}\" title=\"{1}\">{2}</a>", url, tooltip, t);
}
else if (a.Drill != null)
{ // Handle a drill through
StringBuilder args= new StringBuilder("<a target=\"_top\" href=\"");
if (_Asp) // for ASP we go thru the default page and pass it as an argument
args.Append("Default.aspx?rs:url=");
args.Append(a.Drill.ReportName);
args.Append(".rdl");
if (a.Drill.DrillthroughParameters != null)
{
bool bFirst = !_Asp; // ASP already have an argument
foreach (DrillthroughParameter dtp in a.Drill.DrillthroughParameters.Items)
{
if (!dtp.OmitValue(this.r, r))
{
if (bFirst)
{ // First parameter - prefixed by '?'
args.Append('?');
bFirst = false;
}
else
{ // Subsequant parameters - prefixed by '&'
args.Append('&');
}
args.Append(dtp.Name.Nm);
args.Append('=');
args.Append(dtp.ValueValue(this.r, r));
}
}
}
args.Append('"');
if (tooltip != null)
args.Append(String.Format(" title=\"{0}\"", tooltip));
args.Append(">");
args.Append(t);
args.Append("</a>");
result = args.ToString();
}
else if (a.BookmarkLink != null)
{ // Handle a bookmark
string bm = a.BookmarkLinkValue(this.r, r);
if (tooltip == null)
result = String.Format("<a href=\"#{0}\">{1}</a>", bm, t);
else
result = String.Format("<a href=\"#{0}\" title=\"{1}\">{2}</a>", bm, tooltip, t);
}
return result;
}
private string Bookmark(string bm, string t)
{
if (bm == null)
return t;
return String.Format("<div id=\"{0}\">{1}</div>", bm, t);
}
// Generate the CSS styles and put them in the header
private void CssGenerate(TextWriter ftw)
{
if (_styles.Count <= 0)
return;
if (!_Asp)
ftw.WriteLine("<style type='text/css'>");
foreach (CssCacheEntry2 cce in _styles.Values)
{
int i = cce.Css.IndexOf('{');
if (cce.Name.IndexOf('#') >= 0)
ftw.WriteLine("{0} {1}", cce.Name, cce.Css.Substring(i));
else
ftw.WriteLine(".{0} {1}", cce.Name, cce.Css.Substring(i));
}
if (!_Asp)
ftw.WriteLine("</style>");
}
private string CssAdd(Style s, ReportLink rl, Row row)
{
return CssAdd(s, rl, row, false, float.MinValue, float.MinValue);
}
private string CssAdd(Style s, ReportLink rl, Row row, bool bForceRelative)
{
return CssAdd(s, rl, row, bForceRelative, float.MinValue, float.MinValue);
}
private string CssAdd(Style s, ReportLink rl, Row row, bool bForceRelative, float h, float w)
{
string css;
string prefix = CssPrefix(s, rl);
if (_Asp && prefix == "table#")
bForceRelative = true;
if (s != null)
css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + s.GetCSS(this.r, row, true) + "}";
else if (rl is Table || rl is Matrix)
css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + "border-collapse:collapse;}";
else
css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + "}";
CssCacheEntry2 cce = (CssCacheEntry2) _styles[css];
if (cce == null)
{
string name = prefix + this.Prefix + "css" + cssId++.ToString();
cce = new CssCacheEntry2(css, name);
_styles.Add(cce.Css, cce);
}
int i = cce.Name.IndexOf('#');
if (i > 0)
return cce.Name.Substring(i+1);
else
return cce.Name;
}
private string CssPosition(ReportLink rl,Row row, bool bForceRelative, float h, float w)
{
if (!(rl is ReportItem)) // if not a report item then no position
return "";
// no positioning within a table
for (ReportLink p=rl.Parent; p != null; p=p.Parent)
{
if (p is TableCell)
return "";
if (p is RowGrouping ||
p is MatrixCell ||
p is ColumnGrouping ||
p is Corner)
{
StringBuilder sb2 = new StringBuilder();
if (h != float.MinValue)
sb2.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}pt; ", h);
if (w != float.MinValue)
sb2.AppendFormat(NumberFormatInfo.InvariantInfo, "width: {0}pt; ", w);
return sb2.ToString();
}
}
// TODO: optimize by putting this into ReportItem and caching result???
ReportItem ri = (ReportItem) rl;
StringBuilder sb = new StringBuilder();
if (ri.Left != null)
{
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "left: {0}; ", ri.Left.CSS);
}
if (!(ri is Matrix))
{
if (ri.Width != null)
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "width: {0}; ", ri.Width.CSS);
}
if (ri.Top != null)
{
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "top: {0}pt; ", ri.Gap(this.r));
}
if (ri is List)
{
List l = ri as List;
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}pt; ", l.HeightOfList(this.r, GetGraphics,row));
}
else if (ri is Matrix || ri is Table)
{}
else if (ri.Height != null)
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}; ", ri.Height.CSS);
if (sb.Length > 0)
{
if (bForceRelative || ri.YParents != null)
sb.Insert(0, "position: relative; ");
else
sb.Insert(0, "position: absolute; ");
}
return sb.ToString();
}
private Graphics GetGraphics
{
get
{
if (_g == null)
{
_bm = new Bitmap(10, 10);
_g = Graphics.FromImage(_bm);
}
return _g;
}
}
private string CssPrefix(Style s, ReportLink rl)
{
string cssPrefix=null;
ReportLink p;
if (rl is Table || rl is Matrix || rl is Rectangle)
{
cssPrefix = "table#";
}
else if (rl is Body)
{
cssPrefix = "body#";
}
else if (rl is Line)
{
cssPrefix = "table#";
}
else if (rl is List)
{
cssPrefix = "";
}
else if (rl is Subreport)
{
cssPrefix = "";
}
else if (rl is Chart)
{
cssPrefix = "";
}
if (cssPrefix != null)
return cssPrefix;
// now find what the style applies to
for (p=rl.Parent; p != null; p=p.Parent)
{
if (p is TableCell)
{
bool bHead = false;
ReportLink p2;
for (p2=p.Parent; p2 != null; p2=p2.Parent)
{
Type t2 = p2.GetType();
if (t2 == typeof(Header))
{
if (p2.Parent is Table)
bHead=true;
break;
}
}
if (bHead)
cssPrefix = "th#";
else
cssPrefix = "td#";
break;
}
else if (p is RowGrouping ||
p is MatrixCell ||
p is ColumnGrouping ||
p is Corner)
{
cssPrefix = "td#";
break;
}
}
return cssPrefix == null? "": cssPrefix;
}
public void End()
{
string bodyCssId;
if (r.ReportDefinition.Body != null)
bodyCssId = CssAdd(r.ReportDefinition.Body.Style, r.ReportDefinition.Body, null); // add the style for the body
else
bodyCssId = null;
TextWriter ftw = _sg.GetTextWriter(); // the final text writer location
if (_Asp)
{
// do any required JavaScript
StringWriter sw = new StringWriter();
ScriptGenerate(sw);
_JavaScript = sw.ToString();
sw.Close();
// do any required CSS
sw = new StringWriter();
CssGenerate(sw);
_CSS = sw.ToString();
sw.Close();
}
else
{
ftw.WriteLine(@"<html>");
// handle the <head>: description, javascript and CSS goes here
ftw.WriteLine("<head>");
ScriptGenerate(ftw);
CssGenerate(ftw);
if (r.Description != null) // Use description as title if provided
ftw.WriteLine(string.Format(@"<title>{0}</title>", XmlUtil.XmlAnsi(r.Description)));
ftw.WriteLine(@"</head>");
}
// Always want an HTML body - even if report doesn't have a body stmt
if (this._Asp)
{
ftw.WriteLine("<table style=\"position: relative;\">");
}
else if (bodyCssId != null)
ftw.WriteLine(@"<body id='{0}'><table>", bodyCssId);
else
ftw.WriteLine("<body><table>");
ftw.Write(tw.ToString());
if (this._Asp)
ftw.WriteLine(@"</table>");
else
ftw.WriteLine(@"</table></body></html>");
if (_g != null)
{
_g.Dispose();
_g = null;
}
if (_bm != null)
{
_bm.Dispose();
_bm = null;
}
return;
}
// Body: main container for the report
public void BodyStart(Body b)
{
if (b.ReportItems != null && b.ReportItems.Items.Count > 0)
tw.WriteLine("<tr><td><div style=\"POSITION: relative; \">");
}
public void BodyEnd(Body b)
{
if (b.ReportItems != null && b.ReportItems.Items.Count > 0)
tw.WriteLine("</div></td></tr>");
}
public void PageHeaderStart(PageHeader ph)
{
if (ph.ReportItems != null && ph.ReportItems.Items.Count > 0)
tw.WriteLine("<tr><td><div style=\"overflow: clip; POSITION: relative; HEIGHT: {0};\">", ph.Height.CSS);
}
public void PageHeaderEnd(PageHeader ph)
{
if (ph.ReportItems != null && ph.ReportItems.Items.Count > 0)
tw.WriteLine("</div></td></tr>");
}
public void PageFooterStart(PageFooter pf)
{
if (pf.ReportItems != null && pf.ReportItems.Items.Count > 0)
tw.WriteLine("<tr><td><div style=\"overflow: clip; POSITION: relative; HEIGHT: {0};\">", pf.Height.CSS);
}
public void PageFooterEnd(PageFooter pf)
{
if (pf.ReportItems != null && pf.ReportItems.Items.Count > 0)
tw.WriteLine("</div></td></tr>");
}
public void Textbox(Textbox tb, string t, Row row)
{
if (!tb.IsHtml(this.r, row)) // we leave the text as is when request is to treat as html
{ // this can screw up the generated HTML if not properly formed HTML
// make all the characters browser readable
t = XmlUtil.XmlAnsi(t);
// handle any specified bookmark
t = Bookmark(tb.BookmarkValue(this.r, row), t);
// handle any specified actions
t = Action(tb.Action, row, t, tb.ToolTipValue(this.r, row));
}
// determine if we're in a tablecell
Type tp = tb.Parent.Parent.GetType();
bool bCell;
if (tp == typeof(TableCell) ||
tp == typeof(Corner) ||
tp == typeof(DynamicColumns) ||
tp == typeof(DynamicRows) ||
tp == typeof(StaticRow) ||
tp == typeof(StaticColumn) ||
tp == typeof(Subtotal) ||
tp == typeof(MatrixCell))
bCell = true;
else
bCell = false;
if (tp == typeof(Rectangle))
tw.Write("<td>");
if (bCell)
{ // The cell has the formatting for this text
if (t == "")
tw.Write("<br />"); // must have something in cell for formating
else
tw.Write(t);
}
else
{ // Formatting must be specified
string cssName = CssAdd(tb.Style, tb, row); // get the style name for this item
tw.Write("<div class='{0}'>{1}</div>", cssName, t);
}
if (tp == typeof(Rectangle))
tw.Write("</td>");
}
public void DataRegionNoRows(DataRegion d, string noRowsMsg) // no rows in table
{
if (noRowsMsg == null)
noRowsMsg = "";
bool bTableCell = d.Parent.Parent.GetType() == typeof(TableCell);
if (bTableCell)
{
if (noRowsMsg == "")
tw.Write("<br />");
else
tw.Write(noRowsMsg);
}
else
{
string cssName = CssAdd(d.Style, d, null); // get the style name for this item
tw.Write("<div class='{0}'>{1}</div>", cssName, noRowsMsg);
}
}
// Lists
public bool ListStart(List l, Row r)
{
// identifiy reportitem it if necessary
string bookmark = l.BookmarkValue(this.r, r);
if (bookmark != null) //
tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
return true;
}
public void ListEnd(List l, Row r)
{
string bookmark = l.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("</div>");
}
public void ListEntryBegin(List l, Row r)
{
string cssName = CssAdd(l.Style, l, r, true); // get the style name for this item; force to be relative
tw.WriteLine();
tw.WriteLine("<div class={0}>", cssName);
}
public void ListEntryEnd(List l, Row r)
{
tw.WriteLine();
tw.WriteLine("</div>");
}
// Tables // Report item table
public bool TableStart(Table t, Row row)
{
string cssName = CssAdd(t.Style, t, row); // get the style name for this item
// Determine if report custom defn want this table to be sortable
if (IsTableSortable(t))
{
this.bScriptTableSort = true;
}
string bookmark = t.BookmarkValue(this.r, row);
if (bookmark != null)
tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
// Calculate the width of all the columns
int width = t.WidthInPixels(this.r, row);
if (width <= 0)
tw.WriteLine("<table id='{0}'>", cssName);
else
tw.WriteLine("<table id='{0}' width={1}>", cssName, width);
return true;
}
public bool IsTableSortable(Table t)
{
if (t.TableGroups != null || t.Details == null ||
t.Details.TableRows == null || t.Details.TableRows.Items.Count != 1)
return false; // can't have tableGroups; must have 1 detail row
// Determine if report custom defn want this table to be sortable
bool bReturn = false;
if (t.Custom != null)
{
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in t.Custom.CustomXmlNode.ChildNodes)
{
if (xNodeLoop.Name == "HTML")
{
if (xNodeLoop.LastChild.InnerText.ToLower() == "true")
{
bReturn = true;
}
break;
}
}
}
return bReturn;
}
public void TableEnd(Table t, Row row)
{
string bookmark = t.BookmarkValue(this.r, row);
if (bookmark != null)
tw.WriteLine("</div>");
tw.WriteLine("</table>");
return;
}
public void TableBodyStart(Table t, Row row)
{
tw.WriteLine("<tbody>");
}
public void TableBodyEnd(Table t, Row row)
{
tw.WriteLine("</tbody>");
}
public void TableFooterStart(Footer f, Row row)
{
tw.WriteLine("<tfoot>");
}
public void TableFooterEnd(Footer f, Row row)
{
tw.WriteLine("</tfoot>");
}
public void TableHeaderStart(Header h, Row row)
{
tw.WriteLine("<thead>");
}
public void TableHeaderEnd(Header h, Row row)
{
tw.WriteLine("</thead>");
}
public void TableRowStart(TableRow tr, Row row)
{
tw.Write("\t<tr");
ReportLink rl = tr.Parent.Parent;
Visibility v=null;
Textbox togText=null; // holds the toggle text box if any
if (rl is Details)
{
Details d = (Details) rl;
v = d.Visibility;
togText = d.ToggleTextbox;
}
else if (rl.Parent is TableGroup)
{
TableGroup tg = (TableGroup) rl.Parent;
v = tg.Visibility;
togText = tg.ToggleTextbox;
}
if (v != null &&
v.Hidden != null)
{
bool bHide = v.Hidden.EvaluateBoolean(this.r, row);
if (bHide)
tw.Write(" style=\"display:none;\"");
}
if (togText != null && togText.Name != null)
{
string name = togText.Name.Nm + "_" + togText.RunCount(this.r).ToString();
tw.Write(" id='{0}'", name);
}
tw.Write(">");
}
public void TableRowEnd(TableRow tr, Row row)
{
tw.WriteLine("</tr>");
}
public void TableCellStart(TableCell t, Row row)
{
string cellType = t.InTableHeader? "th": "td";
ReportItem r = t.ReportItems.Items[0];
string cssName = CssAdd(r.Style, r, row); // get the style name for this item
tw.Write("<{0} id='{1}'", cellType, cssName);
// calculate width of column
if (t.InTableHeader && t.OwnerTable.TableColumns != null)
{
// Calculate the width across all the spanned columns
int width = 0;
for (int ci=t.ColIndex; ci < t.ColIndex + t.ColSpan; ci++)
{
TableColumn tc = t.OwnerTable.TableColumns.Items[ci] as TableColumn;
if (tc != null && tc.Width != null)
width += tc.Width.PixelsX;
}
if (width > 0)
tw.Write(" width={0}", width);
}
if (t.ColSpan > 1)
tw.Write(" colspan={0}", t.ColSpan);
Textbox tb = r as Textbox;
if (tb != null && // have textbox
tb.IsToggle && // and its a toggle
tb.Name != null) // and need name as well
{
int groupNestCount = t.OwnerTable.GetGroupNestCount(this.r);
if (groupNestCount > 0) // anything to toggle?
{
string name = tb.Name.Nm + "_" + (tb.RunCount(this.r)+1).ToString();
bScriptToggle = true;
// need both hand and pointer because IE and Firefox use different names
tw.Write(" onClick=\"hideShow(this, {0}, '{1}')\" onMouseOver=\"style.cursor ='hand';style.cursor ='pointer'\">", groupNestCount, name);
tw.Write("<img class='toggle' src=\"plus.gif\" align=\"top\"/>");
}
else
tw.Write("<img src=\"empty.gif\" align=\"top\"/>");
}
else
tw.Write(">");
if (t.InTableHeader)
{
// put the second half of the sort tags for the column; if needed
// first half ---- <a href="#" onclick="sort_table(this,sort_cmp_string,1,0);return false;">
// next half follows text ---- <span class="sortarrow"> </span></a></th>
string sortcmp = SortType(t, tb); // obtain the sort type
if (sortcmp != null) // null if sort not needed
{
int headerRows, footerRows;
headerRows = t.OwnerTable.Header.TableRows.Items.Count; // since we're in header we know we have some rows
if (t.OwnerTable.Footer != null &&
t.OwnerTable.Footer.TableRows != null)
footerRows = t.OwnerTable.Footer.TableRows.Items.Count;
else
footerRows = 0;
tw.Write("<a href=\"#\" title='Sort' onclick=\"sort_table(this,{0},{1},{2});return false;\">",sortcmp, headerRows, footerRows);
}
}
return;
}
private string SortType(TableCell tc, Textbox tb)
{
// return of null means don't sort
if (tb == null || !IsTableSortable(tc.OwnerTable))
return null;
// default is true if table is sortable;
// but user may place override on Textbox custom tag
if (tb.Custom != null)
{
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in tb.Custom.CustomXmlNode.ChildNodes)
{
if (xNodeLoop.Name == "HTML")
{
if (xNodeLoop.LastChild.InnerText.ToLower() == "false")
{
return null;
}
break;
}
}
}
// Must find out the type of the detail column
Details d = tc.OwnerTable.Details;
if (d == null)
return null;
TableRow tr = d.TableRows.Items[0] as TableRow;
if (tr == null)
return null;
TableCell dtc = tr.TableCells.Items[tc.ColIndex] as TableCell;
if (dtc == null)
return null;
Textbox dtb = dtc.ReportItems.Items[0] as Textbox;
if (dtb == null)
return null;
string sortcmp;
switch (dtb.Value.Type)
{
case TypeCode.DateTime:
sortcmp = "sort_cmp_date";
break;
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Decimal:
case TypeCode.Single:
case TypeCode.Double:
sortcmp = "sort_cmp_number";
break;
case TypeCode.String:
sortcmp = "sort_cmp_string";
break;
case TypeCode.Empty: // Not a type we know how to sort
default:
sortcmp = null;
break;
}
return sortcmp;
}
public void TableCellEnd(TableCell t, Row row)
{
string cellType = t.InTableHeader? "th": "td";
Textbox tb = t.ReportItems.Items[0] as Textbox;
if (cellType == "th" && SortType(t, tb) != null)
{ // put the second half of the sort tags for the column
// first half ---- <a href="#" onclick="sort_table(this,sort_cmp_string,1,0);return false;">
// next half follows text ---- <span class="sortarrow"> </span></a></th>
tw.Write("<span class=\"sortarrow\"> </span></a>");
}
tw.Write("</{0}>", cellType);
return;
}
public bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) // called first
{
string bookmark = m.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
// output some of the table styles
string cssName = CssAdd(m.Style, m, r); // get the style name for this item
tw.WriteLine("<table id='{0}'>", cssName);
return true;
}
public void MatrixColumns(Matrix m, MatrixColumns mc) // called just after MatrixStart
{
}
public void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan)
{
if (ri == null) // Empty cell?
{
if (_SkipMatrixCols == 0)
tw.Write("<td>");
return;
}
string cssName = CssAdd(ri.Style, ri, r, false, h, w); // get the style name for this item
tw.Write("<td id='{0}'", cssName);
if (colSpan != 1)
{
tw.Write(" colspan={0}", colSpan);
_SkipMatrixCols=-(colSpan-1); // start it as negative as indicator that we need this </td>
}
else
_SkipMatrixCols=0;
if (ri is Textbox)
{
Textbox tb = (Textbox) ri;
if (tb.IsToggle && tb.Name != null) // name is required for this
{
string name = tb.Name.Nm + "_" + (tb.RunCount(this.r)+1).ToString();
bScriptToggle = true; // we need to generate JavaScript in header
// TODO -- need to calculate the hide count correctly
tw.Write(" onClick=\"hideShow(this, {0}, '{1}')\" onMouseOver=\"style.cursor ='hand'\"", 0, name);
}
}
tw.Write(">");
}
public void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r)
{
if (_SkipMatrixCols == 0)
tw.Write("</td>");
else if (_SkipMatrixCols < 0)
{
tw.Write("</td>");
_SkipMatrixCols = -_SkipMatrixCols;
}
else
_SkipMatrixCols--;
return;
}
public void MatrixRowStart(Matrix m, int row, Row r)
{
tw.Write("\t<tr");
tw.Write(">");
}
public void MatrixRowEnd(Matrix m, int row, Row r)
{
tw.WriteLine("</tr>");
}
public void MatrixEnd(Matrix m, Row r) // called last
{
tw.Write("</table>");
string bookmark = m.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("</div>");
return;
}
public void Chart(Chart c, Row r, ChartBase cb)
{
string relativeName;
Stream io = _sg.GetIOStream(out relativeName, "png");
try
{
cb.Save(this.r, io, ImageFormat.Png);
}
finally
{
io.Flush();
io.Close();
}
relativeName = FixupRelativeName(relativeName);
// Create syntax in a string buffer
StringWriter sw = new StringWriter();
string bookmark = c.BookmarkValue(this.r, r);
if (bookmark != null)
sw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
string cssName = CssAdd(c.Style, c, null); // get the style name for this item
sw.Write("<img src=\"{0}\" class='{1}'", relativeName, cssName);
string tooltip = c.ToolTipValue(this.r, r);
if (tooltip != null)
sw.Write(" alt=\"{0}\"", tooltip);
if (c.Height != null)
sw.Write(" height=\"{0}\"", c.Height.PixelsY.ToString());
if (c.Width != null)
sw.Write(" width=\"{0}\"", c.Width.PixelsX.ToString());
sw.Write(">");
if (bookmark != null)
sw.Write("</div>");
tw.Write(Action(c.Action, r, sw.ToString(), tooltip));
return;
}
public void Image(Image i, Row r, string mimeType, Stream ioin)
{
string relativeName;
string suffix;
switch (mimeType)
{
case "image/bmp":
suffix = "bmp";
break;
case "image/jpeg":
suffix = "jpeg";
break;
case "image/gif":
suffix = "gif";
break;
case "image/png":
case "image/x-png":
suffix = "png";
break;
default:
suffix = "unk";
break;
}
Stream io = _sg.GetIOStream(out relativeName, suffix);
try
{
if (ioin.CanSeek) // ioin.Length requires Seek support
{
byte[] ba = new byte[ioin.Length];
ioin.Read(ba, 0, ba.Length);
io.Write(ba, 0, ba.Length);
}
else
{
byte[] ba = new byte[1000]; // read a 1000 bytes at a time
while (true)
{
int length = ioin.Read(ba, 0, ba.Length);
if (length <= 0)
break;
io.Write(ba, 0, length);
}
}
}
finally
{
io.Flush();
io.Close();
}
if (i.ImageSource == ImageSourceEnum.Embedded) // embedded image in html
relativeName = "data:" + mimeType + ";base64," + i.EmbeddedImageData;
else
relativeName = FixupRelativeName(relativeName);
// Create syntax in a string buffer
StringWriter sw = new StringWriter();
string bookmark = i.BookmarkValue(this.r, r);
if (bookmark != null)
sw.WriteLine("<div id=\"{0}\">", bookmark); // we're using for css style
string cssName = CssAdd(i.Style, i, null); // get the style name for this item
sw.Write("<img src=\"{0}\" class='{1}'", relativeName, cssName);
string tooltip = i.ToolTipValue(this.r, r);
if (tooltip != null)
sw.Write(" alt=\"{0}\"", tooltip);
if (i.Height != null)
sw.Write(" height=\"{0}\"", i.Height.PixelsY.ToString());
if (i.Width != null)
sw.Write(" width=\"{0}\"", i.Width.PixelsX.ToString());
sw.Write("/>");
if (bookmark != null)
sw.Write("</div>");
tw.Write(Action(i.Action, r, sw.ToString(), tooltip));
return;
}
public void Line(Line l, Row r)
{
bool bVertical;
string t;
if (l.Height == null || l.Height.PixelsY > 0) // only handle horizontal rule
{
if (l.Width == null || l.Width.PixelsX > 0) // and vertical rules
return;
bVertical = true;
t = "<TABLE style=\"border-collapse:collapse;BORDER-STYLE: none;WIDTH: {0}; POSITION: absolute; LEFT: {1}; TOP: {2}; HEIGHT: {3}; BACKGROUND-COLOR:{4};\"><TBODY><TR style=\"WIDTH:{0}\"><TD style=\"WIDTH:{0}\"></TD></TR></TBODY></TABLE>";
}
else
{
bVertical = false;
t = "<TABLE style=\"border-collapse:collapse;BORDER-STYLE: none;WIDTH: {0}; POSITION: absolute; LEFT: {1}; TOP: {2}; HEIGHT: {3}; BACKGROUND-COLOR:{4};\"><TBODY><TR style=\"HEIGHT:{3}\"><TD style=\"HEIGHT:{3}\"></TD></TR></TBODY></TABLE>";
}
string width, left, top, height, color;
Style s = l.Style;
left = l.Left == null? "0px": l.Left.CSS;
top = l.Top == null? "0px": l.Top.CSS;
if (bVertical)
{
height = l.Height == null? "0px": l.Height.CSS;
// width comes from the BorderWidth
if (s != null && s.BorderWidth != null && s.BorderWidth.Default != null)
width = s.BorderWidth.Default.EvaluateString(this.r, r);
else
width = "1px";
}
else
{
width = l.Width == null? "0px": l.Width.CSS;
// height comes from the BorderWidth
if (s != null && s.BorderWidth != null && s.BorderWidth.Default != null)
height = s.BorderWidth.Default.EvaluateString(this.r, r);
else
height = "1px";
}
if (s != null && s.BorderColor != null && s.BorderColor.Default != null)
color = s.BorderColor.Default.EvaluateString(this.r, r);
else
color = "black";
tw.WriteLine(t, width, left, top, height, color);
return;
}
public bool RectangleStart(RDL.Rectangle rect, Row r)
{
string cssName = CssAdd(rect.Style, rect, r); // get the style name for this item
string bookmark = rect.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
// Calculate the width of all the columns
int width = rect.Width.PixelsX;
if (width < 0)
tw.WriteLine("<table id='{0}'><tr>", cssName);
else
tw.WriteLine("<table id='{0}' width={1}><tr>", cssName, width);
return true;
}
public void RectangleEnd(RDL.Rectangle rect, Row r)
{
tw.WriteLine("</tr></table>");
string bookmark = rect.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("</div>");
return;
}
// Subreport:
public void Subreport(Subreport s, Row r)
{
string cssName = CssAdd(s.Style, s, r); // get the style name for this item
tw.WriteLine("<div class='{0}'>", cssName);
s.ReportDefn.Run(this);
tw.WriteLine("</div>");
}
public void GroupingStart(Grouping g) // called at start of grouping
{
}
public void GroupingInstanceStart(Grouping g) // called at start for each grouping instance
{
}
public void GroupingInstanceEnd(Grouping g) // called at start for each grouping instance
{
}
public void GroupingEnd(Grouping g) // called at end of grouping
{
}
public void RunPages(Pages pgs) // we don't have paging turned on for html
{
}
}
class CssCacheEntry2
{
string _Css; // css
string _Name; // name of entry
public CssCacheEntry2(string css, string name)
{
_Css = css;
_Name = name;
}
public string Css
{
get { return _Css; }
set { _Css = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
namespace OnlineGraph
{
public class GraphMeasurementCollection : SortableCollectionBase, ICustomTypeDescriptor
{
#region CollectionBase implementation
public GraphMeasurementCollection()
{
//In your collection class constructor add this line.
//set the SortObjectType for sorting.
base.SortObjectType = typeof(GraphMeasurement);
}
public GraphMeasurement this[int index]
{
get
{
return ((GraphMeasurement)List[index]);
}
set
{
List[index] = value;
}
}
public int Add(GraphMeasurement value)
{
return (List.Add(value));
}
public int IndexOf(GraphMeasurement value)
{
return (List.IndexOf(value));
}
public void Insert(int index, GraphMeasurement value)
{
List.Insert(index, value);
}
public void Remove(GraphMeasurement value)
{
List.Remove(value);
}
public bool Contains(GraphMeasurement value)
{
// If value is not of type Int16, this will return false.
return (List.Contains(value));
}
protected override void OnInsert(int index, Object value)
{
// Insert additional code to be run only when inserting values.
}
protected override void OnRemove(int index, Object value)
{
// Insert additional code to be run only when removing values.
}
protected override void OnSet(int index, Object oldValue, Object newValue)
{
// Insert additional code to be run only when setting values.
}
protected override void OnValidate(Object value)
{
}
#endregion
[TypeConverter(typeof(GraphMeasurementCollectionConverter))]
public GraphMeasurementCollection Symbols
{
get { return this; }
}
internal class SymbolConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is GraphMeasurement)
{
// Cast the value to an Employee type
GraphMeasurement pp = (GraphMeasurement)value;
return pp.Symbol + ", " + pp.Value.ToString() + ", " + pp.Timestamp.ToString("dd/MM/yyyy HH:mm:ss");
}
return base.ConvertTo(context, culture, value, destType);
}
}
// This is a special type converter which will be associated with the EmployeeCollection class.
// It converts an EmployeeCollection object to a string representation for use in a property grid.
internal class GraphMeasurementCollectionConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is GraphMeasurementCollection)
{
// Return department and department role separated by comma.
return "Symbols";
}
return base.ConvertTo(context, culture, value, destType);
}
}
#region ICustomTypeDescriptor impl
public String GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
public AttributeCollection GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
public String GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
public TypeConverter GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
public EventDescriptor GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
public PropertyDescriptor GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(this, true);
}
public object GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
public EventDescriptorCollection GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
public object GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
/// <summary>
/// Called to get the properties of this type. Returns properties with certain
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
return GetProperties();
}
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{
// Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list of employees
for (int i = 0; i < this.List.Count; i++)
{
// Create a property descriptor for the employee item and add to the property descriptor collection
GraphMeasurementCollectionPropertyDescriptor pd = new GraphMeasurementCollectionPropertyDescriptor(this, i);
pds.Add(pd);
}
// return the property descriptor collection
return pds;
}
#endregion
public class GraphMeasurementCollectionPropertyDescriptor : PropertyDescriptor
{
private GraphMeasurementCollection collection = null;
private int index = -1;
public GraphMeasurementCollectionPropertyDescriptor(GraphMeasurementCollection coll, int idx)
:
base("#" + idx.ToString(), null)
{
this.collection = coll;
this.index = idx;
}
public override AttributeCollection Attributes
{
get
{
return new AttributeCollection(null);
}
}
public override bool CanResetValue(object component)
{
return true;
}
public override Type ComponentType
{
get
{
return this.collection.GetType();
}
}
public override string DisplayName
{
get
{
GraphMeasurement emp = this.collection[index];
return (string)(emp.Symbol);
}
}
public override string Description
{
get
{
GraphMeasurement emp = this.collection[index];
StringBuilder sb = new StringBuilder();
sb.Append(emp.Symbol);
sb.Append(", ");
sb.Append(emp.Value.ToString());
sb.Append(", ");
sb.Append(emp.Timestamp.ToString("dd/MM/yyyy HH:mm:ss"));
return sb.ToString();
}
}
public override object GetValue(object component)
{
return this.collection[index];
}
public override bool IsReadOnly
{
get { return false; }
}
public override string Name
{
get { return "#" + index.ToString(); }
}
public override Type PropertyType
{
get { return this.collection[index].GetType(); }
}
public override void ResetValue(object component)
{
}
public override bool ShouldSerializeValue(object component)
{
return true;
}
public override void SetValue(object component, object value)
{
// this.collection[index] = value;
}
}
}
}
| |
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
// ReSharper disable CheckNamespace
namespace System.Collections.Generic //Based on namespace of IEnumerable<T>
// ReSharper restore CheckNamespace
{
public static class EnumerableExtensions
{
public static bool AnyX(this IEnumerable source)
{
return source.GetEnumerator().MoveNext();
}
}
public static class ListOfTExtensions
{
public static void InsertAndMaintainOrderX<T>(this IList<T> source, T item) where T : IComparable
{
var index = source.FirstIndexOfX(x => x.CompareTo(item) > 0);
if (index == -1)
{
source.Add(item);
}
else
{
source.Insert(index, item);
}
}
}
public static class EnumerableOfTExtensions
{
public static IEnumerable<T> AlterInPlaceX<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
{
action(item);
yield return item;
}
}
public static IEnumerable<T> CyclicX<T>(this IEnumerable<T> source, int numberOfItemsFromStart)
{
var initialItemsCache = new T[numberOfItemsFromStart];
int i = 0;
foreach (var item in source)
{
if (i < numberOfItemsFromStart)
{
initialItemsCache[i++] = item;
}
yield return item;
}
foreach (var repeatedItem in initialItemsCache)
{
yield return repeatedItem;
}
}
public static object ElementAtX(this IEnumerable source, int index)
{
if (source == null)
throw new ArgumentNullException("source");
var list = source as IList;
if (list != null)
return list[index];
if (index < 0)
throw new ArgumentOutOfRangeException("index");
var enumerator = source.GetEnumerator();
while (enumerator.MoveNext())
{
if (index == 0)
return enumerator.Current;
--index;
}
throw new ArgumentOutOfRangeException("index");
}
public static IEnumerable<T> TakeEveryX<T>(this IEnumerable<T> source, int numberToSkip, bool takeFirst)
{
var leftToSkip = takeFirst ? 0 : numberToSkip;
foreach (var item in source)
{
if (leftToSkip == 0)
{
yield return item;
leftToSkip = numberToSkip;
}
else
{
leftToSkip--;
}
}
}
public static IEnumerable<T[]> WithFollowersX<T>(this IEnumerable<T> source, int numberOfFollowers, bool cyclic)
{
var array = source.ToArray();
var numberOfResults = (cyclic ? array.Length : array.Length - numberOfFollowers);
for (var i = 0; i < numberOfResults; i++)
{
var target = new T[1 + numberOfFollowers];
int numFromFirstArray = Math.Min(1 + numberOfFollowers, array.Length - i);
Array.ConstrainedCopy(array, i, target, 0, numFromFirstArray);
int numFromSecondArray = (1 + numberOfFollowers) - numFromFirstArray;
if (numFromSecondArray > 0)
{
Array.ConstrainedCopy(array, 0, target, numFromFirstArray, numFromSecondArray);
}
yield return target;
}
}
public static IEnumerable<TRet> WithFollowersX<T, TRet>(
this IEnumerable<T> source, Func<T, T, TRet> creator, bool cyclic)
{
var array = source.ToArray();
var numberOfResults = (cyclic ? array.Length : array.Length - 1);
for (var i = 0; i < numberOfResults; i++)
{
int indexOfSecondItem = (i == (array.Length - 1)) ? 0 : (i + 1);
yield return creator(array[i], array[indexOfSecondItem]);
}
}
public static IEnumerable<TRet> WithFollowersX<T, TRet>(
this IEnumerable<T> source, Func<T, T, T, TRet> creator, bool cyclic)
{
var array = source.ToArray();
var numberOfResults = (cyclic ? array.Length : array.Length - 2);
for (var i = 0; i < numberOfResults; i++)
{
int indexOfSecondItem = (i == (array.Length - 1)) ? 0 : (i + 1);
int indexOfThirdItem = (indexOfSecondItem == (array.Length - 1)) ? 0 : (indexOfSecondItem + 1);
yield return creator(array[i], array[indexOfSecondItem], array[indexOfThirdItem]);
}
}
public static IEnumerable<T> DistinctByX<T>(this IEnumerable<T> source, params Func<T, object>[] fieldsToCompare)
{
return source.Distinct(AdHocComparer<T>.For(fieldsToCompare));
}
public static IEnumerable<TResult> SelectX<TEntity, TResult>(this IEnumerable<TEntity> source, params Func<TEntity, TResult>[] selectors)
{
return source.SelectMany(x => selectors.Select(y => y(x)));
}
public static IEnumerable<TEntity> SelectIndexesX<TEntity>(this IEnumerable<TEntity> source, params int[] indexes)
{
return source.Where((x, i) => indexes.Contains(i));
}
public static IEnumerable<TResult> SequentialJoinX<TElement, TResult>(this IEnumerable<TElement> source, Func<TElement, TElement, TResult> sequentialAggregator)
{
var first = true;
var previousElement = default(TElement);
foreach (var element in source)
{
if (first)
{
first = false;
previousElement = element;
continue;
}
yield return sequentialAggregator(previousElement, element);
previousElement = element;
}
}
private class AdHocComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, object>[] _FieldsToCompare;
private AdHocComparer(Func<T, object>[] fieldsToCompare)
{
_FieldsToCompare = fieldsToCompare;
}
public static IEqualityComparer<T> For(Func<T, object>[] fieldsToCompare)
{
return new AdHocComparer<T>(fieldsToCompare);
}
public bool Equals(T x, T y)
{
return _FieldsToCompare.All(c => c(x).Equals(c(y)));
}
public int GetHashCode(T obj)
{
return _FieldsToCompare.Aggregate(0, (agg, c) => agg ^ c(obj).GetHashCode());
}
}
public static IEnumerable<TResult> FullOuterJoin<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector)
where TInner : class
where TOuter : class
{
// ReSharper disable PossibleMultipleEnumeration
var innerLookup = inner.ToLookup(innerKeySelector);
var outerLookup = outer.ToLookup(outerKeySelector);
var innerJoinItems = inner
.Where(innerItem => !outerLookup.Contains(innerKeySelector(innerItem)))
.Select(innerItem => resultSelector(null, innerItem));
return outer
.SelectMany(outerItem =>
{
var innerItems = innerLookup[outerKeySelector(outerItem)];
return innerItems.Any() ? innerItems : new TInner[] { null };
}, resultSelector)
.Concat(innerJoinItems);
// ReSharper restore PossibleMultipleEnumeration
}
/// <summary>
/// Behaves just like ToArray, but conveys the reason for execution.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static T[] ExecuteQueryNowX<T>([NotNull]this IQueryable<T> source)
{
return source.ToArray();
}
public static int DeepHashCode<T>([NotNull]this IEnumerable<T> source)
{
return source.Aggregate(0, (agg, x) => agg ^ x.GetHashCode());
}
public static bool DeepEqualsX<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
var firstEnumerator = first.GetEnumerator();
var secondEnumerator = second.GetEnumerator();
while (firstEnumerator.MoveNext())
{
if ((secondEnumerator.MoveNext() == false) || (firstEnumerator.Current.Equals(secondEnumerator.Current) == false))
{
return false;
}
}
return secondEnumerator.MoveNext() == false;
}
public static IEnumerable<IEnumerable<T>> SplitX<T>([NotNull]this IEnumerable<T> source, [NotNull]Predicate<T> seperatorPredicate, SeparatorBehavior separatorBehavior = SeparatorBehavior.Omit)
{
var enumerator = source.GetEnumerator();
var isFirst = true;
while (true)
{
bool isDone;
var arr = GetAllItemsUntilSeparator(isFirst, enumerator, seperatorPredicate, separatorBehavior, out isDone);
if (arr != null)
{
yield return arr;
}
isFirst = false;
if (isDone)
{
yield break;
}
}
}
private static T[] GetAllItemsUntilSeparator<T>(bool isFirstInOuterLoop, IEnumerator<T> enumerator, Predicate<T> seperatorPredicate, SeparatorBehavior separatorBehavior, out bool isDone)
{
if (isFirstInOuterLoop)
{
if (enumerator.MoveNext() == false)
{
isDone = true;
return null;
}
}
var buffer = new List<T>();
var isFirst = true;
do
{
bool shouldReturn;
bool shouldStop;
HandleCurrent(seperatorPredicate(enumerator.Current), separatorBehavior, isFirst, out shouldReturn, out shouldStop);
isFirst = false;
if (shouldReturn)
{
buffer.Add(enumerator.Current);
}
if (shouldStop)
{
if (separatorBehavior == SeparatorBehavior.AttachAsStarter)
{
isDone = false;
}
else
{
isDone = enumerator.MoveNext() == false;
}
return buffer.HasElementsX() ? buffer.ToArray() : null;
}
} while ((enumerator.MoveNext()));
isDone = true;
return buffer.ToArray();
}
private static void HandleCurrent(bool isSeperator, SeparatorBehavior separatorBehavior, bool isFirst, out bool shouldReturn, out bool shouldStop)
{
if (isSeperator == false)
{
shouldStop = false;
shouldReturn = true;
return;
}
if (separatorBehavior == SeparatorBehavior.Omit)
{
shouldStop = true;
shouldReturn = false;
return;
}
if ((separatorBehavior == SeparatorBehavior.AttachAsStarter) && isFirst)
{
shouldStop = false;
shouldReturn = true;
return;
}
shouldStop = true;
shouldReturn = separatorBehavior == SeparatorBehavior.AttachAsLast;
}
// ReSharper disable UnusedMember.Global
public static bool AllX<T>([NotNull]this IEnumerable<T> source, [NotNull, InstantHandle]Func<T, int, bool> predicate)
{
var i = 0;
return source.All(t => predicate(t, i++));
}
public static IEnumerable<K> SafeSelectX<T, K>([NotNull]this IEnumerable<T> source, [NotNull]Func<T, K> converter, Action<Exception, T> errorHandler = null)
{
return source.Select(x =>
{
try
{
return converter(x);
}
catch (Exception ex)
{
if (errorHandler != null)
errorHandler(ex, x);
return default(K);
}
});
}
[NotNull]
public static IEnumerable<T> SafeWhereX<T>([NotNull]this IEnumerable<T> source, [NotNull]Predicate<T> predicate, [NotNull]Action<Exception> errorHandler)
{
return source.Where(x =>
{
try
{
return predicate(x);
}
catch (Exception ex)
{
errorHandler(ex);
return false;
}
});
}
public static Tuple<T, T> FirstAndLastX<T>([NotNull]this IEnumerable<T> source)
{
var gotFirst = false;
T first = default(T), last = default(T);
foreach (var x in source)
{
if (gotFirst == false)
{
first = x;
gotFirst = true;
}
last = x;
}
return new Tuple<T, T>(first, last);
}
[NotNull]
public static IEnumerable<T> FollowedByUnlessNullX<T>(this IEnumerable<T> source, T suffix) where T : class
{
if (source != null)
{
foreach (var enumerable in source)
{
yield return enumerable;
}
}
if (suffix != null)
{
yield return suffix;
}
}
[NotNull]
public static IEnumerable<T> FollowedByX<T>([NotNull]this IEnumerable<T> source, params T[] suffix)
{
foreach (var sourceItem in source)
{
yield return sourceItem;
}
foreach (var suffixItem in suffix)
{
yield return suffixItem;
}
}
[NotNull]
public static IEnumerable<T> WithoutRepeatsX<T>([NotNull]this IEnumerable<T> source)
{
return WithoutRepeatsX(source, EqualityComparer<T>.Default);
}
[NotNull]
public static IEnumerable<T> WithoutRepeatsX<T>([NotNull]this IEnumerable<T> source, IEqualityComparer<T> comparer)
{
T prev = default(T);
bool first = true;
foreach (var current in source)
{
if (first || (comparer.Equals(prev, current) == false))
{
yield return current;
}
first = false;
prev = current;
}
}
[NotNull]
public static ObservableCollection<T> ToObservableCollection<T>([NotNull]this IEnumerable<T> source)
{
return new ObservableCollection<T>(source);
}
public static int FirstIndexOfX<T>([NotNull]this IEnumerable<T> source, [NotNull] Predicate<T> pred)
{
return source.Select((x, i) => pred(x) ? i : -1).FirstOrDefaultX(x => x != -1, -1);
}
public static int LastIndexOfX<T>([NotNull]this IEnumerable<T> source, [NotNull] Predicate<T> pred)
{
return source.Select((x, i) => pred(x) ? i : -1).LastOrDefaultX(x => x != -1, -1);
}
public static List<int> AllIndexesOfX<T>([NotNull]this IEnumerable<T> source, [NotNull] Predicate<T> pred)
{
var i = 0;
var retList = new List<int>(0);
foreach (var item in source)
{
if (pred(item))
{
retList.Add(i);
}
i++;
}
return retList;
}
public static T SingleOrDefaultX<T>([NotNull]this IEnumerable<T> source, T defaultValue)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
var list = source as IList<T>;
if (list != null)
{
switch (list.Count)
{
case 0: return defaultValue;
case 1: return list[0];
}
}
else
{
using (var e = source.GetEnumerator())
{
if (!e.MoveNext()) return defaultValue;
T result = e.Current;
if (!e.MoveNext()) return result;
}
}
throw new InvalidOperationException("MoreThanOneElement");
}
public static T FirstOrDefaultX<T>([NotNull]this IEnumerable<T> source, T defaultValue)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
var list = source as IList<T>;
if (list != null)
{
if (list.Count > 0) return list[0];
}
else
{
using (var e = source.GetEnumerator())
{
if (e.MoveNext()) return e.Current;
}
}
return defaultValue;
}
public static T FirstOrDefaultX<T>([NotNull]this IEnumerable<T> source, Func<T, bool> predicate, T defaultValue)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
foreach (var element in source)
{
if (predicate(element)) return element;
}
return defaultValue;
}
public static T LastOrDefaultX<T>([NotNull]this IEnumerable<T> source, T defaultValue)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
var list = source as IList<T>;
if (list != null)
{
int count = list.Count;
if (count > 0) return list[count - 1];
}
else
{
using (var e = source.GetEnumerator())
{
if (e.MoveNext())
{
T result;
do
{
result = e.Current;
} while (e.MoveNext());
return result;
}
}
}
return defaultValue;
}
public static T LastOrDefaultX<T>([NotNull]this IEnumerable<T> source, Func<T, bool> predicate, T defaultValue)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
T result = defaultValue;
foreach (T element in source)
{
if (predicate(element))
{
result = element;
}
}
return result;
}
public static IEnumerable<T> AsNewEnumerableX<T>([NotNull]this IEnumerable<T> source)
{
return source.Select(x => x);
}
public static bool HasMoreThanOneElementX<T>([NotNull]this IEnumerable<T> source)
{
return source.Skip(1).Any();
}
public static int UncheckedSumX([NotNull]this IEnumerable<int> source)
{
int acc = 0;
//It's the same as sum, except for the "Checked" block.
// ReSharper disable LoopCanBeConvertedToQuery
foreach (var i in source)
{
acc += i;
}
// ReSharper restore LoopCanBeConvertedToQuery
return acc;
}
public static bool HasElementsX<T>([NotNull]this IEnumerable<T> source)
{
return source.Any();
}
public static bool NotNullAndHasElementsX<T>(this IEnumerable<T> source)
{
return source != null && source.Any();
}
public static T MinItemByCriteriaX<T, K>(this IEnumerable<T> source, Func<T, K> criteria)
where K : IComparable<K>
{
var minVal = default(K);
var minItem = default(T);
var isFirst = true;
foreach (var v in source)
{
if (isFirst)
{
minVal = criteria(v);
minItem = v;
isFirst = false;
continue;
}
var currentVal = criteria(v);
if (currentVal.CompareTo(minVal) < 0)
{
minItem = v;
minVal = currentVal;
}
}
return minItem;
}
public static T MaxItemByCriteriaX<T, K>(this IEnumerable<T> source, Func<T, K> criteria)
where K : IComparable<K>
{
var maxVal = default(K);
var maxItem = default(T);
var isFirst = true;
foreach (var v in source)
{
if (isFirst)
{
maxVal = criteria(v);
maxItem = v;
isFirst = false;
continue;
}
var currentVal = criteria(v);
if (currentVal.CompareTo(maxVal) > 0)
{
maxItem = v;
maxVal = currentVal;
}
}
return maxItem;
}
[AssertionMethod]
public static bool IsNullOrEmptyX<T>([AssertionCondition(AssertionConditionType.IS_NOT_NULL)]this IEnumerable<T> source)
{
return source == null || source.IsEmptyX();
}
[AssertionMethod]
public static bool IsNullOrEmptyX<T>([AssertionCondition(AssertionConditionType.IS_NOT_NULL)]this T[] source)
{
return source == null || source.Length == 0;
}
public static IEnumerable<T> PadX<T>(this IEnumerable<T> source, T prefix, T suffix)
{
yield return prefix;
foreach (var item in source)
{
yield return item;
}
yield return suffix;
}
public static bool IsEmptyX<T>([NotNull]this IEnumerable<T> source)
{
return source.Any() == false;
}
public static bool IsEmptyX<T>([NotNull]this T[] source)
{
return source.Length == 0;
}
[NotNull]
public static IEnumerable<T> ExceptNullsX<T>([NotNull]this IEnumerable<T> source) where T : class
{
return source.Where(x => x != null);
}
public static IEnumerable<T> ExceptX<T>([NotNull]this IEnumerable<T> source, Func<T, bool> exclude)
{
return source.Where(x => exclude(x) == false);
}
public static IEnumerable<T> ExceptX<T>([NotNull]this IEnumerable<T> source, T excludedMember)
{
return source.Except(ReferenceEquals(excludedMember, null) ? Enumerable.Empty<T>() : excludedMember.AsEnumerableX());
}
public static IEnumerable<T> ExceptX<T>([NotNull]this IEnumerable<T> source, T excludedMember, IEqualityComparer<T> comparer)
{
return source.Except(ReferenceEquals(excludedMember, null) ? Enumerable.Empty<T>() : excludedMember.AsEnumerableX(), comparer);
}
public static IEnumerable<T> ExceptIndexesX<T>([NotNull]this IEnumerable<T> source, IEnumerable<int> indexes)
{
var orderedIndexes = indexes.OrderBy(x => x).ToArray();
int i = 0;
int j = 0;
var enumerator = source.GetEnumerator();
while (enumerator.MoveNext())
{
if (j >= orderedIndexes.Length || orderedIndexes[j] != i)
{
yield return enumerator.Current;
}
else
{
j++;
}
i++;
}
}
public static T MinOrValueIfEmptyX<T>([NotNull]this IEnumerable<T> source, T value)
{
// ReSharper disable PossibleMultipleEnumeration
return source.IsEmptyX() ? value : source.Min();
// ReSharper restore PossibleMultipleEnumeration
}
public static T MaxOrValueIfEmptyX<T>([NotNull]this IEnumerable<T> source, T value)
{
// ReSharper disable PossibleMultipleEnumeration
return source.IsEmptyX() ? value : source.Max();
// ReSharper restore PossibleMultipleEnumeration
}
public static TSelector MaxOrValueIfEmptyX<TSource, TSelector>([NotNull]this IEnumerable<TSource> source, Func<TSource, TSelector> selector, TSelector value)
{
// ReSharper disable PossibleMultipleEnumeration
return source.IsEmptyX() ? value : source.Max(selector);
// ReSharper restore PossibleMultipleEnumeration
}
public static TSelector MinOrValueIfEmptyX<TSource, TSelector>([NotNull]this IEnumerable<TSource> source, Func<TSource, TSelector> selector, TSelector value)
{
// ReSharper disable PossibleMultipleEnumeration
return source.IsEmptyX() ? value : source.Min(selector);
// ReSharper restore PossibleMultipleEnumeration
}
[NotNull]
public static IEnumerable<T> AsEnumerableEmptyIfNullX<T>(this IEnumerable<T> source)
{
return ReferenceEquals(source, null) ? Enumerable.Empty<T>() : source;
}
//this implemntation was copied from the generic enumerable implemntation
//public static int CountX(this IEnumerable source)
//{
// if (source == null)
// {
// throw new ArgumentNullException("source");
// }
// ICollection is2 = source as ICollection;
// if (is2 != null)
// {
// return is2.Count;
// }
// int num = 0;
// if (source is IDisposable)
// {
// using (IDisposable disposableEnumerator = (IDisposable)source.GetEnumerator())
// {
// IEnumerator enumerator = (IEnumerator)disposableEnumerator;
// while (enumerator.MoveNext())
// {
// num++;
// }
// }
// }
// else
// {
// IEnumerator enumerator = source.GetEnumerator();
// while (enumerator.MoveNext())
// {
// num++;
// }
// }
// return num;
//}
public static HashSet<T> ToHashSet<T>([NotNull]this IEnumerable<T> source)
{
return new HashSet<T>(source);
}
public static HashSet<T> ToHashSet<T>([NotNull]this IEnumerable<T> source, IEqualityComparer<T> comparer)
{
return new HashSet<T>(source, comparer);
}
public static IEnumerable<TResult> ZipX<TFirst, TSecond, TResult>([NotNull]this IEnumerable<TFirst> first, [NotNull]IEnumerable<TSecond> second, [NotNull]Func<TFirst, TSecond, TResult> func)
{
return first.ZipX(second, (x, y, i) => func(x, y));
}
public static IEnumerable<TResult> ZipX<TFirst, TSecond, TResult>([NotNull]this IEnumerable<TFirst> first, [NotNull] IEnumerable<TSecond> second, [NotNull]Func<TFirst, TSecond, int, TResult> func)
{
var ie1 = first.GetEnumerator();
var ie2 = second.GetEnumerator();
var index = 0;
while (ie1.MoveNext() && ie2.MoveNext())
{
yield return func(ie1.Current, ie2.Current, index);
index++;
}
}
public static bool EnumerableEqualsX<T>(this IEnumerable<T> first, IEnumerable<T> second) where T : IEquatable<T>
{
var ie1 = first.GetEnumerator();
var ie2 = second.GetEnumerator();
bool a, b = false;
while ((a = ie1.MoveNext()) && (b = ie2.MoveNext()))
{
if (ie1.Current.Equals(ie2.Current) == false)
{
return false;
}
}
return a == b;
}
public static IEnumerable<T> InRange<T, TValue>(
this IQueryable<T> source,
Expression<Func<T, TValue>> selector,
int blockSize,
IEnumerable<TValue> values)
{
MethodInfo method = null;
foreach (var tmp in typeof(Enumerable).GetMethods(
BindingFlags.Public | BindingFlags.Static))
{
if (tmp.Name == "Contains" && tmp.IsGenericMethodDefinition
&& tmp.GetParameters().Length == 2)
{
method = tmp.MakeGenericMethod(typeof(TValue));
break;
}
}
if (method == null) throw new InvalidOperationException(
"Unable to locate Contains");
foreach (var block in values.GetBlocks(blockSize))
{
var row = Expression.Parameter(typeof(T), "row");
var member = Expression.Invoke(selector, row);
var keys = Expression.Constant(block, typeof(TValue[]));
var predicate = Expression.Call(method, keys, member);
var lambda = Expression.Lambda<Func<T, bool>>(
predicate, row);
foreach (var record in source.Where(lambda))
{
yield return record;
}
}
}
public static IEnumerable<T> RandomOrderedX<T>(this IEnumerable<T> source)
{
return source.OrderBy(x => Guid.NewGuid());
}
public static IEnumerable<TRet> GetBlocksX<T, TRet>(this IEnumerable<T> source, Func<T, T, TRet> selector)
{
T first = default(T);
int i = 0;
foreach (var item in source)
{
if (i++%2 == 0)
{
first = item;
}
else
{
yield return selector(first, item);
}
}
if (i%2 == 1)
{
throw new Exception("Source does not contain a number of elements divisible by 2");
}
}
public static IEnumerable<T[]> GetBlocks<T>(this IEnumerable<T> source, int blockSize)
{
var list = new List<T>(blockSize);
foreach (var item in source)
{
list.Add(item);
if (list.Count == blockSize)
{
yield return list.ToArray();
list.Clear();
}
}
if (list.Count > 0)
{
yield return list.ToArray();
}
}
public static IEnumerable<T[]> GetBlocksWithRoundedSize<T>(this IEnumerable<T> source, int blockSize, T padding)
{
var blocks = GetBlocks(source, blockSize);
foreach (var block in blocks)
{
var newBlockSize = block.Length < 10 ? block.Length : new[] { 20, 50, blockSize }.First(x => x >= block.Length);
yield return (block.Length < newBlockSize)
? block.ConcatX(Enumerable.Repeat(padding, newBlockSize - block.Length)).ToArray()
: block;
}
}
public static IEnumerable<Tuple<T1, T2>> CrossJoinX<T1, T2>(this IEnumerable<T1> source, IEnumerable<T2> source2)
{
return source.CrossJoinX(source2, (x, y) => new Tuple<T1, T2>(x, y));
}
public static IEnumerable<TOut> CrossJoinX<T1, T2, TOut>(this IEnumerable<T1> source, IEnumerable<T2> source2, Func<T1, T2, TOut> selector)
{
return source.Join(source2, x => 1, x => 1, selector);
}
[DebuggerNonUserCode]
public static void ForEachX<T>([NotNull]this IEnumerable<T> source, [NotNull, InstantHandle]Action<T> action)
{
foreach (var item in source)
{
action(item);
}
}
[DebuggerNonUserCode]
public static void ForEachX<T>([NotNull]this IEnumerable<T> source, [NotNull, InstantHandle]Action<T, int> action)
{
var i = 0;
foreach (var item in source)
{
action(item, i++);
}
}
[DebuggerNonUserCode]
public static IEnumerable<T> DoWhileEnumeratingX<T>([NotNull]this IEnumerable<T> source, [NotNull, InstantHandle]Action<T> action)
{
foreach (var item in source)
{
action(item);
yield return item;
}
}
[DebuggerNonUserCode]
public static IEnumerable<T> DoWhileEnumeratingX<T>([NotNull]this IEnumerable<T> source, [NotNull, InstantHandle]Action<T, int> action)
{
var i = 0;
foreach (var item in source)
{
action(item, i++);
yield return item;
}
}
[DebuggerNonUserCode]
public static IEnumerable<T> IterateWhileX<T>([NotNull]this IEnumerable<T> source, bool condition)
{
foreach (var item in source)
{
if (condition)
{
yield return item;
}
else
{
yield break;
}
}
}
[DebuggerNonUserCode]
public static void SafeForEachX<T>([NotNull]this IEnumerable<T> source, [NotNull, InstantHandle]Action<T> action, [CanBeNull]Action<Exception, T> exceptionHandler)
{
foreach (var item in source)
{
try
{
action(item);
}
catch (Exception e)
{
if (exceptionHandler != null)
{
exceptionHandler(e, item);
}
}
}
}
public static IEnumerable<T> MergeSortedX<T>(
this IEnumerable<T> first, IEnumerable<T> second, IComparer<T> comparer, bool allowDuplicates)
{
var firstEnumerator = first.GetEnumerator();
var secondEnumerator = second.GetEnumerator();
var moreFromFirst = firstEnumerator.MoveNext();
var moreFromSecond = secondEnumerator.MoveNext();
do
{
if (moreFromFirst == false)
{
while (moreFromSecond)
{
yield return secondEnumerator.Current;
moreFromSecond = secondEnumerator.MoveNext();
}
yield break;
}
if (moreFromSecond == false)
{
while (moreFromFirst)
{
yield return firstEnumerator.Current;
moreFromFirst = firstEnumerator.MoveNext();
}
yield break;
}
var c = comparer.Compare(firstEnumerator.Current, secondEnumerator.Current);
if (c < 0)
{
yield return firstEnumerator.Current;
moreFromFirst = firstEnumerator.MoveNext();
}
else if (c > 0)
{
yield return secondEnumerator.Current;
moreFromSecond = secondEnumerator.MoveNext();
}
else
{
yield return firstEnumerator.Current;
if (allowDuplicates)
{
yield return secondEnumerator.Current;
}
moreFromFirst = firstEnumerator.MoveNext();
moreFromSecond = secondEnumerator.MoveNext();
}
} while (true);
}
public static IEnumerable<T> Weave<T>(this IEnumerable<T> first, IEnumerable<T> second, bool allowDuplicates)
{
var firstEnumerator = first.GetEnumerator();
var secondEnumerator = second.GetEnumerator();
var firstHasMore = firstEnumerator.MoveNext();
var secondHasMore = secondEnumerator.MoveNext();
var used = new HashSet<T>();
while (firstHasMore || secondHasMore)
{
if (allowDuplicates == false)
{
while (firstHasMore && used.Contains(firstEnumerator.Current))
{
firstHasMore = firstEnumerator.MoveNext();
}
}
if (firstHasMore)
{
if (allowDuplicates == false)
{
used.Add(firstEnumerator.Current);
}
yield return firstEnumerator.Current;
firstHasMore = firstEnumerator.MoveNext();
}
if (allowDuplicates == false)
{
while (secondHasMore && used.Contains(secondEnumerator.Current))
{
secondHasMore = secondEnumerator.MoveNext();
}
}
if (secondHasMore)
{
if (allowDuplicates == false)
{
used.Add(secondEnumerator.Current);
}
yield return secondEnumerator.Current;
secondHasMore = secondEnumerator.MoveNext();
}
}
}
public static IEnumerable<T> ConcatX<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
if (first == null)
{
return second;
}
return second == null ? first : first.Concat(second);
}
[NotNull]
public static IEnumerable<T> AndX<T>([NotNull]this IEnumerable<T> first, T second)
{
foreach (var t in first)
{
yield return t;
}
yield return second;
}
public static TRet ChooseIfX<T, TRet>(this IEnumerable<T> source, bool condition, Func<IEnumerable<T>, TRet> selector1, Func<IEnumerable<T>, TRet> selector2)
{
return condition ? selector1(source) : selector2(source);
}
public static DiffResult<TOld, TNew> Diff<TOld, TNew, TKey>(this IEnumerable<TOld> oldItems, IEnumerable<TNew> newItems, Func<TOld, TKey> oldKeySelector, Func<TNew, TKey> newKeySelector)
{
var oldArr = oldItems.ToArray();
var newArr = newItems.ToArray();
var updates = oldArr.Join(newArr, oldKeySelector, newKeySelector, (x, y) => new Tuple<TOld, TNew>(x, y)).ToArray();
var stale = oldArr.Except(updates.Select(x => x.Item1)).ToArray();
var added = newArr.Except(updates.Select(x => x.Item2)).ToArray();
return new DiffResult<TOld, TNew> { Added = added, Same = updates, Stale = stale };
}
public class DiffResult<TOld, TNew>
{
[NotNull]public TNew[] Added;
[NotNull]public TOld[] Stale;
[NotNull]public Tuple<TOld, TNew>[] Same;
}
public static IEnumerable<T> MinX<T>([NotNull] this IEnumerable<T> source, Func<T, int> criteria, int numberOfElements)
{
var lowest = new Tuple<int, T>[numberOfElements];
foreach (var item in source)
{
var i = item;
var c = criteria(i);
for (int j = 0; j < lowest.Length; j++)
{
if (lowest[j] == null)
{
lowest[j] = new Tuple<int, T>(c, i);
break;
}
if (lowest[j].Item1 > c)
{
var tc = c;
var ti = i;
c = lowest[j].Item1;
i = lowest[j].Item2;
lowest[j] = new Tuple<int, T>(tc, ti);
}
}
}
return lowest.ExceptNullsX().Select(x => x.Item2);
}
public static IEnumerable<T> MaxX<T>([NotNull] this IEnumerable<T> source, Func<T, int> criteria, int numberOfElements)
{
var highest = new Tuple<int, T>[numberOfElements];
foreach (var item in source)
{
var i = item;
var c = criteria(i);
for (int j = 0; j < highest.Length; j++)
{
if (highest[j] == null)
{
highest[j] = new Tuple<int, T>(c, i);
break;
}
if (highest[j].Item1 < c)
{
var tc = c;
var ti = i;
c = highest[j].Item1;
i = highest[j].Item2;
highest[j] = new Tuple<int, T>(tc, ti);
}
}
}
return highest.ExceptNullsX().Select(x => x.Item2);
}
public struct A<TC,TI>
{
public TC Criteria;
public TI Item;
}
// ReSharper restore UnusedMember.Global
}
public enum SeparatorBehavior { AttachAsLast, Omit, AttachAsStarter }
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is1 distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.Record
{
using System;
using System.Web;
using System.IO;
using NPOI.Util;
using NPOI.HSSF.Record;
using NPOI.HSSF.Util;
using NUnit.Framework;
/**
* Test HyperlinkRecord
*
* @author Nick Burch
* @author Yegor Kozlov
*/
[TestFixture]
public class TestHyperlinkRecord
{
/// <summary>
/// Some of the tests are depending on the american culture.
/// </summary>
[SetUp]
public void InitializeCultere()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
}
//link to http://www.lakings.com/
byte[] data1 = { 0x02, 0x00, //First row of the hyperlink
0x02, 0x00, //Last row of the hyperlink
0x00, 0x00, //First column of the hyperlink
0x00, 0x00, //Last column of the hyperlink
//16-byte GUID. Seems to be always the same. Does not depend on the hyperlink type
(byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
(byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
0x02, 0x00, 0x00, 0x00, //integer, always 2
// flags. Define the type of the hyperlink:
// HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL
0x17, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, //length of the label including the trailing '\0'
//label:
0x4D, 0x00, 0x79, 0x00, 0x20, 0x00, 0x4C, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x6B, 0x00, 0x00, 0x00,
//16-byte link moniker: HyperlinkRecord.URL_MONIKER
(byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
(byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
//count of bytes in the address including the tail
0x48, 0x00, 0x00, 0x00, //integer
//the actual link, terminated by '\u0000'
0x68, 0x00, 0x74, 0x00, 0x74, 0x00, 0x70, 0x00, 0x3A, 0x00, 0x2F, 0x00,
0x2F, 0x00, 0x77, 0x00, 0x77, 0x00, 0x77, 0x00, 0x2E, 0x00, 0x6C, 0x00,
0x61, 0x00, 0x6B, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x73, 0x00,
0x2E, 0x00, 0x63, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x2F, 0x00, 0x00, 0x00,
//standard 24-byte tail of a URL link. Seems to always be the same for all URL HLINKs
0x79, 0x58, (byte)0x81, (byte)0xF4, 0x3B, 0x1D, 0x7F, 0x48, (byte)0xAF, 0x2C,
(byte)0x82, 0x5D, (byte)0xC4, (byte)0x85, 0x27, 0x63, 0x00, 0x00, 0x00,
0x00, (byte)0xA5, (byte)0xAB, 0x00, 0x00};
//link to a file in the current directory: link1.xls
byte[] data2 = {0x00, 0x00,
0x00, 0x00,
0x00, 0x00,
0x00, 0x00,
//16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type
(byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
(byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
0x02, 0x00, 0x00, 0x00, //integer, always 2
0x15, 0x00, 0x00, 0x00, //options: HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL
0x05, 0x00, 0x00, 0x00, //length of the label
//label
0x66, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x65, 0x00, 0x00, 0x00,
//16-byte link moniker: HyperlinkRecord.FILE_MONIKER
0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46,
0x00, 0x00, //level
0x0A, 0x00, 0x00, 0x00, //length of the path )
//path to the file (plain ISO-8859 bytes, NOT UTF-16LE!)
0x6C, 0x69, 0x6E, 0x6B, 0x31, 0x2E, 0x78, 0x6C, 0x73, 0x00,
//standard 28-byte tail of a file link
(byte)0xFF, (byte)0xFF, (byte)0xAD, (byte)0xDE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
// mailto:[email protected]?subject=Hello,%20Ebgans!
byte[] data3 = {0x01, 0x00,
0x01, 0x00,
0x00, 0x00,
0x00, 0x00,
//16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type
(byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
(byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
0x02, 0x00, 0x00, 0x00, //integer, always 2
0x17, 0x00, 0x00, 0x00, //options: HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL
0x06, 0x00, 0x00, 0x00, //length of the label
0x65, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x00, 0x00, //label
//16-byte link moniker: HyperlinkRecord.URL_MONIKER
(byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
(byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
//length of the address including the tail.
0x76, 0x00, 0x00, 0x00,
//the address is terminated by '\u0000'
0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x74, 0x00, 0x6F, 0x00,
0x3A, 0x00, 0x65, 0x00, 0x62, 0x00, 0x67, 0x00, 0x61, 0x00, 0x6E, 0x00,
0x73, 0x00, 0x40, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00,
0x2E, 0x00, 0x72, 0x00, 0x75, 0x00, 0x3F, 0x00, 0x73, 0x00, 0x75, 0x00,
0x62, 0x00, 0x6A, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x3D, 0x00,
0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x2C, 0x00,
0x25, 0x00, 0x32, 0x00, 0x30, 0x00, 0x45, 0x00, 0x62, 0x00, 0x67, 0x00,
0x61, 0x00, 0x6E, 0x00, 0x73, 0x00, 0x21, 0x00, 0x00, 0x00,
//standard 24-byte tail of a URL link
0x79, 0x58, (byte)0x81, (byte)0xF4, 0x3B, 0x1D, 0x7F, 0x48, (byte)0xAF, (byte)0x2C,
(byte)0x82, 0x5D, (byte)0xC4, (byte)0x85, 0x27, 0x63, 0x00, 0x00, 0x00,
0x00, (byte)0xA5, (byte)0xAB, 0x00, 0x00
};
//link to a place in worksheet: Sheet1!A1
byte[] data4 = {0x03, 0x00,
0x03, 0x00,
0x00, 0x00,
0x00, 0x00,
//16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type
(byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
(byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
0x02, 0x00, 0x00, 0x00, //integer, always 2
0x1C, 0x00, 0x00, 0x00, //flags: HyperlinkRecord.HLINK_LABEL | HyperlinkRecord.HLINK_PLACE
0x06, 0x00, 0x00, 0x00, //length of the label
0x70, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x63, 0x00, 0x65, 0x00, 0x00, 0x00, //label
0x0A, 0x00, 0x00, 0x00, //length of the document link including trailing zero
//link: Sheet1!A1
0x53, 0x00, 0x68, 0x00, 0x65, 0x00, 0x65, 0x00, 0x74, 0x00, 0x31, 0x00, 0x21,
0x00, 0x41, 0x00, 0x31, 0x00, 0x00, 0x00};
private static byte[] dataLinkToWorkbook = HexRead.ReadFromString("01 00 01 00 01 00 01 00 " +
"D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " +
"02 00 00 00 " +
"1D 00 00 00 " + // options: LABEL | PLACE | FILE_OR_URL
// label: "My Label"
"09 00 00 00 " +
"4D 00 79 00 20 00 4C 00 61 00 62 00 65 00 6C 00 00 00 " +
"03 03 00 00 00 00 00 00 C0 00 00 00 00 00 00 46 " + // file GUID
"00 00 " + // file options
// shortFileName: "YEARFR~1.XLS"
"0D 00 00 00 " +
"59 45 41 52 46 52 7E 31 2E 58 4C 53 00 " +
// FILE_TAIL - unknown byte sequence
"FF FF AD DE 00 00 00 00 " +
"00 00 00 00 00 00 00 00 " +
"00 00 00 00 00 00 00 00 " +
// field len, char data len
"2E 00 00 00 " +
"28 00 00 00 " +
"03 00 " + // unknown ushort
// _address: "yearfracExamples.xls"
"79 00 65 00 61 00 72 00 66 00 72 00 61 00 63 00 " +
"45 00 78 00 61 00 6D 00 70 00 6C 00 65 00 73 00 " +
"2E 00 78 00 6C 00 73 00 " +
// textMark: "Sheet1!B6"
"0A 00 00 00 " +
"53 00 68 00 65 00 65 00 74 00 31 00 21 00 42 00 " +
"36 00 00 00");
private static byte[] dataTargetFrame = HexRead.ReadFromString("0E 00 0E 00 00 00 00 00 " +
"D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " +
"02 00 00 00 " +
"83 00 00 00 " + // options: TARGET_FRAME | ABS | FILE_OR_URL
// targetFrame: "_blank"
"07 00 00 00 " +
"5F 00 62 00 6C 00 61 00 6E 00 6B 00 00 00 " +
// url GUID
"E0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " +
// address: "http://www.regnow.com/softsell/nph-softsell.cgi?currency=USD&item=7924-37"
"94 00 00 00 " +
"68 00 74 00 74 00 70 00 3A 00 2F 00 2F 00 77 00 " +
"77 00 77 00 2E 00 72 00 65 00 67 00 6E 00 6F 00 " +
"77 00 2E 00 63 00 6F 00 6D 00 2F 00 73 00 6F 00 " +
"66 00 74 00 73 00 65 00 6C 00 6C 00 2F 00 6E 00 " +
"70 00 68 00 2D 00 73 00 6F 00 66 00 74 00 73 00 " +
"65 00 6C 00 6C 00 2E 00 63 00 67 00 69 00 3F 00 " +
"63 00 75 00 72 00 72 00 65 00 6E 00 63 00 79 00 " +
"3D 00 55 00 53 00 44 00 26 00 69 00 74 00 65 00 " +
"6D 00 3D 00 37 00 39 00 32 00 34 00 2D 00 33 00 " +
"37 00 00 00");
private static byte[] dataUNC = HexRead.ReadFromString("01 00 01 00 01 00 01 00 " +
"D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " +
"02 00 00 00 " +
"1F 01 00 00 " + // options: UNC_PATH | LABEL | TEXT_MARK | ABS | FILE_OR_URL
"09 00 00 00 " + // label: "My Label"
"4D 00 79 00 20 00 6C 00 61 00 62 00 65 00 6C 00 00 00 " +
// note - no moniker GUID
"27 00 00 00 " + // "\\\\MyServer\\my-share\\myDir\\PRODNAME.xls"
"5C 00 5C 00 4D 00 79 00 53 00 65 00 72 00 76 00 " +
"65 00 72 00 5C 00 6D 00 79 00 2D 00 73 00 68 00 " +
"61 00 72 00 65 00 5C 00 6D 00 79 00 44 00 69 00 " +
"72 00 5C 00 50 00 52 00 4F 00 44 00 4E 00 41 00 " +
"4D 00 45 00 2E 00 78 00 6C 00 73 00 00 00 " +
"0C 00 00 00 " + // textMark: PRODNAME!C2
"50 00 52 00 4F 00 44 00 4E 00 41 00 4D 00 45 00 21 00 " +
"43 00 32 00 00 00");
/**
* From Bugzilla 47498
*/
private static byte[] data_47498 = {
0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xD0, (byte)0xC9,
(byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, (byte)0x8C,
(byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x02, 0x00,
0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x50, 0x00,
0x44, 0x00, 0x46, 0x00, 0x00, 0x00, (byte)0xE0, (byte)0xC9, (byte)0xEA,
0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, (byte)0x11, (byte)0x8C, (byte)0x82,
0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x28, 0x00, 0x00, 0x00,
0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x66, 0x00, 0x6F, 0x00,
0x6C, 0x00, 0x64, 0x00, 0x65, 0x00, 0x72, 0x00, 0x2F, 0x00, 0x74, 0x00,
0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x2E, 0x00, 0x50, 0x00, 0x44, 0x00,
0x46, 0x00, 0x00, 0x00};
private void ConfirmGUID(GUID expectedGuid, GUID actualGuid)
{
Assert.AreEqual(expectedGuid, actualGuid);
}
[Test]
public void TestReadURLLink()
{
RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data1);
HyperlinkRecord link = new HyperlinkRecord(is1);
Assert.AreEqual(2, link.FirstRow);
Assert.AreEqual(2, link.LastRow);
Assert.AreEqual(0, link.FirstColumn);
Assert.AreEqual(0, link.LastColumn);
ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid);
ConfirmGUID(HyperlinkRecord.URL_MONIKER, link.Moniker);
Assert.AreEqual(2, link.LabelOptions);
int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL;
Assert.AreEqual(0x17, opts);
Assert.AreEqual(opts, link.LinkOptions);
Assert.AreEqual(0, link.FileOptions);
Assert.AreEqual("My Link", link.Label);
Assert.AreEqual("http://www.lakings.com/", link.Address);
}
[Test]
public void TestReadFileLink()
{
RecordInputStream is1 = TestcaseRecordInputStream.Create((short)HyperlinkRecord.sid, data2);
HyperlinkRecord link = new HyperlinkRecord(is1);
Assert.AreEqual(0, link.FirstRow);
Assert.AreEqual(0, link.LastRow);
Assert.AreEqual(0, link.FirstColumn);
Assert.AreEqual(0, link.LastColumn);
ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid);
ConfirmGUID(HyperlinkRecord.FILE_MONIKER, link.Moniker);
Assert.AreEqual(2, link.LabelOptions);
int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL;
Assert.AreEqual(0x15, opts);
Assert.AreEqual(opts, link.LinkOptions);
Assert.AreEqual("file", link.Label);
Assert.AreEqual("link1.xls", link.ShortFilename);
}
[Test]
public void TestReadEmailLink()
{
RecordInputStream is1 = TestcaseRecordInputStream.Create((short)HyperlinkRecord.sid, data3);
HyperlinkRecord link = new HyperlinkRecord(is1);
Assert.AreEqual(1, link.FirstRow);
Assert.AreEqual(1, link.LastRow);
Assert.AreEqual(0, link.FirstColumn);
Assert.AreEqual(0, link.LastColumn);
ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid);
ConfirmGUID(HyperlinkRecord.URL_MONIKER, link.Moniker);
Assert.AreEqual(2, link.LabelOptions);
int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL;
Assert.AreEqual(0x17, opts);
Assert.AreEqual(opts, link.LinkOptions);
Assert.AreEqual("email", link.Label);
Assert.AreEqual("mailto:[email protected]?subject=Hello,%20Ebgans!", link.Address);
}
[Test]
public void TestReadDocumentLink()
{
RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data4);
HyperlinkRecord link = new HyperlinkRecord(is1);
Assert.AreEqual(3, link.FirstRow);
Assert.AreEqual(3, link.LastRow);
Assert.AreEqual(0, link.FirstColumn);
Assert.AreEqual(0, link.LastColumn);
ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid);
Assert.AreEqual(2, link.LabelOptions);
int opts = HyperlinkRecord.HLINK_LABEL | HyperlinkRecord.HLINK_PLACE;
Assert.AreEqual(0x1C, opts);
Assert.AreEqual(opts, link.LinkOptions);
Assert.AreEqual("place", link.Label);
Assert.AreEqual("Sheet1!A1", link.TextMark);
Assert.AreEqual("Sheet1!A1", link.Address);
}
private void Serialize(byte[] data)
{
RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data);
HyperlinkRecord link = new HyperlinkRecord(is1);
byte[] bytes1 = link.Serialize();
is1 = TestcaseRecordInputStream.Create(bytes1);
link = new HyperlinkRecord(is1);
byte[] bytes2 = link.Serialize();
Assert.AreEqual(bytes1.Length, bytes2.Length);
Assert.IsTrue(Arrays.Equals(bytes1, bytes2));
}
[Test]
public void TestSerialize()
{
Serialize(data1);
Serialize(data2);
Serialize(data3);
Serialize(data4);
}
[Test]
public void TestCreateURLRecord()
{
HyperlinkRecord link = new HyperlinkRecord();
link.CreateUrlLink();
link.FirstRow = 2;
link.LastRow = 2;
link.Label = "My Link";
link.Address = "http://www.lakings.com/";
byte[] tmp = link.Serialize();
byte[] ser = new byte[tmp.Length - 4];
Array.Copy(tmp, 4, ser, 0, ser.Length);
Assert.AreEqual(data1.Length, ser.Length);
Assert.IsTrue(Arrays.Equals(data1, ser));
}
[Test]
public void TestCreateFileRecord()
{
HyperlinkRecord link = new HyperlinkRecord();
link.CreateFileLink();
link.FirstRow = 0;
link.LastRow = 0;
link.Label = "file";
link.ShortFilename = "link1.xls";
byte[] tmp = link.Serialize();
byte[] ser = new byte[tmp.Length - 4];
Array.Copy(tmp, 4, ser, 0, ser.Length);
Assert.AreEqual(data2.Length, ser.Length);
Assert.IsTrue(Arrays.Equals(data2, ser));
}
[Test]
public void TestCreateDocumentRecord()
{
HyperlinkRecord link = new HyperlinkRecord();
link.CreateDocumentLink();
link.FirstRow = 3;
link.LastRow = 3;
link.Label = "place";
link.TextMark = "Sheet1!A1";
byte[] tmp = link.Serialize();
byte[] ser = new byte[tmp.Length - 4];
Array.Copy(tmp, 4, ser, 0, ser.Length);
//Assert.AreEqual(data4.Length, ser.Length);
Assert.IsTrue(Arrays.Equals(data4, ser));
}
[Test]
public void TestCreateEmailtRecord()
{
HyperlinkRecord link = new HyperlinkRecord();
link.CreateUrlLink();
link.FirstRow = 1;
link.LastRow = 1;
link.Label = "email";
link.Address = "mailto:[email protected]?subject=Hello,%20Ebgans!";
byte[] tmp = link.Serialize();
byte[] ser = new byte[tmp.Length - 4];
Array.Copy(tmp, 4, ser, 0, ser.Length);
Assert.AreEqual(data3.Length, ser.Length);
Assert.IsTrue(Arrays.Equals(data3, ser));
}
[Test]
public void TestClone()
{
byte[][] data = { data1, data2, data3, data4 };
for (int i = 0; i < data.Length; i++)
{
RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data[i]);
HyperlinkRecord link = new HyperlinkRecord(is1);
HyperlinkRecord clone = (HyperlinkRecord)link.Clone();
Assert.IsTrue(Arrays.Equals(link.Serialize(), clone.Serialize()));
}
}
[Test]
public void TestReserializeTargetFrame()
{
RecordInputStream in1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, dataTargetFrame);
HyperlinkRecord hr = new HyperlinkRecord(in1);
byte[] ser = hr.Serialize();
TestcaseRecordInputStream.ConfirmRecordEncoding(HyperlinkRecord.sid, dataTargetFrame, ser);
}
[Test]
public void TestReserializeLinkToWorkbook()
{
RecordInputStream in1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, dataLinkToWorkbook);
HyperlinkRecord hr = new HyperlinkRecord(in1);
byte[] ser = hr.Serialize();
TestcaseRecordInputStream.ConfirmRecordEncoding(HyperlinkRecord.sid, dataLinkToWorkbook, ser);
if ("YEARFR~1.XLS".Equals(hr.Address))
{
throw new AssertionException("Identified bug in reading workbook link");
}
Assert.AreEqual("yearfracExamples.xls", hr.Address);
}
[Test]
public void TestReserializeUNC()
{
RecordInputStream in1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, dataUNC);
HyperlinkRecord hr = new HyperlinkRecord(in1);
byte[] ser = hr.Serialize();
TestcaseRecordInputStream.ConfirmRecordEncoding(HyperlinkRecord.sid, dataUNC, ser);
try
{
hr.ToString();
}
catch (NullReferenceException)
{
throw new AssertionException("Identified bug with option URL and UNC set at same time");
}
}
[Test]
public void TestGUID()
{
GUID g;
g = GUID.Parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301");
ConfirmGUID(g, 0x3F2504E0, 0x4F89, 0x11D3, unchecked((long)0x9A0C0305E82C3301L));
Assert.AreEqual("3F2504E0-4F89-11D3-9A0C-0305E82C3301", g.FormatAsString());
g = GUID.Parse("13579BDF-0246-8ACE-0123-456789ABCDEF");
ConfirmGUID(g, 0x13579BDF, 0x0246, 0x8ACE, unchecked((long)0x0123456789ABCDEFL));
Assert.AreEqual("13579BDF-0246-8ACE-0123-456789ABCDEF", g.FormatAsString());
byte[] buf = new byte[16];
g.Serialize(new LittleEndianByteArrayOutputStream(buf, 0));
String expectedDump = "[DF, 9B, 57, 13, 46, 02, CE, 8A, 01, 23, 45, 67, 89, AB, CD, EF, ]";
Assert.AreEqual(expectedDump, HexDump.ToHex(buf));
// STD Moniker
g = CreateFromStreamDump("[D0, C9, EA, 79, F9, BA, CE, 11, 8C, 82, 00, AA, 00, 4B, A9, 0B]");
Assert.AreEqual("79EAC9D0-BAF9-11CE-8C82-00AA004BA90B", g.FormatAsString());
// URL Moniker
g = CreateFromStreamDump("[E0, C9, EA, 79, F9, BA, CE, 11, 8C, 82, 00, AA, 00, 4B, A9, 0B]");
Assert.AreEqual("79EAC9E0-BAF9-11CE-8C82-00AA004BA90B", g.FormatAsString());
// File Moniker
g = CreateFromStreamDump("[03, 03, 00, 00, 00, 00, 00, 00, C0, 00, 00, 00, 00, 00, 00, 46]");
Assert.AreEqual("00000303-0000-0000-C000-000000000046", g.FormatAsString());
}
private static GUID CreateFromStreamDump(String s)
{
return new GUID(new LittleEndianByteArrayInputStream(HexRead.ReadFromString(s)));
}
private void ConfirmGUID(GUID g, int d1, int d2, int d3, long d4)
{
Assert.AreEqual(new String(HexDump.IntToHex(d1)), new String(HexDump.IntToHex(g.D1)));
Assert.AreEqual(new String(HexDump.ShortToHex(d2)), new String(HexDump.ShortToHex(g.D2)));
Assert.AreEqual(new String(HexDump.ShortToHex(d3)), new String(HexDump.ShortToHex(g.D3)));
Assert.AreEqual(new String(HexDump.LongToHex(d4)), new String(HexDump.LongToHex(g.D4)));
}
[Test]
public void Test47498()
{
RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data_47498);
HyperlinkRecord link = new HyperlinkRecord(is1);
Assert.AreEqual(2, link.FirstRow);
Assert.AreEqual(2, link.LastRow);
Assert.AreEqual(0, link.FirstColumn);
Assert.AreEqual(0, link.LastColumn);
ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid);
ConfirmGUID(HyperlinkRecord.URL_MONIKER, link.Moniker);
Assert.AreEqual(2, link.LabelOptions);
int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL;
Assert.AreEqual(opts, link.LinkOptions);
Assert.AreEqual(0, link.FileOptions);
Assert.AreEqual("PDF", link.Label);
Assert.AreEqual("testfolder/test.PDF", link.Address);
byte[] ser = link.Serialize();
TestcaseRecordInputStream.ConfirmRecordEncoding(HyperlinkRecord.sid, data_47498, ser);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Platibus.Http;
namespace Platibus.Diagnostics
{
/// <inheritdoc />
/// <summary>
/// A <see cref="T:Platibus.Diagnostics.IDiagnosticService" /> implementation that records measurements in InfluxDB
/// </summary>
public class InfluxDBSink : IDiagnosticEventSink
{
private static readonly IDictionary<string, string> DefaultTags;
static InfluxDBSink()
{
var assembly = Assembly.GetEntryAssembly() ??
Assembly.GetExecutingAssembly();
DefaultTags = new Dictionary<string, string>
{
{"host", Environment.MachineName},
{"app", assembly.GetName().Name},
{"app_var", assembly.GetName().Version.ToString()}
};
}
private readonly object _syncRoot = new object();
private readonly string _measurement;
private readonly InfluxDBPrecision _precision;
private readonly string _tagSet;
private readonly TimeSpan _sampleRate;
private readonly HttpClient _client;
private Fields _fields = new Fields();
private DateTime _nextMeasurement = DateTime.UtcNow;
/// <summary>
/// Initializes a new <see cref="InfluxDBSink"/>
/// </summary>
/// <param name="options">Options specifying connection parameters and details governing
/// how points are written to the InfluxDB database</param>
/// <param name="sampleRate">(Optional) The rate at which samples should be taken</param>
public InfluxDBSink(InfluxDBOptions options, TimeSpan sampleRate = default(TimeSpan))
{
if (options == null) throw new ArgumentNullException(nameof(options));
_measurement = string.IsNullOrWhiteSpace(options.Measurement)
? InfluxDBOptions.DefaultMeasurement
: options.Measurement.Trim();
_precision = options.Precision ?? InfluxDBPrecision.Nanosecond;
_sampleRate = sampleRate <= TimeSpan.Zero
? TimeSpan.FromSeconds(5)
: sampleRate;
var parameters = new Dictionary<string, string>();
parameters["db"] = options.Database;
parameters["u"] = options.Username;
parameters["p"] = options.Password;
parameters["precision"] = _precision.Name;
var queryString = string.Join("&", parameters
.Where(param => !string.IsNullOrWhiteSpace(param.Value))
.Select(param => param.Key + "=" + param.Value));
_client = new HttpClient
{
BaseAddress = new UriBuilder(options.Uri)
{
Path = "write",
Query = queryString
}.Uri
};
var myTags = options.Tags.Any() ? options.Tags : DefaultTags;
var validTags = myTags.Where(tag => !string.IsNullOrWhiteSpace(tag.Key));
_tagSet = string.Join(",", validTags.Select(tag => TagEscape(tag.Key) + "=" + TagEscape(tag.Value)));
}
private static string TagEscape(string tagKeyOrValue)
{
return string.IsNullOrWhiteSpace(tagKeyOrValue)
? tagKeyOrValue
: tagKeyOrValue
.Replace(",", @"\,")
.Replace("=", @"\=")
.Replace(" ", @"\ ");
}
/// <inheritdoc />
public void Consume(DiagnosticEvent @event)
{
IncrementCounters(@event);
}
/// <inheritdoc />
public Task ConsumeAsync(DiagnosticEvent @event, CancellationToken cancellationToken = new CancellationToken())
{
IncrementCounters(@event);
return Task.FromResult(0);
}
private void IncrementCounters(DiagnosticEvent @event)
{
switch (@event.Type.Level)
{
case DiagnosticEventLevel.Error:
Interlocked.Increment(ref _fields.Errors);
break;
case DiagnosticEventLevel.Warn:
Interlocked.Increment(ref _fields.Warnings);
break;
}
if (@event.Type == HttpEventType.HttpRequestReceived)
{
Interlocked.Increment(ref _fields.Requests);
}
else if (@event.Type == DiagnosticEventType.MessageReceived)
{
Interlocked.Increment(ref _fields.Received);
}
else if (@event.Type == DiagnosticEventType.MessageAcknowledged)
{
Interlocked.Increment(ref _fields.Acknowledgements);
}
else if (@event.Type == DiagnosticEventType.MessageNotAcknowledged)
{
Interlocked.Increment(ref _fields.AcknowledgementFailures);
}
else if (@event.Type == DiagnosticEventType.MessageSent)
{
Interlocked.Increment(ref _fields.Sent);
}
else if (@event.Type == DiagnosticEventType.MessagePublished)
{
Interlocked.Increment(ref _fields.Published);
}
else if (@event.Type == DiagnosticEventType.MessageDelivered)
{
Interlocked.Increment(ref _fields.Delivered);
}
else if (@event.Type == DiagnosticEventType.MessageDeliveryFailed)
{
Interlocked.Increment(ref _fields.DeliveryFailures);
}
else if (@event.Type == DiagnosticEventType.MessageExpired)
{
Interlocked.Increment(ref _fields.Expired);
}
else if (@event.Type == DiagnosticEventType.DeadLetter)
{
Interlocked.Increment(ref _fields.Dead);
}
bool takeMeasurement;
lock (_syncRoot)
{
takeMeasurement = DateTime.UtcNow >= _nextMeasurement;
if (takeMeasurement)
{
_nextMeasurement += _sampleRate;
}
}
if (takeMeasurement)
{
RecordMeasurements();
}
}
/// <summary>
/// Take measurements and record points in the InfluxDB database
/// </summary>
public void RecordMeasurements()
{
var timestamp = _precision.GetTimestamp();
var fields = Interlocked.Exchange(ref _fields, new Fields());
var fieldSet = "requests=" + fields.Requests
+ ",received=" + fields.Received
+ ",acknowledgements=" + fields.Acknowledgements
+ ",acknowledgement_failures=" + fields.AcknowledgementFailures
+ ",expired=" + fields.Expired
+ ",dead=" + fields.Dead
+ ",sent=" + fields.Sent
+ ",delivered=" + fields.Delivered
+ ",delivery_failures=" + fields.DeliveryFailures
+ ",errors=" + fields.Errors
+ ",warnings=" + fields.Warnings;
var point = string.Join(",", _measurement, _tagSet) + " " + fieldSet + " " + timestamp;
var response = _client.PostAsync("", new StringContent(point)).Result;
response.EnsureSuccessStatusCode();
}
private class Fields
{
public long Requests;
public long Received;
public long Acknowledgements;
public long AcknowledgementFailures;
public long Expired;
public long Dead;
public long Sent;
public long Published;
public long Delivered;
public long DeliveryFailures;
public long Errors;
public long Warnings;
}
}
}
| |
namespace StockSharp.Algo
{
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using StockSharp.Localization;
using StockSharp.Messages;
/// <summary>
/// Subscription counter adapter.
/// </summary>
public class SubscriptionMessageAdapter : MessageAdapterWrapper
{
private readonly SyncObject _sync = new SyncObject();
private readonly Dictionary<Tuple<MarketDataTypes, SecurityId>, RefPair<MarketDataMessage, int>> _subscribers = new Dictionary<Tuple<MarketDataTypes, SecurityId>, RefPair<MarketDataMessage, int>>();
private readonly Dictionary<Tuple<MarketDataTypes, SecurityId, object>, RefPair<MarketDataMessage, int>> _candleSubscribers = new Dictionary<Tuple<MarketDataTypes, SecurityId, object>, RefPair<MarketDataMessage, int>>();
private readonly Dictionary<string, RefPair<MarketDataMessage, int>> _newsSubscribers = new Dictionary<string, RefPair<MarketDataMessage, int>>(StringComparer.InvariantCultureIgnoreCase);
private readonly Dictionary<string, RefPair<PortfolioMessage, int>> _pfSubscribers = new Dictionary<string, RefPair<PortfolioMessage, int>>(StringComparer.InvariantCultureIgnoreCase);
//private readonly Dictionary<Tuple<MarketDataTypes, SecurityId>, List<MarketDataMessage>> _pendingMessages = new Dictionary<Tuple<MarketDataTypes, SecurityId>, List<MarketDataMessage>>();
/// <summary>
/// Initializes a new instance of the <see cref="SubscriptionMessageAdapter"/>.
/// </summary>
/// <param name="innerAdapter">Inner message adapter.</param>
public SubscriptionMessageAdapter(IMessageAdapter innerAdapter)
: base(innerAdapter)
{
}
/// <summary>
/// Restore subscription on reconnect.
/// </summary>
public bool IsRestoreOnReconnect { get; set; }
private void ClearSubscribers()
{
_subscribers.Clear();
_newsSubscribers.Clear();
_pfSubscribers.Clear();
_candleSubscribers.Clear();
}
/// <summary>
/// Send message.
/// </summary>
/// <param name="message">Message.</param>
public override void SendInMessage(Message message)
{
switch (message.Type)
{
case MessageTypes.Reset:
{
lock (_sync)
{
ClearSubscribers();
//_pendingMessages.Clear();
}
base.SendInMessage(message);
break;
}
case MessageTypes.Disconnect:
{
if (!IsRestoreOnReconnect)
{
var messages = new List<Message>();
lock (_sync)
{
if (_newsSubscribers.Count > 0)
messages.AddRange(_newsSubscribers.Values.Select(p => p.First));
if (_subscribers.Count > 0)
messages.AddRange(_subscribers.Values.Select(p => p.First));
if (_candleSubscribers.Count > 0)
messages.AddRange(_candleSubscribers.Values.Select(p => p.First));
if (_pfSubscribers.Count > 0)
messages.AddRange(_pfSubscribers.Values.Select(p => p.First));
ClearSubscribers();
}
foreach (var m in messages)
{
var msg = m.Clone();
var mdMsg = msg as MarketDataMessage;
if (mdMsg != null)
{
mdMsg.TransactionId = InnerAdapter.TransactionIdGenerator.GetNextId();
mdMsg.IsSubscribe = false;
}
else
{
var pfMsg = (PortfolioMessage)msg;
pfMsg.TransactionId = InnerAdapter.TransactionIdGenerator.GetNextId();
pfMsg.IsSubscribe = false;
}
base.SendInMessage(msg);
}
}
base.SendInMessage(message);
break;
}
case MessageTypes.MarketData:
ProcessInMarketDataMessage((MarketDataMessage)message);
break;
case MessageTypes.Portfolio:
{
var pfMsg = (PortfolioMessage)message;
var sendIn = false;
lock (_sync)
{
var pair = _pfSubscribers.TryGetValue(pfMsg.PortfolioName) ?? RefTuple.Create((PortfolioMessage)pfMsg.Clone(), 0);
var subscribersCount = pair.Second;
if (pfMsg.IsSubscribe)
{
subscribersCount++;
sendIn = subscribersCount == 1;
}
else
{
if (subscribersCount > 0)
{
subscribersCount--;
sendIn = subscribersCount == 0;
}
//else
// sendOutMsg = NonExist(message);
}
if (subscribersCount > 0)
{
pair.Second = subscribersCount;
_pfSubscribers[pfMsg.PortfolioName] = pair;
}
else
_pfSubscribers.Remove(pfMsg.PortfolioName);
}
if (sendIn)
base.SendInMessage(message);
break;
}
default:
base.SendInMessage(message);
break;
}
}
/// <summary>
/// Process <see cref="MessageAdapterWrapper.InnerAdapter"/> output message.
/// </summary>
/// <param name="message">The message.</param>
protected override void OnInnerAdapterNewOutMessage(Message message)
{
List<Message> messages = null;
switch (message.Type)
{
case MessageTypes.Connect:
{
var connectMsg = (ConnectMessage)message;
if (connectMsg.Error == null && IsRestoreOnReconnect)
{
messages = new List<Message>();
lock (_sync)
{
messages.AddRange(_subscribers.Values.Select(p => p.First));
messages.AddRange(_newsSubscribers.Values.Select(p => p.First));
messages.AddRange(_candleSubscribers.Values.Select(p => p.First));
messages.AddRange(_pfSubscribers.Values.Select(p => p.First));
ClearSubscribers();
}
if (messages.Count == 0)
messages = null;
}
break;
}
// TODO
//case MessageTypes.MarketData:
// ProcessOutMarketDataMessage((MarketDataMessage)message);
// break;
}
base.OnInnerAdapterNewOutMessage(message);
if (messages != null)
{
foreach (var m in messages)
{
var msg = m.Clone();
msg.IsBack = true;
msg.Adapter = this;
var mdMsg = msg as MarketDataMessage;
if (mdMsg != null)
{
mdMsg.TransactionId = InnerAdapter.TransactionIdGenerator.GetNextId();
}
else
{
var pfMsg = (PortfolioMessage)msg;
pfMsg.TransactionId = InnerAdapter.TransactionIdGenerator.GetNextId();
}
base.OnInnerAdapterNewOutMessage(msg);
}
}
}
private void ProcessInMarketDataMessage(MarketDataMessage message)
{
var sendIn = false;
MarketDataMessage sendOutMsg = null;
lock (_sync)
{
var isSubscribe = message.IsSubscribe;
switch (message.DataType)
{
case MarketDataTypes.News:
{
var subscriber = message.NewsId ?? string.Empty;
var pair = _newsSubscribers.TryGetValue(subscriber) ?? RefTuple.Create((MarketDataMessage)message.Clone(), 0);
var subscribersCount = pair.Second;
if (isSubscribe)
{
subscribersCount++;
sendIn = subscribersCount == 1;
}
else
{
if (subscribersCount > 0)
{
subscribersCount--;
sendIn = subscribersCount == 0;
}
else
sendOutMsg = NonExist(message);
}
if (sendOutMsg == null)
{
if (!sendIn)
{
sendOutMsg = new MarketDataMessage
{
DataType = message.DataType,
IsSubscribe = isSubscribe,
OriginalTransactionId = message.TransactionId,
};
}
if (subscribersCount > 0)
{
pair.Second = subscribersCount;
_newsSubscribers[subscriber] = pair;
}
else
_newsSubscribers.Remove(subscriber);
}
break;
}
case MarketDataTypes.CandleTimeFrame:
case MarketDataTypes.CandleRange:
case MarketDataTypes.CandlePnF:
case MarketDataTypes.CandleRenko:
case MarketDataTypes.CandleTick:
case MarketDataTypes.CandleVolume:
{
var key = Tuple.Create(message.DataType, message.SecurityId, message.Arg);
var pair = _candleSubscribers.TryGetValue(key) ?? RefTuple.Create((MarketDataMessage)message.Clone(), 0);
var subscribersCount = pair.Second;
if (isSubscribe)
{
subscribersCount++;
sendIn = subscribersCount == 1;
}
else
{
if (subscribersCount > 0)
{
subscribersCount--;
sendIn = subscribersCount == 0;
}
else
sendOutMsg = NonExist(message);
}
if (sendOutMsg == null)
{
if (!sendIn)
{
sendOutMsg = new MarketDataMessage
{
DataType = message.DataType,
IsSubscribe = isSubscribe,
SecurityId = message.SecurityId,
Arg = message.Arg,
OriginalTransactionId = message.TransactionId,
};
}
if (subscribersCount > 0)
{
pair.Second = subscribersCount;
_candleSubscribers[key] = pair;
}
else
_candleSubscribers.Remove(key);
}
break;
}
default:
{
var key = Tuple.Create(message.DataType, message.SecurityId);
var pair = _subscribers.TryGetValue(key) ?? RefTuple.Create((MarketDataMessage)message.Clone(), 0);
var subscribersCount = pair.Second;
if (isSubscribe)
{
subscribersCount++;
sendIn = subscribersCount == 1;
}
else
{
if (subscribersCount > 0)
{
subscribersCount--;
sendIn = subscribersCount == 0;
}
else
sendOutMsg = NonExist(message);
}
if (sendOutMsg == null)
{
if (!sendIn)
{
sendOutMsg = new MarketDataMessage
{
DataType = message.DataType,
IsSubscribe = isSubscribe,
SecurityId = message.SecurityId,
OriginalTransactionId = message.TransactionId,
};
}
if (subscribersCount > 0)
{
pair.Second = subscribersCount;
_subscribers[key] = pair;
}
else
_subscribers.Remove(key);
}
break;
}
}
}
if (sendIn)
base.SendInMessage(message);
if (sendOutMsg != null)
RaiseNewOutMessage(sendOutMsg);
}
private static MarketDataMessage NonExist(MarketDataMessage message)
{
return new MarketDataMessage
{
DataType = message.DataType,
IsSubscribe = false,
SecurityId = message.SecurityId,
OriginalTransactionId = message.TransactionId,
Error = new InvalidOperationException(LocalizedStrings.SubscriptionNonExist),
};
}
/// <summary>
/// Create a copy of <see cref="SubscriptionMessageAdapter"/>.
/// </summary>
/// <returns>Copy.</returns>
public override IMessageChannel Clone()
{
return new SubscriptionMessageAdapter(InnerAdapter);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dialogflow.Cx.V3.Snippets
{
using Google.Api.Gax;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedEntityTypesClientSnippets
{
/// <summary>Snippet for ListEntityTypes</summary>
public void ListEntityTypesRequestObject()
{
// Snippet: ListEntityTypes(ListEntityTypesRequest, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
ListEntityTypesRequest request = new ListEntityTypesRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
LanguageCode = "",
};
// Make the request
PagedEnumerable<ListEntityTypesResponse, EntityType> response = entityTypesClient.ListEntityTypes(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (EntityType item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListEntityTypesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (EntityType item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<EntityType> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (EntityType item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEntityTypesAsync</summary>
public async Task ListEntityTypesRequestObjectAsync()
{
// Snippet: ListEntityTypesAsync(ListEntityTypesRequest, CallSettings)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
ListEntityTypesRequest request = new ListEntityTypesRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
LanguageCode = "",
};
// Make the request
PagedAsyncEnumerable<ListEntityTypesResponse, EntityType> response = entityTypesClient.ListEntityTypesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((EntityType item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListEntityTypesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (EntityType item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<EntityType> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (EntityType item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEntityTypes</summary>
public void ListEntityTypes()
{
// Snippet: ListEntityTypes(string, string, int?, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]";
// Make the request
PagedEnumerable<ListEntityTypesResponse, EntityType> response = entityTypesClient.ListEntityTypes(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (EntityType item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListEntityTypesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (EntityType item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<EntityType> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (EntityType item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEntityTypesAsync</summary>
public async Task ListEntityTypesAsync()
{
// Snippet: ListEntityTypesAsync(string, string, int?, CallSettings)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]";
// Make the request
PagedAsyncEnumerable<ListEntityTypesResponse, EntityType> response = entityTypesClient.ListEntityTypesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((EntityType item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListEntityTypesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (EntityType item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<EntityType> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (EntityType item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEntityTypes</summary>
public void ListEntityTypesResourceNames()
{
// Snippet: ListEntityTypes(AgentName, string, int?, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
// Make the request
PagedEnumerable<ListEntityTypesResponse, EntityType> response = entityTypesClient.ListEntityTypes(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (EntityType item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListEntityTypesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (EntityType item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<EntityType> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (EntityType item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEntityTypesAsync</summary>
public async Task ListEntityTypesResourceNamesAsync()
{
// Snippet: ListEntityTypesAsync(AgentName, string, int?, CallSettings)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
// Make the request
PagedAsyncEnumerable<ListEntityTypesResponse, EntityType> response = entityTypesClient.ListEntityTypesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((EntityType item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListEntityTypesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (EntityType item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<EntityType> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (EntityType item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetEntityType</summary>
public void GetEntityTypeRequestObject()
{
// Snippet: GetEntityType(GetEntityTypeRequest, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
GetEntityTypeRequest request = new GetEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"),
LanguageCode = "",
};
// Make the request
EntityType response = entityTypesClient.GetEntityType(request);
// End snippet
}
/// <summary>Snippet for GetEntityTypeAsync</summary>
public async Task GetEntityTypeRequestObjectAsync()
{
// Snippet: GetEntityTypeAsync(GetEntityTypeRequest, CallSettings)
// Additional: GetEntityTypeAsync(GetEntityTypeRequest, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
GetEntityTypeRequest request = new GetEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"),
LanguageCode = "",
};
// Make the request
EntityType response = await entityTypesClient.GetEntityTypeAsync(request);
// End snippet
}
/// <summary>Snippet for GetEntityType</summary>
public void GetEntityType()
{
// Snippet: GetEntityType(string, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/entityTypes/[ENTITY_TYPE]";
// Make the request
EntityType response = entityTypesClient.GetEntityType(name);
// End snippet
}
/// <summary>Snippet for GetEntityTypeAsync</summary>
public async Task GetEntityTypeAsync()
{
// Snippet: GetEntityTypeAsync(string, CallSettings)
// Additional: GetEntityTypeAsync(string, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/entityTypes/[ENTITY_TYPE]";
// Make the request
EntityType response = await entityTypesClient.GetEntityTypeAsync(name);
// End snippet
}
/// <summary>Snippet for GetEntityType</summary>
public void GetEntityTypeResourceNames()
{
// Snippet: GetEntityType(EntityTypeName, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
EntityTypeName name = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]");
// Make the request
EntityType response = entityTypesClient.GetEntityType(name);
// End snippet
}
/// <summary>Snippet for GetEntityTypeAsync</summary>
public async Task GetEntityTypeResourceNamesAsync()
{
// Snippet: GetEntityTypeAsync(EntityTypeName, CallSettings)
// Additional: GetEntityTypeAsync(EntityTypeName, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
EntityTypeName name = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]");
// Make the request
EntityType response = await entityTypesClient.GetEntityTypeAsync(name);
// End snippet
}
/// <summary>Snippet for CreateEntityType</summary>
public void CreateEntityTypeRequestObject()
{
// Snippet: CreateEntityType(CreateEntityTypeRequest, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
CreateEntityTypeRequest request = new CreateEntityTypeRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
EntityType = new EntityType(),
LanguageCode = "",
};
// Make the request
EntityType response = entityTypesClient.CreateEntityType(request);
// End snippet
}
/// <summary>Snippet for CreateEntityTypeAsync</summary>
public async Task CreateEntityTypeRequestObjectAsync()
{
// Snippet: CreateEntityTypeAsync(CreateEntityTypeRequest, CallSettings)
// Additional: CreateEntityTypeAsync(CreateEntityTypeRequest, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
CreateEntityTypeRequest request = new CreateEntityTypeRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
EntityType = new EntityType(),
LanguageCode = "",
};
// Make the request
EntityType response = await entityTypesClient.CreateEntityTypeAsync(request);
// End snippet
}
/// <summary>Snippet for CreateEntityType</summary>
public void CreateEntityType()
{
// Snippet: CreateEntityType(string, EntityType, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]";
EntityType entityType = new EntityType();
// Make the request
EntityType response = entityTypesClient.CreateEntityType(parent, entityType);
// End snippet
}
/// <summary>Snippet for CreateEntityTypeAsync</summary>
public async Task CreateEntityTypeAsync()
{
// Snippet: CreateEntityTypeAsync(string, EntityType, CallSettings)
// Additional: CreateEntityTypeAsync(string, EntityType, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]";
EntityType entityType = new EntityType();
// Make the request
EntityType response = await entityTypesClient.CreateEntityTypeAsync(parent, entityType);
// End snippet
}
/// <summary>Snippet for CreateEntityType</summary>
public void CreateEntityTypeResourceNames()
{
// Snippet: CreateEntityType(AgentName, EntityType, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
EntityType entityType = new EntityType();
// Make the request
EntityType response = entityTypesClient.CreateEntityType(parent, entityType);
// End snippet
}
/// <summary>Snippet for CreateEntityTypeAsync</summary>
public async Task CreateEntityTypeResourceNamesAsync()
{
// Snippet: CreateEntityTypeAsync(AgentName, EntityType, CallSettings)
// Additional: CreateEntityTypeAsync(AgentName, EntityType, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
EntityType entityType = new EntityType();
// Make the request
EntityType response = await entityTypesClient.CreateEntityTypeAsync(parent, entityType);
// End snippet
}
/// <summary>Snippet for UpdateEntityType</summary>
public void UpdateEntityTypeRequestObject()
{
// Snippet: UpdateEntityType(UpdateEntityTypeRequest, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
UpdateEntityTypeRequest request = new UpdateEntityTypeRequest
{
EntityType = new EntityType(),
LanguageCode = "",
UpdateMask = new FieldMask(),
};
// Make the request
EntityType response = entityTypesClient.UpdateEntityType(request);
// End snippet
}
/// <summary>Snippet for UpdateEntityTypeAsync</summary>
public async Task UpdateEntityTypeRequestObjectAsync()
{
// Snippet: UpdateEntityTypeAsync(UpdateEntityTypeRequest, CallSettings)
// Additional: UpdateEntityTypeAsync(UpdateEntityTypeRequest, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
UpdateEntityTypeRequest request = new UpdateEntityTypeRequest
{
EntityType = new EntityType(),
LanguageCode = "",
UpdateMask = new FieldMask(),
};
// Make the request
EntityType response = await entityTypesClient.UpdateEntityTypeAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateEntityType</summary>
public void UpdateEntityType()
{
// Snippet: UpdateEntityType(EntityType, FieldMask, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
EntityType entityType = new EntityType();
FieldMask updateMask = new FieldMask();
// Make the request
EntityType response = entityTypesClient.UpdateEntityType(entityType, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateEntityTypeAsync</summary>
public async Task UpdateEntityTypeAsync()
{
// Snippet: UpdateEntityTypeAsync(EntityType, FieldMask, CallSettings)
// Additional: UpdateEntityTypeAsync(EntityType, FieldMask, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
EntityType entityType = new EntityType();
FieldMask updateMask = new FieldMask();
// Make the request
EntityType response = await entityTypesClient.UpdateEntityTypeAsync(entityType, updateMask);
// End snippet
}
/// <summary>Snippet for DeleteEntityType</summary>
public void DeleteEntityTypeRequestObject()
{
// Snippet: DeleteEntityType(DeleteEntityTypeRequest, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
DeleteEntityTypeRequest request = new DeleteEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"),
Force = false,
};
// Make the request
entityTypesClient.DeleteEntityType(request);
// End snippet
}
/// <summary>Snippet for DeleteEntityTypeAsync</summary>
public async Task DeleteEntityTypeRequestObjectAsync()
{
// Snippet: DeleteEntityTypeAsync(DeleteEntityTypeRequest, CallSettings)
// Additional: DeleteEntityTypeAsync(DeleteEntityTypeRequest, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
DeleteEntityTypeRequest request = new DeleteEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"),
Force = false,
};
// Make the request
await entityTypesClient.DeleteEntityTypeAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteEntityType</summary>
public void DeleteEntityType()
{
// Snippet: DeleteEntityType(string, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/entityTypes/[ENTITY_TYPE]";
// Make the request
entityTypesClient.DeleteEntityType(name);
// End snippet
}
/// <summary>Snippet for DeleteEntityTypeAsync</summary>
public async Task DeleteEntityTypeAsync()
{
// Snippet: DeleteEntityTypeAsync(string, CallSettings)
// Additional: DeleteEntityTypeAsync(string, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/entityTypes/[ENTITY_TYPE]";
// Make the request
await entityTypesClient.DeleteEntityTypeAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteEntityType</summary>
public void DeleteEntityTypeResourceNames()
{
// Snippet: DeleteEntityType(EntityTypeName, CallSettings)
// Create client
EntityTypesClient entityTypesClient = EntityTypesClient.Create();
// Initialize request argument(s)
EntityTypeName name = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]");
// Make the request
entityTypesClient.DeleteEntityType(name);
// End snippet
}
/// <summary>Snippet for DeleteEntityTypeAsync</summary>
public async Task DeleteEntityTypeResourceNamesAsync()
{
// Snippet: DeleteEntityTypeAsync(EntityTypeName, CallSettings)
// Additional: DeleteEntityTypeAsync(EntityTypeName, CancellationToken)
// Create client
EntityTypesClient entityTypesClient = await EntityTypesClient.CreateAsync();
// Initialize request argument(s)
EntityTypeName name = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]");
// Make the request
await entityTypesClient.DeleteEntityTypeAsync(name);
// End snippet
}
}
}
| |
/*
* Copyright (c) 2020, Norsk Helsenett SF and contributors
* See the file CONTRIBUTORS for details.
*
* This file is licensed under the MIT license
* available at https://raw.githubusercontent.com/helsenorge/Helsenorge.Messaging/master/LICENSE
*/
using Helsenorge.Registries.Abstractions;
using Helsenorge.Registries.Configuration;
using Helsenorge.Registries.Mocks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Linq;
using System.ServiceModel;
namespace Helsenorge.Registries.Tests
{
[TestClass]
public class CollaborationRegistryTests
{
private CollaborationProtocolRegistryMock _registry;
private ILoggerFactory _loggerFactory;
private ILogger _logger;
[TestInitialize]
public void Setup()
{
var settings = new CollaborationProtocolRegistrySettings()
{
WcfConfiguration = new WcfConfiguration
{
UserName = "username",
Password = "password",
},
CachingInterval = TimeSpan.FromSeconds(5),
MyHerId = 93238 // matches a value in a CPA test file
};
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(loggingBuilder => loggingBuilder.AddDebug());
var provider = serviceCollection.BuildServiceProvider();
_loggerFactory = provider.GetRequiredService<ILoggerFactory>();
_logger = _loggerFactory.CreateLogger<CollaborationRegistryTests>();
var distributedCache = DistributedCacheFactory.Create();
IAddressRegistry addressRegistry = AddressRegistryTests.GetDefaultAddressRegistryMock();
_registry = new CollaborationProtocolRegistryMock(settings, distributedCache, addressRegistry);
_registry.SetupFindAgreementById(i =>
{
var file = TestFileUtility.GetFullPathToFile(Path.Combine("Files", $"CPA_{i:D}.xml"));
return File.Exists(file) == false ? null : File.ReadAllText(file);
});
_registry.SetupFindAgreementForCounterparty(i =>
{
var file = TestFileUtility.GetFullPathToFile(Path.Combine("Files", $"CPA_{i}.xml"));
return File.Exists(file) == false ? null : File.ReadAllText(file);
});
_registry.SetupFindProtocolForCounterparty(i =>
{
if (i < 0)
{
throw new FaultException(new FaultReason("Dummy fault from mock"), new FaultCode("Client"), string.Empty);
}
var file = TestFileUtility.GetFullPathToFile(Path.Combine("Files", $"CPP_{i}.xml"));
return File.Exists(file) == false ? null : File.ReadAllText(file);
});
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Constructor_Settings_Null()
{
var distributedCache = DistributedCacheFactory.Create();
IAddressRegistry addressRegistry = new AddressRegistryMock(new AddressRegistrySettings(), distributedCache);
new CollaborationProtocolRegistry(null, distributedCache, addressRegistry);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Constructor_Cache_Null()
{
var distributedCache = DistributedCacheFactory.Create();
IAddressRegistry addressRegistry = new AddressRegistryMock(new AddressRegistrySettings(), distributedCache);
new CollaborationProtocolRegistry(new CollaborationProtocolRegistrySettings(), null, addressRegistry);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Constructor_AddressRegistry_Null()
{
var distributedCache = DistributedCacheFactory.Create();
new CollaborationProtocolRegistry(new CollaborationProtocolRegistrySettings(), distributedCache, null);
}
[TestMethod]
public void Read_CollaborationProfile()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.AreEqual(profile.CpaId, Guid.Empty);
Assert.AreEqual("Digitale innbyggertjenester", profile.Name);
Assert.AreEqual(15, profile.Roles.Count);
Assert.IsNotNull(profile.SignatureCertificate);
Assert.IsNotNull(profile.EncryptionCertificate);
var role = profile.Roles[0];
Assert.AreEqual("DIALOG_INNBYGGER_DIGITALBRUKERreceiver", role.RoleName);
Assert.AreEqual("1.1", role.ProcessSpecification.VersionString);
Assert.AreEqual(new Version(1, 1), role.ProcessSpecification.Version);
Assert.AreEqual("Dialog_Innbygger_Digitalbruker", role.ProcessSpecification.Name);
Assert.AreEqual(2, role.ReceiveMessages.Count);
Assert.AreEqual(2, role.SendMessages.Count);
var message = role.ReceiveMessages[0];
Assert.AreEqual("DIALOG_INNBYGGER_DIGITALBRUKER", message.Name);
Assert.AreEqual("sb.test.nhn.no/DigitalDialog/93238_async", message.DeliveryChannel);
Assert.AreEqual(DeliveryProtocol.Amqp, message.DeliveryProtocol);
var part = message.Parts.First();
Assert.AreEqual(1, part.MaxOccurrence);
Assert.AreEqual(0, part.MinOccurrence);
Assert.AreEqual("http://www.kith.no/xmlstds/msghead/2006-05-24", part.XmlNamespace);
Assert.AreEqual("MsgHead-v1_2.xsd", part.XmlSchema);
}
[TestMethod]
public void Read_CollaborationProfile_NotFound()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 1234).Result;
Assert.IsNotNull(profile);
Assert.AreEqual("DummyCollaborationProtocolProfile", profile.Name);
}
[TestMethod, Ignore]
public void Read_CollaborationProfile_FromCache()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNotNull(profile);
// if it's not found in cache, it will cause an exception
_registry.SetupFindProtocolForCounterparty(i =>
{
throw new NotImplementedException();
});
profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNotNull(profile);
}
[TestMethod]
public void Read_CollaborationAgreement_ById()
{
var profile = _registry.FindAgreementByIdAsync(_logger, Guid.Parse("49391409-e528-4919-b4a3-9ccdab72c8c1")).Result;
Assert.AreEqual("Testlege Testlege", profile.Name);
Assert.AreEqual(93252, profile.HerId);
Assert.AreEqual(14, profile.Roles.Count);
Assert.IsNotNull(profile.SignatureCertificate);
Assert.IsNotNull(profile.EncryptionCertificate);
}
[TestMethod]
public void Read_CollaborationAgreement_ByCounterparty()
{
var profile = _registry.FindAgreementForCounterpartyAsync(_logger, 93252).Result;
Assert.AreEqual(profile.HerId, 93252);
Assert.AreEqual(profile.Name, "Testlege Testlege");
Assert.AreEqual(profile.CpaId, new Guid("{9333f3de-e85c-4c26-9066-6800055b1b8e}"));
Assert.IsNotNull(profile.EncryptionCertificate);
Assert.IsNotNull(profile.SignatureCertificate);
Assert.AreEqual(profile.Roles.Count, 14);
}
[TestMethod]
public void Read_CollaborationAgreement_NotFound()
{
var profile = _registry.FindAgreementForCounterpartyAsync(_logger, 1234).Result;
Assert.IsNull(profile);
}
[TestMethod, Ignore]
public void Read_CollaborationAgreement_FromCache()
{
var profile = _registry.FindAgreementForCounterpartyAsync(_logger, 93252).Result;
Assert.IsNotNull(profile);
// if it's not found in cache, it will cause an exception
_registry.SetupFindAgreementForCounterparty(i =>
{
throw new NotImplementedException();
});
profile = _registry.FindAgreementForCounterpartyAsync(_logger, 93252).Result;
Assert.IsNotNull(profile);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FindMessageForSender_ArgumentNull()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNotNull(profile.FindMessageForSender(null));
}
[TestMethod]
public void FindMessageForSender_Found()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNotNull(profile.FindMessageForSender("DIALOG_INNBYGGER_EKONTAKT"));
}
[TestMethod]
public void FindMessageForSender_Found_AppRec()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNotNull(profile.FindMessageForSender("APPREC"));
}
[TestMethod]
public void FindMessageForSender_Found_Ny_CPP()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
var collaborationProtocolMessage = profile.FindMessageForReceiver("DIALOG_INNBYGGER_BEHANDLEROVERSIKT");
Assert.IsNotNull(collaborationProtocolMessage);
Assert.AreEqual("Svar", collaborationProtocolMessage.Name);
}
[TestMethod]
public void FindMessageForSender_NotFound()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNull(profile.FindMessageForSender("BOB"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FindMessageForReceiver_ArgumentNull()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNotNull(profile.FindMessageForReceiver(null));
}
[TestMethod]
public void FindMessageForReceiver_Found()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNotNull(profile.FindMessageForReceiver("DIALOG_INNBYGGER_EKONTAKT"));
}
[TestMethod]
public void FindMessageForReceiver_Found_AppRec()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNotNull(profile.FindMessageForReceiver("APPREC"));
}
[TestMethod]
public void FindMessageForReceiver_Found_Ny_CPP()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
var collaborationProtocolMessage = profile.FindMessageForSender("DIALOG_INNBYGGER_BEHANDLEROVERSIKT");
Assert.IsNotNull(collaborationProtocolMessage);
Assert.AreEqual("Hent", collaborationProtocolMessage.Name);
}
[TestMethod]
public void FindMessageForReceiver_NotFound()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNull(profile.FindMessageForReceiver("BOB"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FindMessagePartsForReceiveMessage_ArgumentNull()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNotNull(profile.FindMessagePartsForReceiveMessage(null));
}
[TestMethod]
public void FindMessagePartsForReceiveMessage_Found()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsTrue(profile.FindMessagePartsForReceiveMessage("DIALOG_INNBYGGER_EKONTAKT").Any());
}
[TestMethod]
public void FindMessagePartsForReceiveMessage_NotFound()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNull(profile.FindMessagePartsForReceiveMessage("BOB"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FindMessagePartsForReceiveAppRec_ArgumentNull()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNotNull(profile.FindMessagePartsForReceiveAppRec(null));
}
[TestMethod]
public void FindMessagePartsForReceiveAppRec_Found()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsTrue(profile.FindMessagePartsForReceiveAppRec("DIALOG_INNBYGGER_EKONTAKT").Any());
}
[TestMethod]
public void FindMessagePartsForReceiveAppRec_NotFound()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNull(profile.FindMessagePartsForReceiveAppRec("BOB"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FindMessagePartsForSendMessage_ArgumentNull()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNotNull(profile.FindMessagePartsForSendMessage(null));
}
[TestMethod]
public void FindMessagePartsForSendMessage_Found()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsTrue(profile.FindMessagePartsForSendMessage("DIALOG_INNBYGGER_EKONTAKT").Any());
}
[TestMethod]
public void FindMessagePartsForSendMessage_NotFound()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNull(profile.FindMessagePartsForSendMessage("BOB"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FindMessagePartsForSendAppRec_ArgumentNull()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNotNull(profile.FindMessagePartsForSendAppRec(null));
}
[TestMethod]
public void FindMessagePartsForSendAppRec_Found()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsTrue(profile.FindMessagePartsForSendAppRec("DIALOG_INNBYGGER_EKONTAKT").Any());
}
[TestMethod]
public void FindMessagePartsForSendAppRec_NotFound()
{
var profile = _registry.FindProtocolForCounterpartyAsync(_logger, 93238).Result;
Assert.IsNull(profile.FindMessagePartsForSendAppRec("BOB"));
}
[TestMethod]
public void Read_CollaborationAgreement_v2_ById()
{
_registry.SetupFindAgreementById(i =>
{
var file = TestFileUtility.GetFullPathToFile(Path.Combine("Files", $"CPA_v2_{i:D}.xml"));
return File.Exists(file) == false ? null : File.ReadAllText(file);
});
var profile = _registry.FindAgreementByIdAsync(_logger, Guid.Parse("51795e2c-9d39-44e0-9168-5bee38f20819")).Result;
Assert.AreEqual("Digitale innbyggertjenester", profile.Name);
Assert.AreEqual(8093240, profile.HerId);
Assert.AreEqual(32, profile.Roles.Count);
Assert.AreEqual(4, profile.Roles[0].SendMessages.Count);
Assert.AreEqual(5, profile.Roles[0].SendMessages[0].Parts.Count());
Assert.AreEqual("MsgHead-v1_2.xsd", profile.Roles[0].SendMessages[0].Parts.ToList()[0].XmlSchema);
Assert.IsNotNull(profile.SignatureCertificate);
Assert.IsNotNull(profile.EncryptionCertificate);
Assert.IsTrue(profile.FindMessagePartsForReceiveMessage("DIALOG_INNBYGGER_TEST").Any());
}
}
}
| |
// 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:
**
**
===========================================================*/
using System;
using System.Collections;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System.IO {
#if FEATURE_SERIALIZATION
[Serializable]
#endif
#if !FEATURE_CORECLR
[FileIOPermissionAttribute(SecurityAction.InheritanceDemand,Unrestricted=true)]
#endif
[ComVisible(true)]
public abstract class FileSystemInfo : MarshalByRefObject, ISerializable {
[System.Security.SecurityCritical] // auto-generated
internal Win32Native.WIN32_FILE_ATTRIBUTE_DATA _data; // Cache the file information
internal int _dataInitialised = -1; // We use this field in conjunction with the Refresh methods, if we succeed
// we store a zero, on failure we store the HResult in it so that we can
// give back a generic error back.
private const int ERROR_INVALID_PARAMETER = 87;
internal const int ERROR_ACCESS_DENIED = 0x5;
protected String FullPath; // fully qualified path of the directory
protected String OriginalPath; // path passed in by the user
private String _displayPath = ""; // path that can be displayed to the user
#if FEATURE_CORECLR
#if FEATURE_CORESYSTEM
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif //FEATURE_CORESYSTEM
#endif
protected FileSystemInfo()
{
}
protected FileSystemInfo(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
// Must use V1 field names here, since V1 didn't implement
// ISerializable.
FullPath = Path.GetFullPathInternal(info.GetString("FullPath"));
OriginalPath = info.GetString("OriginalPath");
// Lazily initialize the file attributes.
_dataInitialised = -1;
}
[System.Security.SecurityCritical]
internal void InitializeFrom(Win32Native.WIN32_FIND_DATA findData)
{
_data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
_data.PopulateFrom(findData);
_dataInitialised = 0;
}
// Full path of the direcory/file
public virtual String FullName {
[System.Security.SecuritySafeCritical]
get
{
String demandDir;
if (this is DirectoryInfo)
demandDir = Directory.GetDemandDir(FullPath, true);
else
demandDir = FullPath;
#if FEATURE_CORECLR
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandDir);
sourceState.EnsureState();
#else
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandDir).Demand();
#endif
return FullPath;
}
}
internal virtual String UnsafeGetFullName
{
[System.Security.SecurityCritical]
get
{
String demandDir;
if (this is DirectoryInfo)
demandDir = Directory.GetDemandDir(FullPath, true);
else
demandDir = FullPath;
#if !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandDir).Demand();
#endif
return FullPath;
}
}
public String Extension
{
get
{
// GetFullPathInternal would have already stripped out the terminating "." if present.
int length = FullPath.Length;
for (int i = length; --i >= 0;) {
char ch = FullPath[i];
if (ch == '.')
return FullPath.Substring(i, length - i);
if (ch == Path.DirectorySeparatorChar || ch == Path.AltDirectorySeparatorChar || ch == Path.VolumeSeparatorChar)
break;
}
return String.Empty;
}
}
// For files name of the file is returned, for directories the last directory in hierarchy is returned if possible,
// otherwise the fully qualified name s returned
public abstract String Name {
get;
}
// Whether a file/directory exists
public abstract bool Exists
{
get;
}
// Delete a file/directory
public abstract void Delete();
public DateTime CreationTime
{
get {
// depends on the security check in get_CreationTimeUtc
return CreationTimeUtc.ToLocalTime();
}
set {
CreationTimeUtc = value.ToUniversalTime();
}
}
[ComVisible(false)]
public DateTime CreationTimeUtc {
[System.Security.SecuritySafeCritical]
get {
#if FEATURE_CORECLR
// get_CreationTime also depends on this security check
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath);
sourceState.EnsureState();
#endif
if (_dataInitialised == -1) {
_data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
Refresh();
}
if (_dataInitialised != 0) // Refresh was unable to initialise the data
__Error.WinIOError(_dataInitialised, DisplayPath);
long fileTime = ((long)_data.ftCreationTimeHigh << 32) | _data.ftCreationTimeLow;
return DateTime.FromFileTimeUtc(fileTime);
}
set {
if (this is DirectoryInfo)
Directory.SetCreationTimeUtc(FullPath,value);
else
File.SetCreationTimeUtc(FullPath,value);
_dataInitialised = -1;
}
}
public DateTime LastAccessTime
{
get {
// depends on the security check in get_LastAccessTimeUtc
return LastAccessTimeUtc.ToLocalTime();
}
set {
LastAccessTimeUtc = value.ToUniversalTime();
}
}
[ComVisible(false)]
public DateTime LastAccessTimeUtc {
[System.Security.SecuritySafeCritical]
get {
#if FEATURE_CORECLR
// get_LastAccessTime also depends on this security check
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath);
sourceState.EnsureState();
#endif
if (_dataInitialised == -1) {
_data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
Refresh();
}
if (_dataInitialised != 0) // Refresh was unable to initialise the data
__Error.WinIOError(_dataInitialised, DisplayPath);
long fileTime = ((long)_data.ftLastAccessTimeHigh << 32) | _data.ftLastAccessTimeLow;
return DateTime.FromFileTimeUtc(fileTime);
}
set {
if (this is DirectoryInfo)
Directory.SetLastAccessTimeUtc(FullPath,value);
else
File.SetLastAccessTimeUtc(FullPath,value);
_dataInitialised = -1;
}
}
public DateTime LastWriteTime
{
get {
// depends on the security check in get_LastWriteTimeUtc
return LastWriteTimeUtc.ToLocalTime();
}
set {
LastWriteTimeUtc = value.ToUniversalTime();
}
}
[ComVisible(false)]
public DateTime LastWriteTimeUtc {
[System.Security.SecuritySafeCritical]
get {
#if FEATURE_CORECLR
// get_LastWriteTime also depends on this security check
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath);
sourceState.EnsureState();
#endif
if (_dataInitialised == -1) {
_data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
Refresh();
}
if (_dataInitialised != 0) // Refresh was unable to initialise the data
__Error.WinIOError(_dataInitialised, DisplayPath);
long fileTime = ((long)_data.ftLastWriteTimeHigh << 32) | _data.ftLastWriteTimeLow;
return DateTime.FromFileTimeUtc(fileTime);
}
set {
if (this is DirectoryInfo)
Directory.SetLastWriteTimeUtc(FullPath,value);
else
File.SetLastWriteTimeUtc(FullPath,value);
_dataInitialised = -1;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public void Refresh()
{
_dataInitialised = File.FillAttributeInfo(FullPath, ref _data, false, false);
}
public FileAttributes Attributes {
[System.Security.SecuritySafeCritical]
get
{
#if FEATURE_CORECLR
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath);
sourceState.EnsureState();
#endif
if (_dataInitialised == -1) {
_data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
Refresh(); // Call refresh to intialise the data
}
if (_dataInitialised != 0) // Refresh was unable to initialise the data
__Error.WinIOError(_dataInitialised, DisplayPath);
return (FileAttributes) _data.fileAttributes;
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
set {
#if !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.Write, FullPath).Demand();
#endif
bool r = Win32Native.SetFileAttributes(FullPath, (int) value);
if (!r) {
int hr = Marshal.GetLastWin32Error();
if (hr==ERROR_INVALID_PARAMETER)
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileAttrs"));
// For whatever reason we are turning ERROR_ACCESS_DENIED into
// ArgumentException here (probably done for some 9x code path).
// We can't change this now but special casing the error message instead.
if (hr == ERROR_ACCESS_DENIED)
throw new ArgumentException(Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName"));
__Error.WinIOError(hr, DisplayPath);
}
_dataInitialised = -1;
}
}
[System.Security.SecurityCritical] // auto-generated_required
[ComVisible(false)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
#if !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, FullPath).Demand();
#endif
info.AddValue("OriginalPath", OriginalPath, typeof(String));
info.AddValue("FullPath", FullPath, typeof(String));
}
internal String DisplayPath
{
get
{
return _displayPath;
}
set
{
_displayPath = value;
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the VgiAClinicosDet class.
/// </summary>
[Serializable]
public partial class VgiAClinicosDetCollection : ActiveList<VgiAClinicosDet, VgiAClinicosDetCollection>
{
public VgiAClinicosDetCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>VgiAClinicosDetCollection</returns>
public VgiAClinicosDetCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
VgiAClinicosDet o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the VGI_AClinicosDet table.
/// </summary>
[Serializable]
public partial class VgiAClinicosDet : ActiveRecord<VgiAClinicosDet>, IActiveRecord
{
#region .ctors and Default Settings
public VgiAClinicosDet()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public VgiAClinicosDet(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public VgiAClinicosDet(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public VgiAClinicosDet(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("VGI_AClinicosDet", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdVGIDatos = new TableSchema.TableColumn(schema);
colvarIdVGIDatos.ColumnName = "idVGIDatos";
colvarIdVGIDatos.DataType = DbType.Int32;
colvarIdVGIDatos.MaxLength = 0;
colvarIdVGIDatos.AutoIncrement = false;
colvarIdVGIDatos.IsNullable = false;
colvarIdVGIDatos.IsPrimaryKey = false;
colvarIdVGIDatos.IsForeignKey = false;
colvarIdVGIDatos.IsReadOnly = false;
colvarIdVGIDatos.DefaultSetting = @"";
colvarIdVGIDatos.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdVGIDatos);
TableSchema.TableColumn colvarIdVGIAClinico = new TableSchema.TableColumn(schema);
colvarIdVGIAClinico.ColumnName = "idVGIAClinico";
colvarIdVGIAClinico.DataType = DbType.Decimal;
colvarIdVGIAClinico.MaxLength = 0;
colvarIdVGIAClinico.AutoIncrement = true;
colvarIdVGIAClinico.IsNullable = false;
colvarIdVGIAClinico.IsPrimaryKey = true;
colvarIdVGIAClinico.IsForeignKey = false;
colvarIdVGIAClinico.IsReadOnly = false;
colvarIdVGIAClinico.DefaultSetting = @"";
colvarIdVGIAClinico.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdVGIAClinico);
TableSchema.TableColumn colvarTa = new TableSchema.TableColumn(schema);
colvarTa.ColumnName = "TA";
colvarTa.DataType = DbType.String;
colvarTa.MaxLength = 50;
colvarTa.AutoIncrement = false;
colvarTa.IsNullable = true;
colvarTa.IsPrimaryKey = false;
colvarTa.IsForeignKey = false;
colvarTa.IsReadOnly = false;
colvarTa.DefaultSetting = @"";
colvarTa.ForeignKeyTableName = "";
schema.Columns.Add(colvarTa);
TableSchema.TableColumn colvarPeso = new TableSchema.TableColumn(schema);
colvarPeso.ColumnName = "Peso";
colvarPeso.DataType = DbType.Decimal;
colvarPeso.MaxLength = 0;
colvarPeso.AutoIncrement = false;
colvarPeso.IsNullable = true;
colvarPeso.IsPrimaryKey = false;
colvarPeso.IsForeignKey = false;
colvarPeso.IsReadOnly = false;
colvarPeso.DefaultSetting = @"";
colvarPeso.ForeignKeyTableName = "";
schema.Columns.Add(colvarPeso);
TableSchema.TableColumn colvarTalla = new TableSchema.TableColumn(schema);
colvarTalla.ColumnName = "Talla";
colvarTalla.DataType = DbType.Decimal;
colvarTalla.MaxLength = 0;
colvarTalla.AutoIncrement = false;
colvarTalla.IsNullable = true;
colvarTalla.IsPrimaryKey = false;
colvarTalla.IsForeignKey = false;
colvarTalla.IsReadOnly = false;
colvarTalla.DefaultSetting = @"";
colvarTalla.ForeignKeyTableName = "";
schema.Columns.Add(colvarTalla);
TableSchema.TableColumn colvarImc = new TableSchema.TableColumn(schema);
colvarImc.ColumnName = "IMC";
colvarImc.DataType = DbType.Decimal;
colvarImc.MaxLength = 0;
colvarImc.AutoIncrement = false;
colvarImc.IsNullable = true;
colvarImc.IsPrimaryKey = false;
colvarImc.IsForeignKey = false;
colvarImc.IsReadOnly = false;
colvarImc.DefaultSetting = @"";
colvarImc.ForeignKeyTableName = "";
schema.Columns.Add(colvarImc);
TableSchema.TableColumn colvarHta = new TableSchema.TableColumn(schema);
colvarHta.ColumnName = "HTA";
colvarHta.DataType = DbType.String;
colvarHta.MaxLength = 2;
colvarHta.AutoIncrement = false;
colvarHta.IsNullable = true;
colvarHta.IsPrimaryKey = false;
colvarHta.IsForeignKey = false;
colvarHta.IsReadOnly = false;
colvarHta.DefaultSetting = @"";
colvarHta.ForeignKeyTableName = "";
schema.Columns.Add(colvarHta);
TableSchema.TableColumn colvarDbt = new TableSchema.TableColumn(schema);
colvarDbt.ColumnName = "DBT";
colvarDbt.DataType = DbType.String;
colvarDbt.MaxLength = 2;
colvarDbt.AutoIncrement = false;
colvarDbt.IsNullable = true;
colvarDbt.IsPrimaryKey = false;
colvarDbt.IsForeignKey = false;
colvarDbt.IsReadOnly = false;
colvarDbt.DefaultSetting = @"";
colvarDbt.ForeignKeyTableName = "";
schema.Columns.Add(colvarDbt);
TableSchema.TableColumn colvarDislip = new TableSchema.TableColumn(schema);
colvarDislip.ColumnName = "Dislip";
colvarDislip.DataType = DbType.String;
colvarDislip.MaxLength = 2;
colvarDislip.AutoIncrement = false;
colvarDislip.IsNullable = true;
colvarDislip.IsPrimaryKey = false;
colvarDislip.IsForeignKey = false;
colvarDislip.IsReadOnly = false;
colvarDislip.DefaultSetting = @"";
colvarDislip.ForeignKeyTableName = "";
schema.Columns.Add(colvarDislip);
TableSchema.TableColumn colvarIrc = new TableSchema.TableColumn(schema);
colvarIrc.ColumnName = "IRC";
colvarIrc.DataType = DbType.String;
colvarIrc.MaxLength = 2;
colvarIrc.AutoIncrement = false;
colvarIrc.IsNullable = true;
colvarIrc.IsPrimaryKey = false;
colvarIrc.IsForeignKey = false;
colvarIrc.IsReadOnly = false;
colvarIrc.DefaultSetting = @"";
colvarIrc.ForeignKeyTableName = "";
schema.Columns.Add(colvarIrc);
TableSchema.TableColumn colvarCardioIsq = new TableSchema.TableColumn(schema);
colvarCardioIsq.ColumnName = "CardioIsq";
colvarCardioIsq.DataType = DbType.String;
colvarCardioIsq.MaxLength = 2;
colvarCardioIsq.AutoIncrement = false;
colvarCardioIsq.IsNullable = true;
colvarCardioIsq.IsPrimaryKey = false;
colvarCardioIsq.IsForeignKey = false;
colvarCardioIsq.IsReadOnly = false;
colvarCardioIsq.DefaultSetting = @"";
colvarCardioIsq.ForeignKeyTableName = "";
schema.Columns.Add(colvarCardioIsq);
TableSchema.TableColumn colvarAcv = new TableSchema.TableColumn(schema);
colvarAcv.ColumnName = "ACV";
colvarAcv.DataType = DbType.String;
colvarAcv.MaxLength = 2;
colvarAcv.AutoIncrement = false;
colvarAcv.IsNullable = true;
colvarAcv.IsPrimaryKey = false;
colvarAcv.IsForeignKey = false;
colvarAcv.IsReadOnly = false;
colvarAcv.DefaultSetting = @"";
colvarAcv.ForeignKeyTableName = "";
schema.Columns.Add(colvarAcv);
TableSchema.TableColumn colvarAmputacion = new TableSchema.TableColumn(schema);
colvarAmputacion.ColumnName = "Amputacion";
colvarAmputacion.DataType = DbType.String;
colvarAmputacion.MaxLength = 2;
colvarAmputacion.AutoIncrement = false;
colvarAmputacion.IsNullable = true;
colvarAmputacion.IsPrimaryKey = false;
colvarAmputacion.IsForeignKey = false;
colvarAmputacion.IsReadOnly = false;
colvarAmputacion.DefaultSetting = @"";
colvarAmputacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarAmputacion);
TableSchema.TableColumn colvarTabaquismo = new TableSchema.TableColumn(schema);
colvarTabaquismo.ColumnName = "Tabaquismo";
colvarTabaquismo.DataType = DbType.String;
colvarTabaquismo.MaxLength = 2;
colvarTabaquismo.AutoIncrement = false;
colvarTabaquismo.IsNullable = true;
colvarTabaquismo.IsPrimaryKey = false;
colvarTabaquismo.IsForeignKey = false;
colvarTabaquismo.IsReadOnly = false;
colvarTabaquismo.DefaultSetting = @"";
colvarTabaquismo.ForeignKeyTableName = "";
schema.Columns.Add(colvarTabaquismo);
TableSchema.TableColumn colvarAlcoholismo = new TableSchema.TableColumn(schema);
colvarAlcoholismo.ColumnName = "Alcoholismo";
colvarAlcoholismo.DataType = DbType.String;
colvarAlcoholismo.MaxLength = 2;
colvarAlcoholismo.AutoIncrement = false;
colvarAlcoholismo.IsNullable = true;
colvarAlcoholismo.IsPrimaryKey = false;
colvarAlcoholismo.IsForeignKey = false;
colvarAlcoholismo.IsReadOnly = false;
colvarAlcoholismo.DefaultSetting = @"";
colvarAlcoholismo.ForeignKeyTableName = "";
schema.Columns.Add(colvarAlcoholismo);
TableSchema.TableColumn colvarParkinson = new TableSchema.TableColumn(schema);
colvarParkinson.ColumnName = "Parkinson";
colvarParkinson.DataType = DbType.String;
colvarParkinson.MaxLength = 2;
colvarParkinson.AutoIncrement = false;
colvarParkinson.IsNullable = true;
colvarParkinson.IsPrimaryKey = false;
colvarParkinson.IsForeignKey = false;
colvarParkinson.IsReadOnly = false;
colvarParkinson.DefaultSetting = @"";
colvarParkinson.ForeignKeyTableName = "";
schema.Columns.Add(colvarParkinson);
TableSchema.TableColumn colvarDemencia = new TableSchema.TableColumn(schema);
colvarDemencia.ColumnName = "Demencia";
colvarDemencia.DataType = DbType.String;
colvarDemencia.MaxLength = 2;
colvarDemencia.AutoIncrement = false;
colvarDemencia.IsNullable = true;
colvarDemencia.IsPrimaryKey = false;
colvarDemencia.IsForeignKey = false;
colvarDemencia.IsReadOnly = false;
colvarDemencia.DefaultSetting = @"";
colvarDemencia.ForeignKeyTableName = "";
schema.Columns.Add(colvarDemencia);
TableSchema.TableColumn colvarProstatismo = new TableSchema.TableColumn(schema);
colvarProstatismo.ColumnName = "Prostatismo";
colvarProstatismo.DataType = DbType.String;
colvarProstatismo.MaxLength = 2;
colvarProstatismo.AutoIncrement = false;
colvarProstatismo.IsNullable = true;
colvarProstatismo.IsPrimaryKey = false;
colvarProstatismo.IsForeignKey = false;
colvarProstatismo.IsReadOnly = false;
colvarProstatismo.DefaultSetting = @"";
colvarProstatismo.ForeignKeyTableName = "";
schema.Columns.Add(colvarProstatismo);
TableSchema.TableColumn colvarIncontinencia = new TableSchema.TableColumn(schema);
colvarIncontinencia.ColumnName = "Incontinencia";
colvarIncontinencia.DataType = DbType.String;
colvarIncontinencia.MaxLength = 2;
colvarIncontinencia.AutoIncrement = false;
colvarIncontinencia.IsNullable = true;
colvarIncontinencia.IsPrimaryKey = false;
colvarIncontinencia.IsForeignKey = false;
colvarIncontinencia.IsReadOnly = false;
colvarIncontinencia.DefaultSetting = @"";
colvarIncontinencia.ForeignKeyTableName = "";
schema.Columns.Add(colvarIncontinencia);
TableSchema.TableColumn colvarNeuplasias = new TableSchema.TableColumn(schema);
colvarNeuplasias.ColumnName = "Neuplasias";
colvarNeuplasias.DataType = DbType.String;
colvarNeuplasias.MaxLength = 100;
colvarNeuplasias.AutoIncrement = false;
colvarNeuplasias.IsNullable = true;
colvarNeuplasias.IsPrimaryKey = false;
colvarNeuplasias.IsForeignKey = false;
colvarNeuplasias.IsReadOnly = false;
colvarNeuplasias.DefaultSetting = @"";
colvarNeuplasias.ForeignKeyTableName = "";
schema.Columns.Add(colvarNeuplasias);
TableSchema.TableColumn colvarOtros = new TableSchema.TableColumn(schema);
colvarOtros.ColumnName = "Otros";
colvarOtros.DataType = DbType.String;
colvarOtros.MaxLength = 100;
colvarOtros.AutoIncrement = false;
colvarOtros.IsNullable = true;
colvarOtros.IsPrimaryKey = false;
colvarOtros.IsForeignKey = false;
colvarOtros.IsReadOnly = false;
colvarOtros.DefaultSetting = @"";
colvarOtros.ForeignKeyTableName = "";
schema.Columns.Add(colvarOtros);
TableSchema.TableColumn colvarRcvg = new TableSchema.TableColumn(schema);
colvarRcvg.ColumnName = "RCVG";
colvarRcvg.DataType = DbType.String;
colvarRcvg.MaxLength = 10;
colvarRcvg.AutoIncrement = false;
colvarRcvg.IsNullable = true;
colvarRcvg.IsPrimaryKey = false;
colvarRcvg.IsForeignKey = false;
colvarRcvg.IsReadOnly = false;
colvarRcvg.DefaultSetting = @"";
colvarRcvg.ForeignKeyTableName = "";
schema.Columns.Add(colvarRcvg);
TableSchema.TableColumn colvarVisionConducir = new TableSchema.TableColumn(schema);
colvarVisionConducir.ColumnName = "VisionConducir";
colvarVisionConducir.DataType = DbType.String;
colvarVisionConducir.MaxLength = 2;
colvarVisionConducir.AutoIncrement = false;
colvarVisionConducir.IsNullable = true;
colvarVisionConducir.IsPrimaryKey = false;
colvarVisionConducir.IsForeignKey = false;
colvarVisionConducir.IsReadOnly = false;
colvarVisionConducir.DefaultSetting = @"";
colvarVisionConducir.ForeignKeyTableName = "";
schema.Columns.Add(colvarVisionConducir);
TableSchema.TableColumn colvarVacunacionDT = new TableSchema.TableColumn(schema);
colvarVacunacionDT.ColumnName = "VacunacionDT";
colvarVacunacionDT.DataType = DbType.String;
colvarVacunacionDT.MaxLength = 2;
colvarVacunacionDT.AutoIncrement = false;
colvarVacunacionDT.IsNullable = true;
colvarVacunacionDT.IsPrimaryKey = false;
colvarVacunacionDT.IsForeignKey = false;
colvarVacunacionDT.IsReadOnly = false;
colvarVacunacionDT.DefaultSetting = @"";
colvarVacunacionDT.ForeignKeyTableName = "";
schema.Columns.Add(colvarVacunacionDT);
TableSchema.TableColumn colvarVacunacionHepB = new TableSchema.TableColumn(schema);
colvarVacunacionHepB.ColumnName = "VacunacionHepB";
colvarVacunacionHepB.DataType = DbType.String;
colvarVacunacionHepB.MaxLength = 2;
colvarVacunacionHepB.AutoIncrement = false;
colvarVacunacionHepB.IsNullable = true;
colvarVacunacionHepB.IsPrimaryKey = false;
colvarVacunacionHepB.IsForeignKey = false;
colvarVacunacionHepB.IsReadOnly = false;
colvarVacunacionHepB.DefaultSetting = @"";
colvarVacunacionHepB.ForeignKeyTableName = "";
schema.Columns.Add(colvarVacunacionHepB);
TableSchema.TableColumn colvarVacunacionGripe = new TableSchema.TableColumn(schema);
colvarVacunacionGripe.ColumnName = "VacunacionGripe";
colvarVacunacionGripe.DataType = DbType.String;
colvarVacunacionGripe.MaxLength = 2;
colvarVacunacionGripe.AutoIncrement = false;
colvarVacunacionGripe.IsNullable = true;
colvarVacunacionGripe.IsPrimaryKey = false;
colvarVacunacionGripe.IsForeignKey = false;
colvarVacunacionGripe.IsReadOnly = false;
colvarVacunacionGripe.DefaultSetting = @"";
colvarVacunacionGripe.ForeignKeyTableName = "";
schema.Columns.Add(colvarVacunacionGripe);
TableSchema.TableColumn colvarVacunacionNeumococo = new TableSchema.TableColumn(schema);
colvarVacunacionNeumococo.ColumnName = "VacunacionNeumococo";
colvarVacunacionNeumococo.DataType = DbType.String;
colvarVacunacionNeumococo.MaxLength = 2;
colvarVacunacionNeumococo.AutoIncrement = false;
colvarVacunacionNeumococo.IsNullable = true;
colvarVacunacionNeumococo.IsPrimaryKey = false;
colvarVacunacionNeumococo.IsForeignKey = false;
colvarVacunacionNeumococo.IsReadOnly = false;
colvarVacunacionNeumococo.DefaultSetting = @"";
colvarVacunacionNeumococo.ForeignKeyTableName = "";
schema.Columns.Add(colvarVacunacionNeumococo);
TableSchema.TableColumn colvarAudicionPSeguirConv = new TableSchema.TableColumn(schema);
colvarAudicionPSeguirConv.ColumnName = "AudicionPSeguirConv";
colvarAudicionPSeguirConv.DataType = DbType.String;
colvarAudicionPSeguirConv.MaxLength = 2;
colvarAudicionPSeguirConv.AutoIncrement = false;
colvarAudicionPSeguirConv.IsNullable = true;
colvarAudicionPSeguirConv.IsPrimaryKey = false;
colvarAudicionPSeguirConv.IsForeignKey = false;
colvarAudicionPSeguirConv.IsReadOnly = false;
colvarAudicionPSeguirConv.DefaultSetting = @"";
colvarAudicionPSeguirConv.ForeignKeyTableName = "";
schema.Columns.Add(colvarAudicionPSeguirConv);
TableSchema.TableColumn colvarMedicacion1 = new TableSchema.TableColumn(schema);
colvarMedicacion1.ColumnName = "Medicacion1";
colvarMedicacion1.DataType = DbType.Int32;
colvarMedicacion1.MaxLength = 0;
colvarMedicacion1.AutoIncrement = false;
colvarMedicacion1.IsNullable = true;
colvarMedicacion1.IsPrimaryKey = false;
colvarMedicacion1.IsForeignKey = false;
colvarMedicacion1.IsReadOnly = false;
colvarMedicacion1.DefaultSetting = @"";
colvarMedicacion1.ForeignKeyTableName = "";
schema.Columns.Add(colvarMedicacion1);
TableSchema.TableColumn colvarMedicacion2 = new TableSchema.TableColumn(schema);
colvarMedicacion2.ColumnName = "Medicacion2";
colvarMedicacion2.DataType = DbType.Int32;
colvarMedicacion2.MaxLength = 0;
colvarMedicacion2.AutoIncrement = false;
colvarMedicacion2.IsNullable = true;
colvarMedicacion2.IsPrimaryKey = false;
colvarMedicacion2.IsForeignKey = false;
colvarMedicacion2.IsReadOnly = false;
colvarMedicacion2.DefaultSetting = @"";
colvarMedicacion2.ForeignKeyTableName = "";
schema.Columns.Add(colvarMedicacion2);
TableSchema.TableColumn colvarMedicacion3 = new TableSchema.TableColumn(schema);
colvarMedicacion3.ColumnName = "Medicacion3";
colvarMedicacion3.DataType = DbType.Int32;
colvarMedicacion3.MaxLength = 0;
colvarMedicacion3.AutoIncrement = false;
colvarMedicacion3.IsNullable = true;
colvarMedicacion3.IsPrimaryKey = false;
colvarMedicacion3.IsForeignKey = false;
colvarMedicacion3.IsReadOnly = false;
colvarMedicacion3.DefaultSetting = @"";
colvarMedicacion3.ForeignKeyTableName = "";
schema.Columns.Add(colvarMedicacion3);
TableSchema.TableColumn colvarMedicacion4 = new TableSchema.TableColumn(schema);
colvarMedicacion4.ColumnName = "Medicacion4";
colvarMedicacion4.DataType = DbType.Int32;
colvarMedicacion4.MaxLength = 0;
colvarMedicacion4.AutoIncrement = false;
colvarMedicacion4.IsNullable = true;
colvarMedicacion4.IsPrimaryKey = false;
colvarMedicacion4.IsForeignKey = false;
colvarMedicacion4.IsReadOnly = false;
colvarMedicacion4.DefaultSetting = @"";
colvarMedicacion4.ForeignKeyTableName = "";
schema.Columns.Add(colvarMedicacion4);
TableSchema.TableColumn colvarMedicacion5 = new TableSchema.TableColumn(schema);
colvarMedicacion5.ColumnName = "Medicacion5";
colvarMedicacion5.DataType = DbType.Int32;
colvarMedicacion5.MaxLength = 0;
colvarMedicacion5.AutoIncrement = false;
colvarMedicacion5.IsNullable = true;
colvarMedicacion5.IsPrimaryKey = false;
colvarMedicacion5.IsForeignKey = false;
colvarMedicacion5.IsReadOnly = false;
colvarMedicacion5.DefaultSetting = @"";
colvarMedicacion5.ForeignKeyTableName = "";
schema.Columns.Add(colvarMedicacion5);
TableSchema.TableColumn colvarCaidasFrecuentes = new TableSchema.TableColumn(schema);
colvarCaidasFrecuentes.ColumnName = "CaidasFrecuentes";
colvarCaidasFrecuentes.DataType = DbType.String;
colvarCaidasFrecuentes.MaxLength = 2;
colvarCaidasFrecuentes.AutoIncrement = false;
colvarCaidasFrecuentes.IsNullable = true;
colvarCaidasFrecuentes.IsPrimaryKey = false;
colvarCaidasFrecuentes.IsForeignKey = false;
colvarCaidasFrecuentes.IsReadOnly = false;
colvarCaidasFrecuentes.DefaultSetting = @"";
colvarCaidasFrecuentes.ForeignKeyTableName = "";
schema.Columns.Add(colvarCaidasFrecuentes);
TableSchema.TableColumn colvarNeuplaciaDet = new TableSchema.TableColumn(schema);
colvarNeuplaciaDet.ColumnName = "NeuplaciaDet";
colvarNeuplaciaDet.DataType = DbType.String;
colvarNeuplaciaDet.MaxLength = 100;
colvarNeuplaciaDet.AutoIncrement = false;
colvarNeuplaciaDet.IsNullable = true;
colvarNeuplaciaDet.IsPrimaryKey = false;
colvarNeuplaciaDet.IsForeignKey = false;
colvarNeuplaciaDet.IsReadOnly = false;
colvarNeuplaciaDet.DefaultSetting = @"";
colvarNeuplaciaDet.ForeignKeyTableName = "";
schema.Columns.Add(colvarNeuplaciaDet);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("VGI_AClinicosDet",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdVGIDatos")]
[Bindable(true)]
public int IdVGIDatos
{
get { return GetColumnValue<int>(Columns.IdVGIDatos); }
set { SetColumnValue(Columns.IdVGIDatos, value); }
}
[XmlAttribute("IdVGIAClinico")]
[Bindable(true)]
public decimal IdVGIAClinico
{
get { return GetColumnValue<decimal>(Columns.IdVGIAClinico); }
set { SetColumnValue(Columns.IdVGIAClinico, value); }
}
[XmlAttribute("Ta")]
[Bindable(true)]
public string Ta
{
get { return GetColumnValue<string>(Columns.Ta); }
set { SetColumnValue(Columns.Ta, value); }
}
[XmlAttribute("Peso")]
[Bindable(true)]
public decimal? Peso
{
get { return GetColumnValue<decimal?>(Columns.Peso); }
set { SetColumnValue(Columns.Peso, value); }
}
[XmlAttribute("Talla")]
[Bindable(true)]
public decimal? Talla
{
get { return GetColumnValue<decimal?>(Columns.Talla); }
set { SetColumnValue(Columns.Talla, value); }
}
[XmlAttribute("Imc")]
[Bindable(true)]
public decimal? Imc
{
get { return GetColumnValue<decimal?>(Columns.Imc); }
set { SetColumnValue(Columns.Imc, value); }
}
[XmlAttribute("Hta")]
[Bindable(true)]
public string Hta
{
get { return GetColumnValue<string>(Columns.Hta); }
set { SetColumnValue(Columns.Hta, value); }
}
[XmlAttribute("Dbt")]
[Bindable(true)]
public string Dbt
{
get { return GetColumnValue<string>(Columns.Dbt); }
set { SetColumnValue(Columns.Dbt, value); }
}
[XmlAttribute("Dislip")]
[Bindable(true)]
public string Dislip
{
get { return GetColumnValue<string>(Columns.Dislip); }
set { SetColumnValue(Columns.Dislip, value); }
}
[XmlAttribute("Irc")]
[Bindable(true)]
public string Irc
{
get { return GetColumnValue<string>(Columns.Irc); }
set { SetColumnValue(Columns.Irc, value); }
}
[XmlAttribute("CardioIsq")]
[Bindable(true)]
public string CardioIsq
{
get { return GetColumnValue<string>(Columns.CardioIsq); }
set { SetColumnValue(Columns.CardioIsq, value); }
}
[XmlAttribute("Acv")]
[Bindable(true)]
public string Acv
{
get { return GetColumnValue<string>(Columns.Acv); }
set { SetColumnValue(Columns.Acv, value); }
}
[XmlAttribute("Amputacion")]
[Bindable(true)]
public string Amputacion
{
get { return GetColumnValue<string>(Columns.Amputacion); }
set { SetColumnValue(Columns.Amputacion, value); }
}
[XmlAttribute("Tabaquismo")]
[Bindable(true)]
public string Tabaquismo
{
get { return GetColumnValue<string>(Columns.Tabaquismo); }
set { SetColumnValue(Columns.Tabaquismo, value); }
}
[XmlAttribute("Alcoholismo")]
[Bindable(true)]
public string Alcoholismo
{
get { return GetColumnValue<string>(Columns.Alcoholismo); }
set { SetColumnValue(Columns.Alcoholismo, value); }
}
[XmlAttribute("Parkinson")]
[Bindable(true)]
public string Parkinson
{
get { return GetColumnValue<string>(Columns.Parkinson); }
set { SetColumnValue(Columns.Parkinson, value); }
}
[XmlAttribute("Demencia")]
[Bindable(true)]
public string Demencia
{
get { return GetColumnValue<string>(Columns.Demencia); }
set { SetColumnValue(Columns.Demencia, value); }
}
[XmlAttribute("Prostatismo")]
[Bindable(true)]
public string Prostatismo
{
get { return GetColumnValue<string>(Columns.Prostatismo); }
set { SetColumnValue(Columns.Prostatismo, value); }
}
[XmlAttribute("Incontinencia")]
[Bindable(true)]
public string Incontinencia
{
get { return GetColumnValue<string>(Columns.Incontinencia); }
set { SetColumnValue(Columns.Incontinencia, value); }
}
[XmlAttribute("Neuplasias")]
[Bindable(true)]
public string Neuplasias
{
get { return GetColumnValue<string>(Columns.Neuplasias); }
set { SetColumnValue(Columns.Neuplasias, value); }
}
[XmlAttribute("Otros")]
[Bindable(true)]
public string Otros
{
get { return GetColumnValue<string>(Columns.Otros); }
set { SetColumnValue(Columns.Otros, value); }
}
[XmlAttribute("Rcvg")]
[Bindable(true)]
public string Rcvg
{
get { return GetColumnValue<string>(Columns.Rcvg); }
set { SetColumnValue(Columns.Rcvg, value); }
}
[XmlAttribute("VisionConducir")]
[Bindable(true)]
public string VisionConducir
{
get { return GetColumnValue<string>(Columns.VisionConducir); }
set { SetColumnValue(Columns.VisionConducir, value); }
}
[XmlAttribute("VacunacionDT")]
[Bindable(true)]
public string VacunacionDT
{
get { return GetColumnValue<string>(Columns.VacunacionDT); }
set { SetColumnValue(Columns.VacunacionDT, value); }
}
[XmlAttribute("VacunacionHepB")]
[Bindable(true)]
public string VacunacionHepB
{
get { return GetColumnValue<string>(Columns.VacunacionHepB); }
set { SetColumnValue(Columns.VacunacionHepB, value); }
}
[XmlAttribute("VacunacionGripe")]
[Bindable(true)]
public string VacunacionGripe
{
get { return GetColumnValue<string>(Columns.VacunacionGripe); }
set { SetColumnValue(Columns.VacunacionGripe, value); }
}
[XmlAttribute("VacunacionNeumococo")]
[Bindable(true)]
public string VacunacionNeumococo
{
get { return GetColumnValue<string>(Columns.VacunacionNeumococo); }
set { SetColumnValue(Columns.VacunacionNeumococo, value); }
}
[XmlAttribute("AudicionPSeguirConv")]
[Bindable(true)]
public string AudicionPSeguirConv
{
get { return GetColumnValue<string>(Columns.AudicionPSeguirConv); }
set { SetColumnValue(Columns.AudicionPSeguirConv, value); }
}
[XmlAttribute("Medicacion1")]
[Bindable(true)]
public int? Medicacion1
{
get { return GetColumnValue<int?>(Columns.Medicacion1); }
set { SetColumnValue(Columns.Medicacion1, value); }
}
[XmlAttribute("Medicacion2")]
[Bindable(true)]
public int? Medicacion2
{
get { return GetColumnValue<int?>(Columns.Medicacion2); }
set { SetColumnValue(Columns.Medicacion2, value); }
}
[XmlAttribute("Medicacion3")]
[Bindable(true)]
public int? Medicacion3
{
get { return GetColumnValue<int?>(Columns.Medicacion3); }
set { SetColumnValue(Columns.Medicacion3, value); }
}
[XmlAttribute("Medicacion4")]
[Bindable(true)]
public int? Medicacion4
{
get { return GetColumnValue<int?>(Columns.Medicacion4); }
set { SetColumnValue(Columns.Medicacion4, value); }
}
[XmlAttribute("Medicacion5")]
[Bindable(true)]
public int? Medicacion5
{
get { return GetColumnValue<int?>(Columns.Medicacion5); }
set { SetColumnValue(Columns.Medicacion5, value); }
}
[XmlAttribute("CaidasFrecuentes")]
[Bindable(true)]
public string CaidasFrecuentes
{
get { return GetColumnValue<string>(Columns.CaidasFrecuentes); }
set { SetColumnValue(Columns.CaidasFrecuentes, value); }
}
[XmlAttribute("NeuplaciaDet")]
[Bindable(true)]
public string NeuplaciaDet
{
get { return GetColumnValue<string>(Columns.NeuplaciaDet); }
set { SetColumnValue(Columns.NeuplaciaDet, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdVGIDatos,string varTa,decimal? varPeso,decimal? varTalla,decimal? varImc,string varHta,string varDbt,string varDislip,string varIrc,string varCardioIsq,string varAcv,string varAmputacion,string varTabaquismo,string varAlcoholismo,string varParkinson,string varDemencia,string varProstatismo,string varIncontinencia,string varNeuplasias,string varOtros,string varRcvg,string varVisionConducir,string varVacunacionDT,string varVacunacionHepB,string varVacunacionGripe,string varVacunacionNeumococo,string varAudicionPSeguirConv,int? varMedicacion1,int? varMedicacion2,int? varMedicacion3,int? varMedicacion4,int? varMedicacion5,string varCaidasFrecuentes,string varNeuplaciaDet)
{
VgiAClinicosDet item = new VgiAClinicosDet();
item.IdVGIDatos = varIdVGIDatos;
item.Ta = varTa;
item.Peso = varPeso;
item.Talla = varTalla;
item.Imc = varImc;
item.Hta = varHta;
item.Dbt = varDbt;
item.Dislip = varDislip;
item.Irc = varIrc;
item.CardioIsq = varCardioIsq;
item.Acv = varAcv;
item.Amputacion = varAmputacion;
item.Tabaquismo = varTabaquismo;
item.Alcoholismo = varAlcoholismo;
item.Parkinson = varParkinson;
item.Demencia = varDemencia;
item.Prostatismo = varProstatismo;
item.Incontinencia = varIncontinencia;
item.Neuplasias = varNeuplasias;
item.Otros = varOtros;
item.Rcvg = varRcvg;
item.VisionConducir = varVisionConducir;
item.VacunacionDT = varVacunacionDT;
item.VacunacionHepB = varVacunacionHepB;
item.VacunacionGripe = varVacunacionGripe;
item.VacunacionNeumococo = varVacunacionNeumococo;
item.AudicionPSeguirConv = varAudicionPSeguirConv;
item.Medicacion1 = varMedicacion1;
item.Medicacion2 = varMedicacion2;
item.Medicacion3 = varMedicacion3;
item.Medicacion4 = varMedicacion4;
item.Medicacion5 = varMedicacion5;
item.CaidasFrecuentes = varCaidasFrecuentes;
item.NeuplaciaDet = varNeuplaciaDet;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdVGIDatos,decimal varIdVGIAClinico,string varTa,decimal? varPeso,decimal? varTalla,decimal? varImc,string varHta,string varDbt,string varDislip,string varIrc,string varCardioIsq,string varAcv,string varAmputacion,string varTabaquismo,string varAlcoholismo,string varParkinson,string varDemencia,string varProstatismo,string varIncontinencia,string varNeuplasias,string varOtros,string varRcvg,string varVisionConducir,string varVacunacionDT,string varVacunacionHepB,string varVacunacionGripe,string varVacunacionNeumococo,string varAudicionPSeguirConv,int? varMedicacion1,int? varMedicacion2,int? varMedicacion3,int? varMedicacion4,int? varMedicacion5,string varCaidasFrecuentes,string varNeuplaciaDet)
{
VgiAClinicosDet item = new VgiAClinicosDet();
item.IdVGIDatos = varIdVGIDatos;
item.IdVGIAClinico = varIdVGIAClinico;
item.Ta = varTa;
item.Peso = varPeso;
item.Talla = varTalla;
item.Imc = varImc;
item.Hta = varHta;
item.Dbt = varDbt;
item.Dislip = varDislip;
item.Irc = varIrc;
item.CardioIsq = varCardioIsq;
item.Acv = varAcv;
item.Amputacion = varAmputacion;
item.Tabaquismo = varTabaquismo;
item.Alcoholismo = varAlcoholismo;
item.Parkinson = varParkinson;
item.Demencia = varDemencia;
item.Prostatismo = varProstatismo;
item.Incontinencia = varIncontinencia;
item.Neuplasias = varNeuplasias;
item.Otros = varOtros;
item.Rcvg = varRcvg;
item.VisionConducir = varVisionConducir;
item.VacunacionDT = varVacunacionDT;
item.VacunacionHepB = varVacunacionHepB;
item.VacunacionGripe = varVacunacionGripe;
item.VacunacionNeumococo = varVacunacionNeumococo;
item.AudicionPSeguirConv = varAudicionPSeguirConv;
item.Medicacion1 = varMedicacion1;
item.Medicacion2 = varMedicacion2;
item.Medicacion3 = varMedicacion3;
item.Medicacion4 = varMedicacion4;
item.Medicacion5 = varMedicacion5;
item.CaidasFrecuentes = varCaidasFrecuentes;
item.NeuplaciaDet = varNeuplaciaDet;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdVGIDatosColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdVGIAClinicoColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn TaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn PesoColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn TallaColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn ImcColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn HtaColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn DbtColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn DislipColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn IrcColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn CardioIsqColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn AcvColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn AmputacionColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn TabaquismoColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn AlcoholismoColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn ParkinsonColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn DemenciaColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn ProstatismoColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn IncontinenciaColumn
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn NeuplasiasColumn
{
get { return Schema.Columns[19]; }
}
public static TableSchema.TableColumn OtrosColumn
{
get { return Schema.Columns[20]; }
}
public static TableSchema.TableColumn RcvgColumn
{
get { return Schema.Columns[21]; }
}
public static TableSchema.TableColumn VisionConducirColumn
{
get { return Schema.Columns[22]; }
}
public static TableSchema.TableColumn VacunacionDTColumn
{
get { return Schema.Columns[23]; }
}
public static TableSchema.TableColumn VacunacionHepBColumn
{
get { return Schema.Columns[24]; }
}
public static TableSchema.TableColumn VacunacionGripeColumn
{
get { return Schema.Columns[25]; }
}
public static TableSchema.TableColumn VacunacionNeumococoColumn
{
get { return Schema.Columns[26]; }
}
public static TableSchema.TableColumn AudicionPSeguirConvColumn
{
get { return Schema.Columns[27]; }
}
public static TableSchema.TableColumn Medicacion1Column
{
get { return Schema.Columns[28]; }
}
public static TableSchema.TableColumn Medicacion2Column
{
get { return Schema.Columns[29]; }
}
public static TableSchema.TableColumn Medicacion3Column
{
get { return Schema.Columns[30]; }
}
public static TableSchema.TableColumn Medicacion4Column
{
get { return Schema.Columns[31]; }
}
public static TableSchema.TableColumn Medicacion5Column
{
get { return Schema.Columns[32]; }
}
public static TableSchema.TableColumn CaidasFrecuentesColumn
{
get { return Schema.Columns[33]; }
}
public static TableSchema.TableColumn NeuplaciaDetColumn
{
get { return Schema.Columns[34]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdVGIDatos = @"idVGIDatos";
public static string IdVGIAClinico = @"idVGIAClinico";
public static string Ta = @"TA";
public static string Peso = @"Peso";
public static string Talla = @"Talla";
public static string Imc = @"IMC";
public static string Hta = @"HTA";
public static string Dbt = @"DBT";
public static string Dislip = @"Dislip";
public static string Irc = @"IRC";
public static string CardioIsq = @"CardioIsq";
public static string Acv = @"ACV";
public static string Amputacion = @"Amputacion";
public static string Tabaquismo = @"Tabaquismo";
public static string Alcoholismo = @"Alcoholismo";
public static string Parkinson = @"Parkinson";
public static string Demencia = @"Demencia";
public static string Prostatismo = @"Prostatismo";
public static string Incontinencia = @"Incontinencia";
public static string Neuplasias = @"Neuplasias";
public static string Otros = @"Otros";
public static string Rcvg = @"RCVG";
public static string VisionConducir = @"VisionConducir";
public static string VacunacionDT = @"VacunacionDT";
public static string VacunacionHepB = @"VacunacionHepB";
public static string VacunacionGripe = @"VacunacionGripe";
public static string VacunacionNeumococo = @"VacunacionNeumococo";
public static string AudicionPSeguirConv = @"AudicionPSeguirConv";
public static string Medicacion1 = @"Medicacion1";
public static string Medicacion2 = @"Medicacion2";
public static string Medicacion3 = @"Medicacion3";
public static string Medicacion4 = @"Medicacion4";
public static string Medicacion5 = @"Medicacion5";
public static string CaidasFrecuentes = @"CaidasFrecuentes";
public static string NeuplaciaDet = @"NeuplaciaDet";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System.Linq;
using Moq;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates;
using Xunit;
using System.Collections.ObjectModel;
using System.Collections;
namespace Avalonia.Controls.UnitTests.Presenters
{
public class CarouselPresenterTests
{
[Fact]
public void Should_Register_With_Host_When_TemplatedParent_Set()
{
var host = new Mock<IItemsPresenterHost>();
var target = new CarouselPresenter();
target.SetValue(Control.TemplatedParentProperty, host.Object);
host.Verify(x => x.RegisterItemsPresenter(target));
}
[Fact]
public void ApplyTemplate_Should_Create_Panel()
{
var target = new CarouselPresenter
{
ItemsPanel = new FuncTemplate<IPanel>(() => new Panel()),
};
target.ApplyTemplate();
Assert.IsType<Panel>(target.Panel);
}
[Fact]
public void ItemContainerGenerator_Should_Be_Picked_Up_From_TemplatedControl()
{
var parent = new TestItemsControl();
var target = new CarouselPresenter
{
[StyledElement.TemplatedParentProperty] = parent,
};
Assert.IsType<ItemContainerGenerator<TestItem>>(target.ItemContainerGenerator);
}
public class Virtualized
{
[Fact]
public void Should_Initially_Materialize_Selected_Container()
{
var target = new CarouselPresenter
{
Items = new[] { "foo", "bar" },
SelectedIndex = 0,
IsVirtualized = true,
};
target.ApplyTemplate();
AssertSingle(target);
}
[Fact]
public void Should_Initially_Materialize_Nothing_If_No_Selected_Container()
{
var target = new CarouselPresenter
{
Items = new[] { "foo", "bar" },
IsVirtualized = true,
};
target.ApplyTemplate();
Assert.Empty(target.Panel.Children);
Assert.Empty(target.ItemContainerGenerator.Containers);
}
[Fact]
public void Switching_To_Virtualized_Should_Reset_Containers()
{
var target = new CarouselPresenter
{
Items = new[] { "foo", "bar" },
SelectedIndex = 0,
IsVirtualized = false,
};
target.ApplyTemplate();
target.IsVirtualized = true;
AssertSingle(target);
}
[Fact]
public void Changing_SelectedIndex_Should_Show_Page()
{
var target = new CarouselPresenter
{
Items = new[] { "foo", "bar" },
SelectedIndex = 0,
IsVirtualized = true,
};
target.ApplyTemplate();
AssertSingle(target);
target.SelectedIndex = 1;
AssertSingle(target);
}
[Fact]
public void Should_Remove_NonCurrent_Page()
{
var target = new CarouselPresenter
{
Items = new[] { "foo", "bar" },
IsVirtualized = true,
SelectedIndex = 0,
};
target.ApplyTemplate();
AssertSingle(target);
target.SelectedIndex = 1;
AssertSingle(target);
}
[Fact]
public void Should_Handle_Inserting_Item_At_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = true,
};
target.ApplyTemplate();
items.Insert(1, "item1a");
AssertSingle(target);
}
[Fact]
public void Should_Handle_Inserting_Item_Before_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 2,
IsVirtualized = true,
};
target.ApplyTemplate();
items.Insert(1, "item1a");
AssertSingle(target);
}
[Fact]
public void Should_Do_Nothing_When_Inserting_Item_After_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = true,
};
target.ApplyTemplate();
var child = AssertSingle(target);
items.Insert(2, "after");
Assert.Same(child, AssertSingle(target));
}
[Fact]
public void Should_Handle_Removing_Item_At_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = true,
};
target.ApplyTemplate();
items.RemoveAt(1);
AssertSingle(target);
}
[Fact]
public void Should_Handle_Removing_Item_Before_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = true,
};
target.ApplyTemplate();
items.RemoveAt(0);
AssertSingle(target);
}
[Fact]
public void Should_Do_Nothing_When_Removing_Item_After_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = true,
};
target.ApplyTemplate();
var child = AssertSingle(target);
items.RemoveAt(2);
Assert.Same(child, AssertSingle(target));
}
[Fact]
public void Should_Handle_Removing_SelectedItem_When_Its_Last()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 2,
IsVirtualized = true,
};
target.ApplyTemplate();
items.RemoveAt(2);
Assert.Equal(1, target.SelectedIndex);
AssertSingle(target);
}
[Fact]
public void Should_Handle_Removing_Last_Item()
{
var items = new ObservableCollection<string>
{
"item0",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 0,
IsVirtualized = true,
};
target.ApplyTemplate();
items.RemoveAt(0);
Assert.Empty(target.Panel.Children);
Assert.Empty(target.ItemContainerGenerator.Containers);
}
[Fact]
public void Should_Handle_Replacing_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = true,
};
target.ApplyTemplate();
items[1] = "replaced";
AssertSingle(target);
}
[Fact]
public void Should_Do_Nothing_When_Replacing_Non_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = true,
};
target.ApplyTemplate();
var child = AssertSingle(target);
items[0] = "replaced";
Assert.Same(child, AssertSingle(target));
}
[Fact]
public void Should_Handle_Moving_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = true,
};
target.ApplyTemplate();
items.Move(1, 0);
AssertSingle(target);
}
private static IControl AssertSingle(CarouselPresenter target)
{
var items = (IList)target.Items;
var index = target.SelectedIndex;
var content = items[index];
var child = Assert.Single(target.Panel.Children);
var presenter = Assert.IsType<ContentPresenter>(child);
var container = Assert.Single(target.ItemContainerGenerator.Containers);
var visible = Assert.Single(target.Panel.Children.Where(x => x.IsVisible));
Assert.Same(child, container.ContainerControl);
Assert.Same(child, visible);
Assert.Equal(content, presenter.Content);
Assert.Equal(content, container.Item);
Assert.Equal(index, container.Index);
return child;
}
}
public class NonVirtualized
{
[Fact]
public void Should_Initially_Materialize_All_Containers()
{
var target = new CarouselPresenter
{
Items = new[] { "foo", "bar" },
IsVirtualized = false,
};
target.ApplyTemplate();
AssertAll(target);
}
[Fact]
public void Should_Initially_Show_Selected_Item()
{
var target = new CarouselPresenter
{
Items = new[] { "foo", "bar" },
SelectedIndex = 1,
IsVirtualized = false,
};
target.ApplyTemplate();
AssertAll(target);
}
[Fact]
public void Switching_To_Non_Virtualized_Should_Reset_Containers()
{
var target = new CarouselPresenter
{
Items = new[] { "foo", "bar" },
SelectedIndex = 0,
IsVirtualized = true,
};
target.ApplyTemplate();
target.IsVirtualized = false;
AssertAll(target);
}
[Fact]
public void Changing_SelectedIndex_Should_Show_Page()
{
var target = new CarouselPresenter
{
Items = new[] { "foo", "bar" },
SelectedIndex = 0,
IsVirtualized = false,
};
target.ApplyTemplate();
AssertAll(target);
target.SelectedIndex = 1;
AssertAll(target);
}
[Fact]
public void Should_Handle_Inserting_Item_At_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = false,
};
target.ApplyTemplate();
items.Insert(1, "item1a");
AssertAll(target);
}
[Fact]
public void Should_Handle_Inserting_Item_Before_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 2,
IsVirtualized = false,
};
target.ApplyTemplate();
items.Insert(1, "item1a");
AssertAll(target);
}
[Fact]
public void Should_Do_Handle_Inserting_Item_After_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = false,
};
target.ApplyTemplate();
items.Insert(2, "after");
AssertAll(target);
}
[Fact]
public void Should_Handle_Removing_Item_At_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = false,
};
target.ApplyTemplate();
items.RemoveAt(1);
AssertAll(target);
}
[Fact]
public void Should_Handle_Removing_Item_Before_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = false,
};
target.ApplyTemplate();
items.RemoveAt(0);
AssertAll(target);
}
[Fact]
public void Should_Handle_Removing_Item_After_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = false,
};
target.ApplyTemplate();
items.RemoveAt(2);
AssertAll(target);
}
[Fact]
public void Should_Handle_Removing_SelectedItem_When_Its_Last()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 2,
IsVirtualized = false,
};
target.ApplyTemplate();
items.RemoveAt(2);
Assert.Equal(1, target.SelectedIndex);
AssertAll(target);
}
[Fact]
public void Should_Handle_Removing_Last_Item()
{
var items = new ObservableCollection<string>
{
"item0",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 0,
IsVirtualized = false,
};
target.ApplyTemplate();
items.RemoveAt(0);
Assert.Empty(target.Panel.Children);
Assert.Empty(target.ItemContainerGenerator.Containers);
}
[Fact]
public void Should_Handle_Replacing_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = false,
};
target.ApplyTemplate();
items[1] = "replaced";
AssertAll(target);
}
[Fact]
public void Should_Handle_Moving_SelectedItem()
{
var items = new ObservableCollection<string>
{
"item0",
"item1",
"item2",
};
var target = new CarouselPresenter
{
Items = items,
SelectedIndex = 1,
IsVirtualized = false,
};
target.ApplyTemplate();
items.Move(1, 0);
AssertAll(target);
}
private static void AssertAll(CarouselPresenter target)
{
var items = (IList)target.Items;
Assert.Equal(items?.Count ?? 0, target.Panel.Children.Count);
Assert.Equal(items?.Count ?? 0, target.ItemContainerGenerator.Containers.Count());
for (var i = 0; i < items?.Count; ++i)
{
var content = items[i];
var child = target.Panel.Children[i];
var presenter = Assert.IsType<ContentPresenter>(child);
var container = target.ItemContainerGenerator.ContainerFromIndex(i);
Assert.Same(child, container);
Assert.Equal(i == target.SelectedIndex, child.IsVisible);
Assert.Equal(content, presenter.Content);
Assert.Equal(i, target.ItemContainerGenerator.IndexFromContainer(container));
}
}
}
private class TestItem : ContentControl
{
}
private class TestItemsControl : ItemsControl
{
protected override IItemContainerGenerator CreateItemContainerGenerator()
{
return new ItemContainerGenerator<TestItem>(this, TestItem.ContentProperty, null);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// IntRangePartitionerTests.cs - Tests for range partitioner for integer range.
//
// PLEASE NOTE !! - For tests that need to iterate the elements inside the partitions more
// than once, we need to call GetPartitions for the second time. Iterating a second times
// over the first enumerable<tuples> / IList<IEnumerator<tuples> will yield no elements
//
// PLEASE NOTE!! - we use lazy evaluation wherever possible to allow for more than Int32.MaxValue
// elements. ToArray / toList will result in an OOM
//
// Taken from:
// \qa\clr\testsrc\pfx\Functional\Common\Partitioner\YetiTests\RangePartitioner\IntRangePartitionerTests.cs
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public class IntRangePartitionerTests
{
/// <summary>
/// Ensure that the partitioner returned has properties set correctly
/// </summary>
[Fact]
public static void CheckKeyProperties()
{
var partitioner = Partitioner.Create(0, 1000);
Assert.True(partitioner.KeysOrderedInEachPartition, "Expected KeysOrderedInEachPartition to be set to true");
Assert.False(partitioner.KeysOrderedAcrossPartitions, "KeysOrderedAcrossPartitions to be set to false");
Assert.True(partitioner.KeysNormalized, "Expected KeysNormalized to be set to true");
partitioner = Partitioner.Create(0, 1000, 90);
Assert.True(partitioner.KeysOrderedInEachPartition, "Expected KeysOrderedInEachPartition to be set to true");
Assert.False(partitioner.KeysOrderedAcrossPartitions, "KeysOrderedAcrossPartitions to be set to false");
Assert.True(partitioner.KeysNormalized, "Expected KeysNormalized to be set to true");
}
/// <summary>
/// GetPartitions returns an IList<IEnumerator<Tuple<int, int>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// </summary>
[Fact]
public static void CheckGetPartitions()
{
CheckGetPartitions(0, 1, 1);
CheckGetPartitions(1, 1999, 3);
CheckGetPartitions(2147473647, 9999, 4);
CheckGetPartitions(-1999, 5000, 63);
CheckGetPartitions(-2147483648, 5000, 63);
}
public static void CheckGetPartitions(int from, int count, int dop)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to);
//var elements = dopPartitions.SelectMany(enumerator => enumerator.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetPartitions(dop))
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetPartitions element mismatch");
}
/// <summary>
/// CheckGetDynamicPartitions returns an IEnumerable<Tuple<int, int>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// </summary>
/// <param name="from"></param>
/// <param name="count"></param>
[Fact]
public static void CheckGetDynamicPartitions()
{
CheckGetDynamicPartitions(0, 1);
CheckGetDynamicPartitions(1, 1999);
CheckGetDynamicPartitions(2147473647, 9999);
CheckGetDynamicPartitions(-1999, 5000);
CheckGetDynamicPartitions(-2147483648, 5000);
}
public static void CheckGetDynamicPartitions(int from, int count)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to);
//var elements = partitioner.GetDynamicPartitions().SelectMany(tuple => tuple.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetDynamicPartitions())
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetDynamicPartitions Element mismatch");
}
/// <summary>
/// GetOrderablePartitions returns an IList<IEnumerator<KeyValuePair<long, Tuple<int, int>>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// Also the indices are extracted to ensure that they are ordered & normalized
/// </summary>
[Fact]
public static void CheckGetOrderablePartitions()
{
CheckGetOrderablePartitions(0, 1, 1);
CheckGetOrderablePartitions(1, 1999, 3);
CheckGetOrderablePartitions(2147473647, 9999, 4);
CheckGetOrderablePartitions(-1999, 5000, 63);
CheckGetOrderablePartitions(-2147483648, 5000, 63);
}
public static void CheckGetOrderablePartitions(int from, int count, int dop)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to);
//var elements = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetPartitions(dop))
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetOrderablePartitions Element mismatch");
//var keys = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRollIndices()).ToArray();
IList<long> keys = new List<long>();
foreach (var partition in partitioner.GetOrderablePartitions(dop))
{
foreach (var item in partition.UnRollIndices())
keys.Add(item);
}
Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderablePartitions key mismatch");
}
/// <summary>
/// GetOrderableDynamicPartitions returns an IEnumerable<KeyValuePair<long, Tuple<int, int>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// Also the indices are extracted to ensure that they are ordered & normalized
/// </summary>
[Fact]
public static void GetOrderableDynamicPartitions()
{
GetOrderableDynamicPartitions(0, 1);
GetOrderableDynamicPartitions(1, 1999);
GetOrderableDynamicPartitions(2147473647, 9999);
GetOrderableDynamicPartitions(-1999, 5000);
GetOrderableDynamicPartitions(-2147483648, 5000);
}
private static void GetOrderableDynamicPartitions(int from, int count)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to);
//var elements = partitioner.GetOrderableDynamicPartitions().SelectMany(tuple => tuple.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetOrderableDynamicPartitions())
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetOrderableDynamicPartitions Element mismatch");
//var keys = partitioner.GetOrderableDynamicPartitions().Select(tuple => tuple.Key).ToArray();
IList<long> keys = new List<long>();
foreach (var tuple in partitioner.GetOrderableDynamicPartitions())
{
keys.Add(tuple.Key);
}
Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderableDynamicPartitions key mismatch");
}
/// <summary>
/// GetPartitions returns an IList<IEnumerator<Tuple<int, int>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// This method tests the partitioner created with user provided desiredRangeSize
/// The range sizes for individual ranges are checked to see if they are equal to
/// desiredRangeSize. The last range may have less than or equal to desiredRangeSize.
/// </summary>
[Fact]
public static void CheckGetPartitionsWithRange()
{
CheckGetPartitionsWithRange(1999, 1000, 20, 1);
CheckGetPartitionsWithRange(-1999, 1000, 100, 2);
CheckGetPartitionsWithRange(1999, 1, 2000, 3);
CheckGetPartitionsWithRange(2147482647, 999, 600, 4);
CheckGetPartitionsWithRange(-2147483648, 1000, 19, 63);
}
public static void CheckGetPartitionsWithRange(int from, int count, int desiredRangeSize, int dop)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to, desiredRangeSize);
//var elements = partitioner.GetPartitions(dop).SelectMany(enumerator => enumerator.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetPartitions(dop))
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetPartitions element mismatch");
//var rangeSizes = partitioner.GetPartitions(dop).SelectMany(enumerator => enumerator.GetRangeSize()).ToArray();
IList<int> rangeSizes = new List<int>();
foreach (var partition in partitioner.GetPartitions(dop))
{
foreach (var item in partition.GetRangeSize())
rangeSizes.Add(item);
}
ValidateRangeSize(desiredRangeSize, rangeSizes);
}
/// <summary>
/// CheckGetDynamicPartitionsWithRange returns an IEnumerable<Tuple<int, int>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// This method tests the partitioner created with user provided desiredRangeSize
/// The range sizes for individual ranges are checked to see if they are equal to
/// desiredRangeSize. The last range may have less than or equal to desiredRangeSize.
/// </summary>
[Fact]
public static void CheckGetDynamicPartitionsWithRange()
{
CheckGetDynamicPartitionsWithRange(1999, 1000, 20);
CheckGetDynamicPartitionsWithRange(-1999, 1000, 100);
CheckGetDynamicPartitionsWithRange(1999, 1, 2000);
CheckGetDynamicPartitionsWithRange(2147482647, 999, 600);
CheckGetDynamicPartitionsWithRange(-2147483648, 1000, 19);
}
public static void CheckGetDynamicPartitionsWithRange(int from, int count, int desiredRangeSize)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to, desiredRangeSize);
//var elements = partitioner.GetDynamicPartitions().SelectMany(tuple => tuple.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetDynamicPartitions())
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetDynamicPartitions Element mismatch");
//var rangeSizes = partitioner.GetDynamicPartitions().Select(tuple => tuple.GetRangeSize()).ToArray();
IList<int> rangeSizes = new List<int>();
foreach (var partition in partitioner.GetDynamicPartitions())
{
rangeSizes.Add(partition.GetRangeSize());
}
ValidateRangeSize(desiredRangeSize, rangeSizes);
}
/// <summary>
/// GetOrderablePartitions returns an IList<IEnumerator<KeyValuePair<long, Tuple<int, int>>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// Also the indices are extracted to ensure that they are ordered & normalized
/// This method tests the partitioner created with user provided desiredRangeSize
/// The range sizes for individual ranges are checked to see if they are equal to
/// desiredRangeSize. The last range may have less than or equal to desiredRangeSize.
/// </summary>
[Fact]
public static void CheckGetOrderablePartitionsWithRange()
{
CheckGetOrderablePartitionsWithRange(1999, 1000, 20, 1);
CheckGetOrderablePartitionsWithRange(-1999, 1000, 100, 2);
CheckGetOrderablePartitionsWithRange(1999, 1, 2000, 3);
CheckGetOrderablePartitionsWithRange(2147482647, 999, 600, 4);
CheckGetOrderablePartitionsWithRange(-2147483648, 1000, 19, 63);
}
private static void CheckGetOrderablePartitionsWithRange(int from, int count, int desiredRangeSize, int dop)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to, desiredRangeSize);
//var elements = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetOrderablePartitions(dop))
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetOrderablePartitions Element mismatch");
//var keys = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRollIndices()).ToArray();
IList<long> keys = new List<long>();
foreach (var partition in partitioner.GetOrderablePartitions(dop))
{
foreach (var item in partition.UnRollIndices())
keys.Add(item);
}
Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderablePartitions key mismatch");
//var rangeSizes = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.GetRangeSize()).ToArray();
IList<int> rangeSizes = new List<int>();
foreach (var partition in partitioner.GetOrderablePartitions(dop))
{
foreach (var item in partition.GetRangeSize())
rangeSizes.Add(item);
}
ValidateRangeSize(desiredRangeSize, rangeSizes);
}
/// <summary>
/// GetOrderableDynamicPartitions returns an IEnumerable<KeyValuePair<long, Tuple<int, int>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// Also the indices are extracted to ensure that they are ordered & normalized
/// This method tests the partitioner created with user provided desiredRangeSize
/// The range sizes for individual ranges are checked to see if they are equal to
/// desiredRangeSize. The last range may have less than or equal to desiredRangeSize.
/// </summary>
[Fact]
public static void GetOrderableDynamicPartitionsWithRange()
{
GetOrderableDynamicPartitionsWithRange(1999, 1000, 20);
GetOrderableDynamicPartitionsWithRange(-1999, 1000, 100);
GetOrderableDynamicPartitionsWithRange(1999, 1, 2000);
GetOrderableDynamicPartitionsWithRange(2147482647, 999, 600);
GetOrderableDynamicPartitionsWithRange(-2147483648, 1000, 19);
}
private static void GetOrderableDynamicPartitionsWithRange(int from, int count, int desiredRangeSize)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to, desiredRangeSize);
//var elements = partitioner.GetOrderableDynamicPartitions().SelectMany(tuple => tuple.UnRoll());
IList<int> elements = new List<int>();
foreach (var tuple in partitioner.GetOrderableDynamicPartitions())
{
foreach (var item in tuple.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetOrderableDynamicPartitions Element mismatch");
//var keys = partitioner.GetOrderableDynamicPartitions().Select(tuple => tuple.Key).ToArray();
IList<long> keys = new List<long>();
foreach (var tuple in partitioner.GetOrderableDynamicPartitions())
{
keys.Add(tuple.Key);
}
Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderableDynamicPartitions key mismatch");
//var rangeSizes = partitioner.GetOrderableDynamicPartitions().Select(tuple => tuple.GetRangeSize()).ToArray();
IList<int> rangeSizes = new List<int>();
foreach (var partition in partitioner.GetOrderableDynamicPartitions())
{
rangeSizes.Add(partition.GetRangeSize());
}
ValidateRangeSize(desiredRangeSize, rangeSizes);
}
/// <summary>
/// Helper function to validate the the range size of the partitioners match what the user specified
/// (desiredRangeSize).
/// </summary>
/// <param name="desiredRangeSize"></param>
/// <param name="rangeSizes"></param>
public static void ValidateRangeSize(int desiredRangeSize, IList<int> rangeSizes)
{
//var rangesWithDifferentRangeSize = rangeSizes.Take(rangeSizes.Length - 1).Where(r => r != desiredRangeSize).ToArray();
IList<int> rangesWithDifferentRangeSize = new List<int>();
// ensuring that every range, size from the last one is the same.
int numToTake = rangeSizes.Count - 1;
for (int i = 0; i < numToTake; i++)
{
int range = rangeSizes[i];
if (range != desiredRangeSize)
rangesWithDifferentRangeSize.Add(range);
}
if (rangesWithDifferentRangeSize.Count != 0)
{
Console.Write("Invalid Range size: ");
foreach (var r in rangesWithDifferentRangeSize)
Console.Write("{0} ", r);
Console.WriteLine();
Assert.False(true,
String.Format("Expected all ranges (except last) to have size {0}. {1} ranges has different size", desiredRangeSize, rangesWithDifferentRangeSize));
}
var lastRange = rangeSizes[rangeSizes.Count - 1];
Assert.True(desiredRangeSize >= lastRange, String.Format("Expect={0}, Actual={1}", desiredRangeSize, lastRange));
}
[Fact]
public static void RangePartitionerChunking()
{
RangePartitionerChunking(1999, 1000, 10);
RangePartitionerChunking(89, 17823, -1);
}
/// <summary>
/// Ensure that the range partitioner doesn't chunk up elements i.e. uses chunk size = 1
/// </summary>
/// <param name="from"></param>
/// <param name="count"></param>
/// <param name="rangeSize"></param>
public static void RangePartitionerChunking(int from, int count, int rangeSize)
{
int to = from + count;
var partitioner = (rangeSize == -1) ? Partitioner.Create(from, to) : Partitioner.Create(from, to, rangeSize);
// Check static partitions
var partitions = partitioner.GetPartitions(2);
// Initialize the from / to values from the first element
if (!partitions[0].MoveNext()) return;
Assert.Equal(from, partitions[0].Current.Item1);
if (rangeSize == -1)
{
rangeSize = partitions[0].Current.Item2 - partitions[0].Current.Item1;
}
int nextExpectedFrom = partitions[0].Current.Item2;
int nextExpectedTo = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
// Ensure that each partition gets one range only
// we check this by alternating partitions asking for elements and make sure
// that we get ranges in a sequence. If chunking were to happen then we wouldn't see a sequence
int actualCount = partitions[0].Current.Item2 - partitions[0].Current.Item1;
while (true)
{
if (!partitions[0].MoveNext()) break;
Assert.Equal(nextExpectedFrom, partitions[0].Current.Item1);
Assert.Equal(nextExpectedTo, partitions[0].Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partitions[0].Current.Item2 - partitions[0].Current.Item1;
if (!partitions[1].MoveNext()) break;
Assert.Equal(nextExpectedFrom, partitions[1].Current.Item1);
Assert.Equal(nextExpectedTo, partitions[1].Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partitions[1].Current.Item2 - partitions[1].Current.Item1;
if (!partitions[1].MoveNext()) break;
Assert.Equal(nextExpectedFrom, partitions[1].Current.Item1);
Assert.Equal(nextExpectedTo, partitions[1].Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partitions[1].Current.Item2 - partitions[1].Current.Item1;
if (!partitions[0].MoveNext()) break;
Assert.Equal(nextExpectedFrom, partitions[0].Current.Item1);
Assert.Equal(nextExpectedTo, partitions[0].Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partitions[0].Current.Item2 - partitions[0].Current.Item1;
}
// Verifying that all items are there
Assert.Equal(count, actualCount);
}
[Fact]
public static void RangePartitionerDynamicChunking()
{
RangePartitionerDynamicChunking(1999, 1000, 10);
RangePartitionerDynamicChunking(1, 884354, -1);
}
/// <summary>
/// Ensure that the range partitioner doesn't chunk up elements i.e. uses chunk size = 1
/// </summary>
/// <param name="from"></param>
/// <param name="count"></param>
/// <param name="rangeSize"></param>
public static void RangePartitionerDynamicChunking(int from, int count, int rangeSize)
{
int to = from + count;
var partitioner = (rangeSize == -1) ? Partitioner.Create(from, to) : Partitioner.Create(from, to, rangeSize);
// Check static partitions
var partitions = partitioner.GetDynamicPartitions();
var partition1 = partitions.GetEnumerator();
var partition2 = partitions.GetEnumerator();
// Initialize the from / to values from the first element
if (!partition1.MoveNext()) return;
Assert.True(from == partition1.Current.Item1);
if (rangeSize == -1)
{
rangeSize = partition1.Current.Item2 - partition1.Current.Item1;
}
int nextExpectedFrom = partition1.Current.Item2;
int nextExpectedTo = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
// Ensure that each partition gets one range only
// we check this by alternating partitions asking for elements and make sure
// that we get ranges in a sequence. If chunking were to happen then we wouldn't see a sequence
int actualCount = partition1.Current.Item2 - partition1.Current.Item1;
while (true)
{
if (!partition1.MoveNext()) break;
Assert.Equal(nextExpectedFrom, partition1.Current.Item1);
Assert.Equal(nextExpectedTo, partition1.Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partition1.Current.Item2 - partition1.Current.Item1;
if (!partition2.MoveNext()) break;
Assert.Equal(nextExpectedFrom, partition2.Current.Item1);
Assert.Equal(nextExpectedTo, partition2.Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partition2.Current.Item2 - partition2.Current.Item1;
if (!partition2.MoveNext()) break;
Assert.Equal(nextExpectedFrom, partition2.Current.Item1);
Assert.Equal(nextExpectedTo, partition2.Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partition2.Current.Item2 - partition2.Current.Item1;
if (!partition1.MoveNext()) break;
Assert.Equal(nextExpectedFrom, partition1.Current.Item1);
Assert.Equal(nextExpectedTo, partition1.Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partition1.Current.Item2 - partition1.Current.Item1;
}
// Verifying that all items are there
Assert.Equal(count, actualCount);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Tracing;
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
using Microsoft.Diagnostics.Tracing.Session;
#endif
using Xunit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BasicEventSourceTests
{
/// <summary>
/// A listener can represent an out of process ETW listener (real time or not) or an EventListener
/// </summary>
public abstract class Listener : IDisposable
{
public Action<Event> OnEvent; // Called when you get events.
public abstract void Dispose();
/// <summary>
/// Send a command to an eventSource. Be careful this is async. You may wish to do a WaitForEnable
/// </summary>
public abstract void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null);
public void EventSourceSynchronousEnable(EventSource eventSource, FilteringOptions options = null)
{
EventSourceCommand(eventSource.Name, EventCommand.Enable, options);
WaitForEnable(eventSource);
}
public void WaitForEnable(EventSource logger)
{
if (!SpinWait.SpinUntil(() => logger.IsEnabled(), TimeSpan.FromSeconds(10)))
{
throw new InvalidOperationException("EventSource not enabled after 5 seconds");
}
}
internal void EnableTimer(EventSource eventSource, int pollingTime)
{
FilteringOptions options = new FilteringOptions();
options.Args = new Dictionary<string, string>();
options.Args.Add("EventCounterIntervalSec", pollingTime.ToString());
EventSourceCommand(eventSource.Name, EventCommand.Enable, options);
}
}
/// <summary>
/// Used to control what options the harness sends to the EventSource when turning it on. If not given
/// it turns on all keywords, Verbose level, and no args.
/// </summary>
public class FilteringOptions
{
public FilteringOptions() { Keywords = EventKeywords.All; Level = EventLevel.Verbose; }
public EventKeywords Keywords;
public EventLevel Level;
public IDictionary<string, string> Args;
public override string ToString()
{
return string.Format("<Options Keywords='{0}' Level'{1}' ArgsCount='{2}'",
((ulong)Keywords).ToString("x"), Level, Args.Count);
}
}
/// <summary>
/// Because events can be written to a EventListener as well as to ETW, we abstract what the result
/// of an event coming out of the pipe. Basically there are properties that fetch the name
/// and the payload values, and we subclass this for the ETW case and for the EventListener case.
/// </summary>
public abstract class Event
{
public virtual bool IsEtw { get { return false; } }
public virtual bool IsEventListener { get { return false; } }
public abstract string ProviderName { get; }
public abstract string EventName { get; }
public abstract object PayloadValue(int propertyIndex, string propertyName);
public abstract int PayloadCount { get; }
public virtual string PayloadString(int propertyIndex, string propertyName)
{
return PayloadValue(propertyIndex, propertyName).ToString();
}
public abstract IEnumerable<string> PayloadNames { get; }
#if DEBUG
/// <summary>
/// This is a convenience function for the debugger. It is not used typically
/// </summary>
public List<object> PayloadValues
{
get
{
var ret = new List<object>();
for (int i = 0; i < PayloadCount; i++)
ret.Add(PayloadValue(i, null));
return ret;
}
}
#endif
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(ProviderName).Append('/').Append(EventName).Append('(');
for (int i = 0; i < PayloadCount; i++)
{
if (i != 0)
sb.Append(',');
sb.Append(PayloadString(i, null));
}
sb.Append(')');
return sb.ToString();
}
}
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/**************************************************************************/
/* Concrete implementation of the Listener abstraction */
/// <summary>
/// Implementation of the Listener abstraction for ETW.
/// </summary>
public class EtwListener : Listener
{
internal static void EnsureStopped()
{
using (var session = new TraceEventSession("EventSourceTestSession", "EventSourceTestData.etl"))
session.Stop();
}
public EtwListener(string dataFileName = "EventSourceTestData.etl", string sessionName = "EventSourceTestSession")
{
_dataFileName = dataFileName;
// Today you have to be Admin to turn on ETW events (anyone can write ETW events).
if (TraceEventSession.IsElevated() != true)
{
throw new ApplicationException("Need to be elevated to run. ");
}
if (dataFileName == null)
{
Debug.WriteLine("Creating a real time session " + sessionName);
Task.Factory.StartNew(delegate ()
{
var session = new TraceEventSession(sessionName, dataFileName);
session.Source.AllEvents += OnEventHelper;
Debug.WriteLine("Listening for real time events");
_session = session; // Indicate that we are alive.
_session.Source.Process();
Debug.WriteLine("Real time listening stopping.");
});
SpinWait.SpinUntil(() => _session != null); // Wait for real time thread to wake up.
}
else
{
// Normalize to a full path name.
dataFileName = Path.GetFullPath(dataFileName);
Debug.WriteLine("Creating ETW data file " + Path.GetFullPath(dataFileName));
_session = new TraceEventSession(sessionName, dataFileName);
}
}
public override void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null)
{
if (command == EventCommand.Enable)
{
if (options == null)
options = new FilteringOptions();
_session.EnableProvider(eventSourceName, (TraceEventLevel)options.Level, (ulong)options.Keywords,
new TraceEventProviderOptions() { Arguments = options.Args });
}
else if (command == EventCommand.Disable)
{
_session.DisableProvider(TraceEventProviders.GetEventSourceGuidFromName(eventSourceName));
}
else
throw new NotImplementedException();
Thread.Sleep(200); // Calls are async, give them time to work.
}
public override void Dispose()
{
_session.Flush();
Thread.Sleep(1010); // Let it drain.
_session.Dispose(); // This also will kill the real time thread
if (_dataFileName != null)
{
using (var traceEventSource = new ETWTraceEventSource(_dataFileName))
{
Debug.WriteLine("Processing data file " + Path.GetFullPath(_dataFileName));
// Parse all the events as best we can, and also send unhandled events there as well.
traceEventSource.Registered.All += OnEventHelper;
traceEventSource.Dynamic.All += OnEventHelper;
traceEventSource.UnhandledEvents += OnEventHelper;
// Process all the events in the file.
traceEventSource.Process();
Debug.WriteLine("Done processing data file " + Path.GetFullPath(_dataFileName));
}
}
}
#region private
private void OnEventHelper(TraceEvent data)
{
// Ignore manifest events.
if ((int)data.ID == 0xFFFE)
return;
this.OnEvent(new EtwEvent(data));
}
/// <summary>
/// EtwEvent implements the 'Event' abstraction for ETW events (it has a TraceEvent in it)
/// </summary>
internal class EtwEvent : Event
{
public override bool IsEtw { get { return true; } }
public override string ProviderName { get { return _data.ProviderName; } }
public override string EventName { get { return _data.EventName; } }
public override object PayloadValue(int propertyIndex, string propertyName)
{
if (propertyName != null)
Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]);
return _data.PayloadValue(propertyIndex);
}
public override string PayloadString(int propertyIndex, string propertyName)
{
Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]);
return _data.PayloadString(propertyIndex);
}
public override int PayloadCount { get { return _data.PayloadNames.Length; } }
public override IEnumerable<string> PayloadNames { get { return _data.PayloadNames; } }
#region private
internal EtwEvent(TraceEvent data) { _data = data.Clone(); }
private TraceEvent _data;
#endregion
}
private string _dataFileName;
private volatile TraceEventSession _session;
#endregion
}
#endif //USE_ETW
public class EventListenerListener : Listener
{
#if false // TODO: Enable when we ship the events. GitHub issue #4865
public event EventHandler<EventSourceCreatedEventArgs> EventSourceCreated
{
add
{
if(this.m_listener != null)
{
this.m_listener.EventSourceCreated += value;
}
}
remove
{
if (this.m_listener != null)
{
this.m_listener.EventSourceCreated -= value;
}
}
}
public event EventHandler<EventWrittenEventArgs> EventWritten
{
add
{
if (this.m_listener != null)
{
this.m_listener.EventWritten += value;
}
}
remove
{
if (this.m_listener != null)
{
this.m_listener.EventWritten -= value;
}
}
}
#endif // false
public EventListenerListener(bool useEventsToListen = false)
{
#if false // TODO: enable when we ship the events. GitHub issue #4865
if (useEventsToListen)
{
m_listener = new HelperEventListener(null);
m_listener.EventSourceCreated += mListenerEventSourceCreated;
m_listener.EventWritten += mListenerEventWritten;
}
else
#endif // false
{
_listener = new HelperEventListener(this);
}
}
private void mListenerEventWritten(object sender, EventWrittenEventArgs eventData)
{
OnEvent(new EventListenerEvent(eventData));
}
#if false // TODO: enable when we ship the events. GitHub issue #4865
private void mListenerEventSourceCreated(object sender, EventSourceCreatedEventArgs eventSource)
{
if(_onEventSourceCreated != null)
{
_onEventSourceCreated(eventSource.EventSource);
}
}
#endif // false
public override void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null)
{
if (options == null)
options = new FilteringOptions();
foreach (EventSource source in EventSource.GetSources())
{
if (source.Name == eventSourceName)
{
DoCommand(source, command, options);
return;
}
}
_onEventSourceCreated += delegate (EventSource sourceBeingCreated)
{
if (eventSourceName != null && eventSourceName == sourceBeingCreated.Name)
{
DoCommand(sourceBeingCreated, command, options);
eventSourceName = null; // so we only do it once.
}
};
}
public override void Dispose()
{
_listener.Dispose();
}
#region private
private void DoCommand(EventSource source, EventCommand command, FilteringOptions options)
{
if (command == EventCommand.Enable)
_listener.EnableEvents(source, options.Level, options.Keywords, options.Args);
else if (command == EventCommand.Disable)
_listener.DisableEvents(source);
else
throw new NotImplementedException();
}
private class HelperEventListener : EventListener
{
public HelperEventListener(EventListenerListener forwardTo) { _forwardTo = forwardTo; }
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
#if false // TODO: EventListener events are not enabled in coreclr. GitHub issue #4865
base.OnEventWritten(eventData);
#endif // false
if (_forwardTo != null && _forwardTo.OnEvent != null)
{
_forwardTo.OnEvent(new EventListenerEvent(eventData));
}
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
base.OnEventSourceCreated(eventSource);
if (_forwardTo != null && _forwardTo._onEventSourceCreated != null)
_forwardTo._onEventSourceCreated(eventSource);
}
private EventListenerListener _forwardTo;
}
/// <summary>
/// EtwEvent implements the 'Event' abstraction for TraceListene events (it has a EventWrittenEventArgs in it)
/// </summary>
internal class EventListenerEvent : Event
{
public override bool IsEventListener { get { return true; } }
public override string ProviderName { get { return _data.EventSource.Name; } }
public override string EventName { get { return _data.EventName; } }
public override object PayloadValue(int propertyIndex, string propertyName)
{
if (propertyName != null)
Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]);
return _data.Payload[propertyIndex];
}
public override int PayloadCount
{
get
{
if (_data.Payload == null)
return 0;
return _data.Payload.Count;
}
}
public override IEnumerable<string> PayloadNames { get { return _data.PayloadNames; } }
#region private
internal EventListenerEvent(EventWrittenEventArgs data) { _data = data; }
private EventWrittenEventArgs _data;
#endregion
}
private EventListener _listener;
private Action<EventSource> _onEventSourceCreated;
#endregion
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System.Diagnostics.CodeAnalysis;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BytesRef = Lucene.Net.Util.BytesRef;
/// <summary>
/// Exposes flex API, merged from flex API of sub-segments.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class MultiDocsAndPositionsEnum : DocsAndPositionsEnum
{
private readonly MultiTermsEnum parent;
internal readonly DocsAndPositionsEnum[] subDocsAndPositionsEnum;
private EnumWithSlice[] subs;
internal int numSubs;
internal int upto;
internal DocsAndPositionsEnum current;
internal int currentBase;
internal int doc = -1;
/// <summary>
/// Sole constructor. </summary>
public MultiDocsAndPositionsEnum(MultiTermsEnum parent, int subReaderCount)
{
this.parent = parent;
subDocsAndPositionsEnum = new DocsAndPositionsEnum[subReaderCount];
}
/// <summary>
/// Returns <c>true</c> if this instance can be reused by
/// the provided <see cref="MultiTermsEnum"/>.
/// </summary>
public bool CanReuse(MultiTermsEnum parent)
{
return this.parent == parent;
}
/// <summary>
/// Re-use and reset this instance on the provided slices. </summary>
public MultiDocsAndPositionsEnum Reset(EnumWithSlice[] subs, int numSubs)
{
this.numSubs = numSubs;
this.subs = new EnumWithSlice[subs.Length];
for (int i = 0; i < subs.Length; i++)
{
this.subs[i] = new EnumWithSlice();
this.subs[i].DocsAndPositionsEnum = subs[i].DocsAndPositionsEnum;
this.subs[i].Slice = subs[i].Slice;
}
upto = -1;
doc = -1;
current = null;
return this;
}
/// <summary>
/// How many sub-readers we are merging. </summary>
/// <see cref="Subs"/>
public int NumSubs => numSubs;
/// <summary>
/// Returns sub-readers we are merging. </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public EnumWithSlice[] Subs => subs;
public override int Freq
{
get
{
if (Debugging.AssertsEnabled) Debugging.Assert(current != null);
return current.Freq;
}
}
public override int DocID => doc;
public override int Advance(int target)
{
if (Debugging.AssertsEnabled) Debugging.Assert(target > doc);
while (true)
{
if (current != null)
{
int doc;
if (target < currentBase)
{
// target was in the previous slice but there was no matching doc after it
doc = current.NextDoc();
}
else
{
doc = current.Advance(target - currentBase);
}
if (doc == NO_MORE_DOCS)
{
current = null;
}
else
{
return this.doc = doc + currentBase;
}
}
else if (upto == numSubs - 1)
{
return this.doc = NO_MORE_DOCS;
}
else
{
upto++;
current = subs[upto].DocsAndPositionsEnum;
currentBase = subs[upto].Slice.Start;
}
}
}
public override int NextDoc()
{
while (true)
{
if (current is null)
{
if (upto == numSubs - 1)
{
return this.doc = NO_MORE_DOCS;
}
else
{
upto++;
current = subs[upto].DocsAndPositionsEnum;
currentBase = subs[upto].Slice.Start;
}
}
int doc = current.NextDoc();
if (doc != NO_MORE_DOCS)
{
return this.doc = currentBase + doc;
}
else
{
current = null;
}
}
}
public override int NextPosition()
{
return current.NextPosition();
}
public override int StartOffset => current.StartOffset;
public override int EndOffset => current.EndOffset;
public override BytesRef GetPayload()
{
return current.GetPayload();
}
// TODO: implement bulk read more efficiently than super
/// <summary>
/// Holds a <see cref="Index.DocsAndPositionsEnum"/> along with the
/// corresponding <see cref="ReaderSlice"/>.
/// </summary>
public sealed class EnumWithSlice
{
internal EnumWithSlice()
{
}
/// <summary>
/// <see cref="Index.DocsAndPositionsEnum"/> for this sub-reader. </summary>
public DocsAndPositionsEnum DocsAndPositionsEnum { get; internal set; } // LUCENENET NOTE: Made setter internal because ctor is internal
/// <summary>
/// <see cref="ReaderSlice"/> describing how this sub-reader
/// fits into the composite reader.
/// </summary>
public ReaderSlice Slice { get; internal set; } // LUCENENET NOTE: Made setter internal because ctor is internal
public override string ToString()
{
return Slice.ToString() + ":" + DocsAndPositionsEnum;
}
}
public override long GetCost()
{
long cost = 0;
for (int i = 0; i < numSubs; i++)
{
cost += subs[i].DocsAndPositionsEnum.GetCost();
}
return cost;
}
public override string ToString()
{
return "MultiDocsAndPositionsEnum(" + Arrays.ToString(Subs) + ")";
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
function ChainToy::create( %this )
{
// Set the sandbox drag mode availability.
Sandbox.allowManipulation( pan );
Sandbox.allowManipulation( pull );
// Set the manipulation mode.
Sandbox.useManipulation( pull );
// Set the scene gravity.
SandboxScene.setGravity(0, -29.8);
// Configure the toy.
ChainToy.GroundWidth = 80;
ChainToy.ChainLinks = 25;
ChainToy.ChainCount = 2;
ChainToy.ChainLimit = true;
ChainToy.BallDensity = 4;
// Add configuration option.
addNumericOption( "Chain Links", 1, 46, 1, "setChainLinks", ChainToy.ChainLinks, true, "Sets the number of links in each chain." );
addNumericOption( "Chain Count", 1, 20, 1, "setChainCount", ChainToy.ChainCount, true, "Sets the number of chains to create." );
addFlagOption("Chain Limit", "setChainLimit", ChainToy.ChainLimit, true, "Whether to restrict the length of the chain with a rope joint or not." );
addNumericOption( "Ball Density", 1, 10, 1, "setBallDensity", ChainToy.BallDensity, true, "Sets the ball density." );
// Reset the toy initially.
ChainToy.reset();
}
//-----------------------------------------------------------------------------
function ChainToy::destroy( %this )
{
}
//-----------------------------------------------------------------------------
function ChainToy::reset(%this)
{
// Clear the scene.
SandboxScene.clear();
// Set the camera size.
SandboxWindow.setCameraSize( 40, 30 );
// Create a background.
%this.createBackground();
// Create the chains.
%chainSpacing = 2;
%chainOffset = (ChainToy.ChainCount-1) * -(%chainSpacing*0.5);
for( %n = 0; %n < ChainToy.ChainCount; %n++ )
{
%this.createChain(%chainOffset, 15);
%chainOffset += %chainSpacing;
}
// Create the ground.
%this.createGround();
}
//-----------------------------------------------------------------------------
function ChainToy::createBackground( %this )
{
// Create the sprite.
%object = new Sprite();
// Set the sprite as "static" so it is not affected by gravity.
%object.setBodyType( static );
// Always try to configure a scene-object prior to adding it to a scene for best performance.
// Set the position.
%object.Position = "0 0";
// Set the size.
%object.Size = "40 30";
// Set to the furthest background layer.
%object.SceneLayer = 31;
// Set an image.
%object.Image = "ToyAssets:jungleSky";
// Add the sprite to the scene.
SandboxScene.add( %object );
}
//-----------------------------------------------------------------------------
function ChainToy::createGround( %this )
{
// Create the ground.
%ground = new Scroller();
%ground.setBodyType("static");
%ground.Image = "ToyAssets:dirtGround";
%ground.setPosition(0, -12);
%ground.setSize(ChainToy.GroundWidth, 6);
%ground.setRepeatX(ChainToy.GroundWidth / 60);
%ground.createEdgeCollisionShape(ChainToy.GroundWidth/-2, 3, ChainToy.GroundWidth/2, 3);
// Add to the scene.
SandboxScene.add(%ground);
// Create the grass.
%grass = new Sprite();
%grass.setBodyType("static");
%grass.Image = "ToyAssets:grassForeground";
%grass.setPosition(0, -8.5);
%grass.setSize(ChainToy.GroundWidth, 2);
// Add to the scene.
SandboxScene.add(%grass);
}
//-----------------------------------------------------------------------------
function ChainToy::createChain(%this, %posX, %posY)
{
// Set-up some initial dimensions.
%linkWidth = 0.25;
%linkHeight = %linkWidth * 2;
%halfLinkHeight = %linkHeight * 0.5;
%weightSize = 1.5;
%weightHalfSize = %weightSize * 0.5;
%pivotDistance = %linkHeight * %this.ChainLinks;
// Create a fixed pivot object.
%fixedObject = new Sprite();
%fixedObject.BodyType = static;
%fixedObject.Image = "ToyAssets:chain";
%fixedObject.setPosition( %posX, %posY );
%fixedObject.setSize( %linkWidth, %linkHeight );
SandboxScene.add( %fixedObject );
// Set-up the last linked object as the fixed pivot.
%lastLinkObj = %fixedObject;
// Now add the rest of the links.
for ( %n = 1; %n <= %this.ChainLinks; %n++ )
{
// Create the link object.
%obj = new Sprite();
%obj.setImage( "ToyAssets:chain" );
%obj.setPosition( %posX, %posY - (%n*%linkHeight) );
%obj.setSize( %linkWidth, %linkHeight );
%obj.setDefaultDensity( 20 );
%obj.setDefaultFriction( 0.2 );
%obj.createPolygonBoxCollisionShape( %linkWidth, %linkHeight );
%obj.setAngularDamping( 0.1 );
%obj.setLinearDamping( 0.1 );
SandboxScene.add( %obj );
// Create a revolute joint from the last link to this one.
SandboxScene.createRevoluteJoint( %lastLinkObj, %obj, 0, -%halfLinkHeight, 0, %halfLinkHeight, false );
// Reference this link as the last link.
%lastLinkObj = %obj;
}
// Create the weight.
%weight = new Sprite();
%weight.setImage( "ToyAssets:whitesphere" );
%weight.BlendColor = DarkGreen;
%weight.setSize( %weightSize );
%weight.setPosition( %posX, %posY - %pivotDistance - %weightHalfSize );
%weight.setDefaultFriction( 0.2 );
%weight.setDefaultDensity( 1 );
%weight.createCircleCollisionShape( %weightHalfSize );
SandboxScene.add( %weight );
// Create a revolute joint from the last link to the weight.
SandboxScene.createRevoluteJoint( %lastLinkObj, %weight, 0, -%halfLinkHeight, 0, %halfLinkHeight, false );
// If the chain limit is on then create a rope join from the fixed pivot to the weight.
if ( %this.ChainLimit )
SandboxScene.createRopeJoint(%fixedObject, %weight, 0, 0, 0, %weightHalfSize, %pivotDistance, false);
}
//-----------------------------------------------------------------------------
function ChainToy::setChainLinks(%this, %value)
{
%this.ChainLinks = %value;
}
//-----------------------------------------------------------------------------
function ChainToy::setChainCount(%this, %value)
{
%this.ChainCount = %value;
}
//-----------------------------------------------------------------------------
function ChainToy::setChainLimit(%this, %value)
{
%this.ChainLimit = %value;
}
//-----------------------------------------------------------------------------
function ChainToy::setBallDensity(%this, %value)
{
%this.BallDensity = %value;
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Database_1
{
public partial class Login : Form
{
private OleDbConnection connection = new OleDbConnection();
public Login()
{
InitializeComponent();
connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=attendance.accdb;
Persist Security Info=False;";
}
private void login_Load(object sender, EventArgs e)
{
strt:
loginbtn.Enabled = false;
createbtn.Enabled = false;
changebtn.Enabled = false;
comboload();
comboload();
this.AcceptButton = loginbtn;
this.AcceptButton = createbtn;
this.AcceptButton = changebtn;
try
{
connection.Open();
status.Text = "Connected";
connection.Close();
}
catch
{
DialogResult dialogResult = MessageBox.Show("Error(s) occure during connecting to Database. \n Press YES to Try again.Press No to Exit", "Connection Problem", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
goto strt;
}
else if (dialogResult == DialogResult.No)
{
this.Close();
}
}
}
private void pass_TextChanged(object sender, EventArgs e)
{
btn_Disable();
}
private void usr_SelectedIndexChanged(object sender, EventArgs e)
{
btn_Disable();
}
private void loginbtn_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "Select * from USERS where User_Name='" + usr.Text + "' and Password='" + pass.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count++;
}
if (count >= 1)
{
this.Hide();
Main f3 = new Main();
Login f2 = new Login();
f3.Show();
f2.Close();
}
if (count < 1)
MessageBox.Show("Username or Password Incorrect.!");
connection.Close();
}
private void btn_Disable()
{
if (creatusr.Text.Length<3 || creatpass.Text == "" || creatpass.Text != confcreatpass.Text)
{
createbtn.Enabled = false;
if (creatpass.Text != "" && creatpass.Text != confcreatpass.Text)
{
this.match.ForeColor = System.Drawing.Color.Red;
match.Text = "Not Match";
}
else
{
match.Text = "";
}
}
else
{
createbtn.Enabled = true;
}
if (creatpass.Text !="" && creatpass.Text == confcreatpass.Text)
{
this.match.ForeColor = System.Drawing.Color.LimeGreen;
match.Text = "Match";
}
if (usr.Text=="" || pass.Text=="")
{
loginbtn.Enabled = false;
}
else
{
loginbtn.Enabled = true;
}
if (oldpass.Text =="" || changpass.Text == "" || changpass.Text != cnfcngpas.Text)
{
changebtn.Enabled = false;
if (changpass.Text != "" && changpass.Text != cnfcngpas.Text)
{
this.match1.ForeColor = System.Drawing.Color.Red;
match1.Text = "Not Match";
}
else
{
match1.Text = "";
}
}
else
{
changebtn.Enabled = true;
}
if (changpass.Text != "" && changpass.Text == cnfcngpas.Text)
{
this.match1.ForeColor = System.Drawing.Color.LimeGreen;
match1.Text = "Match";
}
}
private void createbtn_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "Select * from USERS where User_Name='" + creatusr.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count++;
}
connection.Close();
if (count >= 1)
{
MessageBox.Show("UserName already Exist. \n Try another user","Already Exists");
creatusr.Clear();
creatpass.Clear();
confcreatpass.Clear();
}
if (count < 1)
{
MessageBox.Show("Need Administrator Access.!","Information");
Admin f3 = new Admin();
f3.Show();
f3.FormClosed += new FormClosedEventHandler(f3_FormClosed);
}
}
catch (OleDbException ex2)
{
MessageBox.Show("Error :\n\n " + ex2, "Error");
}
finally
{
connection.Close();
}
}
void f3_FormClosed(object sender, FormClosedEventArgs e)
{
try
{
if (Admin.adminaccess == true)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "Insert into USERS values ('" + creatusr.Text + "','" + creatpass.Text + "')";
command.ExecuteNonQuery();
comboload();
MessageBox.Show("New User successfully added.!");
Admin.adminaccess = false;
}
}
catch (OleDbException ex2)
{
MessageBox.Show("Error :\n\n " + ex2, "Error");
}
finally
{
connection.Close();
}
}
private void comboload()
{
connection.Open();
OleDbDataAdapter d = new OleDbDataAdapter("select [User_Name] from USERS", connection);
DataTable dt = new DataTable();
d.Fill(dt);
usr.DataSource = dt;
usr.DisplayMember = "User_Name";
changeusr.DataSource = dt;
changeusr.DisplayMember = "User_Name";
connection.Close();
}
private void creatusr_TextChanged(object sender, EventArgs e)
{
btn_Disable();
}
private void creatpass_TextChanged(object sender, EventArgs e)
{
btn_Disable();
}
private void confcreatpass_TextChanged(object sender, EventArgs e)
{
btn_Disable();
}
private void changpass_TextChanged(object sender, EventArgs e)
{
btn_Disable();
}
private void cnfcngpas_TextChanged(object sender, EventArgs e)
{
btn_Disable();
}
private void changeusr_SelectedIndexChanged(object sender, EventArgs e)
{
btn_Disable();
}
private void changebtn_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "Update USERS set [Password]='" + changpass.Text + "' where [User_Name]='" + changeusr.Text + "' AND [Password]='" + oldpass.Text + "'";
int num1 = command.ExecuteNonQuery();
connection.Close();
if (num1 >= 1 || num1 < 0)
{
if (num1 == 1)
{
MessageBox.Show("Password change Successfully for User : " + changeusr.Text, "Successfully Changed");
}
else
{
MessageBox.Show("Somthing is Wrong..!! \n \n Contact your Administrator.", "ERROR..!!");
}
}
if (num1 == 0)
{
MessageBox.Show("Usermane or Old_Password incorrect", "Faild");
}
}
}
}
| |
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Core;
using Microsoft.WindowsAzure.Storage.Core.Auth;
using Microsoft.WindowsAzure.Storage.Core.Executor;
using Microsoft.WindowsAzure.Storage.Core.Util;
using Microsoft.WindowsAzure.Storage.File.Protocol;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.WindowsAzure.Storage.File
{
public class CloudFile : IListFileItem
{
public CloudFileClient ServiceClient
{
get; private set;
}
public int StreamWriteSizeInBytes
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
public int StreamMinimumReadSizeInBytes
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
public FileProperties Properties
{
get
{
throw new System.NotImplementedException();
}
internal set
{
throw new System.NotImplementedException();
}
}
public IDictionary<string, string> Metadata
{
get
{
throw new System.NotImplementedException();
}
}
public Uri Uri
{
get
{
throw new System.NotImplementedException();
}
}
public StorageUri StorageUri
{
get
{
throw new System.NotImplementedException();
}
}
public Uri SnapshotQualifiedUri
{
get
{
throw new System.NotImplementedException();
}
}
public StorageUri SnapshotQualifiedStorageUri
{
get
{
throw new System.NotImplementedException();
}
}
public Microsoft.WindowsAzure.Storage.Blob.CopyState CopyState
{
get
{
throw new System.NotImplementedException();
}
}
public virtual string Name
{
get; private set;
}
public CloudFileShare Share
{
get
{
throw new System.NotImplementedException();
}
}
public CloudFileDirectory Parent
{
get
{
throw new System.NotImplementedException();
}
}
public CloudFile(Uri fileAbsoluteUri)
: this(fileAbsoluteUri, (StorageCredentials) null)
{
throw new System.NotImplementedException();
}
public CloudFile(Uri fileAbsoluteUri, StorageCredentials credentials)
: this(new StorageUri(fileAbsoluteUri), credentials)
{
throw new System.NotImplementedException();
}
public CloudFile(StorageUri fileAbsoluteUri, StorageCredentials credentials)
{
throw new System.NotImplementedException();
}
internal CloudFile(StorageUri uri, string fileName, CloudFileShare share)
{
throw new System.NotImplementedException();
}
internal CloudFile(CloudFileAttributes attributes, CloudFileClient serviceClient)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<Stream> OpenReadAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<Stream> OpenReadAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<Stream> OpenReadAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<CloudFileStream> OpenWriteAsync(long? size)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<CloudFileStream> OpenWriteAsync(long? size, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<CloudFileStream> OpenWriteAsync(long? size, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task UploadFromStreamAsync(Stream source)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task UploadFromStreamAsync(Stream source, long length)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task UploadFromStreamAsync(Stream source, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task UploadFromStreamAsync(Stream source, long length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task UploadFromStreamAsync(Stream source, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task UploadFromStreamAsync(Stream source, long length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task UploadFromByteArrayAsync(byte[] buffer, int index, int count)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task UploadFromByteArrayAsync(byte[] buffer, int index, int count, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task UploadFromByteArrayAsync(byte[] buffer, int index, int count, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task UploadTextAsync(string content)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task DownloadToStreamAsync(Stream target)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task DownloadToStreamAsync(Stream target, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task DownloadToStreamAsync(Stream target, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<int> DownloadToByteArrayAsync(byte[] target, int index)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<int> DownloadToByteArrayAsync(byte[] target, int index, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<int> DownloadToByteArrayAsync(byte[] target, int index, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task DownloadRangeToStreamAsync(Stream target, long? offset, long? length)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> DownloadTextAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task DownloadRangeToStreamAsync(Stream target, long? offset, long? length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task DownloadRangeToStreamAsync(Stream target, long? offset, long? length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<int> DownloadRangeToByteArrayAsync(byte[] target, int index, long? fileOffset, long? length)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<int> DownloadRangeToByteArrayAsync(byte[] target, int index, long? fileOffset, long? length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<int> DownloadRangeToByteArrayAsync(byte[] target, int index, long? fileOffset, long? length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task CreateAsync(long size)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task CreateAsync(long size, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task CreateAsync(long size, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> ExistsAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> ExistsAsync(FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> ExistsAsync(FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task FetchAttributesAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task FetchAttributesAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task FetchAttributesAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task DeleteAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task DeleteAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task DeleteAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> DeleteIfExistsAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> DeleteIfExistsAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> DeleteIfExistsAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<IEnumerable<FileRange>> ListRangesAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<IEnumerable<FileRange>> ListRangesAsync(long? offset, long? length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<IEnumerable<FileRange>> ListRangesAsync(long? offset, long? length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task SetPropertiesAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task SetPropertiesAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task SetPropertiesAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task ResizeAsync(long size)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task ResizeAsync(long size, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task ResizeAsync(long size, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task SetMetadataAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task SetMetadataAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task SetMetadataAsync(AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task WriteRangeAsync(Stream rangeData, long startOffset, string contentMD5)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task WriteRangeAsync(Stream rangeData, long startOffset, string contentMD5, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
public virtual Task WriteRangeAsync(Stream rangeData, long startOffset, string contentMD5, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
public virtual Task ClearRangeAsync(long startOffset, long length)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task ClearRangeAsync(long startOffset, long length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task ClearRangeAsync(long startOffset, long length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> StartCopyAsync(Uri source)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> StartCopyAsync(CloudBlob source)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> StartCopyAsync(CloudFile source)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> StartCopyAsync(Uri source, AccessCondition sourceAccessCondition, AccessCondition destAccessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> StartCopyAsync(Uri source, AccessCondition sourceAccessCondition, AccessCondition destAccessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> StartCopyAsync(CloudBlob source, AccessCondition sourceAccessCondition, AccessCondition destAccessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task AbortCopyAsync(string copyId)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task AbortCopyAsync(string copyId, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task AbortCopyAsync(string copyId, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> GetFileImpl(Stream destStream, long? offset, long? length, AccessCondition accessCondition, FileRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> CreateImpl(long sizeInBytes, AccessCondition accessCondition, FileRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> FetchAttributesImpl(AccessCondition accessCondition, FileRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<bool> ExistsImpl(FileRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> DeleteFileImpl(AccessCondition accessCondition, FileRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<IEnumerable<FileRange>> ListRangesImpl(long? offset, long? length, AccessCondition accessCondition, FileRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> SetPropertiesImpl(AccessCondition accessCondition, FileRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> ResizeImpl(long sizeInBytes, AccessCondition accessCondition, FileRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> SetMetadataImpl(AccessCondition accessCondition, FileRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> PutRangeImpl(Stream rangeData, long startOffset, string contentMD5, AccessCondition accessCondition, FileRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> ClearRangeImpl(long startOffset, long length, AccessCondition accessCondition, FileRequestOptions options)
{
throw new System.NotImplementedException();
}
internal static Uri SourceFileToUri(CloudFile source)
{
throw new System.NotImplementedException();
}
internal void AssertNoSnapshot()
{
throw new System.NotImplementedException();
}
public string GetSharedAccessSignature(SharedAccessFilePolicy policy)
{
throw new System.NotImplementedException();
}
public string GetSharedAccessSignature(SharedAccessFilePolicy policy, string groupPolicyIdentifier)
{
throw new System.NotImplementedException();
}
public string GetSharedAccessSignature(SharedAccessFilePolicy policy, SharedAccessFileHeaders headers)
{
throw new System.NotImplementedException();
}
public string GetSharedAccessSignature(SharedAccessFilePolicy policy, SharedAccessFileHeaders headers, string groupPolicyIdentifier)
{
throw new System.NotImplementedException();
}
public string GetSharedAccessSignature(SharedAccessFilePolicy policy, SharedAccessFileHeaders headers, string groupPolicyIdentifier, SharedAccessProtocol? protocols, IPAddressOrRange ipAddressOrRange)
{
throw new System.NotImplementedException();
}
private string GetCanonicalName()
{
throw new System.NotImplementedException();
}
private void ParseQueryAndVerify(StorageUri address, StorageCredentials credentials)
{
throw new System.NotImplementedException();
}
}
}
| |
//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.ComponentModel;
using System.Data;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using LayersPane.Extensions;
namespace LayersPane
{
internal class LayersPaneViewModel : ViewStatePane, INotifyPropertyChanged
{
#region Private Properties
public const string ViewPaneID = "LayersPane_LayersPane";
public const string ViewDefaultPath = "LayersPaneViewModel_Pane_View_Path";
private string _path = null;
private bool _isLoading = false;
private string _status = "";
private Layer _selectedLayer;
private DataTable _dataTable;
private IReadOnlyList<Layer> _allMapLayers;
#endregion Properties
#region CTor
/// <summary>
/// Default construction - Consume the passed in CIMView. Call the base constructor to wire up the CIMView.
/// </summary>
/// <param name="view"></param>
public LayersPaneViewModel(CIMView view)
: base(view)
{
_path = view.ViewXML;
//register
LayersPaneUtils.PaneCreated(this);
//get the active map
MapView activeView = MapView.Active;
//get all the layers in the active map
_allMapLayers = activeView.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().ToList();
//set the selected layer to be the first one from the list
if (_allMapLayers.Count > 0)
_selectedLayer = _allMapLayers[0];
//set up the command for the query
QueryRowsCommand = new RelayCommand(new Action<object>(async (qry) => await QueryRows(qry)), CanQueryRows);
}
#endregion CTor
#region Public Properties
public IReadOnlyList<Layer> AllMapLayers
{
get { return _allMapLayers; }
}
public Layer SelectedLayer
{
get { return _selectedLayer; }
set
{
_selectedLayer = value;
RaisePropertyChanged();
}
}
public DataTable FeatureData
{
get { return _dataTable; }
set
{
_dataTable = value;
RaisePropertyChanged();
}
}
public bool IsLoading
{
get { return _isLoading; }
set
{
SetProperty(ref _isLoading, value, () => IsLoading);
RaisePropertyChanged();
}
}
public string Status
{
get { return _status; }
set
{
SetProperty(ref _status, value, () => Status);
RaisePropertyChanged();
}
}
public string Path
{
get { return _path == null ? ViewDefaultPath : _path; }
}
public ICommand QueryRowsCommand { get; private set; }
#endregion Public Properties
#region Private Helpers
private bool CanQueryRows()
{
return _selectedLayer != null;
}
/// <summary>
/// Execute a query against the selected layer's feature class and
/// display the resulting datatable
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
private async Task QueryRows(object query)
{
var where = string.Empty;
if (query != null) where = query.ToString();
IsLoading = true;
var rowCount = 0;
// get the features using the query
if (_selectedLayer != null)
{
await QueuedTask.Run(() =>
{
var basicFl = _selectedLayer as BasicFeatureLayer;
if (basicFl != null)
{
Table layerTable = basicFl.GetTable();
var dt = new DataTable();
var queryFilter = new ArcGIS.Core.Data.QueryFilter
{
WhereClause = where
};
RowCursor cursor;
// Use try catch to catch invalid SQL statements in queryFilter
try
{
cursor = layerTable.Search(queryFilter);
}
catch (GeodatabaseGeneralException gdbEx)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Error searching data. " + gdbEx.Message,
"Search Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
if (cursor.MoveNext())
{
var maxcols = cursor.Current.GetFields().Count() > 6
? 6
: cursor.Current.GetFields().Count();
for (var c = 0; c < maxcols; c++)
{
Type colType = typeof(string);
var format = string.Empty;
var fldDefinition = cursor.Current.GetFields()[c];
switch (fldDefinition.FieldType)
{
case FieldType.Blob:
format = "Blob";
break;
case FieldType.Raster:
format = "Raster";
break;
case FieldType.Geometry:
format = "Geom";
break;
case FieldType.Date:
colType = typeof(DateTime);
format = @"mm/dd/yyyy";
break;
case FieldType.Double:
format = "0,0.0##";
break;
case FieldType.Integer:
case FieldType.OID:
case FieldType.Single:
case FieldType.SmallInteger:
format = "0,0";
break;
case FieldType.GlobalID:
case FieldType.GUID:
case FieldType.String:
case FieldType.XML:
default:
break;
}
var col = new DataColumn(fldDefinition.Name, colType)
{
Caption = fldDefinition.AliasName
};
dt.Columns.Add(col);
}
do
{
var row = dt.NewRow();
rowCount++;
for (var colIdx = 0; colIdx < maxcols; colIdx++)
{
row[colIdx] = cursor.Current[colIdx];
}
dt.Rows.Add(row);
} while (cursor.MoveNext());
}
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
(Action)(() => UpdateDataTableOnUI(dt)));
}
});
}
Status = string.Format("{0} rows loaded", rowCount);
IsLoading = false;
}
private string GetName(ArcGIS.Core.Data.Field field)
{
return string.IsNullOrEmpty(field.AliasName) ? field.Name : field.AliasName;
}
private DataTable _dtDataTable;
/// <summary>
/// called on UI thread
/// </summary>
internal void UpdateDataTableOnUI(DataTable dt)
{
_dtDataTable = dt.Copy();
FeatureData = _dtDataTable;
}
/// <summary>
/// Must be overridden in child classes - persist the state of the view to the CIM.
/// </summary>
public override CIMView ViewState
{
get
{
var view = CreatePane();
view.InstanceID = (int)InstanceID;//from Framework.Pane
//view.InstanceIDSpecified = true;
return view;
}
}
internal static CIMView CreatePane(string path = ViewDefaultPath)
{
var view = new CIMGenericView();
view.ViewXML = path;
view.ViewType = ViewPaneID;
return view;
}
/// <summary>
/// Create a new instance of the pane.
/// </summary>
internal static LayersPaneViewModel Create()
{
var view = new CIMGenericView();
view.ViewType = ViewPaneID;
return FrameworkApplication.Panes.Create(ViewPaneID, new object[] { view }) as LayersPaneViewModel;
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion Private Helpers
#region Pane Overrides
/// <summary>
/// Called when the pane is initialized.
/// </summary>
protected async override Task InitializeAsync()
{
await base.InitializeAsync();
}
/// <summary>
/// Called when the pane is uninitialized.
/// </summary>
protected async override Task UninitializeAsync()
{
await base.UninitializeAsync();
}
#endregion Pane Overrides
}
/// <summary>
/// Button implementation to create a new instance of the pane and activate it.
/// </summary>
internal class LayersPane_OpenButton : Button
{
protected override void OnClick()
{
//LayersPaneViewModel.Create();
LayersPaneUtils.OpenPaneView(LayersPaneViewModel.ViewPaneID);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
public partial class TextReaderTests
{
protected (char[] chArr, CharArrayTextReader textReader) GetCharArray()
{
CharArrayTextReader tr = new CharArrayTextReader(TestDataProvider.CharData);
return (TestDataProvider.CharData, tr);
}
[Fact]
public void EndOfStream()
{
using (CharArrayTextReader tr = new CharArrayTextReader(TestDataProvider.SmallData))
{
var result = tr.ReadToEnd();
Assert.Equal("HELLO", result);
Assert.True(tr.EndOfStream, "End of TextReader was not true after ReadToEnd");
}
}
[Fact]
public void NotEndOfStream()
{
using (CharArrayTextReader tr = new CharArrayTextReader(TestDataProvider.SmallData))
{
char[] charBuff = new char[3];
var result = tr.Read(charBuff, 0, 3);
Assert.Equal(3, result);
Assert.Equal("HEL", new string(charBuff));
Assert.False(tr.EndOfStream, "End of TextReader was true after ReadToEnd");
}
}
[Fact]
public async Task ReadToEndAsync()
{
using (CharArrayTextReader tr = new CharArrayTextReader(TestDataProvider.LargeData))
{
var result = await tr.ReadToEndAsync();
Assert.Equal(5000, result.Length);
}
}
[Fact]
public void TestRead()
{
(char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
using (CharArrayTextReader tr = baseInfo.textReader)
{
for (int count = 0; count < baseInfo.chArr.Length; ++count)
{
int tmp = tr.Read();
Assert.Equal((int)baseInfo.chArr[count], tmp);
}
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "#23810 not fixed on .NET Framework")]
public void ReadZeroCharacters()
{
using (CharArrayTextReader tr = GetCharArray().textReader)
{
Assert.Equal(0, tr.Read(new char[0], 0, 0));
}
}
[Fact]
public void ArgumentNullOnNullArray()
{
(char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
using (CharArrayTextReader tr = baseInfo.textReader)
{
Assert.Throws<ArgumentNullException>(() => tr.Read(null, 0, 0));
}
}
[Fact]
public void ArgumentOutOfRangeOnInvalidOffset()
{
using (CharArrayTextReader tr = GetCharArray().textReader)
{
Assert.Throws<ArgumentOutOfRangeException>(() => tr.Read(new char[0], -1, 0));
}
}
[Fact]
public void ArgumentOutOfRangeOnNegativCount()
{
using (CharArrayTextReader tr = GetCharArray().textReader)
{
AssertExtensions.Throws<ArgumentException>(null, () => tr.Read(new char[0], 0, 1));
}
}
[Fact]
public void ArgumentExceptionOffsetAndCount()
{
using (CharArrayTextReader tr = GetCharArray().textReader)
{
AssertExtensions.Throws<ArgumentException>(null, () => tr.Read(new char[0], 2, 0));
}
}
[Fact]
public void EmptyInput()
{
using (CharArrayTextReader tr = new CharArrayTextReader(new char[] { }))
{
char[] buffer = new char[10];
int read = tr.Read(buffer, 0, 1);
Assert.Equal(0, read);
}
}
[Fact]
public void ReadCharArr()
{
(char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
using (CharArrayTextReader tr = baseInfo.textReader)
{
char[] chArr = new char[baseInfo.chArr.Length];
var read = tr.Read(chArr, 0, chArr.Length);
Assert.Equal(chArr.Length, read);
for (int count = 0; count < baseInfo.chArr.Length; ++count)
{
Assert.Equal(baseInfo.chArr[count], chArr[count]);
}
}
}
[Fact]
public void ReadBlockCharArr()
{
(char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
using (CharArrayTextReader tr = baseInfo.textReader)
{
char[] chArr = new char[baseInfo.chArr.Length];
var read = tr.ReadBlock(chArr, 0, chArr.Length);
Assert.Equal(chArr.Length, read);
for (int count = 0; count < baseInfo.chArr.Length; ++count)
{
Assert.Equal(baseInfo.chArr[count], chArr[count]);
}
}
}
[Fact]
public async void ReadBlockAsyncCharArr()
{
(char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
using (CharArrayTextReader tr = baseInfo.textReader)
{
char[] chArr = new char[baseInfo.chArr.Length];
var read = await tr.ReadBlockAsync(chArr, 0, chArr.Length);
Assert.Equal(chArr.Length, read);
for (int count = 0; count < baseInfo.chArr.Length; ++count)
{
Assert.Equal(baseInfo.chArr[count], chArr[count]);
}
}
}
[Fact]
public async Task ReadAsync()
{
(char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
using (CharArrayTextReader tr = baseInfo.textReader)
{
char[] chArr = new char[baseInfo.chArr.Length];
var read = await tr.ReadAsync(chArr, 4, 3);
Assert.Equal(read, 3);
for (int count = 0; count < 3; ++count)
{
Assert.Equal(baseInfo.chArr[count], chArr[count + 4]);
}
}
}
[Fact]
public void ReadLines()
{
(char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
using (CharArrayTextReader tr = baseInfo.textReader)
{
string valueString = new string(baseInfo.chArr);
var data = tr.ReadLine();
Assert.Equal(valueString.Substring(0, valueString.IndexOf('\r')), data);
data = tr.ReadLine();
Assert.Equal(valueString.Substring(valueString.IndexOf('\r') + 1, 3), data);
data = tr.ReadLine();
Assert.Equal(valueString.Substring(valueString.IndexOf('\n') + 1, 2), data);
data = tr.ReadLine();
Assert.Equal((valueString.Substring(valueString.LastIndexOf('\n') + 1)), data);
}
}
[Fact]
public void ReadLines2()
{
(char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
using (CharArrayTextReader tr = baseInfo.textReader)
{
string valueString = new string(baseInfo.chArr);
char[] temp = new char[10];
tr.Read(temp, 0, 1);
var data = tr.ReadLine();
Assert.Equal(valueString.Substring(1, valueString.IndexOf('\r') - 1), data);
}
}
[Fact]
public async Task ReadLineAsyncContinuousNewLinesAndTabs()
{
char[] newLineTabData = new char[] { '\n', '\n', '\r', '\r', '\n' };
using (CharArrayTextReader tr = new CharArrayTextReader(newLineTabData))
{
for (int count = 0; count < 4; ++count)
{
var data = await tr.ReadLineAsync();
Assert.Equal(string.Empty, data);
}
var eol = await tr.ReadLineAsync();
Assert.Null(eol);
}
}
}
}
| |
/*
Copyright 2012-2022 Marco De Salvo
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 Microsoft.VisualStudio.TestTools.UnitTesting;
using RDFSharp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
namespace RDFSharp.Test.Model
{
[TestClass]
public class RDFLessThanOrEqualsConstraintTest
{
#region Tests
[TestMethod]
public void ShouldCreateLessThanOrEqualsConstraint()
{
RDFLessThanOrEqualsConstraint LessThanOrEqualsConstraint = new RDFLessThanOrEqualsConstraint(new RDFResource("ex:prop"));
Assert.IsNotNull(LessThanOrEqualsConstraint);
Assert.IsTrue(LessThanOrEqualsConstraint.LessThanOrEqualsPredicate.Equals(new RDFResource("ex:prop")));
}
[TestMethod]
public void ShouldThrowExceptionOnCreatingLessThanOrEqualsConstraint()
=> Assert.ThrowsException<RDFModelException>(() => new RDFLessThanOrEqualsConstraint(null));
[TestMethod]
public void ShouldExportLessThanOrEqualsConstraint()
{
RDFLessThanOrEqualsConstraint LessThanOrEqualsConstraint = new RDFLessThanOrEqualsConstraint(new RDFResource("ex:prop"));
RDFGraph graph = LessThanOrEqualsConstraint.ToRDFGraph(new RDFNodeShape(new RDFResource("ex:NodeShape")));
Assert.IsNotNull(graph);
Assert.IsTrue(graph.TriplesCount == 1);
Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape"))
&& t.Value.Predicate.Equals(RDFVocabulary.SHACL.LESS_THAN_OR_EQUALS)
&& t.Value.Object.Equals(new RDFResource("ex:prop"))));
}
//NS-CONFORMS:TRUE
[TestMethod]
public void ShouldConformNodeShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
nodeShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.KNOWS));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformNodeShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
nodeShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.KNOWS));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformNodeShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.RDF.TYPE));
nodeShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.KNOWS));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformNodeShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.KNOWS));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
//PS-CONFORMS:TRUE
[TestMethod]
public void ShouldConformPropertyShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
propertyShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
propertyShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.INTEREST, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.INTEREST);
propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.INTEREST, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.INTEREST);
propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
//NS-CONFORMS:FALSE
[TestMethod]
public void ShouldNotConformNodeShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
nodeShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.LESS_THAN_OR_EQUALS_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob")));
nodeShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.LESS_THAN_OR_EQUALS_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.RDF.TYPE));
nodeShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.LESS_THAN_OR_EQUALS_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.LESS_THAN_OR_EQUALS_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
//PS-CONFORMS:FALSE
[TestMethod]
public void ShouldNotConformPropertyShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
propertyShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral($"Must have values less than or equals to values of property <{RDFVocabulary.FOAF.AGENT}>")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Steve")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.LESS_THAN_OR_EQUALS_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob")));
propertyShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral($"Must have values less than or equals to values of property <{RDFVocabulary.FOAF.AGENT}>")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Steve")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.LESS_THAN_OR_EQUALS_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.RDF.TYPE));
propertyShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral($"Must have values less than or equals to values of property <{RDFVocabulary.FOAF.AGENT}>")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Steve")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.LESS_THAN_OR_EQUALS_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFLessThanOrEqualsConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral($"Must have values less than or equals to values of property <{RDFVocabulary.FOAF.AGENT}>")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Steve")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.LESS_THAN_OR_EQUALS_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
//MIXED-CONFORMS:TRUE
[TestMethod]
public void ShouldConformNodeShapeWithPropertyShape()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Event1"), new RDFResource("ex:startDate"), new RDFTypedLiteral("1990-12-12", RDFModelEnums.RDFDatatypes.XSD_DATE)));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Event1"), new RDFResource("ex:endDate"), new RDFTypedLiteral("1999-10-12", RDFModelEnums.RDFDatatypes.XSD_DATE)));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Event2"), new RDFResource("ex:startDate"), new RDFTypedLiteral("1992-01-04", RDFModelEnums.RDFDatatypes.XSD_DATE)));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Event2"), new RDFResource("ex:endDate"), new RDFTypedLiteral("1992-01-04", RDFModelEnums.RDFDatatypes.XSD_DATE)));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Event1")));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Event2")));
RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:startDate"));
propShape.AddConstraint(new RDFLessThanOrEqualsConstraint(new RDFResource("ex:endDate")));
nodeShape.AddConstraint(new RDFPropertyConstraint(propShape));
shapesGraph.AddShape(nodeShape);
shapesGraph.AddShape(propShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
//MIXED-CONFORMS:FALSE
[TestMethod]
public void ShouldNotConformNodeShapeWithPropertyShape()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Event1"), new RDFResource("ex:startDate"), new RDFTypedLiteral("1990-12-12", RDFModelEnums.RDFDatatypes.XSD_DATE)));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Event1"), new RDFResource("ex:endDate"), new RDFTypedLiteral("1999-10-12", RDFModelEnums.RDFDatatypes.XSD_DATE)));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Event2"), new RDFResource("ex:startDate"), new RDFTypedLiteral("1992-01-04", RDFModelEnums.RDFDatatypes.XSD_DATE)));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Event2"), new RDFResource("ex:endDate"), new RDFTypedLiteral("1989-10-07", RDFModelEnums.RDFDatatypes.XSD_DATE)));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Event1")));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Event2")));
RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:startDate"));
propShape.AddConstraint(new RDFLessThanOrEqualsConstraint(new RDFResource("ex:endDate")));
nodeShape.AddConstraint(new RDFPropertyConstraint(propShape));
shapesGraph.AddShape(nodeShape);
shapesGraph.AddShape(propShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral($"Must have values less than or equals to values of property <ex:endDate>")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Event2")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFTypedLiteral("1992-01-04", RDFModelEnums.RDFDatatypes.XSD_DATE)));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(new RDFResource("ex:startDate")));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.LESS_THAN_OR_EQUALS_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropShape")));
}
#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.Linq.Impl
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
/// <summary>
/// MethodCall expression visitor.
/// </summary>
internal static class MethodVisitor
{
/// <summary> Property visitors. </summary>
private static readonly Dictionary<MemberInfo, string> Properties = new Dictionary<MemberInfo, string>
{
// ReSharper disable AssignNullToNotNullAttribute
{typeof(string).GetProperty("Length"), "length"},
{typeof(DateTime).GetProperty("Year"), "year"},
{typeof(DateTime).GetProperty("Month"), "month"},
{typeof(DateTime).GetProperty("Day"), "day_of_month"},
{typeof(DateTime).GetProperty("DayOfYear"), "day_of_year"},
{typeof(DateTime).GetProperty("DayOfWeek"), "-1 + day_of_week"},
{typeof(DateTime).GetProperty("Hour"), "hour"},
{typeof(DateTime).GetProperty("Minute"), "minute"},
{typeof(DateTime).GetProperty("Second"), "second"}
// ReSharper restore AssignNullToNotNullAttribute
};
/// <summary> Method visit delegate. </summary>
private delegate void VisitMethodDelegate(MethodCallExpression expression, CacheQueryExpressionVisitor visitor);
/// <summary>
/// Delegates dictionary.
/// </summary>
private static readonly Dictionary<MethodInfo, VisitMethodDelegate> Delegates = new List
<KeyValuePair<MethodInfo, VisitMethodDelegate>>
{
GetStringMethod("ToLower", new Type[0], GetFunc("lower")),
GetStringMethod("ToUpper", new Type[0], GetFunc("upper")),
GetStringMethod("Contains", new[] {typeof (string)}, (e, v) => VisitSqlLike(e, v, "'%' || ? || '%'")),
GetStringMethod("StartsWith", new[] {typeof (string)}, (e, v) => VisitSqlLike(e, v, "? || '%'")),
GetStringMethod("EndsWith", new[] {typeof (string)}, (e, v) => VisitSqlLike(e, v, "'%' || ?")),
GetStringMethod("IndexOf", new[] {typeof (string)}, GetFunc("instr", -1)),
GetStringMethod("IndexOf", new[] {typeof (string), typeof (int)}, GetFunc("instr", -1)),
GetStringMethod("Substring", new[] {typeof (int)}, GetFunc("substring", 0, 1)),
GetStringMethod("Substring", new[] {typeof (int), typeof (int)}, GetFunc("substring", 0, 1)),
GetStringMethod("Trim", "trim"),
GetParameterizedTrimMethod("Trim", "trim"),
GetParameterizedTrimMethod("TrimStart", "ltrim"),
GetParameterizedTrimMethod("TrimEnd", "rtrim"),
GetCharTrimMethod("Trim", "trim"),
GetCharTrimMethod("TrimStart", "ltrim"),
GetCharTrimMethod("TrimEnd", "rtrim"),
GetStringMethod("Replace", "replace", typeof(string), typeof(string)),
GetStringMethod("PadLeft", "lpad", typeof (int)),
GetStringMethod("PadLeft", "lpad", typeof (int), typeof (char)),
GetStringMethod("PadRight", "rpad", typeof (int)),
GetStringMethod("PadRight", "rpad", typeof (int), typeof (char)),
GetStringMethod("Compare", new[] { typeof(string), typeof(string) }, (e, v) => VisitStringCompare(e, v, false)),
GetStringMethod("Compare", new[] { typeof(string), typeof(string), typeof(bool) }, (e, v) => VisitStringCompare(e, v, GetStringCompareIgnoreCaseParameter(e.Arguments[2]))),
GetRegexMethod("Replace", "regexp_replace", typeof (string), typeof (string), typeof (string)),
GetRegexMethod("Replace", "regexp_replace", typeof (string), typeof (string), typeof (string),
typeof(RegexOptions)),
GetRegexMethod("IsMatch", "regexp_like", typeof (string), typeof (string)),
GetRegexMethod("IsMatch", "regexp_like", typeof (string), typeof (string), typeof(RegexOptions)),
GetMethod(typeof (DateTime), "ToString", new[] {typeof (string)},
(e, v) => VisitFunc(e, v, "formatdatetime", ", 'en', 'UTC'")),
GetMathMethod("Abs", typeof (int)),
GetMathMethod("Abs", typeof (long)),
GetMathMethod("Abs", typeof (float)),
GetMathMethod("Abs", typeof (double)),
GetMathMethod("Abs", typeof (decimal)),
GetMathMethod("Abs", typeof (sbyte)),
GetMathMethod("Abs", typeof (short)),
GetMathMethod("Acos", typeof (double)),
GetMathMethod("Asin", typeof (double)),
GetMathMethod("Atan", typeof (double)),
GetMathMethod("Atan2", typeof (double), typeof (double)),
GetMathMethod("Ceiling", typeof (double)),
GetMathMethod("Ceiling", typeof (decimal)),
GetMathMethod("Cos", typeof (double)),
GetMathMethod("Cosh", typeof (double)),
GetMathMethod("Exp", typeof (double)),
GetMathMethod("Floor", typeof (double)),
GetMathMethod("Floor", typeof (decimal)),
GetMathMethod("Log", typeof (double)),
GetMathMethod("Log10", typeof (double)),
GetMathMethod("Pow", "Power", typeof (double), typeof (double)),
GetMathMethod("Round", typeof (double)),
GetMathMethod("Round", typeof (double), typeof (int)),
GetMathMethod("Round", typeof (decimal)),
GetMathMethod("Round", typeof (decimal), typeof (int)),
GetMathMethod("Sign", typeof (double)),
GetMathMethod("Sign", typeof (decimal)),
GetMathMethod("Sign", typeof (float)),
GetMathMethod("Sign", typeof (int)),
GetMathMethod("Sign", typeof (long)),
GetMathMethod("Sign", typeof (short)),
GetMathMethod("Sign", typeof (sbyte)),
GetMathMethod("Sin", typeof (double)),
GetMathMethod("Sinh", typeof (double)),
GetMathMethod("Sqrt", typeof (double)),
GetMathMethod("Tan", typeof (double)),
GetMathMethod("Tanh", typeof (double)),
GetMathMethod("Truncate", typeof (double)),
GetMathMethod("Truncate", typeof (decimal)),
}
.Where(x => x.Key != null)
.ToDictionary(x => x.Key, x => x.Value);
/// <summary> RegexOptions transformations. </summary>
private static readonly Dictionary<RegexOptions, string> RegexOptionFlags = new Dictionary<RegexOptions, string>
{
{ RegexOptions.IgnoreCase, "i" },
{ RegexOptions.Multiline, "m" }
};
/// <summary>
/// Visits the property call expression.
/// </summary>
public static bool VisitPropertyCall(MemberExpression expression, CacheQueryExpressionVisitor visitor)
{
string funcName;
if (!Properties.TryGetValue(expression.Member, out funcName))
return false;
visitor.ResultBuilder.Append(funcName).Append('(');
visitor.Visit(expression.Expression);
visitor.ResultBuilder.Append(')');
return true;
}
/// <summary>
/// Visits the method call expression.
/// </summary>
public static void VisitMethodCall(MethodCallExpression expression, CacheQueryExpressionVisitor visitor)
{
var mtd = expression.Method;
VisitMethodDelegate del;
if (!Delegates.TryGetValue(mtd, out del))
throw new NotSupportedException(string.Format("Method not supported: {0}.({1})",
mtd.DeclaringType == null ? "static" : mtd.DeclaringType.FullName, mtd));
del(expression, visitor);
}
/// <summary>
/// Visits the constant call expression.
/// </summary>
public static bool VisitConstantCall(ConstantExpression expression, CacheQueryExpressionVisitor visitor)
{
if (expression.Type != typeof(RegexOptions))
{
return false;
}
var regexOptions = expression.Value as RegexOptions? ?? RegexOptions.None;
var result = string.Empty;
foreach (var option in RegexOptionFlags)
{
if (regexOptions.HasFlag(option.Key))
{
result += option.Value;
regexOptions &= ~option.Key;
}
}
if (regexOptions != RegexOptions.None)
{
throw new NotSupportedException(string.Format("RegexOptions.{0} is not supported", regexOptions));
}
visitor.AppendParameter(result);
return true;
}
/// <summary>
/// Gets the function.
/// </summary>
private static VisitMethodDelegate GetFunc(string func, params int[] adjust)
{
return (e, v) => VisitFunc(e, v, func, null, adjust);
}
/// <summary>
/// Visits the instance function.
/// </summary>
private static void VisitFunc(MethodCallExpression expression, CacheQueryExpressionVisitor visitor,
string func, string suffix, params int[] adjust)
{
visitor.ResultBuilder.Append(func).Append('(');
var isInstanceMethod = expression.Object != null;
if (isInstanceMethod)
visitor.Visit(expression.Object);
for (int i= 0; i < expression.Arguments.Count; i++)
{
var arg = expression.Arguments[i];
if (isInstanceMethod || (i > 0))
visitor.ResultBuilder.Append(", ");
visitor.Visit(arg);
AppendAdjustment(visitor, adjust, i + 1);
}
visitor.ResultBuilder.Append(suffix).Append(')');
AppendAdjustment(visitor, adjust, 0);
}
/// <summary>
/// Visits the instance function for Trim specific handling.
/// </summary>
private static void VisitParameterizedTrimFunc(MethodCallExpression expression,
CacheQueryExpressionVisitor visitor, string func)
{
visitor.ResultBuilder.Append(func).Append('(');
visitor.Visit(expression.Object);
var arg = expression.Arguments[0];
if (arg != null)
{
visitor.ResultBuilder.Append(", ");
if (arg.NodeType == ExpressionType.Constant)
{
var constant = (ConstantExpression) arg;
if (constant.Value is char)
{
visitor.AppendParameter((char) constant.Value);
}
else
{
var args = constant.Value as IEnumerable<char>;
if (args == null)
{
throw new NotSupportedException("String.Trim function only supports IEnumerable<char>");
}
var enumeratedArgs = args.ToArray();
if (enumeratedArgs.Length != 1)
{
throw new NotSupportedException("String.Trim function only supports a single argument: " +
expression);
}
visitor.AppendParameter(enumeratedArgs[0]);
}
}
else
{
visitor.Visit(arg);
}
}
visitor.ResultBuilder.Append(')');
}
/// <summary>
/// Appends the adjustment.
/// </summary>
private static void AppendAdjustment(CacheQueryExpressionVisitor visitor, int[] adjust, int idx)
{
if (idx < adjust.Length)
{
var delta = adjust[idx];
if (delta > 0)
visitor.ResultBuilder.AppendFormat(" + {0}", delta);
else if (delta < 0)
visitor.ResultBuilder.AppendFormat(" {0}", delta);
}
}
/// <summary>
/// Visits the SQL like expression.
/// </summary>
private static void VisitSqlLike(MethodCallExpression expression, CacheQueryExpressionVisitor visitor,
string likeFormat)
{
visitor.ResultBuilder.Append('(');
visitor.Visit(expression.Object);
visitor.ResultBuilder.AppendFormat(" like {0}) ", likeFormat);
var arg = expression.Arguments[0] as ConstantExpression;
var paramValue = arg != null
? arg.Value
: ExpressionWalker.EvaluateExpression<object>(expression.Arguments[0]);
visitor.Parameters.Add(paramValue);
}
/// <summary>
/// Get IgnoreCase parameter for string.Compare method
/// </summary>
private static bool GetStringCompareIgnoreCaseParameter(Expression expression)
{
var constant = expression as ConstantExpression;
if (constant != null)
{
if (constant.Value is bool)
{
return (bool)constant.Value;
}
}
throw new NotSupportedException(
"Parameter 'ignoreCase' from 'string.Compare method should be specified as a constant expression");
}
/// <summary>
/// Visits string.Compare method
/// </summary>
private static void VisitStringCompare(MethodCallExpression expression, CacheQueryExpressionVisitor visitor, bool ignoreCase)
{
// Ex: nvl2(?, casewhen(_T0.NAME = ?, 0, casewhen(_T0.NAME >= ?, 1, -1)), 1)
visitor.ResultBuilder.Append("nvl2(");
visitor.Visit(expression.Arguments[1]);
visitor.ResultBuilder.Append(", casewhen(");
VisitArg(visitor, expression, 0, ignoreCase);
visitor.ResultBuilder.Append(" = ");
VisitArg(visitor, expression, 1, ignoreCase);
visitor.ResultBuilder.Append(", 0, casewhen(");
VisitArg(visitor, expression, 0, ignoreCase);
visitor.ResultBuilder.Append(" >= ");
VisitArg(visitor, expression, 1, ignoreCase);
visitor.ResultBuilder.Append(", 1, -1)), 1)");
}
/// <summary>
/// Visits member expression argument.
/// </summary>
private static void VisitArg(CacheQueryExpressionVisitor visitor, MethodCallExpression expression, int idx,
bool lower)
{
if (lower)
visitor.ResultBuilder.Append("lower(");
visitor.Visit(expression.Arguments[idx]);
if (lower)
visitor.ResultBuilder.Append(')');
}
/// <summary>
/// Gets the method.
/// </summary>
private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetMethod(Type type, string name,
Type[] argTypes = null, VisitMethodDelegate del = null)
{
var method = argTypes == null ? type.GetMethod(name) : type.GetMethod(name, argTypes);
return new KeyValuePair<MethodInfo, VisitMethodDelegate>(method, del ?? GetFunc(name));
}
/// <summary>
/// Gets the string method.
/// </summary>
private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetStringMethod(string name,
Type[] argTypes = null, VisitMethodDelegate del = null)
{
return GetMethod(typeof(string), name, argTypes, del);
}
/// <summary>
/// Gets the string method.
/// </summary>
private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetStringMethod(string name, string sqlName,
params Type[] argTypes)
{
return GetMethod(typeof(string), name, argTypes, GetFunc(sqlName));
}
/// <summary>
/// Gets the Regex method.
/// </summary>
private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetRegexMethod(string name, string sqlName,
params Type[] argTypes)
{
return GetMethod(typeof(Regex), name, argTypes, GetFunc(sqlName));
}
/// <summary>
/// Gets string parameterized Trim(TrimStart, TrimEnd) method.
/// </summary>
private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetParameterizedTrimMethod(string name,
string sqlName)
{
return GetMethod(typeof(string), name, new[] {typeof(char[])},
(e, v) => VisitParameterizedTrimFunc(e, v, sqlName));
}
/// <summary>
/// Gets string parameterized Trim(TrimStart, TrimEnd) method that takes a single char.
/// </summary>
private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetCharTrimMethod(string name,
string sqlName)
{
return GetMethod(typeof(string), name, new[] {typeof(char)},
(e, v) => VisitParameterizedTrimFunc(e, v, sqlName));
}
/// <summary>
/// Gets the math method.
/// </summary>
private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetMathMethod(string name, string sqlName,
params Type[] argTypes)
{
return GetMethod(typeof(Math), name, argTypes, GetFunc(sqlName));
}
/// <summary>
/// Gets the math method.
/// </summary>
private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetMathMethod(string name, params Type[] argTypes)
{
return GetMathMethod(name, name, argTypes);
}
}
}
| |
using System;
using NLog;
namespace SqlServerCacheClient.Logging
{
internal class NlogWrapper : ILogger
{
protected readonly NLog.Logger logger;
public NlogWrapper(Type type)
{
logger = NLog.LogManager.GetLogger(type.Name, type);
}
public bool IsDebugEnabled
{
get { return logger.IsDebugEnabled; }
}
public bool IsErrorEnabled
{
get { return logger.IsErrorEnabled; }
}
public bool IsFatalEnabled
{
get { return IsFatalEnabled; }
}
public bool IsInfoEnabled
{
get { return IsInfoEnabled; }
}
public bool IsWarnEnabled
{
get { return IsWarnEnabled; }
}
public void SetVerbosity(LoggingVerbosity verbosity)
{
var logLevel = LogLevel.Off;
switch (verbosity)
{
case LoggingVerbosity.Debug:
logLevel = LogLevel.Debug;
break;
case LoggingVerbosity.Info:
logLevel = LogLevel.Info;
break;
case LoggingVerbosity.Warn:
logLevel = LogLevel.Warn;
break;
case LoggingVerbosity.Error:
logLevel = LogLevel.Error;
break;
case LoggingVerbosity.Fatal:
logLevel = LogLevel.Fatal;
break;
}
foreach (var rule in NLog.LogManager.Configuration.LoggingRules)
{
rule.EnableLoggingForLevel(logLevel);
}
NLog.LogManager.ReconfigExistingLoggers();
}
public void Debug(object message)
{
logger.Debug(message);
}
public void Debug(object message, Exception exception)
{
//nlog v2 - v3
//logger.Debug(message.ToString(), exception);
//nlog v4
logger.Debug(exception, message.ToString());
}
public void DebugFormat(string format, params object[] args)
{
logger.Debug(format, args);
}
public void DebugFormat(string format, object arg0)
{
logger.Debug(format, arg0);
}
public void DebugFormat(string format, object arg0, object arg1)
{
logger.Debug(format, arg0, arg1);
}
public void DebugFormat(string format, object arg0, object arg1, object arg2)
{
logger.Debug(format, arg0, arg1, arg2);
}
public void DebugFormat(IFormatProvider provider, string format, params object[] args)
{
logger.Debug(provider, format, args);
}
public void Info(object message)
{
logger.Info(message);
}
public void Info(object message, Exception exception)
{
//nlog v2 - v3
//logger.Info(message.ToString(), exception);
//nlog v4
logger.Info(exception, message.ToString());
}
public void InfoFormat(string format, params object[] args)
{
logger.Info(format, args);
}
public void InfoFormat(string format, object arg0)
{
logger.Info(format, arg0);
}
public void InfoFormat(string format, object arg0, object arg1)
{
logger.Info(format, arg0, arg1);
}
public void InfoFormat(string format, object arg0, object arg1, object arg2)
{
logger.Info(format, arg0, arg1, arg2);
}
public void InfoFormat(IFormatProvider provider, string format, params object[] args)
{
logger.Info(provider, format, args);
}
public void Warn(object message)
{
logger.Warn(message);
}
public void Warn(object message, Exception exception)
{
//nlog v2 - v3
//logger.Warn(message.ToString(), exception);
//nlog v4
logger.Warn(exception, message.ToString());
}
public void WarnFormat(string format, params object[] args)
{
logger.Warn(format, args);
}
public void WarnFormat(string format, object arg0)
{
logger.Warn(format, arg0);
}
public void WarnFormat(string format, object arg0, object arg1)
{
logger.Warn(format, arg0, arg1);
}
public void WarnFormat(string format, object arg0, object arg1, object arg2)
{
logger.Warn(format, arg0, arg1, arg2);
}
public void WarnFormat(IFormatProvider provider, string format, params object[] args)
{
logger.Warn(provider, format, args);
}
public void Error(object message)
{
logger.Error(message);
}
public void Error(object message, Exception exception)
{
//nlog v2 - v3
//logger.Error(message.ToString(), exception);
//nlog v4
logger.Error(exception, message.ToString());
}
public void ErrorFormat(string format, params object[] args)
{
logger.Error(format, args);
}
public void ErrorFormat(string format, object arg0)
{
logger.Error(format, arg0);
}
public void ErrorFormat(string format, object arg0, object arg1)
{
logger.Error(format, arg0, arg1);
}
public void ErrorFormat(string format, object arg0, object arg1, object arg2)
{
logger.Error(format, arg0, arg1, arg2);
}
public void ErrorFormat(IFormatProvider provider, string format, params object[] args)
{
logger.Error(provider, format, args);
}
public void Fatal(object message)
{
logger.Fatal(message);
}
public void Fatal(object message, Exception exception)
{
//nlog v2 - v3
//logger.Fatal(message.ToString(), exception);
//nlog v4
logger.Fatal(exception, message.ToString());
}
public void FatalFormat(string format, params object[] args)
{
logger.Fatal(format, args);
}
public void FatalFormat(string format, object arg0)
{
logger.Fatal(format, arg0);
}
public void FatalFormat(string format, object arg0, object arg1)
{
logger.Fatal(format, arg0, arg1);
}
public void FatalFormat(string format, object arg0, object arg1, object arg2)
{
logger.Fatal(format, arg0, arg1, arg2);
}
public void FatalFormat(IFormatProvider provider, string format, params object[] args)
{
logger.Fatal(provider, format, args);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>AdGroupAdLabel</c> resource.</summary>
public sealed partial class AdGroupAdLabelName : gax::IResourceName, sys::IEquatable<AdGroupAdLabelName>
{
/// <summary>The possible contents of <see cref="AdGroupAdLabelName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>
/// .
/// </summary>
CustomerAdGroupAdLabel = 1,
}
private static gax::PathTemplate s_customerAdGroupAdLabel = new gax::PathTemplate("customers/{customer_id}/adGroupAdLabels/{ad_group_id_ad_id_label_id}");
/// <summary>Creates a <see cref="AdGroupAdLabelName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AdGroupAdLabelName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AdGroupAdLabelName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AdGroupAdLabelName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AdGroupAdLabelName"/> with the pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AdGroupAdLabelName"/> constructed from the provided ids.</returns>
public static AdGroupAdLabelName FromCustomerAdGroupAdLabel(string customerId, string adGroupId, string adId, string labelId) =>
new AdGroupAdLabelName(ResourceNameType.CustomerAdGroupAdLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), adId: gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupAdLabelName"/> with pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdGroupAdLabelName"/> with pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </returns>
public static string Format(string customerId, string adGroupId, string adId, string labelId) =>
FormatCustomerAdGroupAdLabel(customerId, adGroupId, adId, labelId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupAdLabelName"/> with pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdGroupAdLabelName"/> with pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </returns>
public static string FormatCustomerAdGroupAdLabel(string customerId, string adGroupId, string adId, string labelId) =>
s_customerAdGroupAdLabel.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="AdGroupAdLabelName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adGroupAdLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AdGroupAdLabelName"/> if successful.</returns>
public static AdGroupAdLabelName Parse(string adGroupAdLabelName) => Parse(adGroupAdLabelName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AdGroupAdLabelName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupAdLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AdGroupAdLabelName"/> if successful.</returns>
public static AdGroupAdLabelName Parse(string adGroupAdLabelName, bool allowUnparsed) =>
TryParse(adGroupAdLabelName, allowUnparsed, out AdGroupAdLabelName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdGroupAdLabelName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adGroupAdLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdGroupAdLabelName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adGroupAdLabelName, out AdGroupAdLabelName result) =>
TryParse(adGroupAdLabelName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdGroupAdLabelName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupAdLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdGroupAdLabelName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adGroupAdLabelName, bool allowUnparsed, out AdGroupAdLabelName result)
{
gax::GaxPreconditions.CheckNotNull(adGroupAdLabelName, nameof(adGroupAdLabelName));
gax::TemplatedResourceName resourceName;
if (s_customerAdGroupAdLabel.TryParseName(adGroupAdLabelName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerAdGroupAdLabel(resourceName[0], split1[0], split1[1], split1[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(adGroupAdLabelName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private AdGroupAdLabelName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adId = null, string adGroupId = null, string customerId = null, string labelId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AdId = adId;
AdGroupId = adGroupId;
CustomerId = customerId;
LabelId = labelId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AdGroupAdLabelName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
public AdGroupAdLabelName(string customerId, string adGroupId, string adId, string labelId) : this(ResourceNameType.CustomerAdGroupAdLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), adId: gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Ad</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdId { get; }
/// <summary>
/// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdGroupId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>Label</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LabelId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerAdGroupAdLabel: return s_customerAdGroupAdLabel.Expand(CustomerId, $"{AdGroupId}~{AdId}~{LabelId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AdGroupAdLabelName);
/// <inheritdoc/>
public bool Equals(AdGroupAdLabelName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AdGroupAdLabelName a, AdGroupAdLabelName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AdGroupAdLabelName a, AdGroupAdLabelName b) => !(a == b);
}
public partial class AdGroupAdLabel
{
/// <summary>
/// <see cref="AdGroupAdLabelName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal AdGroupAdLabelName ResourceNameAsAdGroupAdLabelName
{
get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupAdLabelName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupAdName"/>-typed view over the <see cref="AdGroupAd"/> resource name property.
/// </summary>
internal AdGroupAdName AdGroupAdAsAdGroupAdName
{
get => string.IsNullOrEmpty(AdGroupAd) ? null : AdGroupAdName.Parse(AdGroupAd, allowUnparsed: true);
set => AdGroupAd = value?.ToString() ?? "";
}
/// <summary><see cref="LabelName"/>-typed view over the <see cref="Label"/> resource name property.</summary>
internal LabelName LabelAsLabelName
{
get => string.IsNullOrEmpty(Label) ? null : LabelName.Parse(Label, allowUnparsed: true);
set => Label = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq.Expressions;
using FluentAssertions.Execution;
namespace FluentAssertions.Primitives
{
/// <summary>
/// Contains a number of methods to assert that a reference type object is in the expected state.
/// </summary>
[DebuggerNonUserCode]
public abstract class ReferenceTypeAssertions<TSubject, TAssertions>
where TAssertions : ReferenceTypeAssertions<TSubject, TAssertions>
{
/// <summary>
/// Gets the object which value is being asserted.
/// </summary>
public TSubject Subject { get; protected set; }
/// <summary>
/// Asserts that the current object has not been initialized yet.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<TAssertions> BeNull(string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(ReferenceEquals(Subject, null))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:" + Context + "} to be <null>{reason}, but found {0}.", Subject);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the current object has been initialized.
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<TAssertions> NotBeNull(string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(!ReferenceEquals(Subject, null))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:" + Context + "} not to be <null>{reason}.");
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that an object reference refers to the exact same object as another object reference.
/// </summary>
/// <param name="expected">The expected object</param>
/// <param name="because">
/// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not
/// start with the word <i>because</i>, it is prepended to the message.
/// </param>
/// <param name="becauseArgs">
/// Zero or more values to use for filling in any <see cref="string.Format(string,object[])" /> compatible placeholders.
/// </param>
public AndConstraint<TAssertions> BeSameAs(TSubject expected, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.UsingLineBreaks
.ForCondition(ReferenceEquals(Subject, expected))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:" + Context + "} to refer to {0}{reason}, but found {1}.", expected, Subject);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that an object reference refers to a different object than another object reference refers to.
/// </summary>
/// <param name="unexpected">The unexpected object</param>
/// <param name="because">
/// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not
/// start with the word <i>because</i>, it is prepended to the message.
/// </param>
/// <param name="becauseArgs">
/// Zero or more values to use for filling in any <see cref="string.Format(string,object[])" /> compatible placeholders.
/// </param>
public AndConstraint<TAssertions> NotBeSameAs(TSubject unexpected, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.UsingLineBreaks
.ForCondition(!ReferenceEquals(Subject, unexpected))
.BecauseOf(because, becauseArgs)
.FailWith("Did not expect reference to object {0}{reason}.", unexpected);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the object is of the specified type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The expected type of the object.</typeparam>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndWhichConstraint<TAssertions, T> BeOfType<T>(string because = "", params object[] becauseArgs)
{
BeOfType(typeof(T), because, becauseArgs);
return new AndWhichConstraint<TAssertions, T>((TAssertions)this, (T)(object)Subject);
}
/// <summary>
/// Asserts that the object is of the specified type <paramref name="expectedType"/>.
/// </summary>
/// <param name="expectedType">
/// The type that the subject is supposed to be of.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<TAssertions> BeOfType(Type expectedType, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(!ReferenceEquals(Subject, null))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:type} to be {0}{reason}, but found <null>.", expectedType);
Type subjectType = Subject.GetType();
if (expectedType.IsGenericTypeDefinition() && subjectType.IsGenericType())
{
subjectType.GetGenericTypeDefinition().Should().Be(expectedType, because, becauseArgs);
}
else
{
subjectType.Should().Be(expectedType, because, becauseArgs);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the object is not of the specified type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type that the subject is not supposed to be of.</typeparam>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<TAssertions> NotBeOfType<T>(string because = "", params object[] becauseArgs)
{
NotBeOfType(typeof(T), because, becauseArgs);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the object is not of the specified type <paramref name="expectedType"/>.
/// </summary>
/// <param name="expectedType">
/// The type that the subject is not supposed to be of.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<TAssertions> NotBeOfType(Type expectedType, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(!ReferenceEquals(Subject, null))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:type} not to be {0}{reason}, but found <null>.", expectedType);
Subject.GetType().Should().NotBe(expectedType, because, becauseArgs);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the object is assignable to a variable of type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type to which the object should be assignable.</typeparam>
/// <param name="because">The reason why the object should be assignable to the type.</param>
/// <param name="becauseArgs">The parameters used when formatting the <paramref name="because"/>.</param>
/// <returns>An <see cref="AndWhichConstraint{TAssertions, T}"/> which can be used to chain assertions.</returns>
public AndWhichConstraint<TAssertions, T> BeAssignableTo<T>(string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(Subject is T)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:" + Context + "} to be assignable to {0}{reason}, but {1} is not",
typeof(T),
Subject.GetType());
return new AndWhichConstraint<TAssertions, T>((TAssertions)this, (T)((object)Subject));
}
/// <summary>
/// Asserts that the object is assignable to a variable of given <paramref name="type"/>.
/// </summary>
/// <param name="type">The type to which the object should be assignable.</param>
/// <param name="because">The parameters used when formatting the <paramref name="because"/>.</param>
/// <param name="becauseArgs"></param>
/// <returns>An <see cref="AndWhichConstraint{TAssertions, T}"/> which can be used to chain assertions.</returns>
public AndConstraint<TAssertions> BeAssignableTo(Type type, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(!ReferenceEquals(Subject, null))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:type} not to be {0}{reason}, but found <null>.", type);
Execute.Assertion
.ForCondition(type.IsAssignableFrom(Subject.GetType()))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:" + Context + "} to be assignable to {0}{reason}, but {1} is not",
type,
Subject.GetType());
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the <paramref name="predicate" /> is satisfied.
/// </summary>
/// <param name="predicate">The predicate which must be satisfied by the <typeparamref name="TSubject" />.</param>
/// <param name="because">The reason why the predicate should be satisfied.</param>
/// <param name="becauseArgs">The parameters used when formatting the <paramref name="because" />.</param>
/// <returns>An <see cref="AndConstraint{T}" /> which can be used to chain assertions.</returns>
public AndConstraint<TAssertions> Match(Expression<Func<TSubject, bool>> predicate,
string because = "",
params object[] becauseArgs)
{
return Match<TSubject>(predicate, because, becauseArgs);
}
/// <summary>
/// Asserts that the <paramref name="predicate" /> is satisfied.
/// </summary>
/// <param name="predicate">The predicate which must be satisfied by the <typeparamref name="TSubject" />.</param>
/// <param name="because">The reason why the predicate should be satisfied.</param>
/// <param name="becauseArgs">The parameters used when formatting the <paramref name="because" />.</param>
/// <returns>An <see cref="AndConstraint{T}" /> which can be used to chain assertions.</returns>
public AndConstraint<TAssertions> Match<T>(Expression<Func<T, bool>> predicate,
string because = "",
params object[] becauseArgs)
where T : TSubject
{
if (predicate == null)
{
throw new NullReferenceException("Cannot match an object against a <null> predicate.");
}
Execute.Assertion
.ForCondition(predicate.Compile()((T)Subject))
.BecauseOf(because, becauseArgs)
.FailWith("Expected {0} to match {1}{reason}.", Subject, predicate.Body);
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Returns the type of the subject the assertion applies on.
/// </summary>
protected abstract string Context { get; }
}
}
| |
/*
* Copyright (c) 2014 Behrooz Amoozad
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the bd2 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 Behrooz Amoozad BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* */
using System;
using System.Collections.Generic;
namespace BD2.Daemon.Buses
{
public sealed class ObjectBus
{
SortedDictionary<Guid, ObjectBusSession> sessions = new SortedDictionary<Guid, ObjectBusSession> ();
SortedDictionary<ObjectBusSession, Action<byte[]>> streamHandlerCallbackHandlers = new SortedDictionary<ObjectBusSession, Action<byte[]>> ();
StreamHandler streamHandler;
ObjectBusSession systemSession;
public void RegisterType (Type type, Action<ObjectBusMessage> action)
{
systemSession.RegisterType (type, action);
}
public void SendMessage (ObjectBusMessage message)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
systemSession.SendMessage (message);
}
void SendMessageHandler (ObjectBusMessage message, ObjectBusSession session)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
byte[] messageBody = message.GetMessageBody ();
byte[] bytes = new byte[32 + messageBody.Length];
System.Buffer.BlockCopy (session.SessionID.ToByteArray (), 0, bytes, 0, 16);
System.Buffer.BlockCopy (message.TypeID.ToByteArray (), 0, bytes, 16, 16);
System.Buffer.BlockCopy (messageBody, 0, bytes, 32, messageBody.Length);
streamHandler.SendMessage (bytes);
}
class tpmessage
{
byte[] message;
Action<byte[]> cb;
public tpmessage (Action<byte[]> cb, byte[] message)
{
this.message = message;
this.cb = cb;
}
public void tpcallback (object tc)
{
cb (message);
}
}
void StreamHandlerCallback (byte[] messageContents)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
if (messageContents == null)
throw new ArgumentNullException ("messageContents");
if (messageContents.Length < 32)
throw new ArgumentException ("messageContents cannot be less than 16 bytes.");
byte[] sessionIDBytes = new byte[16];
System.Buffer.BlockCopy (messageContents, 0, sessionIDBytes, 0, 16);
Guid sessionID = new Guid (sessionIDBytes);
ObjectBusSession session = null;
if (sessionID == Guid.Empty)
session = systemSession;
else {
lock (sessions)
session = sessions [sessionID];
}
byte[] bytes = new byte[messageContents.Length - 16];
System.Buffer.BlockCopy (messageContents, 16, bytes, 0, messageContents.Length - 16);
System.Threading.ThreadPool.QueueUserWorkItem ((new tpmessage (streamHandlerCallbackHandlers [session], bytes)).tpcallback);
}
public ObjectBus (StreamHandler streamHandler)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
if (streamHandler == null)
throw new ArgumentNullException ("streamHandler");
this.streamHandler = streamHandler;
streamHandler.RegisterCallback (StreamHandlerCallback);
streamHandler.RegisterDisconnectHandler (streamHandlerDisconnected);
systemSession = CreateSession (Guid.Empty, SystemSessionDisconnected);
RegisterType (typeof(BusReadyMessage), busReadyMessageReceived);
}
void busReadyMessageReceived (ObjectBusMessage message)
{
BusReadyMessage brm = (BusReadyMessage)message;
sessions [brm.ObjectBusSessionID].setRemoteReady ();
}
void streamHandlerDisconnected (StreamHandler streamHandler)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
foreach (var session in sessions)
session.Value.BusDisconnected ();
systemSession.BusDisconnected ();
}
void SystemSessionDisconnected (ObjectBusSession session)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
if (systemSession != session)
throw new InvalidOperationException ();
//do nothing?
}
public void Start ()
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
streamHandler.Start ();
}
public void Flush ()
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
streamHandler.Flush ();
}
public ObjectBusSession CreateSession (Guid sessionID, Action<ObjectBusSession> sessionDisconnected)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
ObjectBusSession session = new ObjectBusSession (sessionID, SendMessageHandler, RegisterStreamHandlerCallbackHandler, DestroyHandler, sessionDisconnected, sessionReady);
lock (sessions)
sessions.Add (sessionID, session);
return session;
}
void sessionReady (ObjectBusSession session)
{
SendMessage (new BusReadyMessage (session.SessionID));
}
void RegisterStreamHandlerCallbackHandler (Action<byte[]> streamHandlerCallbackHandler, ObjectBusSession session)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
lock (streamHandlerCallbackHandlers)
streamHandlerCallbackHandlers.Add (session, streamHandlerCallbackHandler);
}
public void DestroySession (ServiceDestroyMessage serviceDestroy)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
if (serviceDestroy == null)
throw new ArgumentNullException ("serviceDestroy");
ObjectBusSession session;
lock (sessions) {
//TODO:remove this line
if (!sessions.ContainsKey (serviceDestroy.SessionID))
return;
session = sessions [serviceDestroy.SessionID];
if (session == systemSession) {
if (sessions.Count != 0) {
throw new InvalidOperationException ("System session must be the last session to be destroyed.");
}
}
sessions.Remove (serviceDestroy.SessionID);
}
}
void DestroyHandler (ObjectBusSession session)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
ServiceDestroyMessage serviceDestroy = new ServiceDestroyMessage (session.SessionID);
SendMessage (serviceDestroy);
DestroySession (serviceDestroy);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="BusinessBindingListBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>This is the base class from which most business collections</summary>
//-----------------------------------------------------------------------
#if NETFX_CORE || (ANDROID || IOS)
using System;
namespace Csla
{
/// <summary>
/// This is the base class from which most business collections
/// or lists will be derived.
/// </summary>
/// <typeparam name="T">Type of the business object being defined.</typeparam>
/// <typeparam name="C">Type of the child objects contained in the list.</typeparam>
#if TESTING
[System.Diagnostics.DebuggerStepThrough]
#endif
[Serializable]
public abstract class BusinessBindingListBase<T, C> : BusinessListBase<T, C>
where T : BusinessBindingListBase<T, C>
where C : Csla.Core.IEditableBusinessObject
{
}
}
#else
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Csla.Properties;
using Csla.Core;
using System.Threading.Tasks;
namespace Csla
{
/// <summary>
/// This is the base class from which most business collections
/// or lists will be derived.
/// </summary>
/// <typeparam name="T">Type of the business object being defined.</typeparam>
/// <typeparam name="C">Type of the child objects contained in the list.</typeparam>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[Serializable()]
public abstract class BusinessBindingListBase<T, C> :
Core.ExtendedBindingList<C>,
Core.IEditableCollection, Core.IUndoableObject, ICloneable,
Core.ISavable, Core.ISavable<T>, Core.IParent, Server.IDataPortalTarget,
INotifyBusy
where T : BusinessBindingListBase<T, C>
where C : Core.IEditableBusinessObject
{
#region Constructors
/// <summary>
/// Creates an instance of the object.
/// </summary>
protected BusinessBindingListBase()
{
Initialize();
this.AllowNew = true;
}
#endregion
#region Initialize
/// <summary>
/// Override this method to set up event handlers so user
/// code in a partial class can respond to events raised by
/// generated code.
/// </summary>
protected virtual void Initialize()
{ /* allows subclass to initialize events before any other activity occurs */ }
#endregion
#region IsDirty, IsValid, IsSavable
/// <summary>
/// Gets a value indicating whether this object's data has been changed.
/// </summary>
bool Core.ITrackStatus.IsSelfDirty
{
get { return IsDirty; }
}
/// <summary>
/// Gets a value indicating whether this object's data has been changed.
/// </summary>
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
public bool IsDirty
{
get
{
// any non-new deletions make us dirty
foreach (C item in DeletedList)
if (!item.IsNew)
return true;
// run through all the child objects
// and if any are dirty then then
// collection is dirty
foreach (C child in this)
if (child.IsDirty)
return true;
return false;
}
}
bool Core.ITrackStatus.IsSelfValid
{
get { return IsSelfValid; }
}
/// <summary>
/// Gets a value indicating whether this object is currently in
/// a valid state (has no broken validation rules).
/// </summary>
protected virtual bool IsSelfValid
{
get { return IsValid; }
}
/// <summary>
/// Gets a value indicating whether this object is currently in
/// a valid state (has no broken validation rules).
/// </summary>
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
public virtual bool IsValid
{
get
{
// run through all the child objects
// and if any are invalid then the
// collection is invalid
foreach (C child in this)
if (!child.IsValid)
return false;
return true;
}
}
/// <summary>
/// Returns true if this object is both dirty and valid.
/// </summary>
/// <returns>A value indicating if this object is both dirty and valid.</returns>
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
public virtual bool IsSavable
{
get
{
bool auth = Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.EditObject, this);
return (IsDirty && IsValid && auth && !IsBusy);
}
}
#endregion
#region Begin/Cancel/ApplyEdit
/// <summary>
/// Starts a nested edit on the object.
/// </summary>
/// <remarks>
/// <para>
/// When this method is called the object takes a snapshot of
/// its current state (the values of its variables). This snapshot
/// can be restored by calling <see cref="CancelEdit" />
/// or committed by calling <see cref="ApplyEdit" />.
/// </para><para>
/// This is a nested operation. Each call to BeginEdit adds a new
/// snapshot of the object's state to a stack. You should ensure that
/// for each call to BeginEdit there is a corresponding call to either
/// CancelEdit or ApplyEdit to remove that snapshot from the stack.
/// </para><para>
/// See Chapters 2 and 3 for details on n-level undo and state stacking.
/// </para><para>
/// This method triggers the copying of all child object states.
/// </para>
/// </remarks>
public void BeginEdit()
{
if (this.IsChild)
throw new NotSupportedException(Resources.NoBeginEditChildException);
CopyState(this.EditLevel + 1);
}
/// <summary>
/// Cancels the current edit process, restoring the object's state to
/// its previous values.
/// </summary>
/// <remarks>
/// Calling this method causes the most recently taken snapshot of the
/// object's state to be restored. This resets the object's values
/// to the point of the last <see cref="BeginEdit" />
/// call.
/// <para>
/// This method triggers an undo in all child objects.
/// </para>
/// </remarks>
public void CancelEdit()
{
if (this.IsChild)
throw new NotSupportedException(Resources.NoCancelEditChildException);
UndoChanges(this.EditLevel - 1);
}
/// <summary>
/// Commits the current edit process.
/// </summary>
/// <remarks>
/// Calling this method causes the most recently taken snapshot of the
/// object's state to be discarded, thus committing any changes made
/// to the object's state since the last
/// <see cref="BeginEdit" /> call.
/// <para>
/// This method triggers an <see cref="Core.BusinessBase.ApplyEdit"/>
/// in all child objects.
/// </para>
/// </remarks>
public void ApplyEdit()
{
if (this.IsChild)
throw new NotSupportedException(Resources.NoApplyEditChildException);
AcceptChanges(this.EditLevel - 1);
}
void Core.IParent.ApplyEditChild(Core.IEditableBusinessObject child)
{
EditChildComplete(child);
}
IParent Csla.Core.IParent.Parent
{
get { return this.Parent; }
}
/// <summary>
/// Override this method to be notified when a child object's
/// <see cref="Core.BusinessBase.ApplyEdit" /> method has
/// completed.
/// </summary>
/// <param name="child">The child object that was edited.</param>
protected virtual void EditChildComplete(Core.IEditableBusinessObject child)
{
// do nothing, we don't really care
// when a child has its edits applied
}
#endregion
#region N-level undo
void Core.IUndoableObject.CopyState(int parentEditLevel, bool parentBindingEdit)
{
if (!parentBindingEdit)
CopyState(parentEditLevel);
}
void Core.IUndoableObject.UndoChanges(int parentEditLevel, bool parentBindingEdit)
{
if (!parentBindingEdit)
UndoChanges(parentEditLevel);
}
void Core.IUndoableObject.AcceptChanges(int parentEditLevel, bool parentBindingEdit)
{
if (!parentBindingEdit)
AcceptChanges(parentEditLevel);
}
private void CopyState(int parentEditLevel)
{
if (this.EditLevel + 1 > parentEditLevel)
throw new Core.UndoException(string.Format(Resources.EditLevelMismatchException, "CopyState"));
// we are going a level deeper in editing
_editLevel += 1;
// cascade the call to all child objects
foreach (C child in this)
child.CopyState(_editLevel, false);
// cascade the call to all deleted child objects
foreach (C child in DeletedList)
child.CopyState(_editLevel, false);
}
private bool _completelyRemoveChild;
private void UndoChanges(int parentEditLevel)
{
C child;
if (this.EditLevel - 1 != parentEditLevel)
throw new Core.UndoException(string.Format(Resources.EditLevelMismatchException, "UndoChanges"));
// we are coming up one edit level
_editLevel -= 1;
if (_editLevel < 0) _editLevel = 0;
bool oldRLCE = this.RaiseListChangedEvents;
this.RaiseListChangedEvents = false;
try
{
// Cancel edit on all current items
for (int index = Count - 1; index >= 0; index--)
{
child = this[index];
child.UndoChanges(_editLevel, false);
// if item is below its point of addition, remove
if (child.EditLevelAdded > _editLevel)
{
bool oldAllowRemove = this.AllowRemove;
try
{
this.AllowRemove = true;
_completelyRemoveChild = true;
RemoveAt(index);
}
finally
{
_completelyRemoveChild = false;
this.AllowRemove = oldAllowRemove;
}
}
}
// cancel edit on all deleted items
for (int index = DeletedList.Count - 1; index >= 0; index--)
{
child = DeletedList[index];
child.UndoChanges(_editLevel, false);
if (child.EditLevelAdded > _editLevel)
{
// if item is below its point of addition, remove
DeletedList.RemoveAt(index);
}
else
{
// if item is no longer deleted move back to main list
if (!child.IsDeleted) UnDeleteChild(child);
}
}
}
finally
{
this.RaiseListChangedEvents = oldRLCE;
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
}
private void AcceptChanges(int parentEditLevel)
{
if (this.EditLevel - 1 != parentEditLevel)
throw new Core.UndoException(string.Format(Resources.EditLevelMismatchException, "AcceptChanges"));
// we are coming up one edit level
_editLevel -= 1;
if (_editLevel < 0) _editLevel = 0;
// cascade the call to all child objects
foreach (C child in this)
{
child.AcceptChanges(_editLevel, false);
// if item is below its point of addition, lower point of addition
if (child.EditLevelAdded > _editLevel) child.EditLevelAdded = _editLevel;
}
// cascade the call to all deleted child objects
for (int index = DeletedList.Count - 1; index >= 0; index--)
{
C child = DeletedList[index];
child.AcceptChanges(_editLevel, false);
// if item is below its point of addition, remove
if (child.EditLevelAdded > _editLevel)
DeletedList.RemoveAt(index);
}
}
#endregion
#region Delete and Undelete child
private MobileList<C> _deletedList;
/// <summary>
/// A collection containing all child objects marked
/// for deletion.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design", "CA1002:DoNotExposeGenericLists")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected MobileList<C> DeletedList
{
get
{
if (_deletedList == null)
_deletedList = new MobileList<C>();
return _deletedList;
}
}
private void DeleteChild(C child)
{
// set child edit level
Core.UndoableBase.ResetChildEditLevel(child, this.EditLevel, false);
// mark the object as deleted
child.DeleteChild();
// and add it to the deleted collection for storage
DeletedList.Add(child);
}
private void UnDeleteChild(C child)
{
// since the object is no longer deleted, remove it from
// the deleted collection
DeletedList.Remove(child);
// we are inserting an _existing_ object so
// we need to preserve the object's editleveladded value
// because it will be changed by the normal add process
int saveLevel = child.EditLevelAdded;
Add(child);
child.EditLevelAdded = saveLevel;
}
/// <summary>
/// Returns true if the internal deleted list
/// contains the specified child object.
/// </summary>
/// <param name="item">Child object to check.</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public bool ContainsDeleted(C item)
{
return DeletedList.Contains(item);
}
#endregion
#region Insert, Remove, Clear
/// <summary>
/// Override this method to create a new object that is added
/// to the collection.
/// </summary>
protected override object AddNewCore()
{
var item = DataPortal.CreateChild<C>();
Add(item);
return item;
}
/// <summary>
/// This method is called by a child object when it
/// wants to be removed from the collection.
/// </summary>
/// <param name="child">The child object to remove.</param>
void Core.IEditableCollection.RemoveChild(Csla.Core.IEditableBusinessObject child)
{
Remove((C)child);
}
object IEditableCollection.GetDeletedList()
{
return DeletedList;
}
/// <summary>
/// This method is called by a child object when it
/// wants to be removed from the collection.
/// </summary>
/// <param name="child">The child object to remove.</param>
void Core.IParent.RemoveChild(Csla.Core.IEditableBusinessObject child)
{
Remove((C)child);
}
/// <summary>
/// Sets the edit level of the child object as it is added.
/// </summary>
/// <param name="index">Index of the item to insert.</param>
/// <param name="item">Item to insert.</param>
protected override void InsertItem(int index, C item)
{
// set parent reference
item.SetParent(this);
// set child edit level
Core.UndoableBase.ResetChildEditLevel(item, this.EditLevel, false);
// when an object is inserted we assume it is
// a new object and so the edit level when it was
// added must be set
item.EditLevelAdded = _editLevel;
base.InsertItem(index, item);
}
/// <summary>
/// Marks the child object for deletion and moves it to
/// the collection of deleted objects.
/// </summary>
/// <param name="index">Index of the item to remove.</param>
protected override void RemoveItem(int index)
{
// when an object is 'removed' it is really
// being deleted, so do the deletion work
C child = this[index];
bool oldRaiseListChangedEvents = this.RaiseListChangedEvents;
try
{
this.RaiseListChangedEvents = false;
base.RemoveItem(index);
}
finally
{
this.RaiseListChangedEvents = oldRaiseListChangedEvents;
}
if (!_completelyRemoveChild)
{
// the child shouldn't be completely removed,
// so copy it to the deleted list
DeleteChild(child);
}
if (RaiseListChangedEvents)
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index));
}
/// <summary>
/// Clears the collection, moving all active
/// items to the deleted list.
/// </summary>
protected override void ClearItems()
{
while (base.Count > 0)
RemoveItem(0);
base.ClearItems();
}
/// <summary>
/// Replaces the item at the specified index with
/// the specified item, first moving the original
/// item to the deleted list.
/// </summary>
/// <param name="index">The zero-based index of the item to replace.</param>
/// <param name="item">
/// The new value for the item at the specified index.
/// The value can be null for reference types.
/// </param>
/// <remarks></remarks>
protected override void SetItem(int index, C item)
{
C child = default(C);
if (!(ReferenceEquals((C)(this[index]), item)))
child = this[index];
// replace the original object with this new
// object
bool oldRaiseListChangedEvents = this.RaiseListChangedEvents;
try
{
this.RaiseListChangedEvents = false;
// set parent reference
item.SetParent(this);
// set child edit level
Core.UndoableBase.ResetChildEditLevel(item, this.EditLevel, false);
// reset EditLevelAdded
item.EditLevelAdded = this.EditLevel;
// add to list
base.SetItem(index, item);
}
finally
{
this.RaiseListChangedEvents = oldRaiseListChangedEvents;
}
if (child != null)
DeleteChild(child);
if (RaiseListChangedEvents)
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index));
}
#endregion
#region Cascade child events
/// <summary>
/// Handles any PropertyChanged event from
/// a child object and echoes it up as
/// a ListChanged event.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
protected override void Child_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (_deserialized && RaiseListChangedEvents && e != null)
{
for (int index = 0; index < Count; index++)
{
if (ReferenceEquals(this[index], sender))
{
PropertyDescriptor descriptor = GetPropertyDescriptor(e.PropertyName);
if (descriptor != null)
OnListChanged(new ListChangedEventArgs(
ListChangedType.ItemChanged, index, descriptor));
else
OnListChanged(new ListChangedEventArgs(
ListChangedType.ItemChanged, index));
}
}
}
base.Child_PropertyChanged(sender, e);
}
private static PropertyDescriptorCollection _propertyDescriptors;
private PropertyDescriptor GetPropertyDescriptor(string propertyName)
{
if (_propertyDescriptors == null)
_propertyDescriptors = TypeDescriptor.GetProperties(typeof(C));
PropertyDescriptor result = null;
foreach (PropertyDescriptor desc in _propertyDescriptors)
if (desc.Name == propertyName)
{
result = desc;
break;
}
return result;
}
#endregion
#region Edit level tracking
// keep track of how many edit levels we have
private int _editLevel;
/// <summary>
/// Returns the current edit level of the object.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
protected int EditLevel
{
get { return _editLevel; }
}
int Core.IUndoableObject.EditLevel
{
get
{
return this.EditLevel;
}
}
#endregion
#region IsChild
[NotUndoable()]
private bool _isChild = false;
/// <summary>
/// Indicates whether this collection object is a child object.
/// </summary>
/// <returns>True if this is a child object.</returns>
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
public bool IsChild
{
get { return _isChild; }
}
/// <summary>
/// Marks the object as being a child object.
/// </summary>
/// <remarks>
/// <para>
/// By default all business objects are 'parent' objects. This means
/// that they can be directly retrieved and updated into the database.
/// </para><para>
/// We often also need child objects. These are objects which are contained
/// within other objects. For instance, a parent Invoice object will contain
/// child LineItem objects.
/// </para><para>
/// To create a child object, the MarkAsChild method must be called as the
/// object is created. Please see Chapter 7 for details on the use of the
/// MarkAsChild method.
/// </para>
/// </remarks>
protected void MarkAsChild()
{
_isChild = true;
}
#endregion
#region ICloneable
object ICloneable.Clone()
{
return GetClone();
}
/// <summary>
/// Creates a clone of the object.
/// </summary>
/// <returns>A new object containing the exact data of the original object.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual object GetClone()
{
return Core.ObjectCloner.Clone(this);
}
/// <summary>
/// Creates a clone of the object.
/// </summary>
/// <returns>A new object containing the exact data of the original object.</returns>
public T Clone()
{
return (T)GetClone();
}
#endregion
#region Serialization Notification
[NonSerialized]
[NotUndoable]
private bool _deserialized = false;
/// <summary>
/// This method is called on a newly deserialized object
/// after deserialization is complete.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnDeserialized()
{
_deserialized = true;
base.OnDeserialized();
foreach (Core.IEditableBusinessObject child in this)
{
child.SetParent(this);
}
foreach (Core.IEditableBusinessObject child in DeletedList)
child.SetParent(this);
}
#endregion
#region Child Data Access
/// <summary>
/// Initializes a new instance of the object
/// with default values.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_Create()
{ /* do nothing - list self-initializes */ }
/// <summary>
/// Saves all items in the list, automatically
/// performing insert, update or delete operations
/// as necessary.
/// </summary>
/// <param name="parameters">
/// Optional parameters passed to child update
/// methods.
/// </param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_Update(params object[] parameters)
{
var oldRLCE = this.RaiseListChangedEvents;
this.RaiseListChangedEvents = false;
try
{
foreach (var child in DeletedList)
DataPortal.UpdateChild(child, parameters);
DeletedList.Clear();
foreach (var child in this)
if (child.IsDirty) DataPortal.UpdateChild(child, parameters);
}
finally
{
this.RaiseListChangedEvents = oldRLCE;
}
}
#endregion
#region Data Access
/// <summary>
/// Saves the object to the database.
/// </summary>
/// <remarks>
/// <para>
/// Calling this method starts the save operation, causing the all child
/// objects to be inserted, updated or deleted within the database based on the
/// each object's current state.
/// </para><para>
/// All this is contingent on <see cref="IsDirty" />. If
/// this value is false, no data operation occurs.
/// It is also contingent on <see cref="IsValid" />. If this value is
/// false an exception will be thrown to
/// indicate that the UI attempted to save an invalid object.
/// </para><para>
/// It is important to note that this method returns a new version of the
/// business collection that contains any data updated during the save operation.
/// You MUST update all object references to use this new version of the
/// business collection in order to have access to the correct object data.
/// </para><para>
/// You can override this method to add your own custom behaviors to the save
/// operation. For instance, you may add some security checks to make sure
/// the user can save the object. If all security checks pass, you would then
/// invoke the base Save method via <c>MyBase.Save()</c>.
/// </para>
/// </remarks>
/// <returns>A new object containing the saved values.</returns>
public T Save()
{
try
{
return SaveAsync(null, true).Result;
}
catch (AggregateException ex)
{
if (ex.InnerExceptions.Count > 0)
throw ex.InnerExceptions[0];
else
throw;
}
}
/// <summary>
/// Saves the object to the database.
/// </summary>
public async Task<T> SaveAsync()
{
return await SaveAsync(null, false);
}
/// <summary>
/// Saves the object to the database.
/// </summary>
/// <param name="userState">User state data.</param>
/// <param name="isSync">True if the save operation should be synchronous.</param>
protected virtual async Task<T> SaveAsync(object userState, bool isSync)
{
T result;
if (this.IsChild)
throw new InvalidOperationException(Resources.NoSaveChildException);
if (_editLevel > 0)
throw new InvalidOperationException(Resources.NoSaveEditingException);
if (!IsValid)
throw new Rules.ValidationException(Resources.NoSaveInvalidException);
if (IsBusy)
throw new InvalidOperationException(Resources.BusyObjectsMayNotBeSaved);
if (IsDirty)
{
if (isSync)
{
result = DataPortal.Update<T>((T)this);
}
else
{
result = await DataPortal.UpdateAsync<T>((T)this);
}
}
else
{
result = (T)this;
}
OnSaved(result, null, userState);
return result;
}
/// <summary>
/// Starts an async operation to save the object to the database.
/// </summary>
public void BeginSave()
{
BeginSave(null, null);
}
/// <summary>
/// Starts an async operation to save the object to the database.
/// </summary>
/// <param name="userState">User state object.</param>
public void BeginSave(object userState)
{
BeginSave(null, userState);
}
/// <summary>
/// Starts an async operation to save the object to the database.
/// </summary>
/// <param name="handler">
/// Method called when the operation is complete.
/// </param>
public void BeginSave(EventHandler<SavedEventArgs> handler)
{
BeginSave(handler, null);
}
/// <summary>
/// Starts an async operation to save the object to the database.
/// </summary>
/// <param name="handler">
/// Method called when the operation is complete.
/// </param>
/// <param name="userState">User state object.</param>
public async void BeginSave(EventHandler<SavedEventArgs> handler, object userState)
{
T result = default(T);
Exception error = null;
try
{
result = await SaveAsync(userState, false);
}
catch (AggregateException ex)
{
if (ex.InnerExceptions.Count > 0)
error = ex.InnerExceptions[0];
else
error = ex;
}
catch (Exception ex)
{
error = ex;
}
if (handler != null)
handler(this, new SavedEventArgs(result, error, userState));
}
/// <summary>
/// Override this method to load a new business object with default
/// values from the database.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
protected virtual void DataPortal_Create()
{ }
/// <summary>
/// Override this method to allow retrieval of an existing business
/// object based on data in the database.
/// </summary>
/// <param name="criteria">An object containing criteria values to identify the object.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
protected virtual void DataPortal_Fetch(object criteria)
{
throw new NotSupportedException(Resources.FetchNotSupportedException);
}
/// <summary>
/// Override this method to allow update of a business
/// object.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
protected virtual void DataPortal_Update()
{
throw new NotSupportedException(Resources.UpdateNotSupportedException);
}
/// <summary>
/// Override this method to allow immediate deletion of a business object.
/// </summary>
/// <param name="criteria">An object containing criteria values to identify the object.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
protected virtual void DataPortal_Delete(object criteria)
{
throw new NotSupportedException(Resources.DeleteNotSupportedException);
}
/// <summary>
/// Called by the server-side DataPortal prior to calling the
/// requested DataPortal_xyz method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal after calling the
/// requested DataPortal_xyz method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal if an exception
/// occurs during data access.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
/// <param name="ex">The Exception thrown during data access.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
}
/// <summary>
/// Called by the server-side DataPortal prior to calling the
/// requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_OnDataPortalInvoke(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal after calling the
/// requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal if an exception
/// occurs during data access.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
/// <param name="ex">The Exception thrown during data access.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
}
#endregion
#region ISavable Members
#if !(ANDROID || IOS) && !NETFX_CORE
object Csla.Core.ISavable.Save()
{
return Save();
}
object Csla.Core.ISavable.Save(bool forceUpdate)
{
return Save();
}
#endif
async Task<object> ISavable.SaveAsync()
{
return await SaveAsync();
}
async Task<object> ISavable.SaveAsync(bool forceUpdate)
{
return await SaveAsync();
}
void Csla.Core.ISavable.SaveComplete(object newObject)
{
OnSaved((T)newObject, null, null);
}
#if !(ANDROID || IOS) && !NETFX_CORE
T Csla.Core.ISavable<T>.Save(bool forceUpdate)
{
return Save();
}
#endif
async Task<T> ISavable<T>.SaveAsync(bool forceUpdate)
{
return await SaveAsync();
}
void Csla.Core.ISavable<T>.SaveComplete(T newObject)
{
OnSaved(newObject, null, null);
}
[NonSerialized()]
[NotUndoable]
private EventHandler<Csla.Core.SavedEventArgs> _nonSerializableSavedHandlers;
[NotUndoable]
private EventHandler<Csla.Core.SavedEventArgs> _serializableSavedHandlers;
/// <summary>
/// Event raised when an object has been saved.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design",
"CA1062:ValidateArgumentsOfPublicMethods")]
public event EventHandler<Csla.Core.SavedEventArgs> Saved
{
add
{
if (value.Method.IsPublic &&
(value.Method.DeclaringType.IsSerializable ||
value.Method.IsStatic))
_serializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
System.Delegate.Combine(_serializableSavedHandlers, value);
else
_nonSerializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
System.Delegate.Combine(_nonSerializableSavedHandlers, value);
}
remove
{
if (value.Method.IsPublic &&
(value.Method.DeclaringType.IsSerializable ||
value.Method.IsStatic))
_serializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
System.Delegate.Remove(_serializableSavedHandlers, value);
else
_nonSerializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
System.Delegate.Remove(_nonSerializableSavedHandlers, value);
}
}
/// <summary>
/// Raises the <see cref="Saved"/> event, indicating that the
/// object has been saved, and providing a reference
/// to the new object instance.
/// </summary>
/// <param name="newObject">The new object instance.</param>
/// <param name="e">Execption that occurred during the operation.</param>
/// <param name="userState">User state object.</param>
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnSaved(T newObject, Exception e, object userState)
{
Csla.Core.SavedEventArgs args = new Csla.Core.SavedEventArgs(newObject, e, userState);
if (_nonSerializableSavedHandlers != null)
_nonSerializableSavedHandlers.Invoke(this, args);
if (_serializableSavedHandlers != null)
_serializableSavedHandlers.Invoke(this, args);
}
#endregion
#region Parent/Child link
[NotUndoable(), NonSerialized()]
private Core.IParent _parent;
/// <summary>
/// Provide access to the parent reference for use
/// in child object code.
/// </summary>
/// <remarks>
/// This value will be Nothing for root objects.
/// </remarks>
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public Core.IParent Parent
{
get
{
return _parent;
}
}
/// <summary>
/// Used by BusinessListBase as a child object is
/// created to tell the child object about its
/// parent.
/// </summary>
/// <param name="parent">A reference to the parent collection object.</param>
protected virtual void SetParent(Core.IParent parent)
{
_parent = parent;
}
/// <summary>
/// Used by BusinessListBase as a child object is
/// created to tell the child object about its
/// parent.
/// </summary>
/// <param name="parent">A reference to the parent collection object.</param>
void Core.IEditableCollection.SetParent(Core.IParent parent)
{
this.SetParent(parent);
}
#endregion
#region ToArray
/// <summary>
/// Get an array containing all items in the list.
/// </summary>
public C[] ToArray()
{
List<C> result = new List<C>();
foreach (C item in this)
result.Add(item);
return result.ToArray();
}
#endregion
#region ITrackStatus
bool Core.ITrackStatus.IsNew
{
get
{
return false;
}
}
bool Core.ITrackStatus.IsDeleted
{
get
{
return false;
}
}
/// <summary>
/// Gets the busy status for this object and its child objects.
/// </summary>
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
public override bool IsBusy
{
get
{
// any non-new deletions make us dirty
foreach (C item in DeletedList)
if (item.IsBusy)
return true;
// run through all the child objects
// and if any are dirty then then
// collection is dirty
foreach (C child in this)
if (child.IsBusy)
return true;
return false;
}
}
#endregion
#region IDataPortalTarget Members
void Csla.Server.IDataPortalTarget.CheckRules()
{ }
void Csla.Server.IDataPortalTarget.MarkAsChild()
{
this.MarkAsChild();
}
void Csla.Server.IDataPortalTarget.MarkNew()
{ }
void Csla.Server.IDataPortalTarget.MarkOld()
{ }
void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvoke(DataPortalEventArgs e)
{
this.DataPortal_OnDataPortalInvoke(e);
}
void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
this.DataPortal_OnDataPortalInvokeComplete(e);
}
void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
this.DataPortal_OnDataPortalException(e, ex);
}
void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvoke(DataPortalEventArgs e)
{
this.Child_OnDataPortalInvoke(e);
}
void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
this.Child_OnDataPortalInvokeComplete(e);
}
void Csla.Server.IDataPortalTarget.Child_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
this.Child_OnDataPortalException(e, ex);
}
#endregion
#region Mobile object overrides
/// <summary>
/// Override this method to retrieve your field values
/// from the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnSetState(Csla.Serialization.Mobile.SerializationInfo info)
{
_isChild = info.GetValue<bool>("Csla.BusinessListBase._isChild");
_editLevel = info.GetValue<int>("Csla.BusinessListBase._editLevel");
base.OnSetState(info);
}
/// <summary>
/// Override this method to insert your field values
/// into the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnGetState(Csla.Serialization.Mobile.SerializationInfo info)
{
info.AddValue("Csla.BusinessListBase._isChild", _isChild);
info.AddValue("Csla.BusinessListBase._editLevel", _editLevel);
base.OnGetState(info);
}
/// <summary>
/// Override this method to insert child objects
/// into the MobileFormatter serialization stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
/// <param name="formatter">
/// Reference to the current MobileFormatter.
/// </param>
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnGetChildren(Csla.Serialization.Mobile.SerializationInfo info, Csla.Serialization.Mobile.MobileFormatter formatter)
{
base.OnGetChildren(info, formatter);
if (_deletedList != null)
{
var fieldManagerInfo = formatter.SerializeObject(_deletedList);
info.AddChild("_deletedList", fieldManagerInfo.ReferenceId);
}
}
/// <summary>
/// Override this method to get child objects
/// from the MobileFormatter serialization stream.
/// </summary>
/// <param name="info">
/// Object containing the serialized data.
/// </param>
/// <param name="formatter">
/// Reference to the current MobileFormatter.
/// </param>
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnSetChildren(Csla.Serialization.Mobile.SerializationInfo info, Csla.Serialization.Mobile.MobileFormatter formatter)
{
if (info.Children.ContainsKey("_deletedList"))
{
var childData = info.Children["_deletedList"];
_deletedList = (MobileList<C>)formatter.GetObject(childData.ReferenceId);
}
base.OnSetChildren(info, formatter);
}
#endregion
}
}
#endif
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
namespace Cassandra
{
internal class M3PToken : IToken
{
public static readonly TokenFactory Factory = new M3PTokenFactory();
private readonly long _value;
internal M3PToken(long value)
{
_value = value;
}
public int CompareTo(object obj)
{
var other = obj as M3PToken;
long otherValue = other._value;
return _value < otherValue ? -1 : (_value == otherValue) ? 0 : 1;
}
public override bool Equals(object obj)
{
if (this == obj)
return true;
if (obj == null || GetType() != obj.GetType())
return false;
return _value == ((M3PToken) obj)._value;
}
public override int GetHashCode()
{
return (int) (_value ^ ((long) ((ulong) _value >> 32)));
}
public override string ToString()
{
return _value.ToString();
}
internal class M3PTokenFactory : TokenFactory
{
public override IToken Parse(string tokenStr)
{
return new M3PToken(long.Parse(tokenStr));
}
public override IToken Hash(byte[] partitionKey)
{
var v = Murmur(partitionKey);
return new M3PToken(v == long.MinValue ? long.MaxValue : v);
}
/// <summary>
/// Murmur hash it
/// </summary>
/// <returns></returns>
private static long Murmur(byte[] bytes)
{
// This is an adapted version of the MurmurHash.hash3_x64_128 from Cassandra used
// for M3P. Compared to that methods, there's a few inlining of arguments and we
// only return the first 64-bits of the result since that's all M3P uses.
//Convert to sbyte as in Java byte are signed
sbyte[] data = (sbyte[])(Array)bytes;
int offset = 0;
int length = data.Length;
int nblocks = length >> 4; // Process as 128-bit blocks.
long h1 = 0;
long h2 = 0;
//Instead of using ulong for constants, use long values representing the same bits
//Negated, same bits as ulong: 0x87c37b91114253d5L
const long c1 = -0x783C846EEEBDAC2BL;
const long c2 = 0x4cf5ad432745937fL;
//----------
// body
for (int i = 0; i < nblocks; i++)
{
long k1 = GetBlock(data, offset, i * 2 + 0);
long k2 = GetBlock(data, offset, i * 2 + 1);
k1 *= c1;
k1 = Rotl64(k1, 31);
k1 *= c2;
h1 ^= k1;
h1 = Rotl64(h1, 27);
h1 += h2;
h1 = h1 * 5 + 0x52dce729;
k2 *= c2;
k2 = Rotl64(k2, 33);
k2 *= c1; h2 ^= k2;
h2 = Rotl64(h2, 31);
h2 += h1;
h2 = h2 * 5 + 0x38495ab5;
}
//----------
// tail
// Advance offset to the unprocessed tail of the data.
offset += nblocks * 16;
{
//context
long k1 = 0;
long k2 = 0;
switch (length & 15)
{
case 15:
k2 ^= ((long)data[offset + 14]) << 48;
goto case 14;
case 14:
k2 ^= ((long)data[offset + 13]) << 40;
goto case 13;
case 13:
k2 ^= ((long)data[offset + 12]) << 32;
goto case 12;
case 12:
k2 ^= ((long)data[offset + 11]) << 24;
goto case 11;
case 11:
k2 ^= ((long)data[offset + 10]) << 16;
goto case 10;
case 10:
k2 ^= ((long)data[offset + 9 ]) << 8;
goto case 9;
case 9:
k2 ^= ((long)data[offset + 8 ]) << 0;
k2 *= c2;
k2 = Rotl64(k2, 33);
k2 *= c1;
h2 ^= k2;
goto case 8;
case 8:
k1 ^= ((long)data[offset + 7]) << 56;
goto case 7;
case 7:
k1 ^= ((long)data[offset + 6]) << 48;
goto case 6;
case 6:
k1 ^= ((long)data[offset + 5]) << 40;
goto case 5;
case 5:
k1 ^= ((long)data[offset + 4]) << 32;
goto case 4;
case 4:
k1 ^= ((long)data[offset + 3]) << 24;
goto case 3;
case 3:
k1 ^= ((long)data[offset + 2]) << 16;
goto case 2;
case 2:
k1 ^= ((long)data[offset + 1]) << 8;
goto case 1;
case 1:
k1 ^= ((long)data[offset]);
k1 *= c1;
k1 = Rotl64(k1, 31);
k1 *= c2;
h1 ^= k1;
break;
}
//----------
// finalization
h1 ^= length;
h2 ^= length;
h1 += h2;
h2 += h1;
h1 = Fmix(h1);
h2 = Fmix(h2);
h1 += h2;
return h1;
}
}
private static long GetBlock(sbyte[] key, int offset, int index)
{
int i8 = index << 3;
int blockOffset = offset + i8;
return ((long)key[blockOffset + 0] & 0xff) + (((long)key[blockOffset + 1] & 0xff) << 8) +
(((long)key[blockOffset + 2] & 0xff) << 16) + (((long)key[blockOffset + 3] & 0xff) << 24) +
(((long)key[blockOffset + 4] & 0xff) << 32) + (((long)key[blockOffset + 5] & 0xff) << 40) +
(((long)key[blockOffset + 6] & 0xff) << 48) + (((long)key[blockOffset + 7] & 0xff) << 56);
}
private static long Rotl64(long v, int n)
{
return ((v << n) | ((long)((ulong)v >> (64 - n))));
}
private static long Fmix(long k)
{
k ^= (long)((ulong)k >> 33);
//Negated, same bits as ulong 0xff51afd7ed558ccdL
k *= -0xAE502812AA7333;
k ^= (long)((ulong)k >> 33);
//Negated, same bits as ulong 0xc4ceb9fe1a85ec53L
k *= -0x3B314601E57A13AD;
k ^= (long)((ulong)k >> 33);
return k;
}
}
}
}
| |
using System;
using System.IO;
using System.Security.Cryptography;
namespace Moonlit.Security
{
/// <summary>
///
/// </summary>
public static class RsaHelper
{
public static RSACryptoServiceProvider CreateRsaFromPrivateKey(byte[] privkey)
{
byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;
// --------- Set up stream to decode the asn.1 encoded RSA private key ------
MemoryStream mem = new MemoryStream(privkey);
BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
byte bt = 0;
ushort twobytes = 0;
int elems = 0;
try
{
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
twobytes = binr.ReadUInt16();
if (twobytes != 0x0102) //version number
return null;
bt = binr.ReadByte();
if (bt != 0x00)
return null;
//------ all private key components are Integer sequences ----
elems = GetIntegerSize(binr);
MODULUS = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
E = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
D = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
P = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
Q = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
DP = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
DQ = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
IQ = binr.ReadBytes(elems);
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
CspParameters CspParameters = new CspParameters();
CspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(1024, CspParameters);
RSAParameters RSAparams = new RSAParameters();
RSAparams.Modulus = MODULUS;
RSAparams.Exponent = E;
RSAparams.D = D;
RSAparams.P = P;
RSAparams.Q = Q;
RSAparams.DP = DP;
RSAparams.DQ = DQ;
RSAparams.InverseQ = IQ;
RSA.ImportParameters(RSAparams);
return RSA;
}
catch (Exception ex)
{
return null;
}
finally
{
binr.Close();
}
}
private static bool CompareByteArrays(byte[] a, byte[] b)
{
if (a.Length != b.Length)
return false;
int i = 0;
foreach (byte c in a)
{
if (c != b[i])
return false;
i++;
}
return true;
}
public static RSACryptoServiceProvider CreateRsaFromPublicKey(byte[] publickey)
{
// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
byte[] seq = new byte[15];
// --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------
MemoryStream mem = new MemoryStream(publickey);
BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
byte bt = 0;
ushort twobytes = 0;
try
{
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
seq = binr.ReadBytes(15); //read the Sequence OID
if (!CompareByteArrays(seq, SeqOID)) //make sure Sequence for OID is correct
return null;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8203)
binr.ReadInt16(); //advance 2 bytes
else
return null;
bt = binr.ReadByte();
if (bt != 0x00) //expect null byte next
return null;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
twobytes = binr.ReadUInt16();
byte lowbyte = 0x00;
byte highbyte = 0x00;
if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
else if (twobytes == 0x8202)
{
highbyte = binr.ReadByte(); //advance 2 bytes
lowbyte = binr.ReadByte();
}
else
return null;
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order
int modsize = BitConverter.ToInt32(modint, 0);
byte firstbyte = binr.ReadByte();
binr.BaseStream.Seek(-1, SeekOrigin.Current);
if (firstbyte == 0x00)
{ //if first byte (highest order) of modulus is zero, don't include it
binr.ReadByte(); //skip this null byte
modsize -= 1; //reduce modulus buffer size by 1
}
byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes
if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data
return null;
int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values)
byte[] exponent = binr.ReadBytes(expbytes);
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters();
RSAKeyInfo.Modulus = modulus;
RSAKeyInfo.Exponent = exponent;
RSA.ImportParameters(RSAKeyInfo);
return RSA;
}
catch (Exception)
{
return null;
}
finally { binr.Close(); }
}
private static int GetIntegerSize(BinaryReader binr)
{
byte bt = 0;
byte lowbyte = 0x00;
byte highbyte = 0x00;
int count = 0;
bt = binr.ReadByte();
if (bt != 0x02) //expect integer
return 0;
bt = binr.ReadByte();
if (bt == 0x81)
count = binr.ReadByte(); // data size in next byte
else
if (bt == 0x82)
{
highbyte = binr.ReadByte(); // data size in next 2 bytes
lowbyte = binr.ReadByte();
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
count = BitConverter.ToInt32(modint, 0);
}
else
{
count = bt; // we already have the data size
}
while (binr.ReadByte() == 0x00)
{ //remove high order zeros in data
count -= 1;
}
binr.BaseStream.Seek(-1, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte
return count;
}
public static byte[] BlockEncrypt(this RSACryptoServiceProvider rsa, byte[] pbBuffer)
{
// Setup the return buffer
System.IO.MemoryStream stream = new System.IO.MemoryStream();
// The maximum block size is the length of the modulus in bytes
// minus 11 bytes for padding.
int nMaxBlockSize = rsa.ExportParameters(false).Modulus.Length - 11;
int nLength = pbBuffer.Length;
int nBlocks = ((nLength % nMaxBlockSize) == 0) ? nLength / nMaxBlockSize : nLength / nMaxBlockSize + 1;
int nTotalBytes = 0;
for (int i = 0; i < nBlocks; i++)
{
// Calculate the block length
int nBlockLength = (i == (nBlocks - 1) ? nLength - (i * nMaxBlockSize) : nMaxBlockSize);
// Allocate a new block and copy data from the main buffer
byte[] pbBlock = new byte[nBlockLength];
Array.Copy(pbBuffer, i * nMaxBlockSize, pbBlock, 0, nBlockLength);
// Encrypt the block
byte[] pbOut = rsa.Encrypt(pbBlock, false);
// Copy the block to the output stream
stream.Write(pbOut, 0, pbOut.Length);
// Keep a count of the encrypted bytes
nTotalBytes += pbOut.Length;
}
// Create an output buffer
byte[] pbReturn = new byte[nTotalBytes];
stream.Seek(0, System.IO.SeekOrigin.Begin);
stream.Read(pbReturn, 0, nTotalBytes);
// Return the data
return pbReturn;
}
public static byte[] BlockDecrypt(this RSACryptoServiceProvider rsa, byte[] pbBuffer)
{
// Setup the return buffer
System.IO.MemoryStream stream = new System.IO.MemoryStream();
// The maximum block size is the length of the modulus in bytes
int nMaxBlockSize = rsa.ExportParameters(false).Modulus.Length;
int nLength = pbBuffer.Length;
int nBlocks = ((nLength % nMaxBlockSize) == 0) ? nLength / nMaxBlockSize : nLength / nMaxBlockSize + 1;
int nTotalBytes = 0;
for (int i = 0; i < nBlocks; i++)
{
// Calculate the block length
int nBlockLength = (i == (nBlocks - 1) ? nLength - (i * nMaxBlockSize) : nMaxBlockSize);
// Allocate a new block and copy data from the main buffer
byte[] pbBlock = new byte[nBlockLength];
Array.Copy(pbBuffer, i * nMaxBlockSize, pbBlock, 0, nBlockLength);
// Encrypt the block
byte[] pbOut = rsa.Decrypt(pbBlock, false);
// Copy the block to the output stream
stream.Write(pbOut, 0, pbOut.Length);
// Keep a count of the encrypted bytes
nTotalBytes += pbOut.Length;
}
// Create an output buffer
byte[] pbReturn = new byte[nTotalBytes];
stream.Seek(0, System.IO.SeekOrigin.Begin);
stream.Read(pbReturn, 0, nTotalBytes);
// Return the data
return pbReturn;
}
}
}
| |
//
// CmsSigner.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.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.IO;
using System.Collections.Generic;
#if !PORTABLE && !COREFX
using X509Certificate2 = System.Security.Cryptography.X509Certificates.X509Certificate2;
#endif
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Security;
namespace MimeKit.Cryptography {
/// <summary>
/// An S/MIME signer.
/// </summary>
/// <remarks>
/// If the X.509 certificate is known for the signer, you may wish to use a
/// <see cref="CmsSigner"/> as opposed to having the <see cref="CryptographyContext"/>
/// do its own certificate lookup for the signer's <see cref="MailboxAddress"/>.
/// </remarks>
public class CmsSigner
{
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsSigner"/> class.
/// </summary>
/// <remarks>
/// <para>The initial value of the <see cref="DigestAlgorithm"/> will be set to
/// <see cref="MimeKit.Cryptography.DigestAlgorithm.Sha1"/> and both the
/// <see cref="SignedAttributes"/> and <see cref="UnsignedAttributes"/> properties
/// will be initialized to empty tables.</para>
/// </remarks>
CmsSigner ()
{
UnsignedAttributes = new AttributeTable (new Dictionary<DerObjectIdentifier, Asn1Encodable> ());
SignedAttributes = new AttributeTable (new Dictionary<DerObjectIdentifier, Asn1Encodable> ());
DigestAlgorithm = DigestAlgorithm.Sha1;
}
static void CheckCertificateCanBeUsedForSigning (X509Certificate certificate)
{
var flags = certificate.GetKeyUsageFlags ();
if (flags != X509KeyUsageFlags.None && (flags & SecureMimeContext.DigitalSignatureKeyUsageFlags) == 0)
throw new ArgumentException ("The certificate cannot be used for signing.");
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsSigner"/> class.
/// </summary>
/// <remarks>
/// <para>The initial value of the <see cref="DigestAlgorithm"/> will be set to
/// <see cref="MimeKit.Cryptography.DigestAlgorithm.Sha1"/> and both the
/// <see cref="SignedAttributes"/> and <see cref="UnsignedAttributes"/> properties
/// will be initialized to empty tables.</para>
/// </remarks>
/// <param name="chain">The chain of certificates starting with the signer's certificate back to the root.</param>
/// <param name="key">The signer's private key.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="chain"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="key"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="chain"/> did not contain any certificates.</para>
/// <para>-or-</para>
/// <para>The certificate cannot be used for signing.</para>
/// <para>-or-</para>
/// <para><paramref name="key"/> is not a private key.</para>
/// </exception>
public CmsSigner (IEnumerable<X509Certificate> chain, AsymmetricKeyParameter key) : this ()
{
if (chain == null)
throw new ArgumentNullException ("chain");
if (key == null)
throw new ArgumentNullException ("key");
CertificateChain = new X509CertificateChain (chain);
if (CertificateChain.Count == 0)
throw new ArgumentException ("The certificate chain was empty.", "chain");
CheckCertificateCanBeUsedForSigning (CertificateChain[0]);
if (!key.IsPrivate)
throw new ArgumentException ("The key must be a private key.", "key");
Certificate = CertificateChain[0];
PrivateKey = key;
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsSigner"/> class.
/// </summary>
/// <remarks>
/// <para>The initial value of the <see cref="MimeKit.Cryptography.DigestAlgorithm"/> will
/// be set to <see cref="MimeKit.Cryptography.DigestAlgorithm.Sha1"/> and both the
/// <see cref="SignedAttributes"/> and <see cref="UnsignedAttributes"/> properties will be
/// initialized to empty tables.</para>
/// </remarks>
/// <param name="certificate">The signer's certificate.</param>
/// <param name="key">The signer's private key.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="certificate"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="key"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="certificate"/> cannot be used for signing.</para>
/// <para>-or-</para>
/// <para><paramref name="key"/> is not a private key.</para>
/// </exception>
public CmsSigner (X509Certificate certificate, AsymmetricKeyParameter key) : this ()
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
CheckCertificateCanBeUsedForSigning (certificate);
if (key == null)
throw new ArgumentNullException ("key");
if (!key.IsPrivate)
throw new ArgumentException ("The key must be a private key.", "key");
CertificateChain = new X509CertificateChain ();
CertificateChain.Add (certificate);
Certificate = certificate;
PrivateKey = key;
}
void LoadPkcs12 (Stream stream, string password)
{
var pkcs12 = new Pkcs12Store (stream, password.ToCharArray ());
foreach (string alias in pkcs12.Aliases) {
if (!pkcs12.IsKeyEntry (alias))
continue;
var chain = pkcs12.GetCertificateChain (alias);
var key = pkcs12.GetKey (alias);
if (!key.Key.IsPrivate || chain.Length == 0)
continue;
var flags = chain[0].Certificate.GetKeyUsageFlags ();
if (flags != X509KeyUsageFlags.None && (flags & SecureMimeContext.DigitalSignatureKeyUsageFlags) == 0)
continue;
CheckCertificateCanBeUsedForSigning (chain[0].Certificate);
CertificateChain = new X509CertificateChain ();
Certificate = chain[0].Certificate;
PrivateKey = key.Key;
foreach (var entry in chain)
CertificateChain.Add (entry.Certificate);
break;
}
if (PrivateKey == null)
throw new ArgumentException ("The stream did not contain a private key.", "stream");
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsSigner"/> class.
/// </summary>
/// <remarks>
/// <para>Creates a new <see cref="CmsSigner"/>, loading the X.509 certificate and private key
/// from the specified stream.</para>
/// <para>The initial value of the <see cref="MimeKit.Cryptography.DigestAlgorithm"/> will
/// be set to <see cref="MimeKit.Cryptography.DigestAlgorithm.Sha1"/> and both the
/// <see cref="SignedAttributes"/> and <see cref="UnsignedAttributes"/> properties will be
/// initialized to empty tables.</para>
/// </remarks>
/// <param name="stream">The raw certificate and key data in pkcs12 format.</param>
/// <param name="password">The password to unlock the stream.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="stream"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="password"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="stream"/> does not contain a private key.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public CmsSigner (Stream stream, string password) : this ()
{
if (stream == null)
throw new ArgumentNullException ("stream");
if (password == null)
throw new ArgumentNullException ("password");
LoadPkcs12 (stream, password);
}
#if !PORTABLE
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsSigner"/> class.
/// </summary>
/// <remarks>
/// <para>Creates a new <see cref="CmsSigner"/>, loading the X.509 certificate and private key
/// from the specified file.</para>
/// <para>The initial value of the <see cref="MimeKit.Cryptography.DigestAlgorithm"/> will
/// be set to <see cref="MimeKit.Cryptography.DigestAlgorithm.Sha1"/> and both the
/// <see cref="SignedAttributes"/> and <see cref="UnsignedAttributes"/> properties will be
/// initialized to empty tables.</para>
/// </remarks>
/// <param name="fileName">The raw certificate and key data in pkcs12 format.</param>
/// <param name="password">The password to unlock the stream.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="fileName"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="password"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="fileName"/> is a zero-length string, contains only white space, or
/// contains one or more invalid characters as defined by
/// <see cref="System.IO.Path.InvalidPathChars"/>.
/// </exception>
/// <exception cref="System.IO.DirectoryNotFoundException">
/// <paramref name="fileName"/> is an invalid file path.
/// </exception>
/// <exception cref="System.IO.FileNotFoundException">
/// The specified file path could not be found.
/// </exception>
/// <exception cref="System.UnauthorizedAccessException">
/// The user does not have access to read the specified file.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public CmsSigner (string fileName, string password) : this ()
{
if (fileName == null)
throw new ArgumentNullException ("fileName");
if (password == null)
throw new ArgumentNullException ("password");
using (var stream = File.OpenRead (fileName))
LoadPkcs12 (stream, password);
}
#endif
#if !PORTABLE && !COREFX
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsSigner"/> class.
/// </summary>
/// <remarks>
/// <para>The initial value of the <see cref="MimeKit.Cryptography.DigestAlgorithm"/> will
/// be set to <see cref="MimeKit.Cryptography.DigestAlgorithm.Sha1"/> and both the
/// <see cref="SignedAttributes"/> and <see cref="UnsignedAttributes"/> properties will be
/// initialized to empty tables.</para>
/// </remarks>
/// <param name="certificate">The signer's certificate.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="certificate"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="certificate"/> cannot be used for signing.
/// </exception>
public CmsSigner (X509Certificate2 certificate) : this ()
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
if (!certificate.HasPrivateKey)
throw new ArgumentException ("The certificate does not contain a private key.", "certificate");
var cert = DotNetUtilities.FromX509Certificate (certificate);
var key = DotNetUtilities.GetKeyPair (certificate.PrivateKey);
CheckCertificateCanBeUsedForSigning (cert);
CertificateChain = new X509CertificateChain ();
CertificateChain.Add (cert);
Certificate = cert;
PrivateKey = key.Private;
}
#endif
/// <summary>
/// Gets the signer's certificate.
/// </summary>
/// <remarks>
/// The signer's certificate that contains a public key that can be used for
/// verifying the digital signature.
/// </remarks>
/// <value>The signer's certificate.</value>
public X509Certificate Certificate {
get; private set;
}
/// <summary>
/// Gets the certificate chain.
/// </summary>
/// <remarks>
/// Gets the certificate chain.
/// </remarks>
/// <value>The certificate chain.</value>
public X509CertificateChain CertificateChain {
get; private set;
}
/// <summary>
/// Gets or sets the digest algorithm.
/// </summary>
/// <remarks>
/// Specifies which digest algorithm to use to generate the
/// cryptographic hash of the content being signed.
/// </remarks>
/// <value>The digest algorithm.</value>
public DigestAlgorithm DigestAlgorithm {
get; set;
}
/// <summary>
/// Gets the private key.
/// </summary>
/// <remarks>
/// The private key used for signing.
/// </remarks>
/// <value>The private key.</value>
public AsymmetricKeyParameter PrivateKey {
get; private set;
}
/// <summary>
/// Gets or sets the signed attributes.
/// </summary>
/// <remarks>
/// A table of attributes that should be included in the signature.
/// </remarks>
/// <value>The signed attributes.</value>
public AttributeTable SignedAttributes {
get; set;
}
/// <summary>
/// Gets or sets the unsigned attributes.
/// </summary>
/// <remarks>
/// A table of attributes that should not be signed in the signature,
/// but still included in transport.
/// </remarks>
/// <value>The unsigned attributes.</value>
public AttributeTable UnsignedAttributes {
get; set;
}
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using Zutatensuppe.D2Reader;
using Zutatensuppe.D2Reader.Models;
using Zutatensuppe.DiabloInterface.Lib;
namespace DiabloInterface.Plugin.HttpClient
{
class RequestBody
{
private static readonly List<string> AutocompareProps = new List<string> {
"Area",
"InventoryTab",
"Difficulty",
"PlayersX",
"Seed",
"SeedIsArg",
"Name",
"CharClass",
"IsHardcore",
"IsExpansion",
"IsDead",
"Deaths",
"Level",
"Experience",
"Strength",
"Dexterity",
"Vitality",
"Energy",
"Life",
"LifeMax",
"Mana",
"ManaMax",
"FireResist",
"ColdResist",
"LightningResist",
"PoisonResist",
"Gold",
"GoldStash",
"FasterCastRate",
"FasterHitRecovery",
"FasterRunWalk",
"IncreasedAttackSpeed",
"MagicFind",
};
public string Event { get; private set; }
public string Headers { get; set; }
public int? Area { get; set; }
public byte? InventoryTab { get; set; }
public GameDifficulty? Difficulty { get; set; }
public int? PlayersX { get; set; }
public uint? Seed { get; set; }
public bool? SeedIsArg { get; set; }
public uint? GameCount { get; set; }
public uint? CharCount { get; set; }
public bool? NewCharacter { get; set; }
public string Name { get; set; }
public string Guid { get; set; }
public CharacterClass? CharClass { get; set; }
public bool? IsHardcore { get; set; }
public bool? IsExpansion { get; set; }
public bool? IsDead { get; set; }
public short? Deaths { get; set; }
public int? Level { get; set; }
public int? Experience { get; set; }
public int? Strength { get; set; }
public int? Dexterity { get; set; }
public int? Vitality { get; set; }
public int? Energy { get; set; }
public int? FireResist { get; set; }
public int? ColdResist { get; set; }
public int? LightningResist { get; set; }
public int? PoisonResist { get; set; }
public int? Gold { get; set; }
public int? GoldStash { get; set; }
public int? Life { get; set; }
public int? LifeMax { get; set; }
public int? Mana { get; set; }
public int? ManaMax { get; set; }
public int? FasterCastRate { get; set; }
public int? FasterHitRecovery { get; set; }
public int? FasterRunWalk { get; set; }
public int? IncreasedAttackSpeed { get; set; }
public int? MagicFind { get; set; }
public List<ItemInfo> Items { get; set; }
public List<ItemInfo> AddedItems { get; set; }
public List<ItemInfo> RemovedItems { get; set; }
public List<SkillInfo> Skills { get; set; }
public Dictionary<GameDifficulty, List<QuestId>> Quests { get; set; }
public Dictionary<GameDifficulty, List<QuestId>> CompletedQuests { get; set; }
public HirelingDiff Hireling { get; set; }
public List<Monster> KilledMonsters { get; set; }
[JsonConverter(typeof(ProcessInfoConverter))]
public ProcessInfo D2ProcessInfo { get; set; }
[JsonConverter(typeof(DIApplicationInfoConverter))]
public IApplicationInfo DIApplicationInfo { get; set; }
public static RequestBody FromDataReadEventArgs(DataReadEventArgs e, IDiabloInterface di)
{
return new RequestBody()
{
Event = "DataRead",
Area = e.Game.Area,
InventoryTab = e.Game.InventoryTab,
Difficulty = e.Game.Difficulty,
PlayersX = e.Game.PlayersX,
Seed = e.Game.Seed,
SeedIsArg = e.Game.SeedIsArg,
GameCount = e.Game.GameCount,
CharCount = e.Game.CharCount,
Name = e.Character.Name,
Guid = e.Character.Guid,
CharClass = e.Character.CharClass,
IsHardcore = e.Character.IsHardcore,
IsExpansion = e.Character.IsExpansion,
IsDead = e.Character.IsDead,
Deaths = e.Character.Deaths,
Level = e.Character.Level,
Experience = e.Character.Experience,
Strength = e.Character.Strength,
Dexterity = e.Character.Dexterity,
Vitality = e.Character.Vitality,
Energy = e.Character.Energy,
Life = e.Character.Life,
LifeMax = e.Character.LifeMax,
Mana = e.Character.Mana,
ManaMax = e.Character.ManaMax,
FireResist = e.Character.FireResist,
ColdResist = e.Character.ColdResist,
LightningResist = e.Character.LightningResist,
PoisonResist = e.Character.PoisonResist,
Gold = e.Character.Gold,
GoldStash = e.Character.GoldStash,
FasterCastRate = e.Character.FasterCastRate,
FasterHitRecovery = e.Character.FasterHitRecovery,
FasterRunWalk = e.Character.FasterRunWalk,
IncreasedAttackSpeed = e.Character.IncreasedAttackSpeed,
MagicFind = e.Character.MagicFind,
Items = e.Character.Items,
Skills = e.Character.Skills,
Quests = e.Quests.CompletedQuestIds,
Hireling = new HirelingDiff
{
Name = e.Game.Hireling?.Name,
Class = e.Game.Hireling?.Class,
Skills = e.Game.Hireling?.Skills,
Level = e.Game.Hireling?.Level,
Experience = e.Game.Hireling?.Experience,
Strength = e.Game.Hireling?.Strength,
Dexterity = e.Game.Hireling?.Dexterity,
FireResist = e.Game.Hireling?.FireResist,
ColdResist = e.Game.Hireling?.ColdResist,
LightningResist = e.Game.Hireling?.LightningResist,
PoisonResist = e.Game.Hireling?.PoisonResist,
Items = e.Game.Hireling?.Items
},
KilledMonsters = e.KilledMonsters,
D2ProcessInfo = e.ProcessInfo,
DIApplicationInfo = di.appInfo,
};
}
public static RequestBody FromProcessFoundEventArgs(ProcessFoundEventArgs e, IDiabloInterface di)
{
return new RequestBody()
{
Event = "ProcessFound",
D2ProcessInfo = e.ProcessInfo,
DIApplicationInfo = di.appInfo,
};
}
public static RequestBody GetDiff(
RequestBody curr,
RequestBody prev
) {
var diff = new RequestBody();
// TODO: while this check is correct, D2DataReader should probably
// provide the information about 'new char or not' directly
// in a property of the DataReadEventArgs
if (curr.CharCount > 0 && !curr.CharCount.Equals(prev.CharCount))
{
diff.NewCharacter = true;
prev = new RequestBody();
}
if (!curr.GameCount.Equals(prev.GameCount))
{
prev = new RequestBody();
}
var hasDiff = false;
foreach (string propertyName in AutocompareProps)
{
var property = typeof(RequestBody).GetProperty(propertyName);
var prevValue = property.GetValue(prev);
var newValue = property.GetValue(curr);
if (!DiffUtil.ObjectsEqual(prevValue, newValue))
{
hasDiff = true;
property.SetValue(diff, newValue);
}
}
var itemsDiff = DiffUtil.ItemsDiff(curr.Items, prev.Items);
diff.AddedItems = itemsDiff.Item1;
diff.RemovedItems = itemsDiff.Item2;
if (!DiffUtil.ListsEqual(curr.Skills, prev.Skills))
diff.Skills = curr.Skills;
diff.CompletedQuests = DiffUtil.CompletedQuestsDiff(
curr.Quests,
prev.Quests
);
diff.Hireling = HirelingDiff.GetDiff(
curr.Hireling,
prev.Hireling
);
if (curr.KilledMonsters != null && curr.KilledMonsters.Count > 0)
{
diff.KilledMonsters = curr.KilledMonsters;
}
hasDiff = hasDiff
|| diff.AddedItems != null
|| diff.RemovedItems != null
|| diff.Skills != null
|| diff.CompletedQuests != null
|| diff.Hireling != null
|| diff.KilledMonsters != null;
if (hasDiff)
{
diff.Event = curr.Event;
diff.Name = curr.Name;
diff.Guid = curr.Guid;
// always send application info, if something is sent
diff.DIApplicationInfo = curr.DIApplicationInfo;
// always send d2 info, if something is sent
diff.D2ProcessInfo = curr.D2ProcessInfo;
return diff;
}
return null;
}
}
class ProcessInfoConverter : JsonConverter
{
public override void WriteJson(
JsonWriter writer,
object value,
JsonSerializer serializer
) {
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
return;
}
var info = (ProcessInfo)value;
JObject o = new JObject();
o.Add("Type", info.ReadableType());
o.Add("Version", info.ReadableVersion());
o.Add("CommandLineArgs", new JArray(info.CommandLineArgs));
o.WriteTo(writer);
}
public override object ReadJson(
JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer
) {
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ProcessInfo);
}
public override bool CanRead
{
get { return false; }
}
}
class DIApplicationInfoConverter : JsonConverter
{
public override void WriteJson(
JsonWriter writer,
object value,
JsonSerializer serializer
) {
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
return;
}
var info = (IApplicationInfo)value;
JObject o = new JObject();
o.Add("Version", info.Version);
o.WriteTo(writer);
}
public override object ReadJson(
JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer
) {
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(IApplicationInfo);
}
public override bool CanRead
{
get { return false; }
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Threading;
using NLog.Common;
using NLog.Internal;
using NLog.Internal.NetworkSenders;
using NLog.Layouts;
/// <summary>
/// Sends log messages over the network.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/Network-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/Network/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/Network/Simple/Example.cs" />
/// <p>
/// To print the results, use any application that's able to receive messages over
/// TCP or UDP. <a href="http://m.nu/program/util/netcat/netcat.html">NetCat</a> is
/// a simple but very powerful command-line tool that can be used for that. This image
/// demonstrates the NetCat tool receiving log messages from Network target.
/// </p>
/// <img src="examples/targets/Screenshots/Network/Output.gif" />
/// <p>
/// NOTE: If your receiver application is ever likely to be off-line, don't use TCP protocol
/// or you'll get TCP timeouts and your application will be very slow.
/// Either switch to UDP transport or use <a href="target.AsyncWrapper.html">AsyncWrapper</a> target
/// so that your application threads will not be blocked by the timing-out connection attempts.
/// </p>
/// <p>
/// There are two specialized versions of the Network target: <a href="target.Chainsaw.html">Chainsaw</a>
/// and <a href="target.NLogViewer.html">NLogViewer</a> which write to instances of Chainsaw log4j viewer
/// or NLogViewer application respectively.
/// </p>
/// </example>
[Target("Network")]
public class NetworkTarget : TargetWithLayout
{
private readonly Dictionary<string, LinkedListNode<NetworkSender>> _currentSenderCache = new Dictionary<string, LinkedListNode<NetworkSender>>();
private readonly LinkedList<NetworkSender> _openNetworkSenders = new LinkedList<NetworkSender>();
private readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(16 * 1024);
/// <summary>
/// Initializes a new instance of the <see cref="NetworkTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public NetworkTarget()
{
SenderFactory = NetworkSenderFactory.Default;
Encoding = Encoding.UTF8;
OnOverflow = NetworkTargetOverflowAction.Split;
KeepConnection = true;
MaxMessageSize = 65000;
ConnectionCacheSize = 5;
LineEnding = LineEndingMode.CRLF;
OptimizeBufferReuse = GetType() == typeof(NetworkTarget); // Class not sealed, reduce breaking changes
}
/// <summary>
/// Initializes a new instance of the <see cref="NetworkTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
/// <param name="name">Name of the target.</param>
public NetworkTarget(string name) : this()
{
Name = name;
}
/// <summary>
/// Gets or sets the network address.
/// </summary>
/// <remarks>
/// The network address can be:
/// <ul>
/// <li>tcp://host:port - TCP (auto select IPv4/IPv6) (not supported on Windows Phone 7.0)</li>
/// <li>tcp4://host:port - force TCP/IPv4 (not supported on Windows Phone 7.0)</li>
/// <li>tcp6://host:port - force TCP/IPv6 (not supported on Windows Phone 7.0)</li>
/// <li>udp://host:port - UDP (auto select IPv4/IPv6, not supported on Silverlight and on Windows Phone 7.0)</li>
/// <li>udp4://host:port - force UDP/IPv4 (not supported on Silverlight and on Windows Phone 7.0)</li>
/// <li>udp6://host:port - force UDP/IPv6 (not supported on Silverlight and on Windows Phone 7.0)</li>
/// <li>http://host:port/pageName - HTTP using POST verb</li>
/// <li>https://host:port/pageName - HTTPS using POST verb</li>
/// </ul>
/// For SOAP-based webservice support over HTTP use WebService target.
/// </remarks>
/// <docgen category='Connection Options' order='10' />
public Layout Address { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to keep connection open whenever possible.
/// </summary>
/// <docgen category='Connection Options' order='10' />
[DefaultValue(true)]
public bool KeepConnection { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to append newline at the end of log message.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[DefaultValue(false)]
public bool NewLine { get; set; }
/// <summary>
/// Gets or sets the end of line value if a newline is appended at the end of log message <see cref="NewLine"/>.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[DefaultValue("CRLF")]
public LineEndingMode LineEnding { get; set; }
/// <summary>
/// Gets or sets the maximum message size in bytes.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[DefaultValue(65000)]
public int MaxMessageSize { get; set; }
/// <summary>
/// Gets or sets the size of the connection cache (number of connections which are kept alive).
/// </summary>
/// <docgen category="Connection Options" order="10"/>
[DefaultValue(5)]
public int ConnectionCacheSize { get; set; }
/// <summary>
/// Gets or sets the maximum current connections. 0 = no maximum.
/// </summary>
/// <docgen category="Connection Options" order="10"/>
public int MaxConnections { get; set; }
/// <summary>
/// Gets or sets the action that should be taken if the will be more connections than <see cref="MaxConnections"/>.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public NetworkTargetConnectionsOverflowAction OnConnectionOverflow { get; set; }
/// <summary>
/// Gets or sets the maximum queue size.
/// </summary>
/// <docgen category='Connection Options' order='10' />
[DefaultValue(0)]
public int MaxQueueSize { get; set; }
/// <summary>
/// Gets or sets the action that should be taken if the message is larger than
/// maxMessageSize.
/// </summary>
/// <docgen category='Connection Options' order='10' />
[DefaultValue(NetworkTargetOverflowAction.Split)]
public NetworkTargetOverflowAction OnOverflow { get; set; }
/// <summary>
/// Gets or sets the encoding to be used.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[DefaultValue("utf-8")]
public Encoding Encoding { get; set; }
#if !SILVERLIGHT
/// <summary>
/// Get or set the SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public System.Security.Authentication.SslProtocols SslProtocols { get; set; } = System.Security.Authentication.SslProtocols.None;
/// <summary>
/// The number of seconds a connection will remain idle before the first keep-alive probe is sent
/// </summary>
/// <docgen category='Connection Options' order='10' />
public int KeepAliveTimeSeconds { get; set; }
#endif
internal INetworkSenderFactory SenderFactory { get; set; }
/// <summary>
/// Flush any pending log messages asynchronously (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
int remainingCount;
void Continuation(Exception ex)
{
// ignore exception
if (Interlocked.Decrement(ref remainingCount) == 0)
{
asyncContinuation(null);
}
}
lock (_openNetworkSenders)
{
remainingCount = _openNetworkSenders.Count;
if (remainingCount == 0)
{
// nothing to flush
asyncContinuation(null);
}
else
{
// otherwise call FlushAsync() on all senders
// and invoke continuation at the very end
foreach (var openSender in _openNetworkSenders)
{
openSender.FlushAsync(Continuation);
}
}
}
}
/// <summary>
/// Closes the target.
/// </summary>
protected override void CloseTarget()
{
base.CloseTarget();
lock (_openNetworkSenders)
{
foreach (var openSender in _openNetworkSenders)
{
openSender.Close(ex => { });
}
_openNetworkSenders.Clear();
}
}
/// <summary>
/// Sends the
/// rendered logging event over the network optionally concatenating it with a newline character.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
string address = RenderLogEvent(Address, logEvent.LogEvent);
InternalLogger.Trace("NetworkTarget(Name={0}): Sending to address: '{1}'", Name, address);
byte[] bytes = GetBytesToWrite(logEvent.LogEvent);
if (KeepConnection)
{
LinkedListNode<NetworkSender> senderNode;
try
{
senderNode = GetCachedNetworkSender(address);
}
catch (Exception ex)
{
InternalLogger.Error(ex, "NetworkTarget(Name={0}): Failed to create sender to address: '{1}'", Name, address);
throw;
}
ChunkedSend(
senderNode.Value,
bytes,
ex =>
{
if (ex != null)
{
InternalLogger.Error(ex, "NetworkTarget(Name={0}): Error when sending.", Name);
ReleaseCachedConnection(senderNode);
}
logEvent.Continuation(ex);
});
}
else
{
NetworkSender sender;
LinkedListNode<NetworkSender> linkedListNode;
lock (_openNetworkSenders)
{
//handle too many connections
var tooManyConnections = _openNetworkSenders.Count >= MaxConnections;
if (tooManyConnections && MaxConnections > 0)
{
switch (OnConnectionOverflow)
{
case NetworkTargetConnectionsOverflowAction.DiscardMessage:
InternalLogger.Warn("NetworkTarget(Name={0}): Discarding message otherwise to many connections.", Name);
logEvent.Continuation(null);
return;
case NetworkTargetConnectionsOverflowAction.AllowNewConnnection:
InternalLogger.Debug("NetworkTarget(Name={0}): Too may connections, but this is allowed", Name);
break;
case NetworkTargetConnectionsOverflowAction.Block:
while (_openNetworkSenders.Count >= MaxConnections)
{
InternalLogger.Debug("NetworkTarget(Name={0}): Blocking networktarget otherwhise too many connections.", Name);
Monitor.Wait(_openNetworkSenders);
InternalLogger.Trace("NetworkTarget(Name={0}): Entered critical section.", Name);
}
InternalLogger.Trace("NetworkTarget(Name={0}): Limit ok.", Name);
break;
}
}
try
{
sender = CreateNetworkSender(address);
}
catch (Exception ex)
{
InternalLogger.Error(ex, "NetworkTarget(Name={0}): Failed to create sender to address: '{1}'", Name, address);
throw;
}
linkedListNode = _openNetworkSenders.AddLast(sender);
}
ChunkedSend(
sender,
bytes,
ex =>
{
lock (_openNetworkSenders)
{
TryRemove(_openNetworkSenders, linkedListNode);
if (OnConnectionOverflow == NetworkTargetConnectionsOverflowAction.Block)
{
Monitor.PulseAll(_openNetworkSenders);
}
}
if (ex != null)
{
InternalLogger.Error(ex, "NetworkTarget(Name={0}): Error when sending.", Name);
}
sender.Close(ex2 => { });
logEvent.Continuation(ex);
});
}
}
/// <summary>
/// Try to remove.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="node"></param>
/// <returns>removed something?</returns>
private static bool TryRemove<T>(LinkedList<T> list, LinkedListNode<T> node)
{
if (node == null || list != node.List)
{
return false;
}
list.Remove(node);
return true;
}
/// <summary>
/// Gets the bytes to be written.
/// </summary>
/// <param name="logEvent">Log event.</param>
/// <returns>Byte array.</returns>
protected virtual byte[] GetBytesToWrite(LogEventInfo logEvent)
{
if (OptimizeBufferReuse)
{
using (var localBuffer = _reusableEncodingBuffer.Allocate())
{
if (!NewLine && logEvent.TryGetCachedLayoutValue(Layout, out var text))
{
return GetBytesFromString(localBuffer.Result, text?.ToString() ?? string.Empty);
}
else
{
using (var localBuilder = ReusableLayoutBuilder.Allocate())
{
Layout.RenderAppendBuilder(logEvent, localBuilder.Result, false);
if (NewLine)
{
localBuilder.Result.Append(LineEnding.NewLineCharacters);
}
return GetBytesFromStringBuilder(localBuffer.Result, localBuilder.Result);
}
}
}
}
else
{
var rendered = Layout.Render(logEvent);
InternalLogger.Trace("NetworkTarget(Name={0}): Sending: {1}", Name, rendered);
if (NewLine)
{
rendered += LineEnding.NewLineCharacters;
}
return Encoding.GetBytes(rendered);
}
}
private byte[] GetBytesFromStringBuilder(char[] charBuffer, StringBuilder stringBuilder)
{
InternalLogger.Trace("NetworkTarget(Name={0}): Sending {1} chars", Name, stringBuilder.Length);
#if !SILVERLIGHT
if (stringBuilder.Length <= charBuffer.Length)
{
stringBuilder.CopyTo(0, charBuffer, 0, stringBuilder.Length);
return Encoding.GetBytes(charBuffer, 0, stringBuilder.Length);
}
#endif
return Encoding.GetBytes(stringBuilder.ToString());
}
private byte[] GetBytesFromString(char[] charBuffer, string layoutMessage)
{
InternalLogger.Trace("NetworkTarget(Name={0}): Sending {1}", Name, layoutMessage);
#if !SILVERLIGHT
if (layoutMessage.Length <= charBuffer.Length)
{
layoutMessage.CopyTo(0, charBuffer, 0, layoutMessage.Length);
return Encoding.GetBytes(charBuffer, 0, layoutMessage.Length);
}
#endif
return Encoding.GetBytes(layoutMessage);
}
private LinkedListNode<NetworkSender> GetCachedNetworkSender(string address)
{
lock (_currentSenderCache)
{
// already have address
if (_currentSenderCache.TryGetValue(address, out var senderNode))
{
senderNode.Value.CheckSocket();
return senderNode;
}
if (_currentSenderCache.Count >= ConnectionCacheSize)
{
// make room in the cache by closing the least recently used connection
int minAccessTime = int.MaxValue;
LinkedListNode<NetworkSender> leastRecentlyUsed = null;
foreach (var pair in _currentSenderCache)
{
var networkSender = pair.Value.Value;
if (networkSender.LastSendTime < minAccessTime)
{
minAccessTime = networkSender.LastSendTime;
leastRecentlyUsed = pair.Value;
}
}
if (leastRecentlyUsed != null)
{
ReleaseCachedConnection(leastRecentlyUsed);
}
}
NetworkSender sender = CreateNetworkSender(address);
lock (_openNetworkSenders)
{
senderNode = _openNetworkSenders.AddLast(sender);
}
_currentSenderCache.Add(address, senderNode);
return senderNode;
}
}
private NetworkSender CreateNetworkSender(string address)
{
#if !SILVERLIGHT
var sender = SenderFactory.Create(address, MaxQueueSize, SslProtocols, TimeSpan.FromSeconds(KeepAliveTimeSeconds));
#else
var sender = SenderFactory.Create(address, MaxQueueSize);
#endif
sender.Initialize();
return sender;
}
private void ReleaseCachedConnection(LinkedListNode<NetworkSender> senderNode)
{
lock (_currentSenderCache)
{
var networkSender = senderNode.Value;
lock (_openNetworkSenders)
{
if (TryRemove(_openNetworkSenders, senderNode))
{
// only remove it once
networkSender.Close(ex => { });
}
}
// make sure the current sender for this address is the one we want to remove
if (_currentSenderCache.TryGetValue(networkSender.Address, out var sender2) && ReferenceEquals(senderNode, sender2))
{
_currentSenderCache.Remove(networkSender.Address);
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using property names in message.")]
private void ChunkedSend(NetworkSender sender, byte[] buffer, AsyncContinuation continuation)
{
int tosend = buffer.Length;
if (tosend <= MaxMessageSize)
{
// Chunking is not needed, no need to perform delegate capture
InternalLogger.Trace("NetworkTarget(Name={0}): Sending chunk, position: {1}, length: {2}", Name, 0, tosend);
if (tosend <= 0)
{
continuation(null);
return;
}
sender.Send(buffer, 0, tosend, continuation);
}
else
{
int pos = 0;
void SendNextChunk(Exception ex)
{
if (ex != null)
{
continuation(ex);
return;
}
InternalLogger.Trace("NetworkTarget(Name={0}): Sending chunk, position: {1}, length: {2}", Name, pos, tosend);
if (tosend <= 0)
{
continuation(null);
return;
}
int chunksize = tosend;
if (chunksize > MaxMessageSize)
{
if (OnOverflow == NetworkTargetOverflowAction.Discard)
{
InternalLogger.Trace("NetworkTarget(Name={0}): Discard because chunksize > this.MaxMessageSize", Name);
continuation(null);
return;
}
if (OnOverflow == NetworkTargetOverflowAction.Error)
{
continuation(new OverflowException($"Attempted to send a message larger than MaxMessageSize ({MaxMessageSize}). Actual size was: {buffer.Length}. Adjust OnOverflow and MaxMessageSize parameters accordingly."));
return;
}
chunksize = MaxMessageSize;
}
int pos0 = pos;
tosend -= chunksize;
pos += chunksize;
sender.Send(buffer, pos0, chunksize, SendNextChunk);
}
SendNextChunk(null);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.Abstractions;
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
namespace System.Xml.Tests
{
//[TestCase(Name = "TC_SchemaSet_Add_URL", Desc = "")]
public class TC_SchemaSet_Add_URL
{
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v1 - ns = null, URL = null", Priority = 0)]
public void v1()
{
try
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add((String)null, (String)null);
}
catch (ArgumentNullException)
{
// GLOBALIZATION
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v2 - ns = null, URL = valid", Priority = 0)]
public void v2()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema = sc.Add((String)null, TestData._FileXSD1);
Assert.Equal(Schema != null, true);
return;
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v3 - ns = valid, URL = valid")]
public void v3()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema = sc.Add("xsdauthor", TestData._XsdAuthor);
Assert.Equal(Schema != null, true);
return;
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v4 - ns = valid, URL = invalid")]
public void v4()
{
try
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add("xsdauthor", "http://Bla");
}
catch (Exception)
{
// GLOBALIZATION
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v5 - ns = unmatching, URL = valid")]
public void v5()
{
try
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add("", TestData._FileXSD1);
}
catch (XmlSchemaException)
{
// GLOBALIZATION
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v6 - adding same chameleon for diff NS")]
public void v6()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema1 = sc.Add("xsdauthor1", TestData._XsdNoNs);
XmlSchema Schema2 = sc.Add("xsdauthor2", TestData._XsdNoNs);
Assert.Equal(sc.Count, 2);
Assert.Equal(Schema1 != null, true);
// the second call to add should be ignored with Add returning the first obj
Assert.Equal((Schema2 == Schema1), false);
return;
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v7 - adding same URL for null ns")]
public void v7()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
XmlSchema Schema2 = sc.Add(null, TestData._XsdAuthor);
Assert.Equal(sc.Count, 1);
Assert.Equal(Schema1 != null, true);
// the second call to add should be ignored with Add returning the first obj
Assert.Equal(Schema2, Schema1);
return;
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v8 - adding a schema with NS and one without, to a NS.")]
public void v8()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema1 = sc.Add("xsdauthor", TestData._XsdAuthor);
XmlSchema Schema2 = sc.Add("xsdauthor", TestData._XsdNoNs);
Assert.Equal(sc.Count, 2);
Assert.Equal(Schema1 != null, true);
Assert.Equal((Schema2 == Schema1), false);
return;
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v9 - adding URL to XSD schema")]
public void v9()
{
XmlSchemaSet sc = new XmlSchemaSet();
try
{
sc.Add(null, TestData._Root + "schema1.xdr");
}
catch (XmlSchemaException)
{
Assert.Equal(sc.Count, 0);
// GLOBALIZATION
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v10 - Adding schema with top level element collision")]
public void v10()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema1 = sc.Add("xsdauthor", TestData._XsdAuthor);
XmlSchema Schema2 = sc.Add("xsdauthor", TestData._XsdAuthorDup);
// schemas should be successfully added
Assert.Equal(sc.Count, 2);
try
{
sc.Compile();
}
catch (XmlSchemaException)
{
Assert.Equal(sc.Count, 2);
// GLOBALIZATION
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v11 - Adding schema with top level element collision to Compiled Schemaset")]
public void v11()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema1 = sc.Add("xsdauthor", TestData._XsdAuthor);
sc.Compile();
XmlSchema Schema2 = sc.Add("xsdauthor", TestData._XsdAuthorDup);
// schemas should be successfully added
Assert.Equal(sc.Count, 2);
try
{
sc.Compile();
}
catch (XmlSchemaException)
{
Assert.Equal(sc.Count, 2);
// GLOBALIZATION
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "v12 - Adding schema with no tagetNS with element already existing in NS")]
public void v12()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema1 = sc.Add("xsdauthor", TestData._XsdAuthor);
XmlSchema Schema2 = sc.Add("xsdauthor", TestData._XsdAuthorNoNs);
// schemas should be successfully added
try
{
sc.Compile();
}
catch (XmlSchemaException)
{
// GLOBALIZATION
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
[Fact]
//[Variation(Desc = "435368 - schema validation error")]
public void v13()
{
string xsdPath = TestData._Root + @"bug435368.xsd";
string xmlPath = TestData._Root + @"bug435368.xml";
XmlSchemaSet xs = new XmlSchemaSet();
xs.Add(null, xsdPath);
XmlDocument xd = new XmlDocument();
xd.Load(xmlPath);
xd.Schemas = xs;
// Modify a, partially validate
XPathNavigator xpn = xd.CreateNavigator().SelectSingleNode("/root/a");
xpn.SetValue("b");
xd.Validate(null, ((IHasXmlNode)xpn).GetNode());
// Modify sg1, partially validate- validate will throw exception
xpn = xd.CreateNavigator().SelectSingleNode("/root/sg1");
xpn.SetValue("a");
xd.Validate(null, ((IHasXmlNode)xpn).GetNode());
return;
}
//====================TFS_298991 XMLSchemaSet.Compile of an XSD containing with a large number of elements results in a System.StackOverflow error
private static void GenerateSequenceXsdFile(int size, string xsdFileName)
{
// generate the xsd file, the file is some thing like this
//-------------------------------------------------------
//<?xml version='1.0'?>
//<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' >
//<xsd:element name='field0' />
//<xsd:element name='field1' />
//<xsd:element name='field2' />
//<xsd:element name='myFields'>
// <xsd:complexType>
// <xsd:sequence>
// <xsd:element ref='field0' minOccurs='0' />
// <xsd:element ref='field1' minOccurs='0' />
// <xsd:element ref='field2' minOccurs='0' />
// </xsd:sequence>
// </xsd:complexType>
//</xsd:element>
//</xsd:schema>
//------------------------------------------------------
StreamWriter sw = new StreamWriter(new FileStream(xsdFileName, FileMode.Create, FileAccess.Write));
string head = @"<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' >";
string body = @" <xsd:element name='myFields'>
<xsd:complexType>
<xsd:sequence>";
string end = @" </xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>";
sw.WriteLine(head);
for (int ii = 0; ii < size; ++ii)
sw.WriteLine(" <xsd:element name='field{0}' />", ii);
sw.WriteLine(body);
for (int ii = 0; ii < size; ++ii)
sw.WriteLine(" <xsd:element ref='field{0}' minOccurs='0' />", ii);
sw.WriteLine(end);
sw.Dispose();
}
private static void GenerateChoiceXsdFile(int size, string xsdFileName)
{
// generate the xsd file, the file is some thing like this
//-------------------------------------------------------
//<?xml version='1.0'?>
//<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' >
//<xsd:element name='field0' />
//<xsd:element name='field1' />
//<xsd:element name='field2' />
//<xsd:element name='myFields'>
// <xsd:complexType>
// <xsd:choice>
// <xsd:element ref='field0' minOccurs='0' />
// <xsd:element ref='field1' minOccurs='0' />
// <xsd:element ref='field2' minOccurs='0' />
// </xsd:choice>
// </xsd:complexType>
//</xsd:element>
//</xsd:schema>
//------------------------------------------------------
StreamWriter sw = new StreamWriter(new FileStream(xsdFileName, FileMode.Create, FileAccess.Write));
string head = @"<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' >";
string body = @" <xsd:element name='myFields'>
<xsd:complexType>
<xsd:choice>";
string end = @" </xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>";
sw.WriteLine(head);
for (int ii = 0; ii < size; ++ii)
sw.WriteLine(" <xsd:element name='field{0}' />", ii);
sw.WriteLine(body);
for (int ii = 0; ii < size; ++ii)
sw.WriteLine(" <xsd:element ref='field{0}' minOccurs='0' />", ii);
sw.WriteLine(end);
sw.Dispose();
}
public void verifyXsd(string file)
{
try
{
XmlSchemaSet ss = new XmlSchemaSet();
ss.Add("", file);
ss.Compile(); // if throws StackOfFlowException will cause test failure
}
catch (OutOfMemoryException)
{
// throw OutOfMemoryException is ok since it is catchable.
}
}
[OuterLoop]
[Theory]
[InlineData(5000, "5000s.xsd")]
[InlineData(10000, "10000s.xsd")]
//[Variation(Desc = "Bug 298991 XMLSchemaSet.Compile cause StackOverflow - Sequence, 5000", Params = new object[] { 5000, "5000s.xsd" })]
//[Variation(Desc = "Bug 298991 XMLSchemaSet.Compile cause StackOverflow - Sequence, 10000", Params = new object[] { 10000, "10000s.xsd" })]
public void bug298991Sequence(int size, string xsdFileName)
{
GenerateSequenceXsdFile(size, xsdFileName);
verifyXsd(xsdFileName);
return;
}
[OuterLoop]
[Theory]
[InlineData(5000, "5000c.xsd")]
//[Variation(Desc = "Bug 298991 XMLSchemaSet.Compile cause StackOverflow - Choice, 5000", Params = new object[] { 5000, "5000c.xsd" })]
public void bug298991Choice(int size, string xsdFileName)
{
GenerateChoiceXsdFile(size, xsdFileName);
verifyXsd(xsdFileName);
return;
}
}
}
| |
using System;
using ICSharpCode.NRefactory;
using ICSharpCode.NRefactory.Visitors;
using ICSharpCode.NRefactory.Ast;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering
{
public class CSharpToHLSL
{
public static bool GenerateHLSL(System.Type type, GenerateHLSL attribute, out string shaderSource)
{
List<string> errors;
return GenerateHLSL(type, attribute, out shaderSource, out errors);
}
public static bool GenerateHLSL(System.Type type, GenerateHLSL attribute, out string shaderSource, out List<string> errors)
{
ShaderTypeGenerator gen = new ShaderTypeGenerator(type, attribute);
bool success = gen.Generate();
if (success)
{
shaderSource = gen.Emit();
}
else
{
shaderSource = null;
}
errors = gen.errors;
return success;
}
public static void GenerateAll()
{
s_TypeName = new Dictionary<string, ShaderTypeGenerator>();
// Iterate over assemblyList, discover all applicable types with fully qualified names
var assemblyList = AppDomain.CurrentDomain.GetAssemblies()
// We need to exclude dynamic assemblies (their type can't be queried, throwing an exception below)
.Where(ass => !(ass.ManifestModule is System.Reflection.Emit.ModuleBuilder))
.ToList();
foreach (var assembly in assemblyList)
{
var types = assembly.GetExportedTypes();
foreach (var type in types)
{
var attributes = type.GetCustomAttributes(true);
foreach (var attr in attributes)
{
if (attr is GenerateHLSL)
{
ShaderTypeGenerator gen;
if (s_TypeName.TryGetValue(type.FullName, out gen))
{
Debug.LogError("Duplicate typename with the GenerateHLSL attribute detected: " + type.FullName +
" declared in both " + gen.type.Assembly.FullName + " and " + type.Assembly.FullName + ". Skipping the second instance.");
}
s_TypeName[type.FullName] = new ShaderTypeGenerator(type, attr as GenerateHLSL);
}
}
}
}
// Now that we have extracted all the typenames that we care about, parse all .cs files in all asset
// paths and figure out in which files those types are actually declared.
s_SourceGenerators = new Dictionary<string, List<ShaderTypeGenerator>>();
var assetPaths = AssetDatabase.GetAllAssetPaths().Where(s => s.EndsWith(".cs")).ToList();
foreach (var assetPath in assetPaths)
{
LoadTypes(assetPath);
}
// Finally, write out the generated code
foreach (var it in s_SourceGenerators)
{
string fileName = it.Key + ".hlsl";
bool skipFile = false;
foreach (var gen in it.Value)
{
if (!gen.Generate())
{
// Error reporting will be done by the generator. Skip this file.
gen.PrintErrors();
skipFile = true;
break;
}
}
if (skipFile)
continue;
using (var writer = File.CreateText(fileName))
{
var guard = Path.GetFileName(fileName).Replace(".", "_").ToUpper();
if (!char.IsLetter(guard[0]))
guard = "_" + guard;
writer.Write("//\n");
writer.Write("// This file was automatically generated. Please don't edit by hand.\n");
writer.Write("//\n\n");
writer.Write("#ifndef " + guard + "\n");
writer.Write("#define " + guard + "\n");
foreach (var gen in it.Value)
{
if (gen.hasStatics)
{
writer.Write(gen.EmitDefines() + "\n");
}
}
foreach (var gen in it.Value)
{
if (gen.hasFields)
{
writer.Write(gen.EmitTypeDecl() + "\n");
}
}
foreach (var gen in it.Value)
{
if (gen.hasFields && gen.needAccessors && !gen.hasPackedInfo)
{
writer.Write(gen.EmitAccessors());
writer.Write(gen.EmitSetters());
const bool emitInitters = true;
writer.Write(gen.EmitSetters(emitInitters));
}
}
foreach (var gen in it.Value)
{
if (gen.hasStatics && gen.hasFields && gen.needParamDebug && !gen.hasPackedInfo)
{
writer.Write(gen.EmitFunctions() + "\n");
}
}
foreach (var gen in it.Value)
{
if(gen.hasPackedInfo)
{
writer.Write(gen.EmitPackedInfo() + "\n");
}
}
writer.Write("\n#endif\n");
var customFile = it.Key + ".custom.hlsl";
if (File.Exists(customFile))
writer.Write("#include \"{0}\"", Path.GetFileName(customFile));
}
}
}
static Dictionary<string, ShaderTypeGenerator> s_TypeName;
static void LoadTypes(string fileName)
{
using (var parser = ParserFactory.CreateParser(fileName))
{
// @TODO any standard preprocessor symbols we need?
/*var uniqueSymbols = new HashSet<string>(definedSymbols.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
foreach (var symbol in uniqueSymbols)
{
parser.Lexer.ConditionalCompilationSymbols.Add(symbol, string.Empty);
}*/
parser.Lexer.EvaluateConditionalCompilation = true;
parser.Parse();
try
{
var visitor = new NamespaceVisitor();
var data = new VisitorData { typeName = s_TypeName };
parser.CompilationUnit.AcceptVisitor(visitor, data);
if (data.generators.Count > 0)
s_SourceGenerators[fileName] = data.generators;
}
catch
{
// does NRefactory throw anything we can handle here?
throw;
}
}
}
static Dictionary<string, List<ShaderTypeGenerator>> s_SourceGenerators;
class VisitorData
{
public VisitorData()
{
currentNamespaces = new Stack<string>();
currentClasses = new Stack<string>();
generators = new List<ShaderTypeGenerator>();
}
public string GetTypePrefix()
{
var fullNamespace = string.Empty;
var separator = "";
fullNamespace = currentClasses.Aggregate(fullNamespace, (current, ns) => ns + "+" + current);
foreach (var ns in currentNamespaces)
{
if (fullNamespace == string.Empty)
{
separator = ".";
fullNamespace = ns;
}
else
fullNamespace = ns + "." + fullNamespace;
}
var name = "";
if (fullNamespace != string.Empty)
{
name = fullNamespace + separator + name;
}
return name;
}
public readonly Stack<string> currentNamespaces;
public readonly Stack<string> currentClasses;
public readonly List<ShaderTypeGenerator> generators;
public Dictionary<string, ShaderTypeGenerator> typeName;
}
class NamespaceVisitor : AbstractAstVisitor
{
public override object VisitNamespaceDeclaration(ICSharpCode.NRefactory.Ast.NamespaceDeclaration namespaceDeclaration, object data)
{
var visitorData = (VisitorData)data;
visitorData.currentNamespaces.Push(namespaceDeclaration.Name);
namespaceDeclaration.AcceptChildren(this, visitorData);
visitorData.currentNamespaces.Pop();
return null;
}
public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
{
// Structured types only
if (typeDeclaration.Type == ClassType.Class || typeDeclaration.Type == ClassType.Struct || typeDeclaration.Type == ClassType.Enum)
{
var visitorData = (VisitorData)data;
var name = visitorData.GetTypePrefix() + typeDeclaration.Name;
ShaderTypeGenerator gen;
if (visitorData.typeName.TryGetValue(name, out gen))
{
visitorData.generators.Add(gen);
}
visitorData.currentClasses.Push(typeDeclaration.Name);
typeDeclaration.AcceptChildren(this, visitorData);
visitorData.currentClasses.Pop();
}
return null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Xml;
using System.Diagnostics;
using System.Collections.Generic;
namespace System.Xml.Schema
{
internal enum AttributeMatchState
{
AttributeFound,
AnyIdAttributeFound,
UndeclaredElementAndAttribute,
UndeclaredAttribute,
AnyAttributeLax,
AnyAttributeSkip,
ProhibitedAnyAttribute,
ProhibitedAttribute,
AttributeNameMismatch,
ValidateAttributeInvalidCall,
}
internal class SchemaInfo : IDtdInfo
{
private Dictionary<XmlQualifiedName, SchemaElementDecl> _elementDecls = new Dictionary<XmlQualifiedName, SchemaElementDecl>();
private Dictionary<XmlQualifiedName, SchemaElementDecl> _undeclaredElementDecls = new Dictionary<XmlQualifiedName, SchemaElementDecl>();
private Dictionary<XmlQualifiedName, SchemaEntity> _generalEntities;
private Dictionary<XmlQualifiedName, SchemaEntity> _parameterEntities;
private XmlQualifiedName _docTypeName = XmlQualifiedName.Empty;
private string _internalDtdSubset = string.Empty;
private bool _hasNonCDataAttributes = false;
private bool _hasDefaultAttributes = false;
private Dictionary<string, bool> _targetNamespaces = new Dictionary<string, bool>();
private Dictionary<XmlQualifiedName, SchemaAttDef> _attributeDecls = new Dictionary<XmlQualifiedName, SchemaAttDef>();
private int _errorCount;
private SchemaType _schemaType;
private Dictionary<XmlQualifiedName, SchemaElementDecl> _elementDeclsByType = new Dictionary<XmlQualifiedName, SchemaElementDecl>();
private Dictionary<string, SchemaNotation> _notations;
internal SchemaInfo()
{
_schemaType = SchemaType.None;
}
public XmlQualifiedName DocTypeName
{
get { return _docTypeName; }
set { _docTypeName = value; }
}
internal string InternalDtdSubset
{
get { return _internalDtdSubset; }
set { _internalDtdSubset = value; }
}
internal Dictionary<XmlQualifiedName, SchemaElementDecl> ElementDecls
{
get { return _elementDecls; }
}
internal Dictionary<XmlQualifiedName, SchemaElementDecl> UndeclaredElementDecls
{
get { return _undeclaredElementDecls; }
}
internal Dictionary<XmlQualifiedName, SchemaEntity> GeneralEntities
{
get
{
if (_generalEntities == null)
{
_generalEntities = new Dictionary<XmlQualifiedName, SchemaEntity>();
}
return _generalEntities;
}
}
internal Dictionary<XmlQualifiedName, SchemaEntity> ParameterEntities
{
get
{
if (_parameterEntities == null)
{
_parameterEntities = new Dictionary<XmlQualifiedName, SchemaEntity>();
}
return _parameterEntities;
}
}
internal SchemaType SchemaType
{
get { return _schemaType; }
set { _schemaType = value; }
}
internal Dictionary<string, bool> TargetNamespaces
{
get { return _targetNamespaces; }
}
internal Dictionary<XmlQualifiedName, SchemaElementDecl> ElementDeclsByType
{
get { return _elementDeclsByType; }
}
internal Dictionary<XmlQualifiedName, SchemaAttDef> AttributeDecls
{
get { return _attributeDecls; }
}
internal Dictionary<string, SchemaNotation> Notations
{
get
{
if (_notations == null)
{
_notations = new Dictionary<string, SchemaNotation>();
}
return _notations;
}
}
internal int ErrorCount
{
get { return _errorCount; }
set { _errorCount = value; }
}
internal SchemaElementDecl GetElementDecl(XmlQualifiedName qname)
{
SchemaElementDecl elemDecl;
if (_elementDecls.TryGetValue(qname, out elemDecl))
{
return elemDecl;
}
return null;
}
internal SchemaElementDecl GetTypeDecl(XmlQualifiedName qname)
{
SchemaElementDecl elemDecl;
if (_elementDeclsByType.TryGetValue(qname, out elemDecl))
{
return elemDecl;
}
return null;
}
internal XmlSchemaElement GetElement(XmlQualifiedName qname)
{
SchemaElementDecl ed = GetElementDecl(qname);
if (ed != null)
{
return ed.SchemaElement;
}
return null;
}
internal bool HasSchema(string ns)
{
return _targetNamespaces.ContainsKey(ns);
}
internal bool Contains(string ns)
{
return _targetNamespaces.ContainsKey(ns);
}
internal SchemaAttDef GetAttributeXdr(SchemaElementDecl ed, XmlQualifiedName qname)
{
SchemaAttDef attdef = null;
if (ed != null)
{
attdef = ed.GetAttDef(qname); ;
if (attdef == null)
{
if (!ed.ContentValidator.IsOpen || qname.Namespace.Length == 0)
{
throw new XmlSchemaException(SR.Sch_UndeclaredAttribute, qname.ToString());
}
if (!_attributeDecls.TryGetValue(qname, out attdef) && _targetNamespaces.ContainsKey(qname.Namespace))
{
throw new XmlSchemaException(SR.Sch_UndeclaredAttribute, qname.ToString());
}
}
}
return attdef;
}
internal SchemaAttDef GetAttributeXsd(SchemaElementDecl ed, XmlQualifiedName qname, XmlSchemaObject partialValidationType, out AttributeMatchState attributeMatchState)
{
SchemaAttDef attdef = null;
attributeMatchState = AttributeMatchState.UndeclaredAttribute;
if (ed != null)
{
attdef = ed.GetAttDef(qname);
if (attdef != null)
{
attributeMatchState = AttributeMatchState.AttributeFound;
return attdef;
}
XmlSchemaAnyAttribute any = ed.AnyAttribute;
if (any != null)
{
if (!any.NamespaceList.Allows(qname))
{
attributeMatchState = AttributeMatchState.ProhibitedAnyAttribute;
}
else if (any.ProcessContentsCorrect != XmlSchemaContentProcessing.Skip)
{
if (_attributeDecls.TryGetValue(qname, out attdef))
{
if (attdef.Datatype.TypeCode == XmlTypeCode.Id)
{ //anyAttribute match whose type is ID
attributeMatchState = AttributeMatchState.AnyIdAttributeFound;
}
else
{
attributeMatchState = AttributeMatchState.AttributeFound;
}
}
else if (any.ProcessContentsCorrect == XmlSchemaContentProcessing.Lax)
{
attributeMatchState = AttributeMatchState.AnyAttributeLax;
}
}
else
{
attributeMatchState = AttributeMatchState.AnyAttributeSkip;
}
}
else if (ed.ProhibitedAttributes.ContainsKey(qname))
{
attributeMatchState = AttributeMatchState.ProhibitedAttribute;
}
}
else if (partialValidationType != null)
{
XmlSchemaAttribute attr = partialValidationType as XmlSchemaAttribute;
if (attr != null)
{
if (qname.Equals(attr.QualifiedName))
{
attdef = attr.AttDef;
attributeMatchState = AttributeMatchState.AttributeFound;
}
else
{
attributeMatchState = AttributeMatchState.AttributeNameMismatch;
}
}
else
{
attributeMatchState = AttributeMatchState.ValidateAttributeInvalidCall;
}
}
else
{
if (_attributeDecls.TryGetValue(qname, out attdef))
{
attributeMatchState = AttributeMatchState.AttributeFound;
}
else
{
attributeMatchState = AttributeMatchState.UndeclaredElementAndAttribute;
}
}
return attdef;
}
internal SchemaAttDef GetAttributeXsd(SchemaElementDecl ed, XmlQualifiedName qname, ref bool skip)
{
AttributeMatchState attributeMatchState;
SchemaAttDef attDef = GetAttributeXsd(ed, qname, null, out attributeMatchState);
switch (attributeMatchState)
{
case AttributeMatchState.UndeclaredAttribute:
throw new XmlSchemaException(SR.Sch_UndeclaredAttribute, qname.ToString());
case AttributeMatchState.ProhibitedAnyAttribute:
case AttributeMatchState.ProhibitedAttribute:
throw new XmlSchemaException(SR.Sch_ProhibitedAttribute, qname.ToString());
case AttributeMatchState.AttributeFound:
case AttributeMatchState.AnyIdAttributeFound:
case AttributeMatchState.AnyAttributeLax:
case AttributeMatchState.UndeclaredElementAndAttribute:
break;
case AttributeMatchState.AnyAttributeSkip:
skip = true;
break;
default:
Debug.Fail($"Unexpected match state {attributeMatchState}");
break;
}
return attDef;
}
internal void Add(SchemaInfo sinfo, ValidationEventHandler eventhandler)
{
if (_schemaType == SchemaType.None)
{
_schemaType = sinfo.SchemaType;
}
else if (_schemaType != sinfo.SchemaType)
{
if (eventhandler != null)
{
eventhandler(this, new ValidationEventArgs(new XmlSchemaException(SR.Sch_MixSchemaTypes, string.Empty)));
}
return;
}
foreach (string tns in sinfo.TargetNamespaces.Keys)
{
if (!_targetNamespaces.ContainsKey(tns))
{
_targetNamespaces.Add(tns, true);
}
}
foreach (KeyValuePair<XmlQualifiedName, SchemaElementDecl> entry in sinfo._elementDecls)
{
if (!_elementDecls.ContainsKey(entry.Key))
{
_elementDecls.Add(entry.Key, entry.Value);
}
}
foreach (KeyValuePair<XmlQualifiedName, SchemaElementDecl> entry in sinfo._elementDeclsByType)
{
if (!_elementDeclsByType.ContainsKey(entry.Key))
{
_elementDeclsByType.Add(entry.Key, entry.Value);
}
}
foreach (SchemaAttDef attdef in sinfo.AttributeDecls.Values)
{
if (!_attributeDecls.ContainsKey(attdef.Name))
{
_attributeDecls.Add(attdef.Name, attdef);
}
}
foreach (SchemaNotation notation in sinfo.Notations.Values)
{
if (!Notations.ContainsKey(notation.Name.Name))
{
Notations.Add(notation.Name.Name, notation);
}
}
}
internal void Finish()
{
Dictionary<XmlQualifiedName, SchemaElementDecl> elements = _elementDecls;
for (int i = 0; i < 2; i++)
{
foreach (SchemaElementDecl e in elements.Values)
{
if (e.HasNonCDataAttribute)
{
_hasNonCDataAttributes = true;
}
if (e.DefaultAttDefs != null)
{
_hasDefaultAttributes = true;
}
}
elements = _undeclaredElementDecls;
}
}
//
// IDtdInfo interface
//
#region IDtdInfo Members
bool IDtdInfo.HasDefaultAttributes
{
get
{
return _hasDefaultAttributes;
}
}
bool IDtdInfo.HasNonCDataAttributes
{
get
{
return _hasNonCDataAttributes;
}
}
IDtdAttributeListInfo IDtdInfo.LookupAttributeList(string prefix, string localName)
{
XmlQualifiedName qname = new XmlQualifiedName(prefix, localName);
SchemaElementDecl elementDecl;
if (!_elementDecls.TryGetValue(qname, out elementDecl))
{
_undeclaredElementDecls.TryGetValue(qname, out elementDecl);
}
return elementDecl;
}
IEnumerable<IDtdAttributeListInfo> IDtdInfo.GetAttributeLists()
{
foreach (SchemaElementDecl elemDecl in _elementDecls.Values)
{
IDtdAttributeListInfo eleDeclAsAttList = (IDtdAttributeListInfo)elemDecl;
yield return eleDeclAsAttList;
}
}
IDtdEntityInfo IDtdInfo.LookupEntity(string name)
{
if (_generalEntities == null)
{
return null;
}
XmlQualifiedName qname = new XmlQualifiedName(name);
SchemaEntity entity;
if (_generalEntities.TryGetValue(qname, out entity))
{
return entity;
}
return null;
}
XmlQualifiedName IDtdInfo.Name
{
get { return _docTypeName; }
}
string IDtdInfo.InternalDtdSubset
{
get { return _internalDtdSubset; }
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using log4net;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
public enum ProfileShape : byte
{
Circle = 0,
Square = 1,
IsometricTriangle = 2,
EquilateralTriangle = 3,
RightTriangle = 4,
HalfCircle = 5
}
public enum HollowShape : byte
{
Same = 0,
Circle = 16,
Square = 32,
Triangle = 48
}
public enum PCodeEnum : byte
{
Primitive = 9,
Avatar = 47,
Grass = 95,
NewTree = 111,
ParticleSystem = 143,
Tree = 255
}
public enum Extrusion : byte
{
Straight = 16,
Curve1 = 32,
Curve2 = 48,
Flexible = 128
}
[Serializable]
public class PrimitiveBaseShape
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly byte[] DEFAULT_TEXTURE = new Primitive.TextureEntry(new UUID("89556747-24cb-43ed-920b-47caed15465f")).GetBytes();
private byte[] m_textureEntry;
private ushort _pathBegin;
private byte _pathCurve;
private ushort _pathEnd;
private sbyte _pathRadiusOffset;
private byte _pathRevolutions;
private byte _pathScaleX;
private byte _pathScaleY;
private byte _pathShearX;
private byte _pathShearY;
private sbyte _pathSkew;
private sbyte _pathTaperX;
private sbyte _pathTaperY;
private sbyte _pathTwist;
private sbyte _pathTwistBegin;
private byte _pCode;
private ushort _profileBegin;
private ushort _profileEnd;
private ushort _profileHollow;
private Vector3 _scale;
private byte _state;
private ProfileShape _profileShape;
private HollowShape _hollowShape;
// Sculpted
[XmlIgnore] private UUID _sculptTexture;
[XmlIgnore] private byte _sculptType;
[XmlIgnore] private byte[] _sculptData = Utils.EmptyBytes;
// Flexi
[XmlIgnore] private int _flexiSoftness;
[XmlIgnore] private float _flexiTension;
[XmlIgnore] private float _flexiDrag;
[XmlIgnore] private float _flexiGravity;
[XmlIgnore] private float _flexiWind;
[XmlIgnore] private float _flexiForceX;
[XmlIgnore] private float _flexiForceY;
[XmlIgnore] private float _flexiForceZ;
//Bright n sparkly
[XmlIgnore] private float _lightColorR;
[XmlIgnore] private float _lightColorG;
[XmlIgnore] private float _lightColorB;
[XmlIgnore] private float _lightColorA = 1.0f;
[XmlIgnore] private float _lightRadius;
[XmlIgnore] private float _lightCutoff;
[XmlIgnore] private float _lightFalloff;
[XmlIgnore] private float _lightIntensity = 1.0f;
[XmlIgnore] private bool _flexiEntry;
[XmlIgnore] private bool _lightEntry;
[XmlIgnore] private bool _sculptEntry;
// Light Projection Filter
[XmlIgnore] private bool _projectionEntry;
[XmlIgnore] private UUID _projectionTextureID;
[XmlIgnore] private float _projectionFOV;
[XmlIgnore] private float _projectionFocus;
[XmlIgnore] private float _projectionAmb;
public byte ProfileCurve
{
get { return (byte)((byte)HollowShape | (byte)ProfileShape); }
set
{
// Handle hollow shape component
byte hollowShapeByte = (byte)(value & 0xf0);
if (!Enum.IsDefined(typeof(HollowShape), hollowShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a hollow shape value of {0}, which isn't a valid enum. Replacing with default shape.",
hollowShapeByte);
this._hollowShape = HollowShape.Same;
}
else
{
this._hollowShape = (HollowShape)hollowShapeByte;
}
// Handle profile shape component
byte profileShapeByte = (byte)(value & 0xf);
if (!Enum.IsDefined(typeof(ProfileShape), profileShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a profile shape value of {0}, which isn't a valid enum. Replacing with square.",
profileShapeByte);
this._profileShape = ProfileShape.Square;
}
else
{
this._profileShape = (ProfileShape)profileShapeByte;
}
}
}
/// <summary>
/// Entries to store media textures on each face
/// </summary>
/// Do not change this value directly - always do it through an IMoapModule.
/// Lock before manipulating.
public MediaList Media { get; set; }
public PrimitiveBaseShape()
{
PCode = (byte)PCodeEnum.Primitive;
m_textureEntry = DEFAULT_TEXTURE;
}
/// <summary>
/// Construct a PrimitiveBaseShape object from a OpenMetaverse.Primitive object
/// </summary>
/// <param name="prim"></param>
public PrimitiveBaseShape(Primitive prim)
{
// m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: Creating from {0}", prim.ID);
PCode = (byte)prim.PrimData.PCode;
State = prim.PrimData.State;
PathBegin = Primitive.PackBeginCut(prim.PrimData.PathBegin);
PathEnd = Primitive.PackEndCut(prim.PrimData.PathEnd);
PathScaleX = Primitive.PackPathScale(prim.PrimData.PathScaleX);
PathScaleY = Primitive.PackPathScale(prim.PrimData.PathScaleY);
PathShearX = (byte)Primitive.PackPathShear(prim.PrimData.PathShearX);
PathShearY = (byte)Primitive.PackPathShear(prim.PrimData.PathShearY);
PathSkew = Primitive.PackPathTwist(prim.PrimData.PathSkew);
ProfileBegin = Primitive.PackBeginCut(prim.PrimData.ProfileBegin);
ProfileEnd = Primitive.PackEndCut(prim.PrimData.ProfileEnd);
Scale = prim.Scale;
PathCurve = (byte)prim.PrimData.PathCurve;
ProfileCurve = (byte)prim.PrimData.ProfileCurve;
ProfileHollow = Primitive.PackProfileHollow(prim.PrimData.ProfileHollow);
PathRadiusOffset = Primitive.PackPathTwist(prim.PrimData.PathRadiusOffset);
PathRevolutions = Primitive.PackPathRevolutions(prim.PrimData.PathRevolutions);
PathTaperX = Primitive.PackPathTaper(prim.PrimData.PathTaperX);
PathTaperY = Primitive.PackPathTaper(prim.PrimData.PathTaperY);
PathTwist = Primitive.PackPathTwist(prim.PrimData.PathTwist);
PathTwistBegin = Primitive.PackPathTwist(prim.PrimData.PathTwistBegin);
m_textureEntry = prim.Textures.GetBytes();
if (prim.Sculpt != null)
{
SculptEntry = (prim.Sculpt.Type != OpenMetaverse.SculptType.None);
SculptData = prim.Sculpt.GetBytes();
SculptTexture = prim.Sculpt.SculptTexture;
SculptType = (byte)prim.Sculpt.Type;
}
else
{
SculptType = (byte)OpenMetaverse.SculptType.None;
}
}
[XmlIgnore]
public Primitive.TextureEntry Textures
{
get
{
// m_log.DebugFormat("[SHAPE]: get m_textureEntry length {0}", m_textureEntry.Length);
try { return new Primitive.TextureEntry(m_textureEntry, 0, m_textureEntry.Length); }
catch { }
m_log.Warn("[SHAPE]: Failed to decode texture, length=" + ((m_textureEntry != null) ? m_textureEntry.Length : 0));
return new Primitive.TextureEntry(UUID.Zero);
}
set { m_textureEntry = value.GetBytes(); }
}
public byte[] TextureEntry
{
get { return m_textureEntry; }
set
{
if (value == null)
m_textureEntry = new byte[1];
else
m_textureEntry = value;
}
}
public static PrimitiveBaseShape Default
{
get
{
PrimitiveBaseShape boxShape = CreateBox();
boxShape.SetScale(0.5f);
return boxShape;
}
}
public static PrimitiveBaseShape Create()
{
PrimitiveBaseShape shape = new PrimitiveBaseShape();
return shape;
}
public static PrimitiveBaseShape CreateBox()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Straight;
shape._profileShape = ProfileShape.Square;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateSphere()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Curve1;
shape._profileShape = ProfileShape.HalfCircle;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateCylinder()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Curve1;
shape._profileShape = ProfileShape.Square;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public void SetScale(float side)
{
_scale = new Vector3(side, side, side);
}
public void SetHeigth(float height)
{
_scale.Z = height;
}
public void SetRadius(float radius)
{
_scale.X = _scale.Y = radius * 2f;
}
// TODO: void returns need to change of course
public virtual void GetMesh()
{
}
public PrimitiveBaseShape Copy()
{
return (PrimitiveBaseShape) MemberwiseClone();
}
public static PrimitiveBaseShape CreateCylinder(float radius, float heigth)
{
PrimitiveBaseShape shape = CreateCylinder();
shape.SetHeigth(heigth);
shape.SetRadius(radius);
return shape;
}
public void SetPathRange(Vector3 pathRange)
{
_pathBegin = Primitive.PackBeginCut(pathRange.X);
_pathEnd = Primitive.PackEndCut(pathRange.Y);
}
public void SetPathRange(float begin, float end)
{
_pathBegin = Primitive.PackBeginCut(begin);
_pathEnd = Primitive.PackEndCut(end);
}
public void SetSculptProperties(byte sculptType, UUID SculptTextureUUID)
{
_sculptType = sculptType;
_sculptTexture = SculptTextureUUID;
}
public void SetProfileRange(Vector3 profileRange)
{
_profileBegin = Primitive.PackBeginCut(profileRange.X);
_profileEnd = Primitive.PackEndCut(profileRange.Y);
}
public void SetProfileRange(float begin, float end)
{
_profileBegin = Primitive.PackBeginCut(begin);
_profileEnd = Primitive.PackEndCut(end);
}
public byte[] ExtraParams
{
get
{
return ExtraParamsToBytes();
}
set
{
ReadInExtraParamsBytes(value);
}
}
public ushort PathBegin {
get {
return _pathBegin;
}
set {
_pathBegin = value;
}
}
public byte PathCurve {
get {
return _pathCurve;
}
set {
_pathCurve = value;
}
}
public ushort PathEnd {
get {
return _pathEnd;
}
set {
_pathEnd = value;
}
}
public sbyte PathRadiusOffset {
get {
return _pathRadiusOffset;
}
set {
_pathRadiusOffset = value;
}
}
public byte PathRevolutions {
get {
return _pathRevolutions;
}
set {
_pathRevolutions = value;
}
}
public byte PathScaleX {
get {
return _pathScaleX;
}
set {
_pathScaleX = value;
}
}
public byte PathScaleY {
get {
return _pathScaleY;
}
set {
_pathScaleY = value;
}
}
public byte PathShearX {
get {
return _pathShearX;
}
set {
_pathShearX = value;
}
}
public byte PathShearY {
get {
return _pathShearY;
}
set {
_pathShearY = value;
}
}
public sbyte PathSkew {
get {
return _pathSkew;
}
set {
_pathSkew = value;
}
}
public sbyte PathTaperX {
get {
return _pathTaperX;
}
set {
_pathTaperX = value;
}
}
public sbyte PathTaperY {
get {
return _pathTaperY;
}
set {
_pathTaperY = value;
}
}
public sbyte PathTwist {
get {
return _pathTwist;
}
set {
_pathTwist = value;
}
}
public sbyte PathTwistBegin {
get {
return _pathTwistBegin;
}
set {
_pathTwistBegin = value;
}
}
public byte PCode {
get {
return _pCode;
}
set {
_pCode = value;
}
}
public ushort ProfileBegin {
get {
return _profileBegin;
}
set {
_profileBegin = value;
}
}
public ushort ProfileEnd {
get {
return _profileEnd;
}
set {
_profileEnd = value;
}
}
public ushort ProfileHollow {
get {
return _profileHollow;
}
set {
_profileHollow = value;
}
}
public Vector3 Scale {
get {
return _scale;
}
set {
_scale = value;
}
}
public byte State {
get {
return _state;
}
set {
_state = value;
}
}
public ProfileShape ProfileShape {
get {
return _profileShape;
}
set {
_profileShape = value;
}
}
public HollowShape HollowShape {
get {
return _hollowShape;
}
set {
_hollowShape = value;
}
}
public UUID SculptTexture {
get {
return _sculptTexture;
}
set {
_sculptTexture = value;
}
}
public byte SculptType
{
get
{
return _sculptType;
}
set
{
_sculptType = value;
}
}
// This is only used at runtime. For sculpties this holds the texture data, and for meshes
// the mesh data.
public byte[] SculptData
{
get
{
return _sculptData;
}
set
{
// m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: Setting SculptData to data with length {0}", value.Length);
_sculptData = value;
}
}
public int FlexiSoftness
{
get
{
return _flexiSoftness;
}
set
{
_flexiSoftness = value;
}
}
public float FlexiTension {
get {
return _flexiTension;
}
set {
_flexiTension = value;
}
}
public float FlexiDrag {
get {
return _flexiDrag;
}
set {
_flexiDrag = value;
}
}
public float FlexiGravity {
get {
return _flexiGravity;
}
set {
_flexiGravity = value;
}
}
public float FlexiWind {
get {
return _flexiWind;
}
set {
_flexiWind = value;
}
}
public float FlexiForceX {
get {
return _flexiForceX;
}
set {
_flexiForceX = value;
}
}
public float FlexiForceY {
get {
return _flexiForceY;
}
set {
_flexiForceY = value;
}
}
public float FlexiForceZ {
get {
return _flexiForceZ;
}
set {
_flexiForceZ = value;
}
}
public float LightColorR {
get {
return _lightColorR;
}
set {
_lightColorR = value;
}
}
public float LightColorG {
get {
return _lightColorG;
}
set {
_lightColorG = value;
}
}
public float LightColorB {
get {
return _lightColorB;
}
set {
_lightColorB = value;
}
}
public float LightColorA {
get {
return _lightColorA;
}
set {
_lightColorA = value;
}
}
public float LightRadius {
get {
return _lightRadius;
}
set {
_lightRadius = value;
}
}
public float LightCutoff {
get {
return _lightCutoff;
}
set {
_lightCutoff = value;
}
}
public float LightFalloff {
get {
return _lightFalloff;
}
set {
_lightFalloff = value;
}
}
public float LightIntensity {
get {
return _lightIntensity;
}
set {
_lightIntensity = value;
}
}
public bool FlexiEntry {
get {
return _flexiEntry;
}
set {
_flexiEntry = value;
}
}
public bool LightEntry {
get {
return _lightEntry;
}
set {
_lightEntry = value;
}
}
public bool SculptEntry {
get {
return _sculptEntry;
}
set {
_sculptEntry = value;
}
}
public bool ProjectionEntry {
get {
return _projectionEntry;
}
set {
_projectionEntry = value;
}
}
public UUID ProjectionTextureUUID {
get {
return _projectionTextureID;
}
set {
_projectionTextureID = value;
}
}
public float ProjectionFOV {
get {
return _projectionFOV;
}
set {
_projectionFOV = value;
}
}
public float ProjectionFocus {
get {
return _projectionFocus;
}
set {
_projectionFocus = value;
}
}
public float ProjectionAmbiance {
get {
return _projectionAmb;
}
set {
_projectionAmb = value;
}
}
public ulong GetMeshKey(Vector3 size, float lod)
{
ulong hash = 5381;
hash = djb2(hash, this.PathCurve);
hash = djb2(hash, (byte)((byte)this.HollowShape | (byte)this.ProfileShape));
hash = djb2(hash, this.PathBegin);
hash = djb2(hash, this.PathEnd);
hash = djb2(hash, this.PathScaleX);
hash = djb2(hash, this.PathScaleY);
hash = djb2(hash, this.PathShearX);
hash = djb2(hash, this.PathShearY);
hash = djb2(hash, (byte)this.PathTwist);
hash = djb2(hash, (byte)this.PathTwistBegin);
hash = djb2(hash, (byte)this.PathRadiusOffset);
hash = djb2(hash, (byte)this.PathTaperX);
hash = djb2(hash, (byte)this.PathTaperY);
hash = djb2(hash, this.PathRevolutions);
hash = djb2(hash, (byte)this.PathSkew);
hash = djb2(hash, this.ProfileBegin);
hash = djb2(hash, this.ProfileEnd);
hash = djb2(hash, this.ProfileHollow);
// TODO: Separate scale out from the primitive shape data (after
// scaling is supported at the physics engine level)
byte[] scaleBytes = size.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
// Include LOD in hash, accounting for endianness
byte[] lodBytes = new byte[4];
Buffer.BlockCopy(BitConverter.GetBytes(lod), 0, lodBytes, 0, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(lodBytes, 0, 4);
}
for (int i = 0; i < lodBytes.Length; i++)
hash = djb2(hash, lodBytes[i]);
// include sculpt UUID
if (this.SculptEntry)
{
scaleBytes = this.SculptTexture.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
}
return hash;
}
private ulong djb2(ulong hash, byte c)
{
return ((hash << 5) + hash) + (ulong)c;
}
private ulong djb2(ulong hash, ushort c)
{
hash = ((hash << 5) + hash) + (ulong)((byte)c);
return ((hash << 5) + hash) + (ulong)(c >> 8);
}
public byte[] ExtraParamsToBytes()
{
// m_log.DebugFormat("[EXTRAPARAMS]: Called ExtraParamsToBytes()");
ushort FlexiEP = 0x10;
ushort LightEP = 0x20;
ushort SculptEP = 0x30;
ushort ProjectionEP = 0x40;
int i = 0;
uint TotalBytesLength = 1; // ExtraParamsNum
uint ExtraParamsNum = 0;
if (_flexiEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (_lightEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (_sculptEntry)
{
ExtraParamsNum++;
TotalBytesLength += 17;// data
TotalBytesLength += 2 + 4; // type
}
if (_projectionEntry)
{
ExtraParamsNum++;
TotalBytesLength += 28;// data
TotalBytesLength += 2 + 4;// type
}
byte[] returnbytes = new byte[TotalBytesLength];
// uint paramlength = ExtraParamsNum;
// Stick in the number of parameters
returnbytes[i++] = (byte)ExtraParamsNum;
if (_flexiEntry)
{
byte[] FlexiData = GetFlexiBytes();
returnbytes[i++] = (byte)(FlexiEP % 256);
returnbytes[i++] = (byte)((FlexiEP >> 8) % 256);
returnbytes[i++] = (byte)(FlexiData.Length % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 8) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 16) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 24) % 256);
Array.Copy(FlexiData, 0, returnbytes, i, FlexiData.Length);
i += FlexiData.Length;
}
if (_lightEntry)
{
byte[] LightData = GetLightBytes();
returnbytes[i++] = (byte)(LightEP % 256);
returnbytes[i++] = (byte)((LightEP >> 8) % 256);
returnbytes[i++] = (byte)(LightData.Length % 256);
returnbytes[i++] = (byte)((LightData.Length >> 8) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 16) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 24) % 256);
Array.Copy(LightData, 0, returnbytes, i, LightData.Length);
i += LightData.Length;
}
if (_sculptEntry)
{
byte[] SculptData = GetSculptBytes();
returnbytes[i++] = (byte)(SculptEP % 256);
returnbytes[i++] = (byte)((SculptEP >> 8) % 256);
returnbytes[i++] = (byte)(SculptData.Length % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 8) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 16) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 24) % 256);
Array.Copy(SculptData, 0, returnbytes, i, SculptData.Length);
i += SculptData.Length;
}
if (_projectionEntry)
{
byte[] ProjectionData = GetProjectionBytes();
returnbytes[i++] = (byte)(ProjectionEP % 256);
returnbytes[i++] = (byte)((ProjectionEP >> 8) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 16) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 20) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 24) % 256);
Array.Copy(ProjectionData, 0, returnbytes, i, ProjectionData.Length);
i += ProjectionData.Length;
}
if (!_flexiEntry && !_lightEntry && !_sculptEntry && !_projectionEntry)
{
byte[] returnbyte = new byte[1];
returnbyte[0] = 0;
return returnbyte;
}
return returnbytes;
}
public void ReadInUpdateExtraParam(ushort type, bool inUse, byte[] data)
{
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
const ushort ProjectionEP = 0x40;
switch (type)
{
case FlexiEP:
if (!inUse)
{
_flexiEntry = false;
return;
}
ReadFlexiData(data, 0);
break;
case LightEP:
if (!inUse)
{
_lightEntry = false;
return;
}
ReadLightData(data, 0);
break;
case SculptEP:
if (!inUse)
{
_sculptEntry = false;
return;
}
ReadSculptData(data, 0);
break;
case ProjectionEP:
if (!inUse)
{
_projectionEntry = false;
return;
}
ReadProjectionData(data, 0);
break;
}
}
public void ReadInExtraParamsBytes(byte[] data)
{
if (data == null || data.Length == 1)
return;
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
const ushort ProjectionEP = 0x40;
bool lGotFlexi = false;
bool lGotLight = false;
bool lGotSculpt = false;
bool lGotFilter = false;
int i = 0;
byte extraParamCount = 0;
if (data.Length > 0)
{
extraParamCount = data[i++];
}
for (int k = 0; k < extraParamCount; k++)
{
ushort epType = Utils.BytesToUInt16(data, i);
i += 2;
// uint paramLength = Helpers.BytesToUIntBig(data, i);
i += 4;
switch (epType)
{
case FlexiEP:
ReadFlexiData(data, i);
i += 16;
lGotFlexi = true;
break;
case LightEP:
ReadLightData(data, i);
i += 16;
lGotLight = true;
break;
case SculptEP:
ReadSculptData(data, i);
i += 17;
lGotSculpt = true;
break;
case ProjectionEP:
ReadProjectionData(data, i);
i += 28;
lGotFilter = true;
break;
}
}
if (!lGotFlexi)
_flexiEntry = false;
if (!lGotLight)
_lightEntry = false;
if (!lGotSculpt)
_sculptEntry = false;
if (!lGotFilter)
_projectionEntry = false;
}
public void ReadSculptData(byte[] data, int pos)
{
UUID SculptUUID;
byte SculptTypel;
if (data.Length-pos >= 17)
{
_sculptEntry = true;
byte[] SculptTextureUUID = new byte[16];
SculptTypel = data[16 + pos];
Array.Copy(data, pos, SculptTextureUUID,0, 16);
SculptUUID = new UUID(SculptTextureUUID, 0);
}
else
{
_sculptEntry = false;
SculptUUID = UUID.Zero;
SculptTypel = 0x00;
}
if (_sculptEntry)
{
if (_sculptType != (byte)1 && _sculptType != (byte)2 && _sculptType != (byte)3 && _sculptType != (byte)4)
_sculptType = 4;
}
_sculptTexture = SculptUUID;
_sculptType = SculptTypel;
//m_log.Info("[SCULPT]:" + SculptUUID.ToString());
}
public byte[] GetSculptBytes()
{
byte[] data = new byte[17];
_sculptTexture.GetBytes().CopyTo(data, 0);
data[16] = (byte)_sculptType;
return data;
}
public void ReadFlexiData(byte[] data, int pos)
{
if (data.Length-pos >= 16)
{
_flexiEntry = true;
_flexiSoftness = ((data[pos] & 0x80) >> 6) | ((data[pos + 1] & 0x80) >> 7);
_flexiTension = (float)(data[pos++] & 0x7F) / 10.0f;
_flexiDrag = (float)(data[pos++] & 0x7F) / 10.0f;
_flexiGravity = (float)(data[pos++] / 10.0f) - 10.0f;
_flexiWind = (float)data[pos++] / 10.0f;
Vector3 lForce = new Vector3(data, pos);
_flexiForceX = lForce.X;
_flexiForceY = lForce.Y;
_flexiForceZ = lForce.Z;
}
else
{
_flexiEntry = false;
_flexiSoftness = 0;
_flexiTension = 0.0f;
_flexiDrag = 0.0f;
_flexiGravity = 0.0f;
_flexiWind = 0.0f;
_flexiForceX = 0f;
_flexiForceY = 0f;
_flexiForceZ = 0f;
}
}
public byte[] GetFlexiBytes()
{
byte[] data = new byte[16];
int i = 0;
// Softness is packed in the upper bits of tension and drag
data[i] = (byte)((_flexiSoftness & 2) << 6);
data[i + 1] = (byte)((_flexiSoftness & 1) << 7);
data[i++] |= (byte)((byte)(_flexiTension * 10.01f) & 0x7F);
data[i++] |= (byte)((byte)(_flexiDrag * 10.01f) & 0x7F);
data[i++] = (byte)((_flexiGravity + 10.0f) * 10.01f);
data[i++] = (byte)(_flexiWind * 10.01f);
Vector3 lForce = new Vector3(_flexiForceX, _flexiForceY, _flexiForceZ);
lForce.GetBytes().CopyTo(data, i);
return data;
}
public void ReadLightData(byte[] data, int pos)
{
if (data.Length - pos >= 16)
{
_lightEntry = true;
Color4 lColor = new Color4(data, pos, false);
_lightIntensity = lColor.A;
_lightColorA = 1f;
_lightColorR = lColor.R;
_lightColorG = lColor.G;
_lightColorB = lColor.B;
_lightRadius = Utils.BytesToFloat(data, pos + 4);
_lightCutoff = Utils.BytesToFloat(data, pos + 8);
_lightFalloff = Utils.BytesToFloat(data, pos + 12);
}
else
{
_lightEntry = false;
_lightColorA = 1f;
_lightColorR = 0f;
_lightColorG = 0f;
_lightColorB = 0f;
_lightRadius = 0f;
_lightCutoff = 0f;
_lightFalloff = 0f;
_lightIntensity = 0f;
}
}
public byte[] GetLightBytes()
{
byte[] data = new byte[16];
// Alpha channel in color is intensity
Color4 tmpColor = new Color4(_lightColorR,_lightColorG,_lightColorB,_lightIntensity);
tmpColor.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(_lightRadius).CopyTo(data, 4);
Utils.FloatToBytes(_lightCutoff).CopyTo(data, 8);
Utils.FloatToBytes(_lightFalloff).CopyTo(data, 12);
return data;
}
public void ReadProjectionData(byte[] data, int pos)
{
byte[] ProjectionTextureUUID = new byte[16];
if (data.Length - pos >= 28)
{
_projectionEntry = true;
Array.Copy(data, pos, ProjectionTextureUUID,0, 16);
_projectionTextureID = new UUID(ProjectionTextureUUID, 0);
_projectionFOV = Utils.BytesToFloat(data, pos + 16);
_projectionFocus = Utils.BytesToFloat(data, pos + 20);
_projectionAmb = Utils.BytesToFloat(data, pos + 24);
}
else
{
_projectionEntry = false;
_projectionTextureID = UUID.Zero;
_projectionFOV = 0f;
_projectionFocus = 0f;
_projectionAmb = 0f;
}
}
public byte[] GetProjectionBytes()
{
byte[] data = new byte[28];
_projectionTextureID.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(_projectionFOV).CopyTo(data, 16);
Utils.FloatToBytes(_projectionFocus).CopyTo(data, 20);
Utils.FloatToBytes(_projectionAmb).CopyTo(data, 24);
return data;
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <returns></returns>
public Primitive ToOmvPrimitive()
{
// position and rotation defaults here since they are not available in PrimitiveBaseShape
return ToOmvPrimitive(new Vector3(0.0f, 0.0f, 0.0f),
new Quaternion(0.0f, 0.0f, 0.0f, 1.0f));
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <param name="position"></param>
/// <param name="rotation"></param>
/// <returns></returns>
public Primitive ToOmvPrimitive(Vector3 position, Quaternion rotation)
{
OpenMetaverse.Primitive prim = new OpenMetaverse.Primitive();
prim.Scale = this.Scale;
prim.Position = position;
prim.Rotation = rotation;
if (this.SculptEntry)
{
prim.Sculpt = new Primitive.SculptData();
prim.Sculpt.Type = (OpenMetaverse.SculptType)this.SculptType;
prim.Sculpt.SculptTexture = this.SculptTexture;
}
prim.PrimData.PathShearX = this.PathShearX < 128 ? (float)this.PathShearX * 0.01f : (float)(this.PathShearX - 256) * 0.01f;
prim.PrimData.PathShearY = this.PathShearY < 128 ? (float)this.PathShearY * 0.01f : (float)(this.PathShearY - 256) * 0.01f;
prim.PrimData.PathBegin = (float)this.PathBegin * 2.0e-5f;
prim.PrimData.PathEnd = 1.0f - (float)this.PathEnd * 2.0e-5f;
prim.PrimData.PathScaleX = (200 - this.PathScaleX) * 0.01f;
prim.PrimData.PathScaleY = (200 - this.PathScaleY) * 0.01f;
prim.PrimData.PathTaperX = this.PathTaperX * 0.01f;
prim.PrimData.PathTaperY = this.PathTaperY * 0.01f;
prim.PrimData.PathTwistBegin = this.PathTwistBegin * 0.01f;
prim.PrimData.PathTwist = this.PathTwist * 0.01f;
prim.PrimData.ProfileBegin = (float)this.ProfileBegin * 2.0e-5f;
prim.PrimData.ProfileEnd = 1.0f - (float)this.ProfileEnd * 2.0e-5f;
prim.PrimData.ProfileHollow = (float)this.ProfileHollow * 2.0e-5f;
prim.PrimData.profileCurve = this.ProfileCurve;
prim.PrimData.ProfileHole = (HoleType)this.HollowShape;
prim.PrimData.PathCurve = (PathCurve)this.PathCurve;
prim.PrimData.PathRadiusOffset = 0.01f * this.PathRadiusOffset;
prim.PrimData.PathRevolutions = 1.0f + 0.015f * this.PathRevolutions;
prim.PrimData.PathSkew = 0.01f * this.PathSkew;
prim.PrimData.PCode = OpenMetaverse.PCode.Prim;
prim.PrimData.State = 0;
if (this.FlexiEntry)
{
prim.Flexible = new Primitive.FlexibleData();
prim.Flexible.Drag = this.FlexiDrag;
prim.Flexible.Force = new Vector3(this.FlexiForceX, this.FlexiForceY, this.FlexiForceZ);
prim.Flexible.Gravity = this.FlexiGravity;
prim.Flexible.Softness = this.FlexiSoftness;
prim.Flexible.Tension = this.FlexiTension;
prim.Flexible.Wind = this.FlexiWind;
}
if (this.LightEntry)
{
prim.Light = new Primitive.LightData();
prim.Light.Color = new Color4(this.LightColorR, this.LightColorG, this.LightColorB, this.LightColorA);
prim.Light.Cutoff = this.LightCutoff;
prim.Light.Falloff = this.LightFalloff;
prim.Light.Intensity = this.LightIntensity;
prim.Light.Radius = this.LightRadius;
}
prim.Textures = this.Textures;
prim.Properties = new Primitive.ObjectProperties();
prim.Properties.Name = "Primitive";
prim.Properties.Description = "";
prim.Properties.CreatorID = UUID.Zero;
prim.Properties.GroupID = UUID.Zero;
prim.Properties.OwnerID = UUID.Zero;
prim.Properties.Permissions = new Permissions();
prim.Properties.SalePrice = 10;
prim.Properties.SaleType = new SaleType();
return prim;
}
/// <summary>
/// Encapsulates a list of media entries.
/// </summary>
/// This class is necessary because we want to replace auto-serialization of MediaEntry with something more
/// OSD like and less vulnerable to change.
public class MediaList : List<MediaEntry>, IXmlSerializable
{
public const string MEDIA_TEXTURE_TYPE = "sl";
public MediaList() : base() {}
public MediaList(IEnumerable<MediaEntry> collection) : base(collection) {}
public MediaList(int capacity) : base(capacity) {}
public XmlSchema GetSchema()
{
return null;
}
public string ToXml()
{
lock (this)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter xtw = new XmlTextWriter(sw))
{
xtw.WriteStartElement("OSMedia");
xtw.WriteAttributeString("type", MEDIA_TEXTURE_TYPE);
xtw.WriteAttributeString("version", "0.1");
OSDArray meArray = new OSDArray();
foreach (MediaEntry me in this)
{
OSD osd = (null == me ? new OSD() : me.GetOSD());
meArray.Add(osd);
}
xtw.WriteStartElement("OSData");
xtw.WriteRaw(OSDParser.SerializeLLSDXmlString(meArray));
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.Flush();
return sw.ToString();
}
}
}
}
public void WriteXml(XmlWriter writer)
{
writer.WriteRaw(ToXml());
}
public static MediaList FromXml(string rawXml)
{
MediaList ml = new MediaList();
ml.ReadXml(rawXml);
return ml;
}
public void ReadXml(string rawXml)
{
using (StringReader sr = new StringReader(rawXml))
{
using (XmlTextReader xtr = new XmlTextReader(sr))
{
xtr.MoveToContent();
string type = xtr.GetAttribute("type");
//m_log.DebugFormat("[MOAP]: Loaded media texture entry with type {0}", type);
if (type != MEDIA_TEXTURE_TYPE)
return;
xtr.ReadStartElement("OSMedia");
OSDArray osdMeArray = (OSDArray)OSDParser.DeserializeLLSDXml(xtr.ReadInnerXml());
foreach (OSD osdMe in osdMeArray)
{
MediaEntry me = (osdMe is OSDMap ? MediaEntry.FromOSD(osdMe) : new MediaEntry());
Add(me);
}
xtr.ReadEndElement();
}
}
}
public void ReadXml(XmlReader reader)
{
if (reader.IsEmptyElement)
return;
ReadXml(reader.ReadInnerXml());
}
}
}
}
| |
namespace Epi.Windows.Analysis.Dialogs
{
partial class DialogDialog : CommandDesignDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DialogDialog));
this.gbxDialogType = new System.Windows.Forms.GroupBox();
this.rdbListofValues = new System.Windows.Forms.RadioButton();
this.rdbGetVar = new System.Windows.Forms.RadioButton();
this.rdbSimple = new System.Windows.Forms.RadioButton();
this.lblTitle = new System.Windows.Forms.Label();
this.txtTitle = new System.Windows.Forms.TextBox();
this.lblPrompt = new System.Windows.Forms.Label();
this.txtPrompt = new System.Windows.Forms.TextBox();
this.btnHelp = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.cmbInputVar = new System.Windows.Forms.ComboBox();
this.lblInputVar = new System.Windows.Forms.Label();
this.cmbDialogType = new Epi.Windows.Controls.LocalizedComboBox();
this.lblDialogType = new System.Windows.Forms.Label();
this.lblVarType = new System.Windows.Forms.Label();
this.lblShowTable = new System.Windows.Forms.Label();
this.cmbShowTable = new System.Windows.Forms.ComboBox();
this.lblShowVar = new System.Windows.Forms.Label();
this.cmbShowVar = new System.Windows.Forms.ComboBox();
this.lblInputMask = new System.Windows.Forms.Label();
this.cmbInputMask = new System.Windows.Forms.ComboBox();
this.cmbVarType = new Epi.Windows.Controls.LocalizedComboBox();
this.lblLength = new System.Windows.Forms.Label();
this.txtLength = new System.Windows.Forms.MaskedTextBox();
this.btnSaveOnly = new System.Windows.Forms.Button();
this.gbxDialogType.SuspendLayout();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
//
// gbxDialogType
//
resources.ApplyResources(this.gbxDialogType, "gbxDialogType");
this.gbxDialogType.Controls.Add(this.rdbListofValues);
this.gbxDialogType.Controls.Add(this.rdbGetVar);
this.gbxDialogType.Controls.Add(this.rdbSimple);
this.gbxDialogType.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.gbxDialogType.Name = "gbxDialogType";
this.gbxDialogType.TabStop = false;
//
// rdbListofValues
//
resources.ApplyResources(this.rdbListofValues, "rdbListofValues");
this.rdbListofValues.Name = "rdbListofValues";
this.rdbListofValues.Click += new System.EventHandler(this.RadioButtonClick);
//
// rdbGetVar
//
resources.ApplyResources(this.rdbGetVar, "rdbGetVar");
this.rdbGetVar.Name = "rdbGetVar";
this.rdbGetVar.Click += new System.EventHandler(this.RadioButtonClick);
//
// rdbSimple
//
this.rdbSimple.Checked = true;
resources.ApplyResources(this.rdbSimple, "rdbSimple");
this.rdbSimple.Name = "rdbSimple";
this.rdbSimple.TabStop = true;
this.rdbSimple.Click += new System.EventHandler(this.RadioButtonClick);
//
// lblTitle
//
this.lblTitle.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblTitle, "lblTitle");
this.lblTitle.Name = "lblTitle";
//
// txtTitle
//
resources.ApplyResources(this.txtTitle, "txtTitle");
this.txtTitle.Name = "txtTitle";
//
// lblPrompt
//
this.lblPrompt.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblPrompt, "lblPrompt");
this.lblPrompt.Name = "lblPrompt";
//
// txtPrompt
//
resources.ApplyResources(this.txtPrompt, "txtPrompt");
this.txtPrompt.Name = "txtPrompt";
//
// btnHelp
//
resources.ApplyResources(this.btnHelp, "btnHelp");
this.btnHelp.Name = "btnHelp";
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
//
// btnOK
//
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.Name = "btnOK";
//
// btnClear
//
resources.ApplyResources(this.btnClear, "btnClear");
this.btnClear.Name = "btnClear";
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// cmbInputVar
//
this.cmbInputVar.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbInputVar, "cmbInputVar");
this.cmbInputVar.Name = "cmbInputVar";
this.cmbInputVar.SelectedIndexChanged += new System.EventHandler(this.SelectedIndexChanged);
//
// lblInputVar
//
this.lblInputVar.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblInputVar, "lblInputVar");
this.lblInputVar.Name = "lblInputVar";
//
// cmbDialogType
//
this.cmbDialogType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbDialogType, "cmbDialogType");
this.cmbDialogType.Name = "cmbDialogType";
this.cmbDialogType.SkipTranslation = false;
this.cmbDialogType.SelectedIndexChanged += new System.EventHandler(this.cmbDialogType_SelectedIndexChanged);
//
// lblDialogType
//
this.lblDialogType.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblDialogType, "lblDialogType");
this.lblDialogType.Name = "lblDialogType";
//
// lblVarType
//
this.lblVarType.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblVarType, "lblVarType");
this.lblVarType.Name = "lblVarType";
//
// lblShowTable
//
this.lblShowTable.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblShowTable, "lblShowTable");
this.lblShowTable.Name = "lblShowTable";
//
// cmbShowTable
//
this.cmbShowTable.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbShowTable.Items.AddRange(new object[] {
resources.GetString("cmbShowTable.Items"),
resources.GetString("cmbShowTable.Items1"),
resources.GetString("cmbShowTable.Items2"),
resources.GetString("cmbShowTable.Items3")});
resources.ApplyResources(this.cmbShowTable, "cmbShowTable");
this.cmbShowTable.Name = "cmbShowTable";
this.cmbShowTable.SelectedIndexChanged += new System.EventHandler(this.cmbShowTable_SelectedIndexChanged);
//
// lblShowVar
//
this.lblShowVar.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblShowVar, "lblShowVar");
this.lblShowVar.Name = "lblShowVar";
//
// cmbShowVar
//
this.cmbShowVar.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbShowVar.Items.AddRange(new object[] {
resources.GetString("cmbShowVar.Items"),
resources.GetString("cmbShowVar.Items1"),
resources.GetString("cmbShowVar.Items2"),
resources.GetString("cmbShowVar.Items3")});
resources.ApplyResources(this.cmbShowVar, "cmbShowVar");
this.cmbShowVar.Name = "cmbShowVar";
this.cmbShowVar.SelectedIndexChanged += new System.EventHandler(this.SelectedIndexChanged);
//
// lblInputMask
//
this.lblInputMask.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblInputMask, "lblInputMask");
this.lblInputMask.Name = "lblInputMask";
//
// cmbInputMask
//
resources.ApplyResources(this.cmbInputMask, "cmbInputMask");
this.cmbInputMask.Name = "cmbInputMask";
this.cmbInputMask.SelectedIndexChanged += new System.EventHandler(this.SelectedIndexChanged);
//
// cmbVarType
//
this.cmbVarType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbVarType, "cmbVarType");
this.cmbVarType.Name = "cmbVarType";
this.cmbVarType.SkipTranslation = false;
this.cmbVarType.SelectedIndexChanged += new System.EventHandler(this.cmbVarType_SelectedIndexChanged);
//
// lblLength
//
this.lblLength.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblLength, "lblLength");
this.lblLength.Name = "lblLength";
//
// txtLength
//
resources.ApplyResources(this.txtLength, "txtLength");
this.txtLength.Name = "txtLength";
this.txtLength.ValidatingType = typeof(int);
//
// btnSaveOnly
//
resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly");
this.btnSaveOnly.Name = "btnSaveOnly";
//
// DialogDialog
//
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.btnSaveOnly);
this.Controls.Add(this.cmbVarType);
this.Controls.Add(this.lblVarType);
this.Controls.Add(this.lblInputVar);
this.Controls.Add(this.cmbInputVar);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.lblPrompt);
this.Controls.Add(this.txtPrompt);
this.Controls.Add(this.txtTitle);
this.Controls.Add(this.lblTitle);
this.Controls.Add(this.gbxDialogType);
this.Controls.Add(this.txtLength);
this.Controls.Add(this.lblLength);
this.Controls.Add(this.lblShowTable);
this.Controls.Add(this.cmbShowTable);
this.Controls.Add(this.lblInputMask);
this.Controls.Add(this.cmbInputMask);
this.Controls.Add(this.lblDialogType);
this.Controls.Add(this.cmbDialogType);
this.Controls.Add(this.lblShowVar);
this.Controls.Add(this.cmbShowVar);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DialogDialog";
this.Load += new System.EventHandler(this.DialogDialog_Load);
this.gbxDialogType.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox gbxDialogType;
private System.Windows.Forms.RadioButton rdbListofValues;
private System.Windows.Forms.RadioButton rdbGetVar;
private System.Windows.Forms.RadioButton rdbSimple;
private System.Windows.Forms.Label lblTitle;
private System.Windows.Forms.TextBox txtTitle;
private System.Windows.Forms.Label lblPrompt;
private System.Windows.Forms.TextBox txtPrompt;
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.ComboBox cmbInputVar;
private System.Windows.Forms.Label lblInputVar;
private System.Windows.Forms.Label lblDialogType;
private Epi.Windows.Controls.LocalizedComboBox cmbDialogType;
private System.Windows.Forms.Label lblVarType;
private System.Windows.Forms.Label lblShowTable;
private System.Windows.Forms.ComboBox cmbShowTable;
private System.Windows.Forms.Label lblShowVar;
private System.Windows.Forms.ComboBox cmbShowVar;
private System.Windows.Forms.Label lblInputMask;
private System.Windows.Forms.ComboBox cmbInputMask;
private Epi.Windows.Controls.LocalizedComboBox cmbVarType;
private System.Windows.Forms.Label lblLength;
private System.Windows.Forms.MaskedTextBox txtLength;
private System.Windows.Forms.Button btnSaveOnly;
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using PrimerProObjects;
using PrimerProLocalization;
namespace PrimerProForms
{
/// <summary>
/// Summary description for FormSearchInsertionMode.
/// </summary>
public class FormSearchInsertionMode : System.Windows.Forms.Form
{
private System.Windows.Forms.RadioButton rbResults;
private System.Windows.Forms.RadioButton rbDefinitions;
private System.Windows.Forms.RadioButton rbBoth;
private System.Windows.Forms.GroupBox gbMode;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private bool m_SearchInsertionResults;
private bool m_SearchInsertionDefinitions;
public FormSearchInsertionMode(Settings s)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
m_SearchInsertionResults = s.SearchInsertionResults;
m_SearchInsertionDefinitions = s.SearchInsertionDefinitions;
if (m_SearchInsertionDefinitions)
{
if (m_SearchInsertionResults)
this.rbBoth.Checked = true;
else this.rbDefinitions.Checked = true;
}
else this.rbResults.Checked = true;
}
public FormSearchInsertionMode(Settings s, LocalizationTable table)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
m_SearchInsertionResults = s.SearchInsertionResults;
m_SearchInsertionDefinitions = s.SearchInsertionDefinitions;
if (m_SearchInsertionDefinitions)
{
if (m_SearchInsertionResults)
this.rbBoth.Checked = true;
else this.rbDefinitions.Checked = true;
}
else this.rbResults.Checked = true;
this.UpdateFormForLocalization(table);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormSearchInsertionMode));
this.rbResults = new System.Windows.Forms.RadioButton();
this.rbDefinitions = new System.Windows.Forms.RadioButton();
this.rbBoth = new System.Windows.Forms.RadioButton();
this.gbMode = new System.Windows.Forms.GroupBox();
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.gbMode.SuspendLayout();
this.SuspendLayout();
//
// rbResults
//
this.rbResults.CausesValidation = false;
this.rbResults.Checked = true;
this.rbResults.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.rbResults.Location = new System.Drawing.Point(24, 36);
this.rbResults.Name = "rbResults";
this.rbResults.Size = new System.Drawing.Size(372, 25);
this.rbResults.TabIndex = 1;
this.rbResults.TabStop = true;
this.rbResults.Text = "Display search &results only";
//
// rbDefinitions
//
this.rbDefinitions.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.rbDefinitions.Location = new System.Drawing.Point(24, 67);
this.rbDefinitions.Name = "rbDefinitions";
this.rbDefinitions.Size = new System.Drawing.Size(372, 25);
this.rbDefinitions.TabIndex = 2;
this.rbDefinitions.Text = "Display search &definitions only";
//
// rbBoth
//
this.rbBoth.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.rbBoth.Location = new System.Drawing.Point(24, 98);
this.rbBoth.Name = "rbBoth";
this.rbBoth.Size = new System.Drawing.Size(372, 25);
this.rbBoth.TabIndex = 3;
this.rbBoth.Text = "Display &both";
//
// gbMode
//
this.gbMode.Controls.Add(this.rbBoth);
this.gbMode.Controls.Add(this.rbDefinitions);
this.gbMode.Controls.Add(this.rbResults);
this.gbMode.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.gbMode.Location = new System.Drawing.Point(16, 16);
this.gbMode.Name = "gbMode";
this.gbMode.Size = new System.Drawing.Size(438, 145);
this.gbMode.TabIndex = 0;
this.gbMode.TabStop = false;
this.gbMode.Text = "Set Search Insertion Mode";
//
// btnOK
//
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnOK.Location = new System.Drawing.Point(108, 198);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(100, 32);
this.btnOK.TabIndex = 4;
this.btnOK.Text = "OK";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCancel.Location = new System.Drawing.Point(242, 198);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(100, 32);
this.btnCancel.TabIndex = 5;
this.btnCancel.Text = "Cancel";
//
// FormSearchInsertionMode
//
this.AcceptButton = this.btnOK;
this.AutoScaleBaseSize = new System.Drawing.Size(7, 17);
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(480, 242);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.gbMode);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "FormSearchInsertionMode";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Search Insertion Mode";
this.gbMode.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public bool SearchInsertionResults
{
get { return m_SearchInsertionResults; }
}
public bool SearchInsertionDefinitions
{
get { return m_SearchInsertionDefinitions; }
}
private void btnOK_Click(object sender, System.EventArgs e)
{
if (this.rbResults.Checked)
{
m_SearchInsertionResults = true;
m_SearchInsertionDefinitions = false;
}
else if (this.rbDefinitions.Checked)
{
m_SearchInsertionResults = false;
m_SearchInsertionDefinitions = true;
}
else if (this.rbBoth.Checked)
{
m_SearchInsertionResults = true;
m_SearchInsertionDefinitions = true;
}
}
private void UpdateFormForLocalization(LocalizationTable table)
{
string strText = "";
strText = table.GetForm("FormSearchInsertionModeT");
if (strText != "")
this.Text = strText;
strText = table.GetForm("FormSearchInsertionMode0");
if (strText != "")
this.gbMode.Text = strText;
strText = table.GetForm("FormSearchInsertionMode1");
if (strText != "")
this.rbResults.Text = strText;
strText = table.GetForm("FormSearchInsertionMode2");
if (strText != "")
this.rbDefinitions.Text = strText;
strText = table.GetForm("FormSearchInsertionMode3");
if (strText != "")
this.rbBoth.Text = strText;
strText = table.GetForm("FormSearchInsertionMode4");
if (strText != "")
this.btnOK.Text = strText;
strText = table.GetForm("FormSearchInsertionMode5");
if (strText != "")
this.btnCancel.Text = strText;
return;
}
}
}
| |
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
//#define ConfigTrace
using Microsoft.VisualStudio.Shell.Interop;
using MSBuild = Microsoft.Build.Evaluation;
using MSBuildExecution = Microsoft.Build.Execution;
using MSBuildConstruction = Microsoft.Build.Construction;
namespace Microsoft.VisualStudio.Project
{
[CLSCompliant(false), ComVisible(true)]
public class ProjectConfig :
IVsCfg,
IVsProjectCfg,
IVsProjectCfg2,
IVsProjectFlavorCfg,
IVsDebuggableProjectCfg,
ISpecifyPropertyPages,
IVsSpecifyProjectDesignerPages,
IVsCfgBrowseObject
{
#region constants
internal const string Debug = "Debug";
internal const string Release = "Release";
internal const string AnyCPU = "AnyCPU";
#endregion
#region fields
private ProjectNode project;
private string configName;
private MSBuildExecution.ProjectInstance currentConfig;
private List<OutputGroup> outputGroups;
private IProjectConfigProperties configurationProperties;
private IVsProjectFlavorCfg flavoredCfg;
private BuildableProjectConfig buildableCfg;
#endregion
#region properties
public ProjectNode ProjectMgr
{
get
{
return this.project;
}
}
public string ConfigName
{
get
{
return this.configName;
}
set
{
this.configName = value;
}
}
public virtual object ConfigurationProperties
{
get
{
if(this.configurationProperties == null)
{
this.configurationProperties = new ProjectConfigProperties(this);
}
return this.configurationProperties;
}
}
protected IList<OutputGroup> OutputGroups
{
get
{
if(null == this.outputGroups)
{
// Initialize output groups
this.outputGroups = new List<OutputGroup>();
// Get the list of group names from the project.
// The main reason we get it from the project is to make it easier for someone to modify
// it by simply overriding that method and providing the correct MSBuild target(s).
IList<KeyValuePair<string, string>> groupNames = project.GetOutputGroupNames();
if(groupNames != null)
{
// Populate the output array
foreach(KeyValuePair<string, string> group in groupNames)
{
OutputGroup outputGroup = CreateOutputGroup(project, group);
this.outputGroups.Add(outputGroup);
}
}
}
return this.outputGroups;
}
}
#endregion
#region ctors
public ProjectConfig(ProjectNode project, string configuration)
{
this.project = project;
this.configName = configuration;
// Because the project can be aggregated by a flavor, we need to make sure
// we get the outer most implementation of that interface (hence: project --> IUnknown --> Interface)
IntPtr projectUnknown = Marshal.GetIUnknownForObject(this.ProjectMgr);
try
{
IVsProjectFlavorCfgProvider flavorCfgProvider = (IVsProjectFlavorCfgProvider)Marshal.GetTypedObjectForIUnknown(projectUnknown, typeof(IVsProjectFlavorCfgProvider));
ErrorHandler.ThrowOnFailure(flavorCfgProvider.CreateProjectFlavorCfg(this, out flavoredCfg));
if(flavoredCfg == null)
throw new COMException();
}
finally
{
if(projectUnknown != IntPtr.Zero)
Marshal.Release(projectUnknown);
}
// if the flavored object support XML fragment, initialize it
IPersistXMLFragment persistXML = flavoredCfg as IPersistXMLFragment;
if(null != persistXML)
{
this.project.LoadXmlFragment(persistXML, this.DisplayName);
}
}
#endregion
#region methods
protected virtual OutputGroup CreateOutputGroup(ProjectNode project, KeyValuePair<string, string> group)
{
OutputGroup outputGroup = new OutputGroup(group.Key, group.Value, project, this);
return outputGroup;
}
public void PrepareBuild(bool clean)
{
project.PrepareBuild(this.configName, clean);
}
public virtual string GetConfigurationProperty(string propertyName, bool resetCache)
{
MSBuildExecution.ProjectPropertyInstance property = GetMsBuildProperty(propertyName, resetCache);
if (property == null)
return null;
return property.EvaluatedValue;
}
public virtual void SetConfigurationProperty(string propertyName, string propertyValue)
{
if(!this.project.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
string condition = String.Format(CultureInfo.InvariantCulture, ConfigProvider.configString, this.ConfigName);
SetPropertyUnderCondition(propertyName, propertyValue, condition);
// property cache will need to be updated
this.currentConfig = null;
// Signal the output groups that something is changed
foreach(OutputGroup group in this.OutputGroups)
{
group.InvalidateGroup();
}
this.project.SetProjectFileDirty(true);
return;
}
/// <summary>
/// Emulates the behavior of SetProperty(name, value, condition) on the old MSBuild object model.
/// This finds a property group with the specified condition (or creates one if necessary) then sets the property in there.
/// </summary>
private void SetPropertyUnderCondition(string propertyName, string propertyValue, string condition)
{
string conditionTrimmed = (condition == null) ? String.Empty : condition.Trim();
if (conditionTrimmed.Length == 0)
{
this.project.BuildProject.SetProperty(propertyName, propertyValue);
return;
}
// New OM doesn't have a convenient equivalent for setting a property with a particular property group condition.
// So do it ourselves.
MSBuildConstruction.ProjectPropertyGroupElement newGroup = null;
foreach (MSBuildConstruction.ProjectPropertyGroupElement group in this.project.BuildProject.Xml.PropertyGroups)
{
if (String.Equals(group.Condition.Trim(), conditionTrimmed, StringComparison.OrdinalIgnoreCase))
{
newGroup = group;
break;
}
}
if (newGroup == null)
{
newGroup = this.project.BuildProject.Xml.AddPropertyGroup(); // Adds after last existing PG, else at start of project
newGroup.Condition = condition;
}
foreach (MSBuildConstruction.ProjectPropertyElement property in newGroup.PropertiesReversed) // If there's dupes, pick the last one so we win
{
if (String.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase) && property.Condition.Length == 0)
{
property.Value = propertyValue;
return;
}
}
newGroup.AddProperty(propertyName, propertyValue);
}
/// <summary>
/// If flavored, and if the flavor config can be dirty, ask it if it is dirty
/// </summary>
/// <param name="storageType">Project file or user file</param>
/// <returns>0 = not dirty</returns>
internal int IsFlavorDirty(_PersistStorageType storageType)
{
int isDirty = 0;
if(this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment)
{
ErrorHandler.ThrowOnFailure(((IPersistXMLFragment)this.flavoredCfg).IsFragmentDirty((uint)storageType, out isDirty));
}
return isDirty;
}
/// <summary>
/// If flavored, ask the flavor if it wants to provide an XML fragment
/// </summary>
/// <param name="flavor">Guid of the flavor</param>
/// <param name="storageType">Project file or user file</param>
/// <param name="fragment">Fragment that the flavor wants to save</param>
/// <returns>HRESULT</returns>
internal int GetXmlFragment(Guid flavor, _PersistStorageType storageType, out string fragment)
{
fragment = null;
int hr = VSConstants.S_OK;
if(this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment)
{
Guid flavorGuid = flavor;
hr = ((IPersistXMLFragment)this.flavoredCfg).Save(ref flavorGuid, (uint)storageType, out fragment, 1);
}
return hr;
}
#endregion
#region IVsSpecifyPropertyPages
public void GetPages(CAUUID[] pages)
{
this.GetCfgPropertyPages(pages);
}
#endregion
#region IVsSpecifyProjectDesignerPages
/// <summary>
/// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration dependent.
/// </summary>
/// <param name="pages">The pages to return.</param>
/// <returns>VSConstants.S_OK</returns>
public virtual int GetProjectDesignerPages(CAUUID[] pages)
{
this.GetCfgPropertyPages(pages);
return VSConstants.S_OK;
}
#endregion
#region IVsCfg methods
/// <summary>
/// The display name is a two part item
/// first part is the config name, 2nd part is the platform name
/// </summary>
public virtual int get_DisplayName(out string name)
{
name = DisplayName;
return VSConstants.S_OK;
}
private string DisplayName
{
get
{
string name;
string[] platform = new string[1];
uint[] actual = new uint[1];
name = this.configName;
// currently, we only support one platform, so just add it..
IVsCfgProvider provider;
ErrorHandler.ThrowOnFailure(project.GetCfgProvider(out provider));
ErrorHandler.ThrowOnFailure(((IVsCfgProvider2)provider).GetPlatformNames(1, platform, actual));
if(!string.IsNullOrEmpty(platform[0]))
{
name += "|" + platform[0];
}
return name;
}
}
public virtual int get_IsDebugOnly(out int fDebug)
{
fDebug = 0;
if(this.configName == "Debug")
{
fDebug = 1;
}
return VSConstants.S_OK;
}
public virtual int get_IsReleaseOnly(out int fRelease)
{
CCITracing.TraceCall();
fRelease = 0;
if(this.configName == "Release")
{
fRelease = 1;
}
return VSConstants.S_OK;
}
#endregion
#region IVsProjectCfg methods
public virtual int EnumOutputs(out IVsEnumOutputs eo)
{
CCITracing.TraceCall();
eo = null;
return VSConstants.E_NOTIMPL;
}
public virtual int get_BuildableProjectCfg(out IVsBuildableProjectCfg pb)
{
CCITracing.TraceCall();
if(buildableCfg == null)
buildableCfg = new BuildableProjectConfig(this);
pb = buildableCfg;
return VSConstants.S_OK;
}
public virtual int get_CanonicalName(out string name)
{
return ((IVsCfg)this).get_DisplayName(out name);
}
public virtual int get_IsPackaged(out int pkgd)
{
CCITracing.TraceCall();
pkgd = 0;
return VSConstants.S_OK;
}
public virtual int get_IsSpecifyingOutputSupported(out int f)
{
CCITracing.TraceCall();
f = 1;
return VSConstants.S_OK;
}
public virtual int get_Platform(out Guid platform)
{
CCITracing.TraceCall();
platform = Guid.Empty;
return VSConstants.E_NOTIMPL;
}
public virtual int get_ProjectCfgProvider(out IVsProjectCfgProvider p)
{
CCITracing.TraceCall();
p = null;
IVsCfgProvider cfgProvider = null;
this.project.GetCfgProvider(out cfgProvider);
if(cfgProvider != null)
{
p = cfgProvider as IVsProjectCfgProvider;
}
return (null == p) ? VSConstants.E_NOTIMPL : VSConstants.S_OK;
}
public virtual int get_RootURL(out string root)
{
CCITracing.TraceCall();
root = null;
return VSConstants.S_OK;
}
public virtual int get_TargetCodePage(out uint target)
{
CCITracing.TraceCall();
target = (uint)System.Text.Encoding.Default.CodePage;
return VSConstants.S_OK;
}
public virtual int get_UpdateSequenceNumber(ULARGE_INTEGER[] li)
{
if (li == null)
{
throw new ArgumentNullException("li");
}
CCITracing.TraceCall();
li[0] = new ULARGE_INTEGER();
li[0].QuadPart = 0;
return VSConstants.S_OK;
}
public virtual int OpenOutput(string name, out IVsOutput output)
{
CCITracing.TraceCall();
output = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsDebuggableProjectCfg methods
/// <summary>
/// Called by the vs shell to start debugging (managed or unmanaged).
/// Override this method to support other debug engines.
/// </summary>
/// <param name="grfLaunch">A flag that determines the conditions under which to start the debugger. For valid grfLaunch values, see __VSDBGLAUNCHFLAGS</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code</returns>
public virtual int DebugLaunch(uint grfLaunch)
{
CCITracing.TraceCall();
try
{
VsDebugTargetInfo info = new VsDebugTargetInfo();
info.cbSize = (uint)Marshal.SizeOf(info);
info.dlo = Microsoft.VisualStudio.Shell.Interop.DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;
// On first call, reset the cache, following calls will use the cached values
string property = GetConfigurationProperty("StartProgram", true);
if(string.IsNullOrEmpty(property))
{
info.bstrExe = this.project.GetOutputAssembly(this.ConfigName);
}
else
{
info.bstrExe = property;
}
property = GetConfigurationProperty("WorkingDirectory", false);
if(string.IsNullOrEmpty(property))
{
info.bstrCurDir = Path.GetDirectoryName(info.bstrExe);
}
else
{
info.bstrCurDir = property;
}
property = GetConfigurationProperty("CmdArgs", false);
if(!string.IsNullOrEmpty(property))
{
info.bstrArg = property;
}
property = GetConfigurationProperty("RemoteDebugMachine", false);
if(property != null && property.Length > 0)
{
info.bstrRemoteMachine = property;
}
info.fSendStdoutToOutputWindow = 0;
property = GetConfigurationProperty("EnableUnmanagedDebugging", false);
if(property != null && string.Compare(property, "true", StringComparison.OrdinalIgnoreCase) == 0)
{
//Set the unmanged debugger
//TODO change to vsconstant when it is available in VsConstants (guidNativeOnlyEng was the old name, maybe it has got a new name)
info.clsidCustom = new Guid("{3B476D35-A401-11D2-AAD4-00C04F990171}");
}
else
{
//Set the managed debugger
info.clsidCustom = VSConstants.CLSID_ComPlusOnlyDebugEngine;
}
info.grfLaunch = grfLaunch;
VsShellUtilities.LaunchDebugger(this.project.Site, info);
}
catch(Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
return Marshal.GetHRForException(e);
}
return VSConstants.S_OK;
}
/// <summary>
/// Determines whether the debugger can be launched, given the state of the launch flags.
/// </summary>
/// <param name="flags">Flags that determine the conditions under which to launch the debugger.
/// For valid grfLaunch values, see __VSDBGLAUNCHFLAGS or __VSDBGLAUNCHFLAGS2.</param>
/// <param name="fCanLaunch">true if the debugger can be launched, otherwise false</param>
/// <returns>S_OK if the method succeeds, otherwise an error code</returns>
public virtual int QueryDebugLaunch(uint flags, out int fCanLaunch)
{
CCITracing.TraceCall();
string assembly = this.project.GetAssemblyName(this.ConfigName);
fCanLaunch = (assembly != null && assembly.ToUpperInvariant().EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) ? 1 : 0;
if(fCanLaunch == 0)
{
string property = GetConfigurationProperty("StartProgram", true);
fCanLaunch = (property != null && property.Length > 0) ? 1 : 0;
}
return VSConstants.S_OK;
}
#endregion
#region IVsProjectCfg2 Members
public virtual int OpenOutputGroup(string szCanonicalName, out IVsOutputGroup ppIVsOutputGroup)
{
ppIVsOutputGroup = null;
// Search through our list of groups to find the one they are looking forgroupName
foreach(OutputGroup group in OutputGroups)
{
string groupName;
group.get_CanonicalName(out groupName);
if(String.Compare(groupName, szCanonicalName, StringComparison.OrdinalIgnoreCase) == 0)
{
ppIVsOutputGroup = group;
break;
}
}
return (ppIVsOutputGroup != null) ? VSConstants.S_OK : VSConstants.E_FAIL;
}
public virtual int OutputsRequireAppRoot(out int pfRequiresAppRoot)
{
pfRequiresAppRoot = 0;
return VSConstants.E_NOTIMPL;
}
public virtual int get_CfgType(ref Guid iidCfg, out IntPtr ppCfg)
{
// Delegate to the flavored configuration (to enable a flavor to take control)
// Since we can be asked for Configuration we don't support, avoid throwing and return the HRESULT directly
int hr = flavoredCfg.get_CfgType(ref iidCfg, out ppCfg);
return hr;
}
public virtual int get_IsPrivate(out int pfPrivate)
{
pfPrivate = 0;
return VSConstants.S_OK;
}
public virtual int get_OutputGroups(uint celt, IVsOutputGroup[] rgpcfg, uint[] pcActual)
{
// Are they only asking for the number of groups?
if(celt == 0)
{
if((null == pcActual) || (0 == pcActual.Length))
{
throw new ArgumentNullException("pcActual");
}
pcActual[0] = (uint)OutputGroups.Count;
return VSConstants.S_OK;
}
// Check that the array of output groups is not null
if((null == rgpcfg) || (rgpcfg.Length == 0))
{
throw new ArgumentNullException("rgpcfg");
}
// Fill the array with our output groups
uint count = 0;
foreach(OutputGroup group in OutputGroups)
{
if(rgpcfg.Length > count && celt > count && group != null)
{
rgpcfg[count] = group;
++count;
}
}
if(pcActual != null && pcActual.Length > 0)
pcActual[0] = count;
// If the number asked for does not match the number returned, return S_FALSE
return (count == celt) ? VSConstants.S_OK : VSConstants.S_FALSE;
}
public virtual int get_VirtualRoot(out string pbstrVRoot)
{
pbstrVRoot = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsCfgBrowseObject
/// <summary>
/// Maps back to the configuration corresponding to the browse object.
/// </summary>
/// <param name="cfg">The IVsCfg object represented by the browse object</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetCfg(out IVsCfg cfg)
{
cfg = this;
return VSConstants.S_OK;
}
/// <summary>
/// Maps back to the hierarchy or project item object corresponding to the browse object.
/// </summary>
/// <param name="hier">Reference to the hierarchy object.</param>
/// <param name="itemid">Reference to the project item.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid)
{
if(this.project == null || this.project.NodeProperties == null)
{
throw new InvalidOperationException();
}
return this.project.NodeProperties.GetProjectItem(out hier, out itemid);
}
#endregion
#region helper methods
/// <summary>
/// Splits the canonical configuration name into platform and configuration name.
/// </summary>
/// <param name="canonicalName">The canonicalName name.</param>
/// <param name="configName">The name of the configuration.</param>
/// <param name="platformName">The name of the platform.</param>
/// <returns>true if successfull.</returns>
internal static bool TrySplitConfigurationCanonicalName(string canonicalName, out string configName, out string platformName)
{
configName = String.Empty;
platformName = String.Empty;
if(String.IsNullOrEmpty(canonicalName))
{
return false;
}
string[] splittedCanonicalName = canonicalName.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
if(splittedCanonicalName == null || (splittedCanonicalName.Length != 1 && splittedCanonicalName.Length != 2))
{
return false;
}
configName = splittedCanonicalName[0];
if(splittedCanonicalName.Length == 2)
{
platformName = splittedCanonicalName[1];
}
return true;
}
private MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, bool resetCache)
{
if (resetCache || this.currentConfig == null)
{
// Get properties for current configuration from project file and cache it
this.project.SetConfiguration(this.ConfigName);
this.project.BuildProject.ReevaluateIfNecessary();
// Create a snapshot of the evaluated project in its current state
this.currentConfig = this.project.BuildProject.CreateProjectInstance();
// Restore configuration
project.SetCurrentConfiguration();
}
if (this.currentConfig == null)
throw new Exception("Failed to retrieve properties");
// return property asked for
return this.currentConfig.GetProperty(propertyName);
}
/// <summary>
/// Retrieves the configuration dependent property pages.
/// </summary>
/// <param name="pages">The pages to return.</param>
private void GetCfgPropertyPages(CAUUID[] pages)
{
// We do not check whether the supportsProjectDesigner is set to true on the ProjectNode.
// We rely that the caller knows what to call on us.
if(pages == null)
{
throw new ArgumentNullException("pages");
}
if(pages.Length == 0)
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "pages");
}
// Retrive the list of guids from hierarchy properties.
// Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy
string guidsList = String.Empty;
IVsHierarchy hierarchy = HierarchyNode.GetOuterHierarchy(this.project);
object variant = null;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList, out variant), new int[] { VSConstants.DISP_E_MEMBERNOTFOUND, VSConstants.E_NOTIMPL });
guidsList = (string)variant;
Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList);
if(guids == null || guids.Length == 0)
{
pages[0] = new CAUUID();
pages[0].cElems = 0;
}
else
{
pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids);
}
}
#endregion
#region IVsProjectFlavorCfg Members
/// <summary>
/// This is called to let the flavored config let go
/// of any reference it may still be holding to the base config
/// </summary>
/// <returns></returns>
int IVsProjectFlavorCfg.Close()
{
// This is used to release the reference the flavored config is holding
// on the base config, but in our scenario these 2 are the same object
// so we have nothing to do here.
return VSConstants.S_OK;
}
/// <summary>
/// Actual implementation of get_CfgType.
/// When not flavored or when the flavor delegate to use
/// we end up creating the requested config if we support it.
/// </summary>
/// <param name="iidCfg">IID representing the type of config object we should create</param>
/// <param name="ppCfg">Config object that the method created</param>
/// <returns>HRESULT</returns>
int IVsProjectFlavorCfg.get_CfgType(ref Guid iidCfg, out IntPtr ppCfg)
{
ppCfg = IntPtr.Zero;
// See if this is an interface we support
if(iidCfg == typeof(IVsDebuggableProjectCfg).GUID)
ppCfg = Marshal.GetComInterfaceForObject(this, typeof(IVsDebuggableProjectCfg));
else if(iidCfg == typeof(IVsBuildableProjectCfg).GUID)
{
IVsBuildableProjectCfg buildableConfig;
this.get_BuildableProjectCfg(out buildableConfig);
ppCfg = Marshal.GetComInterfaceForObject(buildableConfig, typeof(IVsBuildableProjectCfg));
}
// If not supported
if(ppCfg == IntPtr.Zero)
return VSConstants.E_NOINTERFACE;
return VSConstants.S_OK;
}
#endregion
}
//=============================================================================
// NOTE: advises on out of proc build execution to maximize
// future cross-platform targeting capabilities of the VS tools.
[CLSCompliant(false)]
[ComVisible(true)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Buildable")]
public class BuildableProjectConfig : IVsBuildableProjectCfg
{
#region fields
ProjectConfig config = null;
EventSinkCollection callbacks = new EventSinkCollection();
#endregion
#region ctors
public BuildableProjectConfig(ProjectConfig config)
{
this.config = config;
}
#endregion
#region IVsBuildableProjectCfg methods
public virtual int AdviseBuildStatusCallback(IVsBuildStatusCallback callback, out uint cookie)
{
CCITracing.TraceCall();
cookie = callbacks.Add(callback);
return VSConstants.S_OK;
}
public virtual int get_ProjectCfg(out IVsProjectCfg p)
{
CCITracing.TraceCall();
p = config;
return VSConstants.S_OK;
}
public virtual int QueryStartBuild(uint options, int[] supported, int[] ready)
{
CCITracing.TraceCall();
if(supported != null && supported.Length > 0)
supported[0] = 1;
if(ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartClean(uint options, int[] supported, int[] ready)
{
CCITracing.TraceCall();
config.PrepareBuild(false);
if(supported != null && supported.Length > 0)
supported[0] = 1;
if(ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartUpToDateCheck(uint options, int[] supported, int[] ready)
{
CCITracing.TraceCall();
config.PrepareBuild(false);
if(supported != null && supported.Length > 0)
supported[0] = 0; // TODO:
if(ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStatus(out int done)
{
CCITracing.TraceCall();
done = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int StartBuild(IVsOutputWindowPane pane, uint options)
{
CCITracing.TraceCall();
config.PrepareBuild(false);
// Current version of MSBuild wish to be called in an STA
uint flags = VSConstants.VS_BUILDABLEPROJECTCFGOPTS_REBUILD;
// If we are not asked for a rebuild, then we build the default target (by passing null)
this.Build(options, pane, ((options & flags) != 0) ? MsBuildTarget.Rebuild : null);
return VSConstants.S_OK;
}
public virtual int StartClean(IVsOutputWindowPane pane, uint options)
{
CCITracing.TraceCall();
config.PrepareBuild(true);
// Current version of MSBuild wish to be called in an STA
this.Build(options, pane, MsBuildTarget.Clean);
return VSConstants.S_OK;
}
public virtual int StartUpToDateCheck(IVsOutputWindowPane pane, uint options)
{
CCITracing.TraceCall();
return VSConstants.E_NOTIMPL;
}
public virtual int Stop(int fsync)
{
CCITracing.TraceCall();
return VSConstants.S_OK;
}
public virtual int UnadviseBuildStatusCallback(uint cookie)
{
CCITracing.TraceCall();
callbacks.RemoveAt(cookie);
return VSConstants.S_OK;
}
public virtual int Wait(uint ms, int fTickWhenMessageQNotEmpty)
{
CCITracing.TraceCall();
return VSConstants.E_NOTIMPL;
}
#endregion
#region helpers
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private bool NotifyBuildBegin()
{
int shouldContinue = 1;
foreach (IVsBuildStatusCallback cb in callbacks)
{
try
{
ErrorHandler.ThrowOnFailure(cb.BuildBegin(ref shouldContinue));
if (shouldContinue == 0)
{
return false;
}
}
catch (Exception e)
{
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
}
}
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void NotifyBuildEnd(MSBuildResult result, string buildTarget)
{
int success = ((result == MSBuildResult.Successful) ? 1 : 0);
foreach (IVsBuildStatusCallback cb in callbacks)
{
try
{
ErrorHandler.ThrowOnFailure(cb.BuildEnd(success));
}
catch (Exception e)
{
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
}
finally
{
// We want to refresh the references if we are building with the Build or Rebuild target or if the project was opened for browsing only.
bool shouldRepaintReferences = (buildTarget == null || buildTarget == MsBuildTarget.Build || buildTarget == MsBuildTarget.Rebuild);
// Now repaint references if that is needed.
// We hardly rely here on the fact the ResolveAssemblyReferences target has been run as part of the build.
// One scenario to think at is when an assembly reference is renamed on disk thus becomming unresolvable,
// but msbuild can actually resolve it.
// Another one if the project was opened only for browsing and now the user chooses to build or rebuild.
if (shouldRepaintReferences && (result == MSBuildResult.Successful))
{
this.RefreshReferences();
}
}
}
}
private void Build(uint options, IVsOutputWindowPane output, string target)
{
if (!this.NotifyBuildBegin())
{
return;
}
try
{
config.ProjectMgr.BuildAsync(options, this.config.ConfigName, output, target, (result, buildTarget) => this.NotifyBuildEnd(result, buildTarget));
}
catch(Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
this.NotifyBuildEnd(MSBuildResult.Failed, target);
throw;
}
finally
{
ErrorHandler.ThrowOnFailure(output.FlushToTaskList());
}
}
/// <summary>
/// Refreshes references and redraws them correctly.
/// </summary>
private void RefreshReferences()
{
// Refresh the reference container node for assemblies that could be resolved.
IReferenceContainer referenceContainer = this.config.ProjectMgr.GetReferenceContainer();
foreach(ReferenceNode referenceNode in referenceContainer.EnumReferences())
{
referenceNode.RefreshReference();
}
}
#endregion
}
}
| |
#region OMIT_COMPILEOPTION_DIAGS
#if !OMIT_COMPILEOPTION_DIAGS
using System;
namespace Core
{
public partial class CompileTime
{
static string[] _compileOpt = {
#if _32BIT_ROWID
"32BIT_ROWID",
#endif
#if _4_BYTE_ALIGNED_MALLOC
"4_BYTE_ALIGNED_MALLOC",
#endif
#if CASE_SENSITIVE_LIKE
"CASE_SENSITIVE_LIKE",
#endif
#if CHECK_PAGES
"CHECK_PAGES",
#endif
#if COVERAGE_TEST
"COVERAGE_TEST",
#endif
#if DEBUG
"DEBUG",
#endif
#if DEFAULT_LOCKING_MODE
"DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(DEFAULT_LOCKING_MODE),
#endif
#if DISABLE_DIRSYNC
"DISABLE_DIRSYNC",
#endif
#if DISABLE_LFS
"DISABLE_LFS",
#endif
#if ENABLE_ATOMIC_WRITE
"ENABLE_ATOMIC_WRITE",
#endif
#if ENABLE_CEROD
"ENABLE_CEROD",
#endif
#if ENABLE_COLUMN_METADATA
"ENABLE_COLUMN_METADATA",
#endif
#if ENABLE_EXPENSIVE_ASSERT
"ENABLE_EXPENSIVE_ASSERT",
#endif
#if ENABLE_FTS1
"ENABLE_FTS1",
#endif
#if ENABLE_FTS2
"ENABLE_FTS2",
#endif
#if ENABLE_FTS3
"ENABLE_FTS3",
#endif
#if ENABLE_FTS3_PARENTHESIS
"ENABLE_FTS3_PARENTHESIS",
#endif
#if ENABLE_FTS4
"ENABLE_FTS4",
#endif
#if ENABLE_ICU
"ENABLE_ICU",
#endif
#if ENABLE_IOTRACE
"ENABLE_IOTRACE",
#endif
#if ENABLE_LOAD_EXTENSION
"ENABLE_LOAD_EXTENSION",
#endif
#if ENABLE_LOCKING_STYLE
"ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(ENABLE_LOCKING_STYLE),
#endif
#if ENABLE_MEMORY_MANAGEMENT
"ENABLE_MEMORY_MANAGEMENT",
#endif
#if ENABLE_MEMSYS3
"ENABLE_MEMSYS3",
#endif
#if ENABLE_MEMSYS5
"ENABLE_MEMSYS5",
#endif
#if ENABLE_OVERSIZE_CELL_CHECK
"ENABLE_OVERSIZE_CELL_CHECK",
#endif
#if ENABLE_RTREE
"ENABLE_RTREE",
#endif
#if ENABLE_STAT2
"ENABLE_STAT2",
#endif
#if ENABLE_UNLOCK_NOTIFY
"ENABLE_UNLOCK_NOTIFY",
#endif
#if ENABLE_UPDATE_DELETE_LIMIT
"ENABLE_UPDATE_DELETE_LIMIT",
#endif
#if HAS_CODEC
"HAS_CODEC",
#endif
#if HAVE_ISNAN
"HAVE_ISNAN",
#endif
#if HOMEGROWN_RECURSIVE_MUTEX
"HOMEGROWN_RECURSIVE_MUTEX",
#endif
#if IGNORE_AFP_LOCK_ERRORS
"IGNORE_AFP_LOCK_ERRORS",
#endif
#if IGNORE_FLOCK_LOCK_ERRORS
"IGNORE_FLOCK_LOCK_ERRORS",
#endif
#if INT64_TYPE
"INT64_TYPE",
#endif
#if LOCK_TRACE
"LOCK_TRACE",
#endif
#if MEMDEBUG
"MEMDEBUG",
#endif
#if MIXED_ENDIAN_64BIT_FLOAT
"MIXED_ENDIAN_64BIT_FLOAT",
#endif
#if NO_SYNC
"NO_SYNC",
#endif
#if OMIT_ALTERTABLE
"OMIT_ALTERTABLE",
#endif
#if OMIT_ANALYZE
"OMIT_ANALYZE",
#endif
#if OMIT_ATTACH
"OMIT_ATTACH",
#endif
#if OMIT_AUTHORIZATION
"OMIT_AUTHORIZATION",
#endif
#if OMIT_AUTOINCREMENT
"OMIT_AUTOINCREMENT",
#endif
#if OMIT_AUTOINIT
"OMIT_AUTOINIT",
#endif
#if OMIT_AUTOMATIC_INDEX
"OMIT_AUTOMATIC_INDEX",
#endif
#if OMIT_AUTORESET
"OMIT_AUTORESET",
#endif
#if OMIT_AUTOVACUUM
"OMIT_AUTOVACUUM",
#endif
#if OMIT_BETWEEN_OPTIMIZATION
"OMIT_BETWEEN_OPTIMIZATION",
#endif
#if OMIT_BLOB_LITERAL
"OMIT_BLOB_LITERAL",
#endif
#if OMIT_BTREECOUNT
"OMIT_BTREECOUNT",
#endif
#if OMIT_BUILTIN_TEST
"OMIT_BUILTIN_TEST",
#endif
#if OMIT_CAST
"OMIT_CAST",
#endif
#if OMIT_CHECK
"OMIT_CHECK",
#endif
/* // redundant
** #if OMIT_COMPILEOPTION_DIAGS
** "OMIT_COMPILEOPTION_DIAGS",
** #endif
*/
#if OMIT_COMPLETE
"OMIT_COMPLETE",
#endif
#if OMIT_COMPOUND_SELECT
"OMIT_COMPOUND_SELECT",
#endif
#if OMIT_DATETIME_FUNCS
"OMIT_DATETIME_FUNCS",
#endif
#if OMIT_DECLTYPE
"OMIT_DECLTYPE",
#endif
#if OMIT_DEPRECATED
"OMIT_DEPRECATED",
#endif
#if OMIT_DISKIO
"OMIT_DISKIO",
#endif
#if OMIT_EXPLAIN
"OMIT_EXPLAIN",
#endif
#if OMIT_FLAG_PRAGMAS
"OMIT_FLAG_PRAGMAS",
#endif
#if OMIT_FLOATING_POINT
"OMIT_FLOATING_POINT",
#endif
#if OMIT_FOREIGN_KEY
"OMIT_FOREIGN_KEY",
#endif
#if OMIT_GET_TABLE
"OMIT_GET_TABLE",
#endif
#if OMIT_INCRBLOB
"OMIT_INCRBLOB",
#endif
#if OMIT_INTEGRITY_CHECK
"OMIT_INTEGRITY_CHECK",
#endif
#if OMIT_LIKE_OPTIMIZATION
"OMIT_LIKE_OPTIMIZATION",
#endif
#if OMIT_LOAD_EXTENSION
"OMIT_LOAD_EXTENSION",
#endif
#if OMIT_LOCALTIME
"OMIT_LOCALTIME",
#endif
#if OMIT_LOOKASIDE
"OMIT_LOOKASIDE",
#endif
#if OMIT_MEMORYDB
"OMIT_MEMORYDB",
#endif
#if OMIT_OR_OPTIMIZATION
"OMIT_OR_OPTIMIZATION",
#endif
#if OMIT_PAGER_PRAGMAS
"OMIT_PAGER_PRAGMAS",
#endif
#if OMIT_PRAGMA
"OMIT_PRAGMA",
#endif
#if OMIT_PROGRESS_CALLBACK
"OMIT_PROGRESS_CALLBACK",
#endif
#if OMIT_QUICKBALANCE
"OMIT_QUICKBALANCE",
#endif
#if OMIT_REINDEX
"OMIT_REINDEX",
#endif
#if OMIT_SCHEMA_PRAGMAS
"OMIT_SCHEMA_PRAGMAS",
#endif
#if OMIT_SCHEMA_VERSION_PRAGMAS
"OMIT_SCHEMA_VERSION_PRAGMAS",
#endif
#if OMIT_SHARED_CACHE
"OMIT_SHARED_CACHE",
#endif
#if OMIT_SUBQUERY
"OMIT_SUBQUERY",
#endif
#if OMIT_TCL_VARIABLE
"OMIT_TCL_VARIABLE",
#endif
#if OMIT_TEMPDB
"OMIT_TEMPDB",
#endif
#if OMIT_TRACE
"OMIT_TRACE",
#endif
#if OMIT_TRIGGER
"OMIT_TRIGGER",
#endif
#if OMIT_TRUNCATE_OPTIMIZATION
"OMIT_TRUNCATE_OPTIMIZATION",
#endif
#if OMIT_UTF16
"OMIT_UTF16",
#endif
#if OMIT_VACUUM
"OMIT_VACUUM",
#endif
#if OMIT_VIEW
"OMIT_VIEW",
#endif
#if OMIT_VIRTUALTABLE
"OMIT_VIRTUALTABLE",
#endif
#if OMIT_WAL
"OMIT_WAL",
#endif
#if OMIT_WSD
"OMIT_WSD",
#endif
#if OMIT_XFER_OPT
"OMIT_XFER_OPT",
#endif
#if PERFORMANCE_TRACE
"PERFORMANCE_TRACE",
#endif
#if PROXY_DEBUG
"PROXY_DEBUG",
#endif
#if SECURE_DELETE
"SECURE_DELETE",
#endif
#if SMALL_STACK
"SMALL_STACK",
#endif
#if SOUNDEX
"SOUNDEX",
#endif
#if TCL
"TCL",
#endif
//#if TEMP_STORE
"TEMP_STORE=1",//CTIMEOPT_VAL(TEMP_STORE),
//#endif
#if _TEST
"_TEST",
#endif
#if THREADSAFE
"THREADSAFE=2", // For C#, hardcode to = 2 CTIMEOPT_VAL(THREADSAFE),
#else
"THREADSAFE=0", // For C#, hardcode to = 0
#endif
#if USE_ALLOCA
"USE_ALLOCA",
#endif
#if ZERO_MALLOC
"ZERO_MALLOC"
#endif
};
public static bool OptionUsed(string optName)
{
if (optName.EndsWith("=")) return false;
int length = 0;
if (optName.StartsWith("", StringComparison.InvariantCultureIgnoreCase)) length = 7;
// Since ArraySize(azCompileOpt) is normally in single digits, a linear search is adequate. No need for a binary search.
if (!string.IsNullOrEmpty(optName))
for (int i = 0; i < _compileOpt.Length; i++)
{
int n1 = (optName.Length - length < _compileOpt[i].Length) ? optName.Length - length : _compileOpt[i].Length;
if (string.Compare(optName, length, _compileOpt[i], 0, n1, StringComparison.InvariantCultureIgnoreCase) == 0)
return true;
}
return false;
}
public static string Get(int id)
{
return (id >= 0 && id < _compileOpt.Length ? _compileOpt[id] : null);
}
}
}
#endif
#endregion
| |
// Copyright (c) 2003, Paul Welter
// All rights reserved.
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
namespace NetSpell.SpellChecker.Forms
{
/// <summary>
/// The OptionForm is an internal form for setting the spell checker options
/// </summary>
internal class OptionForm : Form
{
private readonly Spelling SpellChecker;
private readonly Container components = null;
private Button CancelBtn;
private CheckBox IgnoreDigitsCheck;
private CheckBox IgnoreHtmlCheck;
private CheckBox IgnoreUpperCheck;
private TextBox MaxSuggestions;
private Button OkButton;
private TabPage aboutTab;
private ListView assembliesListView;
private ColumnHeader assemblyColumnHeader;
private ColumnHeader dateColumnHeader;
private TabPage dictionaryTab;
private TabPage generalTab;
private Label label1;
private Label lblCopyright;
private Label lblDescription;
private Label lblTitle;
private Label lblVersion;
private Label lbllabel1;
private LinkLabel linkWebSite;
private TabControl optionsTabControl;
private PictureBox pbIcon;
private TextBox txtCopyright;
private ColumnHeader versionColumnHeader;
private TabPage versionsTab;
/// <summary>
/// Default Constructor
/// </summary>
public OptionForm(ref Spelling spell)
{
SpellChecker = spell;
InitializeComponent();
}
private void OkButton_Click(object sender, EventArgs e)
{
SpellChecker.IgnoreWordsWithDigits = IgnoreDigitsCheck.Checked;
SpellChecker.IgnoreAllCapsWords = IgnoreUpperCheck.Checked;
SpellChecker.IgnoreHtml = IgnoreHtmlCheck.Checked;
SpellChecker.MaxSuggestions = int.Parse(MaxSuggestions.Text, CultureInfo.CurrentUICulture);
Close();
}
private void OptionForm_Load(object sender, EventArgs e)
{
IgnoreDigitsCheck.Checked = SpellChecker.IgnoreWordsWithDigits;
IgnoreUpperCheck.Checked = SpellChecker.IgnoreAllCapsWords;
IgnoreHtmlCheck.Checked = SpellChecker.IgnoreHtml;
MaxSuggestions.Text = SpellChecker.MaxSuggestions.ToString(CultureInfo.CurrentUICulture);
// set dictionary info
txtCopyright.Text = SpellChecker.Dictionary.Copyright;
// set about info
pbIcon.Image = Owner.Icon.ToBitmap();
var aInfo = new AssemblyInfo(typeof (OptionForm));
lblTitle.Text = aInfo.Title;
lblVersion.Text = string.Format("Version {0}", aInfo.Version);
lblCopyright.Text = aInfo.Copyright;
lblDescription.Text = aInfo.Description;
//this.lblCompany.Text = aInfo.Company;
// Get all modules
var localItems = new ArrayList();
foreach (ProcessModule module in Process.GetCurrentProcess().Modules)
{
var item = new ListViewItem();
item.Text = module.ModuleName;
// Get version info
FileVersionInfo verInfo = module.FileVersionInfo;
string versionStr = String.Format("{0}.{1}.{2}.{3}",
verInfo.FileMajorPart,
verInfo.FileMinorPart,
verInfo.FileBuildPart,
verInfo.FilePrivatePart);
item.SubItems.Add(versionStr);
// Get file date info
DateTime lastWriteDate = File.GetLastWriteTime(module.FileName);
string dateStr = lastWriteDate.ToString("MMM dd, yyyy", CultureInfo.CurrentUICulture);
item.SubItems.Add(dateStr);
assembliesListView.Items.Add(item);
// Stash assemply related list view items for later
if (module.ModuleName.ToLower().StartsWith("netspell"))
{
localItems.Add(item);
}
}
// Extract the assemply related modules and move them to the top
for (int i = localItems.Count; i > 0; i--)
{
var localItem = (ListViewItem) localItems[i - 1];
assembliesListView.Items.Remove(localItem);
assembliesListView.Items.Insert(0, localItem);
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private void linkWebSite_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("http://www.loresoft.com");
}
#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.optionsTabControl = new System.Windows.Forms.TabControl();
this.generalTab = new System.Windows.Forms.TabPage();
this.IgnoreHtmlCheck = new System.Windows.Forms.CheckBox();
this.lbllabel1 = new System.Windows.Forms.Label();
this.MaxSuggestions = new System.Windows.Forms.TextBox();
this.IgnoreUpperCheck = new System.Windows.Forms.CheckBox();
this.IgnoreDigitsCheck = new System.Windows.Forms.CheckBox();
this.dictionaryTab = new System.Windows.Forms.TabPage();
this.txtCopyright = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.versionsTab = new System.Windows.Forms.TabPage();
this.assembliesListView = new System.Windows.Forms.ListView();
this.assemblyColumnHeader = new System.Windows.Forms.ColumnHeader();
this.versionColumnHeader = new System.Windows.Forms.ColumnHeader();
this.dateColumnHeader = new System.Windows.Forms.ColumnHeader();
this.aboutTab = new System.Windows.Forms.TabPage();
this.linkWebSite = new System.Windows.Forms.LinkLabel();
this.lblCopyright = new System.Windows.Forms.Label();
this.lblDescription = new System.Windows.Forms.Label();
this.lblVersion = new System.Windows.Forms.Label();
this.lblTitle = new System.Windows.Forms.Label();
this.pbIcon = new System.Windows.Forms.PictureBox();
this.OkButton = new System.Windows.Forms.Button();
this.CancelBtn = new System.Windows.Forms.Button();
this.optionsTabControl.SuspendLayout();
this.generalTab.SuspendLayout();
this.dictionaryTab.SuspendLayout();
this.versionsTab.SuspendLayout();
this.aboutTab.SuspendLayout();
this.SuspendLayout();
//
// optionsTabControl
//
this.optionsTabControl.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.optionsTabControl.Controls.Add(this.generalTab);
this.optionsTabControl.Controls.Add(this.dictionaryTab);
this.optionsTabControl.Controls.Add(this.versionsTab);
this.optionsTabControl.Controls.Add(this.aboutTab);
this.optionsTabControl.Location = new System.Drawing.Point(8, 8);
this.optionsTabControl.Name = "optionsTabControl";
this.optionsTabControl.SelectedIndex = 0;
this.optionsTabControl.Size = new System.Drawing.Size(386, 184);
this.optionsTabControl.TabIndex = 0;
//
// generalTab
//
this.generalTab.Controls.Add(this.IgnoreHtmlCheck);
this.generalTab.Controls.Add(this.lbllabel1);
this.generalTab.Controls.Add(this.MaxSuggestions);
this.generalTab.Controls.Add(this.IgnoreUpperCheck);
this.generalTab.Controls.Add(this.IgnoreDigitsCheck);
this.generalTab.Location = new System.Drawing.Point(4, 22);
this.generalTab.Name = "generalTab";
this.generalTab.Size = new System.Drawing.Size(378, 158);
this.generalTab.TabIndex = 0;
this.generalTab.Text = "General";
//
// IgnoreHtmlCheck
//
this.IgnoreHtmlCheck.Checked = true;
this.IgnoreHtmlCheck.CheckState = System.Windows.Forms.CheckState.Checked;
this.IgnoreHtmlCheck.Location = new System.Drawing.Point(32, 72);
this.IgnoreHtmlCheck.Name = "IgnoreHtmlCheck";
this.IgnoreHtmlCheck.Size = new System.Drawing.Size(296, 24);
this.IgnoreHtmlCheck.TabIndex = 9;
this.IgnoreHtmlCheck.Text = "Ignore HTML Tags";
//
// lbllabel1
//
this.lbllabel1.Location = new System.Drawing.Point(48, 112);
this.lbllabel1.Name = "lbllabel1";
this.lbllabel1.Size = new System.Drawing.Size(264, 16);
this.lbllabel1.TabIndex = 8;
this.lbllabel1.Text = "Maximum &Suggestion Count";
//
// MaxSuggestions
//
this.MaxSuggestions.Location = new System.Drawing.Point(24, 112);
this.MaxSuggestions.MaxLength = 2;
this.MaxSuggestions.Name = "MaxSuggestions";
this.MaxSuggestions.Size = new System.Drawing.Size(24, 20);
this.MaxSuggestions.TabIndex = 3;
this.MaxSuggestions.Text = "25";
//
// IgnoreUpperCheck
//
this.IgnoreUpperCheck.Checked = true;
this.IgnoreUpperCheck.CheckState = System.Windows.Forms.CheckState.Checked;
this.IgnoreUpperCheck.Location = new System.Drawing.Point(32, 48);
this.IgnoreUpperCheck.Name = "IgnoreUpperCheck";
this.IgnoreUpperCheck.Size = new System.Drawing.Size(296, 24);
this.IgnoreUpperCheck.TabIndex = 2;
this.IgnoreUpperCheck.Text = "Ignore Words in all &Upper Case";
//
// IgnoreDigitsCheck
//
this.IgnoreDigitsCheck.Location = new System.Drawing.Point(32, 24);
this.IgnoreDigitsCheck.Name = "IgnoreDigitsCheck";
this.IgnoreDigitsCheck.Size = new System.Drawing.Size(296, 24);
this.IgnoreDigitsCheck.TabIndex = 1;
this.IgnoreDigitsCheck.Text = "Ignore Words with &Digits";
//
// dictionaryTab
//
this.dictionaryTab.Controls.Add(this.txtCopyright);
this.dictionaryTab.Controls.Add(this.label1);
this.dictionaryTab.Location = new System.Drawing.Point(4, 22);
this.dictionaryTab.Name = "dictionaryTab";
this.dictionaryTab.Size = new System.Drawing.Size(378, 158);
this.dictionaryTab.TabIndex = 2;
this.dictionaryTab.Text = "Dictionary";
//
// txtCopyright
//
this.txtCopyright.Location = new System.Drawing.Point(8, 32);
this.txtCopyright.Multiline = true;
this.txtCopyright.Name = "txtCopyright";
this.txtCopyright.ReadOnly = true;
this.txtCopyright.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtCopyright.Size = new System.Drawing.Size(360, 112);
this.txtCopyright.TabIndex = 0;
this.txtCopyright.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(208, 16);
this.label1.TabIndex = 1;
this.label1.Text = "Dictionary Copyright:";
//
// versionsTab
//
this.versionsTab.Controls.Add(this.assembliesListView);
this.versionsTab.Location = new System.Drawing.Point(4, 22);
this.versionsTab.Name = "versionsTab";
this.versionsTab.Size = new System.Drawing.Size(378, 158);
this.versionsTab.TabIndex = 3;
this.versionsTab.Text = "Versions";
//
// assembliesListView
//
this.assembliesListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[]
{
this.assemblyColumnHeader,
this.versionColumnHeader,
this.dateColumnHeader
});
this.assembliesListView.Dock = System.Windows.Forms.DockStyle.Fill;
this.assembliesListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.assembliesListView.Location = new System.Drawing.Point(0, 0);
this.assembliesListView.Name = "assembliesListView";
this.assembliesListView.Size = new System.Drawing.Size(378, 158);
this.assembliesListView.TabIndex = 5;
this.assembliesListView.View = System.Windows.Forms.View.Details;
//
// assemblyColumnHeader
//
this.assemblyColumnHeader.Text = "Module";
this.assemblyColumnHeader.Width = 176;
//
// versionColumnHeader
//
this.versionColumnHeader.Text = "Version";
this.versionColumnHeader.Width = 92;
//
// dateColumnHeader
//
this.dateColumnHeader.Text = "Date";
this.dateColumnHeader.Width = 87;
//
// aboutTab
//
this.aboutTab.Controls.Add(this.linkWebSite);
this.aboutTab.Controls.Add(this.lblCopyright);
this.aboutTab.Controls.Add(this.lblDescription);
this.aboutTab.Controls.Add(this.lblVersion);
this.aboutTab.Controls.Add(this.lblTitle);
this.aboutTab.Controls.Add(this.pbIcon);
this.aboutTab.Location = new System.Drawing.Point(4, 22);
this.aboutTab.Name = "aboutTab";
this.aboutTab.Size = new System.Drawing.Size(378, 158);
this.aboutTab.TabIndex = 4;
this.aboutTab.Text = "About";
//
// linkWebSite
//
this.linkWebSite.Location = new System.Drawing.Point(64, 128);
this.linkWebSite.Name = "linkWebSite";
this.linkWebSite.Size = new System.Drawing.Size(296, 23);
this.linkWebSite.TabIndex = 16;
this.linkWebSite.TabStop = true;
this.linkWebSite.Text = "http://www.loresoft.com";
this.linkWebSite.LinkClicked +=
new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkWebSite_LinkClicked);
//
// lblCopyright
//
this.lblCopyright.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblCopyright.Location = new System.Drawing.Point(64, 64);
this.lblCopyright.Name = "lblCopyright";
this.lblCopyright.Size = new System.Drawing.Size(296, 23);
this.lblCopyright.TabIndex = 12;
this.lblCopyright.Text = "Application Copyright";
//
// lblDescription
//
this.lblDescription.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblDescription.Location = new System.Drawing.Point(64, 88);
this.lblDescription.Name = "lblDescription";
this.lblDescription.Size = new System.Drawing.Size(296, 40);
this.lblDescription.TabIndex = 11;
this.lblDescription.Text = "Application Description";
//
// lblVersion
//
this.lblVersion.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblVersion.Location = new System.Drawing.Point(64, 40);
this.lblVersion.Name = "lblVersion";
this.lblVersion.Size = new System.Drawing.Size(296, 23);
this.lblVersion.TabIndex = 10;
this.lblVersion.Text = "Application Version";
//
// lblTitle
//
this.lblTitle.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblTitle.Location = new System.Drawing.Point(64, 16);
this.lblTitle.Name = "lblTitle";
this.lblTitle.Size = new System.Drawing.Size(296, 24);
this.lblTitle.TabIndex = 9;
this.lblTitle.Text = "Application Title";
//
// pbIcon
//
this.pbIcon.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.pbIcon.Location = new System.Drawing.Point(16, 16);
this.pbIcon.Name = "pbIcon";
this.pbIcon.Size = new System.Drawing.Size(32, 32);
this.pbIcon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pbIcon.TabIndex = 15;
this.pbIcon.TabStop = false;
//
// OkButton
//
this.OkButton.Anchor =
((System.Windows.Forms.AnchorStyles)
((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.OkButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.OkButton.Location = new System.Drawing.Point(226, 200);
this.OkButton.Name = "OkButton";
this.OkButton.TabIndex = 6;
this.OkButton.Text = "&OK";
this.OkButton.Click += new System.EventHandler(this.OkButton_Click);
//
// CancelBtn
//
this.CancelBtn.Anchor =
((System.Windows.Forms.AnchorStyles)
((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.CancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CancelBtn.Location = new System.Drawing.Point(314, 200);
this.CancelBtn.Name = "CancelBtn";
this.CancelBtn.TabIndex = 7;
this.CancelBtn.Text = "&Cancel";
//
// OptionForm
//
this.AcceptButton = this.OkButton;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.CancelBtn;
this.ClientSize = new System.Drawing.Size(402, 232);
this.Controls.Add(this.CancelBtn);
this.Controls.Add(this.OkButton);
this.Controls.Add(this.optionsTabControl);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "OptionForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Options";
this.Load += new System.EventHandler(this.OptionForm_Load);
this.optionsTabControl.ResumeLayout(false);
this.generalTab.ResumeLayout(false);
this.dictionaryTab.ResumeLayout(false);
this.versionsTab.ResumeLayout(false);
this.aboutTab.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
}
}
| |
/*
Copyright (c) 2010-2015 by Genstein and Jason Lautzenheiser.
This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using DevComponents.DotNetBar;
using PdfSharp.Drawing;
namespace Trizbort
{
/// <summary>
/// An element in the project, represented visually on the canvas.
/// </summary>
/// <remarks>
/// Elements have a position and size and may be drawn.
/// Elements have zero or more ports to which connections may be made.
/// </remarks>
internal abstract class Element : IComparable<Element>, IComponent
{
private int m_id;
public Element(Project project)
{
Ports = new ReadOnlyCollection<Port>(PortList);
Project = project;
var id = 1;
while (Project.IsElementIDInUse(id))
{
++id;
}
ID = id;
}
// Added this second constructor to be used when loading a room
// This constructor is significantly faster as it doesn't look for gap in the element IDs
public Element(Project project, int TotalIDs)
{
Ports = new ReadOnlyCollection<Port>(PortList);
Project = project;
ID = TotalIDs;
}
/// <summary>
/// Get the project of which this element is part.
/// </summary>
/// <remarks>
/// The project defines the namespace in which element identifiers are unique.
/// </remarks>
public Project Project { get; }
/// <summary>
/// Get the unique identifier of this element.
/// </summary>
public int ID
{
get { return m_id; }
set
{
if (!Project.IsElementIDInUse(value))
{
m_id = value;
}
}
}
/// <summary>
/// Get the drawing priority of this element.
/// </summary>
/// <remarks>
/// Elements with a higher drawing priority are drawn last.
/// </remarks>
public virtual Depth Depth => Depth.Low;
/// <summary>
/// Get/set whether to raise change events.
/// </summary>
protected bool RaiseChangedEvents { get; set; } = true;
/// <summary>
/// Get whether the element has a properties dialog which may be displayed.
/// </summary>
public virtual bool HasDialog => false;
/// <summary>
/// Get the collection of ports on the element.
/// </summary>
public ReadOnlyCollection<Port> Ports { get; }
/// <summary>
/// Get the collection of ports on the element.
/// </summary>
protected List<Port> PortList { get; } = new List<Port>();
/// <summary>
/// Get/set whether this element is flagged. For temporary use by the Canvas when traversing elements.
/// </summary>
public bool Flagged { get; set; }
public virtual Vector Position { get; set; }
/// <summary>
/// Compare this element to another.
/// </summary>
/// <param name="element">The other element.</param>
/// <remarks>
/// This method is used to sort into drawing order. Depth is the
/// primary criterion; after that a deterministic sort order is
/// guaranteed by using a unique, monotonically increasing sort
/// identifier for each element.
/// </remarks>
public int CompareTo(Element element)
{
var delta = Depth.CompareTo(element.Depth);
if (delta == 0)
{
delta = ID.CompareTo(element.ID);
}
return delta;
}
public virtual void Dispose()
{
//There is nothing to clean.
Disposed?.Invoke(this, EventArgs.Empty);
}
public ISite Site { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } }
public event EventHandler Disposed;
/// <summary>
/// Event raised when the element changes.
/// </summary>
public event EventHandler Changed;
/// <summary>
/// Raise the Changed event.
/// </summary>
protected void RaiseChanged()
{
if (!RaiseChangedEvents) return;
var changed = Changed;
changed?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Recompute any "smart" line segments we use when drawing.
/// </summary>
public virtual void RecomputeSmartLineSegments(DrawingContext context)
{
}
/// <summary>
/// Perform a pre-drawing pass for this element.
/// </summary>
/// <param name="context">The context in which drawing is taking place.</param>
/// <remarks>
/// Elements which wish to add to context.LinesDrawn such that
/// Connections lines will detect them may do so here.
/// </remarks>
public virtual void PreDraw(DrawingContext context)
{
}
/// <summary>
/// Draw the element.
/// </summary>
/// <param name="graphics">The graphics with which to draw.</param>
/// <param name="palette">The palette from which to obtain drawing tools.</param>
/// <param name="context">The context in which drawing is taking place.</param>
public abstract void Draw(XGraphics graphics, Palette palette, DrawingContext context);
/// <summary>
/// Enlarge the given rectangle so as to fully incorporate this element.
/// </summary>
/// <param name="rect">The rectangle to enlarge.</param>
/// <param name="includeMargins">True to include suitable margins around elements which need them; false otherwise.</param>
/// <returns>The new rectangle which incorporates this element.</returns>
/// <remarks>
/// This method is used to determine the bounds of the canvas on which
/// elements are drawn when exporting as an image or PDF.
/// For that usage, includeMargins should be set to true.
/// For more exacting bounds tests, includeMargins should be set to false.
/// </remarks>
public abstract Rect UnionBoundsWith(Rect rect, bool includeMargins);
/// <summary>
/// Get the distance from this element to the given point.
/// </summary>
/// <param name="includeMargins">True to include suitable margins around elements which need them; false otherwise.</param>
public abstract float Distance(Vector pos, bool includeMargins);
/// <summary>
/// Get whether this element intersects the given rectangle.
/// </summary>
public abstract bool Intersects(Rect rect);
/// <summary>
/// Display the element's properties dialog.
/// </summary>
public virtual void ShowDialog()
{
}
/// <summary>
/// Get the position of a given port on the element.
/// </summary>
/// <param name="port">The port in question.</param>
/// <returns>The position of the port.</returns>
public abstract Vector GetPortPosition(Port port);
/// <summary>
/// Get the position of the end of the "stalk" on the given port; or the port position if none.
/// </summary>
/// <param name="port">The port in question.</param>
/// <returns>The position of the end of the stalk, or the port position.</returns>
public abstract Vector GetPortStalkPosition(Port port);
public abstract string GetToolTipText();
public abstract eTooltipColor GetToolTipColor();
public abstract string GetToolTipFooter();
public abstract string GetToolTipHeader();
public abstract bool HasTooltip();
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.IO;
using System.Text;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Execution
{
/// <summary>
/// EventListenerTextWriter sends text output to the currently active
/// ITestEventListener in the form of a TestOutput object. If no event
/// listener is active in the context, or if there is no context,
/// the output is forwarded to the supplied default writer.
/// </summary>
public class EventListenerTextWriter : TextWriter
{
private readonly TextWriter _defaultWriter;
private readonly string _streamName;
/// <summary>
/// Construct an EventListenerTextWriter
/// </summary>
/// <param name="streamName">The name of the stream to use for events</param>
/// <param name="defaultWriter">The default writer to use if no listener is available</param>
public EventListenerTextWriter( string streamName, TextWriter defaultWriter )
{
_streamName = streamName;
_defaultWriter = defaultWriter;
}
/// <summary>
/// Get the Encoding for this TextWriter
/// </summary>
public override Encoding Encoding { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
private string FormatForListener(object value)
{
return
value is null ? string.Empty :
value is IFormattable formattable ? formattable.ToString(null, FormatProvider) :
value.ToString();
}
private bool TrySendToListener(string text)
{
var context = TestExecutionContext.CurrentContext;
if (context == null || context.Listener == null)
return false;
context.Listener.TestOutput(new TestOutput(text, _streamName,
context.CurrentTest?.Id, context.CurrentTest?.FullName));
return true;
}
private bool TrySendLineToListener(string text)
{
return TrySendToListener(text + Environment.NewLine);
}
#region Write/WriteLine Methods
// NB: We explicitly implement each of the Write and WriteLine methods so that
// we are not dependent on the implementation of the TextWriter base class.
//
// For example, ideally, calling WriteLine(char[]) will send the text once,
// however, the base implementation will send one character at a time.
/// <summary>
/// Write formatted string
/// </summary>
public override void Write(string format, params object[] arg)
{
if (!TrySendToListener(String.Format(FormatProvider, format, arg)))
_defaultWriter.Write(format, arg);
}
/// <summary>
/// Write formatted string
/// </summary>
public override void Write(string format, object arg0, object arg1, object arg2)
{
if (!TrySendToListener(String.Format(FormatProvider, format, arg0, arg1, arg2)))
_defaultWriter.Write(format, arg0, arg1, arg2);
}
/// <summary>
/// Write formatted string
/// </summary>
public override void Write(string format, object arg0)
{
if (!TrySendToListener(String.Format(FormatProvider, format, arg0)))
_defaultWriter.Write(format, arg0);
}
/// <summary>
/// Write an object
/// </summary>
public override void Write(object value)
{
if (value == null || !TrySendToListener(FormatForListener(value)))
_defaultWriter.Write(value);
}
/// <summary>
/// Write a string
/// </summary>
public override void Write(string value)
{
if (!TrySendToListener(value))
_defaultWriter.Write(value);
}
/// <summary>
/// Write a decimal
/// </summary>
public override void Write(decimal value)
{
if (!TrySendToListener(value.ToString(FormatProvider)))
_defaultWriter.Write(value);
}
/// <summary>
/// Write a double
/// </summary>
public override void Write(double value)
{
if (!TrySendToListener(value.ToString(FormatProvider)))
_defaultWriter.Write(value);
}
/// <summary>
/// Write formatted string
/// </summary>
public override void Write(string format, object arg0, object arg1)
{
if (!TrySendToListener(String.Format(FormatProvider, format, arg0, arg1)))
_defaultWriter.Write(format, arg0, arg1);
}
/// <summary>
/// Write a ulong
/// </summary>
[CLSCompliant(false)]
public override void Write(ulong value)
{
if (!TrySendToListener(value.ToString(FormatProvider)))
_defaultWriter.Write(value);
}
/// <summary>
/// Write a long
/// </summary>
public override void Write(long value)
{
if (!TrySendToListener(value.ToString(FormatProvider)))
_defaultWriter.Write(value);
}
/// <summary>
/// Write a uint
/// </summary>
[CLSCompliant(false)]
public override void Write(uint value)
{
if (!TrySendToListener(value.ToString(FormatProvider)))
_defaultWriter.Write(value);
}
/// <summary>
/// Write an int
/// </summary>
public override void Write(int value)
{
if (!TrySendToListener(value.ToString(FormatProvider)))
_defaultWriter.Write(value);
}
/// <summary>
/// Write a char
/// </summary>
public override void Write(char value)
{
if (!TrySendToListener(value.ToString()))
_defaultWriter.Write(value);
}
/// <summary>
/// Write a boolean
/// </summary>
public override void Write(bool value)
{
if (!TrySendToListener(value ? Boolean.TrueString : Boolean.FalseString))
_defaultWriter.Write(value);
}
/// <summary>
/// Write chars
/// </summary>
public override void Write(char[] buffer, int index, int count)
{
if (!TrySendToListener(new string(buffer, index, count)))
_defaultWriter.Write(buffer, index, count);
}
/// <summary>
/// Write chars
/// </summary>
public override void Write(char[] buffer)
{
if (!TrySendToListener(new string(buffer)))
_defaultWriter.Write(buffer);
}
/// <summary>
/// Write a float
/// </summary>
public override void Write(float value)
{
if (!TrySendToListener(value.ToString(FormatProvider)))
_defaultWriter.Write(value);
}
/// <summary>
/// Write a string with newline
/// </summary>
public override void WriteLine(string value)
{
if (!TrySendLineToListener(value))
_defaultWriter.WriteLine(value);
}
/// <summary>
/// Write an object with newline
/// </summary>
public override void WriteLine(object value)
{
if (!TrySendLineToListener(FormatForListener(value)))
_defaultWriter.WriteLine(value);
}
/// <summary>
/// Write formatted string with newline
/// </summary>
public override void WriteLine(string format, params object[] arg)
{
if (!TrySendLineToListener(String.Format(FormatProvider, format, arg)))
_defaultWriter.WriteLine(format, arg);
}
/// <summary>
/// Write formatted string with newline
/// </summary>
public override void WriteLine(string format, object arg0, object arg1)
{
if (!TrySendLineToListener(String.Format(FormatProvider, format, arg0, arg1)))
_defaultWriter.WriteLine(format, arg0, arg1);
}
/// <summary>
/// Write formatted string with newline
/// </summary>
public override void WriteLine(string format, object arg0, object arg1, object arg2)
{
if (!TrySendLineToListener(String.Format(FormatProvider, format, arg0, arg1, arg2)))
_defaultWriter.WriteLine(format, arg0, arg1, arg2);
}
/// <summary>
/// Write a decimal with newline
/// </summary>
public override void WriteLine(decimal value)
{
if (!TrySendLineToListener(value.ToString(FormatProvider)))
_defaultWriter.WriteLine(value);
}
/// <summary>
/// Write a formatted string with newline
/// </summary>
public override void WriteLine(string format, object arg0)
{
if (!TrySendLineToListener(String.Format(FormatProvider, format, arg0)))
_defaultWriter.WriteLine(format, arg0);
}
/// <summary>
/// Write a double with newline
/// </summary>
public override void WriteLine(double value)
{
if (!TrySendLineToListener(value.ToString(FormatProvider)))
_defaultWriter.WriteLine(value);
}
/// <summary>
/// Write a uint with newline
/// </summary>
[CLSCompliant(false)]
public override void WriteLine(uint value)
{
if (!TrySendLineToListener(value.ToString(FormatProvider)))
_defaultWriter.WriteLine(value);
}
/// <summary>
/// Write a ulong with newline
/// </summary>
[CLSCompliant(false)]
public override void WriteLine(ulong value)
{
if (!TrySendLineToListener(value.ToString(FormatProvider)))
_defaultWriter.WriteLine(value);
}
/// <summary>
/// Write a long with newline
/// </summary>
public override void WriteLine(long value)
{
if (!TrySendLineToListener(value.ToString(FormatProvider)))
_defaultWriter.WriteLine(value);
}
/// <summary>
/// Write an int with newline
/// </summary>
public override void WriteLine(int value)
{
if (!TrySendLineToListener(value.ToString(FormatProvider)))
_defaultWriter.WriteLine(value);
}
/// <summary>
/// Write a bool with newline
/// </summary>
public override void WriteLine(bool value)
{
if (!TrySendLineToListener(value ? Boolean.TrueString : Boolean.FalseString))
_defaultWriter.WriteLine(value);
}
/// <summary>
/// Write chars with newline
/// </summary>
public override void WriteLine(char[] buffer, int index, int count)
{
if (!TrySendLineToListener(new string(buffer, index, count)))
_defaultWriter.WriteLine(buffer, index, count);
}
/// <summary>
/// Write chars with newline
/// </summary>
public override void WriteLine(char[] buffer)
{
if (!TrySendLineToListener(new string(buffer)))
_defaultWriter.WriteLine(buffer);
}
/// <summary>
/// Write a char with newline
/// </summary>
public override void WriteLine(char value)
{
if (!TrySendLineToListener(value.ToString()))
_defaultWriter.WriteLine(value);
}
/// <summary>
/// Write a float with newline
/// </summary>
public override void WriteLine(float value)
{
if (!TrySendLineToListener(value.ToString(FormatProvider)))
_defaultWriter.WriteLine(value);
}
/// <summary>
/// Write newline
/// </summary>
public override void WriteLine()
{
if (!TrySendLineToListener(string.Empty))
_defaultWriter.WriteLine();
}
#endregion
}
}
| |
#region Copyright & License
//
// Copyright 2001-2005 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Reflection;
using System.Collections;
using log4net;
using log4net.Core;
using log4net.Repository;
using log4net.Repository.Hierarchy;
/*
* Custom Logging Classes to support Event IDs.
*/
namespace log4net.Ext.EventID
{
public class EventIDLogManager
{
#region Static Member Variables
/// <summary>
/// The wrapper map to use to hold the <see cref="EventIDLogImpl"/> objects
/// </summary>
private static readonly WrapperMap s_wrapperMap = new WrapperMap(new WrapperCreationHandler(WrapperCreationHandler));
#endregion
#region Constructor
/// <summary>
/// Private constructor to prevent object creation
/// </summary>
private EventIDLogManager() { }
#endregion
#region Type Specific Manager Methods
/// <summary>
/// Returns the named logger if it exists
/// </summary>
/// <remarks>
/// <para>If the named logger exists (in the default hierarchy) then it
/// returns a reference to the logger, otherwise it returns
/// <c>null</c>.</para>
/// </remarks>
/// <param name="name">The fully qualified logger name to look for</param>
/// <returns>The logger found, or null</returns>
public static IEventIDLog Exists(string name)
{
return Exists(Assembly.GetCallingAssembly(), name);
}
/// <summary>
/// Returns the named logger if it exists
/// </summary>
/// <remarks>
/// <para>If the named logger exists (in the specified domain) then it
/// returns a reference to the logger, otherwise it returns
/// <c>null</c>.</para>
/// </remarks>
/// <param name="domain">the domain to lookup in</param>
/// <param name="name">The fully qualified logger name to look for</param>
/// <returns>The logger found, or null</returns>
public static IEventIDLog Exists(string domain, string name)
{
return WrapLogger(LoggerManager.Exists(domain, name));
}
/// <summary>
/// Returns the named logger if it exists
/// </summary>
/// <remarks>
/// <para>If the named logger exists (in the specified assembly's domain) then it
/// returns a reference to the logger, otherwise it returns
/// <c>null</c>.</para>
/// </remarks>
/// <param name="assembly">the assembly to use to lookup the domain</param>
/// <param name="name">The fully qualified logger name to look for</param>
/// <returns>The logger found, or null</returns>
public static IEventIDLog Exists(Assembly assembly, string name)
{
return WrapLogger(LoggerManager.Exists(assembly, name));
}
/// <summary>
/// Returns all the currently defined loggers in the default domain.
/// </summary>
/// <remarks>
/// <para>The root logger is <b>not</b> included in the returned array.</para>
/// </remarks>
/// <returns>All the defined loggers</returns>
public static IEventIDLog[] GetCurrentLoggers()
{
return GetCurrentLoggers(Assembly.GetCallingAssembly());
}
/// <summary>
/// Returns all the currently defined loggers in the specified domain.
/// </summary>
/// <param name="domain">the domain to lookup in</param>
/// <remarks>
/// The root logger is <b>not</b> included in the returned array.
/// </remarks>
/// <returns>All the defined loggers</returns>
public static IEventIDLog[] GetCurrentLoggers(string domain)
{
return WrapLoggers(LoggerManager.GetCurrentLoggers(domain));
}
/// <summary>
/// Returns all the currently defined loggers in the specified assembly's domain.
/// </summary>
/// <param name="assembly">the assembly to use to lookup the domain</param>
/// <remarks>
/// The root logger is <b>not</b> included in the returned array.
/// </remarks>
/// <returns>All the defined loggers</returns>
public static IEventIDLog[] GetCurrentLoggers(Assembly assembly)
{
return WrapLoggers(LoggerManager.GetCurrentLoggers(assembly));
}
/// <summary>
/// Retrieve or create a named logger.
/// </summary>
/// <remarks>
/// <para>Retrieve a logger named as the <paramref name="name"/>
/// parameter. If the named logger already exists, then the
/// existing instance will be returned. Otherwise, a new instance is
/// created.</para>
///
/// <para>By default, loggers do not have a set level but inherit
/// it from the hierarchy. This is one of the central features of
/// log4net.</para>
/// </remarks>
/// <param name="name">The name of the logger to retrieve.</param>
/// <returns>the logger with the name specified</returns>
public static IEventIDLog GetLogger(string name)
{
return GetLogger(Assembly.GetCallingAssembly(), name);
}
/// <summary>
/// Retrieve or create a named logger.
/// </summary>
/// <remarks>
/// <para>Retrieve a logger named as the <paramref name="name"/>
/// parameter. If the named logger already exists, then the
/// existing instance will be returned. Otherwise, a new instance is
/// created.</para>
///
/// <para>By default, loggers do not have a set level but inherit
/// it from the hierarchy. This is one of the central features of
/// log4net.</para>
/// </remarks>
/// <param name="domain">the domain to lookup in</param>
/// <param name="name">The name of the logger to retrieve.</param>
/// <returns>the logger with the name specified</returns>
public static IEventIDLog GetLogger(string domain, string name)
{
return WrapLogger(LoggerManager.GetLogger(domain, name));
}
/// <summary>
/// Retrieve or create a named logger.
/// </summary>
/// <remarks>
/// <para>Retrieve a logger named as the <paramref name="name"/>
/// parameter. If the named logger already exists, then the
/// existing instance will be returned. Otherwise, a new instance is
/// created.</para>
///
/// <para>By default, loggers do not have a set level but inherit
/// it from the hierarchy. This is one of the central features of
/// log4net.</para>
/// </remarks>
/// <param name="assembly">the assembly to use to lookup the domain</param>
/// <param name="name">The name of the logger to retrieve.</param>
/// <returns>the logger with the name specified</returns>
public static IEventIDLog GetLogger(Assembly assembly, string name)
{
return WrapLogger(LoggerManager.GetLogger(assembly, name));
}
/// <summary>
/// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
/// </summary>
/// <remarks>
/// Get the logger for the fully qualified name of the type specified.
/// </remarks>
/// <param name="type">The full name of <paramref name="type"/> will
/// be used as the name of the logger to retrieve.</param>
/// <returns>the logger with the name specified</returns>
public static IEventIDLog GetLogger(Type type)
{
return GetLogger(Assembly.GetCallingAssembly(), type.FullName);
}
/// <summary>
/// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
/// </summary>
/// <remarks>
/// Get the logger for the fully qualified name of the type specified.
/// </remarks>
/// <param name="domain">the domain to lookup in</param>
/// <param name="type">The full name of <paramref name="type"/> will
/// be used as the name of the logger to retrieve.</param>
/// <returns>the logger with the name specified</returns>
public static IEventIDLog GetLogger(string domain, Type type)
{
return WrapLogger(LoggerManager.GetLogger(domain, type));
}
/// <summary>
/// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
/// </summary>
/// <remarks>
/// Get the logger for the fully qualified name of the type specified.
/// </remarks>
/// <param name="assembly">the assembly to use to lookup the domain</param>
/// <param name="type">The full name of <paramref name="type"/> will
/// be used as the name of the logger to retrieve.</param>
/// <returns>the logger with the name specified</returns>
public static IEventIDLog GetLogger(Assembly assembly, Type type)
{
return WrapLogger(LoggerManager.GetLogger(assembly, type));
}
#endregion
#region Extension Handlers
/// <summary>
/// Lookup the wrapper object for the logger specified
/// </summary>
/// <param name="logger">the logger to get the wrapper for</param>
/// <returns>the wrapper for the logger specified</returns>
private static IEventIDLog WrapLogger(ILogger logger)
{
return (IEventIDLog)s_wrapperMap.GetWrapper(logger);
}
/// <summary>
/// Lookup the wrapper objects for the loggers specified
/// </summary>
/// <param name="loggers">the loggers to get the wrappers for</param>
/// <returns>Lookup the wrapper objects for the loggers specified</returns>
private static IEventIDLog[] WrapLoggers(ILogger[] loggers)
{
IEventIDLog[] results = new IEventIDLog[loggers.Length];
for(int i=0; i<loggers.Length; i++)
{
results[i] = WrapLogger(loggers[i]);
}
return results;
}
/// <summary>
/// Method to create the <see cref="ILoggerWrapper"/> objects used by
/// this manager.
/// </summary>
/// <param name="logger">The logger to wrap</param>
/// <returns>The wrapper for the logger specified</returns>
private static ILoggerWrapper WrapperCreationHandler(ILogger logger)
{
return new EventIDLogImpl(logger);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Asn1.Cms.Ecc;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.Utilities;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.Cms
{
/**
* the RecipientInfo class for a recipient who has been sent a message
* encrypted using key agreement.
*/
public class KeyAgreeRecipientInformation
: RecipientInformation
{
private KeyAgreeRecipientInfo info;
private Asn1OctetString encryptedKey;
internal static void ReadRecipientInfo(IList infos, KeyAgreeRecipientInfo info,
CmsSecureReadable secureReadable)
{
try
{
foreach (Asn1Encodable rek in info.RecipientEncryptedKeys)
{
RecipientEncryptedKey id = RecipientEncryptedKey.GetInstance(rek.ToAsn1Object());
RecipientID rid = new RecipientID();
Asn1.Cms.KeyAgreeRecipientIdentifier karid = id.Identifier;
Asn1.Cms.IssuerAndSerialNumber iAndSN = karid.IssuerAndSerialNumber;
if (iAndSN != null)
{
rid.Issuer = iAndSN.Name;
rid.SerialNumber = iAndSN.SerialNumber.Value;
}
else
{
Asn1.Cms.RecipientKeyIdentifier rKeyID = karid.RKeyID;
// Note: 'date' and 'other' fields of RecipientKeyIdentifier appear to be only informational
rid.SubjectKeyIdentifier = rKeyID.SubjectKeyIdentifier.GetOctets();
}
infos.Add(new KeyAgreeRecipientInformation(info, rid, id.EncryptedKey,
secureReadable));
}
}
catch (IOException e)
{
throw new ArgumentException("invalid rid in KeyAgreeRecipientInformation", e);
}
}
internal KeyAgreeRecipientInformation(
KeyAgreeRecipientInfo info,
RecipientID rid,
Asn1OctetString encryptedKey,
CmsSecureReadable secureReadable)
: base(info.KeyEncryptionAlgorithm, secureReadable)
{
this.info = info;
this.rid = rid;
this.encryptedKey = encryptedKey;
}
private IAsymmetricKeyParameter GetSenderPublicKey(
IAsymmetricKeyParameter receiverPrivateKey,
OriginatorIdentifierOrKey originator)
{
OriginatorPublicKey opk = originator.OriginatorPublicKey;
if (opk != null)
{
return GetPublicKeyFromOriginatorPublicKey(receiverPrivateKey, opk);
}
OriginatorID origID = new OriginatorID();
Asn1.Cms.IssuerAndSerialNumber iAndSN = originator.IssuerAndSerialNumber;
if (iAndSN != null)
{
origID.Issuer = iAndSN.Name;
origID.SerialNumber = iAndSN.SerialNumber.Value;
}
else
{
SubjectKeyIdentifier ski = originator.SubjectKeyIdentifier;
origID.SubjectKeyIdentifier = ski.GetKeyIdentifier();
}
return GetPublicKeyFromOriginatorID(origID);
}
private IAsymmetricKeyParameter GetPublicKeyFromOriginatorPublicKey(
IAsymmetricKeyParameter receiverPrivateKey,
OriginatorPublicKey originatorPublicKey)
{
PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(receiverPrivateKey);
SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(
privInfo.AlgorithmID,
originatorPublicKey.PublicKey.GetBytes());
return PublicKeyFactory.CreateKey(pubInfo);
}
private IAsymmetricKeyParameter GetPublicKeyFromOriginatorID(
OriginatorID origID)
{
// TODO Support all alternatives for OriginatorIdentifierOrKey
// see RFC 3852 6.2.2
throw new CmsException("No support for 'originator' as IssuerAndSerialNumber or SubjectKeyIdentifier");
}
private KeyParameter CalculateAgreedWrapKey(
string wrapAlg,
IAsymmetricKeyParameter senderPublicKey,
IAsymmetricKeyParameter receiverPrivateKey)
{
DerObjectIdentifier agreeAlgID = keyEncAlg.ObjectID;
ICipherParameters senderPublicParams = senderPublicKey;
ICipherParameters receiverPrivateParams = receiverPrivateKey;
if (agreeAlgID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
{
byte[] ukmEncoding = info.UserKeyingMaterial.GetOctets();
MQVuserKeyingMaterial ukm = MQVuserKeyingMaterial.GetInstance(
Asn1Object.FromByteArray(ukmEncoding));
IAsymmetricKeyParameter ephemeralKey = GetPublicKeyFromOriginatorPublicKey(
receiverPrivateKey, ukm.EphemeralPublicKey);
senderPublicParams = new MqvPublicParameters(
(ECPublicKeyParameters)senderPublicParams,
(ECPublicKeyParameters)ephemeralKey);
receiverPrivateParams = new MqvPrivateParameters(
(ECPrivateKeyParameters)receiverPrivateParams,
(ECPrivateKeyParameters)receiverPrivateParams);
}
IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
agreeAlgID, wrapAlg);
agreement.Init(receiverPrivateParams);
IBigInteger agreedValue = agreement.CalculateAgreement(senderPublicParams);
int wrapKeySize = GeneratorUtilities.GetDefaultKeySize(wrapAlg) / 8;
byte[] wrapKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, wrapKeySize);
return ParameterUtilities.CreateKeyParameter(wrapAlg, wrapKeyBytes);
}
private KeyParameter UnwrapSessionKey(
string wrapAlg,
KeyParameter agreedKey)
{
byte[] encKeyOctets = encryptedKey.GetOctets();
IWrapper keyCipher = WrapperUtilities.GetWrapper(wrapAlg);
keyCipher.Init(false, agreedKey);
byte[] sKeyBytes = keyCipher.Unwrap(encKeyOctets, 0, encKeyOctets.Length);
return ParameterUtilities.CreateKeyParameter(GetContentAlgorithmName(), sKeyBytes);
}
internal KeyParameter GetSessionKey(
IAsymmetricKeyParameter receiverPrivateKey)
{
try
{
string wrapAlg = DerObjectIdentifier.GetInstance(
Asn1Sequence.GetInstance(keyEncAlg.Parameters)[0]).Id;
IAsymmetricKeyParameter senderPublicKey = GetSenderPublicKey(
receiverPrivateKey, info.Originator);
KeyParameter agreedWrapKey = CalculateAgreedWrapKey(wrapAlg,
senderPublicKey, receiverPrivateKey);
return UnwrapSessionKey(wrapAlg, agreedWrapKey);
}
catch (SecurityUtilityException e)
{
throw new CmsException("couldn't create cipher.", e);
}
catch (InvalidKeyException e)
{
throw new CmsException("key invalid in message.", e);
}
catch (Exception e)
{
throw new CmsException("originator key invalid.", e);
}
}
/**
* decrypt the content and return an input stream.
*/
public override CmsTypedStream GetContentStream(
ICipherParameters key)
{
if (!(key is AsymmetricKeyParameter))
throw new ArgumentException(@"KeyAgreement requires asymmetric key", "key");
IAsymmetricKeyParameter receiverPrivateKey = (AsymmetricKeyParameter) key;
if (!receiverPrivateKey.IsPrivate)
throw new ArgumentException(@"Expected private key", "key");
KeyParameter sKey = GetSessionKey(receiverPrivateKey);
return GetContentFromSessionKey(sKey);
}
}
}
| |
using System;
using System.IO;
using System.Drawing;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.CodeDom.Compiler;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing.Design;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Windows.Forms.Design;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using Microsoft.Win32;
using System.Workflow.ComponentModel.Compiler;
namespace System.Workflow.ComponentModel.Design
{
/// <summary>
/// Summary description for ThemeConfigurationDialog.
/// </summary>
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class ThemeConfigurationDialog : System.Windows.Forms.Form
{
#region [....] Generated Members
private System.Windows.Forms.Button button3;
private System.Windows.Forms.TreeView designerTreeView;
private System.Windows.Forms.Label themeNameLabel;
private System.Windows.Forms.Label themeLocationLabel;
private System.Windows.Forms.TextBox themeNameTextBox;
private System.Windows.Forms.Panel themePanel;
private System.Windows.Forms.Panel themeConfigPanel;
private System.Windows.Forms.Panel dummyPreviewPanel;
private System.Windows.Forms.TextBox themeLocationTextBox;
private System.Windows.Forms.Label previewLabel;
private System.Windows.Forms.Label selectDesignerLabel;
private System.Windows.Forms.PropertyGrid propertiesGrid;
private System.Windows.Forms.Button themeLocationButton;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button previewButton;
private System.ComponentModel.IContainer components = null;
#endregion
#region Member Variables
private IServiceProvider serviceProvider;
private bool previewShown = false;
private WorkflowTheme bufferedTheme;
private DesignerPreview designerPreview;
private Splitter splitter;
private TableLayoutPanel okCancelTableLayoutPanel;
private TableLayoutPanel nameLocationTableLayoutPanel;
private bool themeDirty = false;
#endregion
#region Constructor/Destructor
public ThemeConfigurationDialog(IServiceProvider serviceProvider)
: this(serviceProvider, null)
{
}
public ThemeConfigurationDialog(IServiceProvider serviceProvider, WorkflowTheme theme)
{
if (serviceProvider == null)
throw new ArgumentNullException("serviceProvider");
this.serviceProvider = serviceProvider;
if (theme == null)
{
this.bufferedTheme = new WorkflowTheme();
this.themeDirty = true;
}
else
{
this.bufferedTheme = theme;
this.themeDirty = false;
}
this.bufferedTheme.ReadOnly = false;
InitializeComponent();
this.themeLocationButton.AutoSize = true;
//Set dialog fonts
Font = StandardFont;
SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(OnOperatingSystemSettingsChanged);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
components.Dispose();
SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(OnOperatingSystemSettingsChanged);
if (this.designerPreview != null)
{
this.designerPreview.Dispose();
this.designerPreview = null;
}
if (this.bufferedTheme != null)
{
((IDisposable)this.bufferedTheme).Dispose();
this.bufferedTheme = null;
}
}
base.Dispose(disposing);
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ThemeConfigurationDialog));
this.designerTreeView = new System.Windows.Forms.TreeView();
this.themeNameLabel = new System.Windows.Forms.Label();
this.themeLocationLabel = new System.Windows.Forms.Label();
this.themeNameTextBox = new System.Windows.Forms.TextBox();
this.nameLocationTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.themeLocationButton = new System.Windows.Forms.Button();
this.themeLocationTextBox = new System.Windows.Forms.TextBox();
this.button3 = new System.Windows.Forms.Button();
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.themePanel = new System.Windows.Forms.Panel();
this.themeConfigPanel = new System.Windows.Forms.Panel();
this.propertiesGrid = new System.Windows.Forms.PropertyGrid();
this.previewLabel = new System.Windows.Forms.Label();
this.selectDesignerLabel = new System.Windows.Forms.Label();
this.dummyPreviewPanel = new System.Windows.Forms.Panel();
this.previewButton = new System.Windows.Forms.Button();
this.okCancelTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.nameLocationTableLayoutPanel.SuspendLayout();
this.themePanel.SuspendLayout();
this.themeConfigPanel.SuspendLayout();
this.okCancelTableLayoutPanel.SuspendLayout();
this.SuspendLayout();
//
// designerTreeView
//
resources.ApplyResources(this.designerTreeView, "designerTreeView");
this.designerTreeView.Name = "designerTreeView";
//
// themeNameLabel
//
resources.ApplyResources(this.themeNameLabel, "themeNameLabel");
this.themeNameLabel.Margin = new System.Windows.Forms.Padding(0, 0, 3, 3);
this.themeNameLabel.Name = "themeNameLabel";
//
// themeLocationLabel
//
resources.ApplyResources(this.themeLocationLabel, "themeLocationLabel");
this.themeLocationLabel.Margin = new System.Windows.Forms.Padding(0, 3, 3, 0);
this.themeLocationLabel.Name = "themeLocationLabel";
//
// themeNameTextBox
//
resources.ApplyResources(this.themeNameTextBox, "themeNameTextBox");
this.nameLocationTableLayoutPanel.SetColumnSpan(this.themeNameTextBox, 2);
this.themeNameTextBox.Margin = new System.Windows.Forms.Padding(3, 0, 0, 3);
this.themeNameTextBox.Name = "themeNameTextBox";
//
// nameLocationTableLayoutPanel
//
resources.ApplyResources(this.nameLocationTableLayoutPanel, "nameLocationTableLayoutPanel");
this.nameLocationTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.nameLocationTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.nameLocationTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.nameLocationTableLayoutPanel.Controls.Add(this.themeNameLabel, 0, 0);
this.nameLocationTableLayoutPanel.Controls.Add(this.themeNameTextBox, 1, 0);
this.nameLocationTableLayoutPanel.Controls.Add(this.themeLocationButton, 2, 1);
this.nameLocationTableLayoutPanel.Controls.Add(this.themeLocationLabel, 0, 1);
this.nameLocationTableLayoutPanel.Controls.Add(this.themeLocationTextBox, 1, 1);
this.nameLocationTableLayoutPanel.Name = "nameLocationTableLayoutPanel";
this.nameLocationTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.nameLocationTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
//
// themeLocationButton
//
resources.ApplyResources(this.themeLocationButton, "themeLocationButton");
this.themeLocationButton.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0);
this.themeLocationButton.Name = "themeLocationButton";
//
// themeLocationTextBox
//
resources.ApplyResources(this.themeLocationTextBox, "themeLocationTextBox");
this.themeLocationTextBox.Margin = new System.Windows.Forms.Padding(3, 3, 3, 0);
this.themeLocationTextBox.Name = "themeLocationTextBox";
//
// button3
//
resources.ApplyResources(this.button3, "button3");
this.button3.Name = "button3";
//
// okButton
//
resources.ApplyResources(this.okButton, "okButton");
this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okButton.Margin = new System.Windows.Forms.Padding(0, 0, 3, 0);
this.okButton.Name = "okButton";
//
// cancelButton
//
resources.ApplyResources(this.cancelButton, "cancelButton");
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
this.cancelButton.Name = "cancelButton";
//
// themePanel
//
this.themePanel.Controls.Add(this.themeConfigPanel);
this.themePanel.Controls.Add(this.previewLabel);
this.themePanel.Controls.Add(this.selectDesignerLabel);
this.themePanel.Controls.Add(this.dummyPreviewPanel);
resources.ApplyResources(this.themePanel, "themePanel");
this.themePanel.Margin = new System.Windows.Forms.Padding(4);
this.themePanel.Name = "themePanel";
//
// themeConfigPanel
//
this.themeConfigPanel.Controls.Add(this.designerTreeView);
this.themeConfigPanel.Controls.Add(this.propertiesGrid);
resources.ApplyResources(this.themeConfigPanel, "themeConfigPanel");
this.themeConfigPanel.Name = "themeConfigPanel";
//
// propertiesGrid
//
this.propertiesGrid.CommandsVisibleIfAvailable = true;
resources.ApplyResources(this.propertiesGrid, "propertiesGrid");
this.propertiesGrid.Name = "propertiesGrid";
this.propertiesGrid.ToolbarVisible = false;
//
// previewLabel
//
resources.ApplyResources(this.previewLabel, "previewLabel");
this.previewLabel.Name = "previewLabel";
//
// selectDesignerLabel
//
resources.ApplyResources(this.selectDesignerLabel, "selectDesignerLabel");
this.selectDesignerLabel.Name = "selectDesignerLabel";
//
// dummyPreviewPanel
//
resources.ApplyResources(this.dummyPreviewPanel, "dummyPreviewPanel");
this.dummyPreviewPanel.Name = "dummyPreviewPanel";
//
// previewButton
//
resources.ApplyResources(this.previewButton, "previewButton");
this.previewButton.Margin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.previewButton.Name = "previewButton";
//
// okCancelTableLayoutPanel
//
resources.ApplyResources(this.okCancelTableLayoutPanel, "okCancelTableLayoutPanel");
this.okCancelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33F));
this.okCancelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33F));
this.okCancelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33F));
this.okCancelTableLayoutPanel.Controls.Add(this.okButton, 0, 0);
this.okCancelTableLayoutPanel.Controls.Add(this.cancelButton, 1, 0);
this.okCancelTableLayoutPanel.Controls.Add(this.previewButton, 2, 0);
this.okCancelTableLayoutPanel.Name = "okCancelTableLayoutPanel";
this.okCancelTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
//
// ThemeConfigurationDialog
//
this.AcceptButton = this.okButton;
this.CancelButton = this.cancelButton;
resources.ApplyResources(this, "$this");
this.Controls.Add(this.nameLocationTableLayoutPanel);
this.Controls.Add(this.okCancelTableLayoutPanel);
this.Controls.Add(this.themePanel);
this.Controls.Add(this.button3);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ThemeConfigurationDialog";
this.ShowInTaskbar = false;
this.HelpButton = true;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.nameLocationTableLayoutPanel.ResumeLayout(false);
this.nameLocationTableLayoutPanel.PerformLayout();
this.themePanel.ResumeLayout(false);
this.themeConfigPanel.ResumeLayout(false);
this.okCancelTableLayoutPanel.ResumeLayout(false);
this.okCancelTableLayoutPanel.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
#region Properties and Methods
public WorkflowTheme ComposedTheme
{
get
{
return this.bufferedTheme;
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
try
{
Cursor.Current = Cursors.WaitCursor;
InitializeControls();
}
finally
{
Cursor.Current = Cursors.Default;
}
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
this.bufferedTheme.ReadOnly = true;
}
#endregion
#region Helper Functions
private Font StandardFont
{
get
{
Font font = SystemInformation.MenuFont;
if (this.serviceProvider != null)
{
IUIService uisvc = (IUIService)this.serviceProvider.GetService(typeof(IUIService));
if (uisvc != null)
font = (Font)uisvc.Styles["DialogFont"];
}
return font;
}
}
private void InitializeControls()
{
HelpButtonClicked += new CancelEventHandler(OnHelpClicked);
this.themeNameTextBox.Text = this.bufferedTheme.Name;
this.themeLocationTextBox.Text = this.bufferedTheme.FilePath;
this.propertiesGrid.PropertySort = PropertySort.Categorized;
//Make sure that size and location are changed after adding the control to the parent
//this will autoscale the control correctly
this.designerPreview = new DesignerPreview(this);
this.dummyPreviewPanel.Parent.Controls.Add(this.designerPreview);
this.designerPreview.TabStop = false;
this.designerPreview.Location = this.dummyPreviewPanel.Location;
this.designerPreview.Size = this.dummyPreviewPanel.Size;
this.dummyPreviewPanel.Visible = false;
this.designerPreview.Parent.Controls.Remove(this.dummyPreviewPanel);
this.designerTreeView.ShowLines = false;
this.designerTreeView.ShowPlusMinus = false;
this.designerTreeView.ShowRootLines = false;
this.designerTreeView.ShowNodeToolTips = true;
this.designerTreeView.HideSelection = false;
this.designerTreeView.ItemHeight = Math.Max(this.designerTreeView.ItemHeight, 18);
ThemeConfigHelpers.PopulateActivities(this.serviceProvider, this.designerTreeView);
this.themeConfigPanel.Controls.Remove(this.designerTreeView);
this.themeConfigPanel.Controls.Remove(this.propertiesGrid);
this.designerTreeView.Dock = DockStyle.Left;
this.splitter = new Splitter();
this.splitter.Dock = DockStyle.Left;
this.propertiesGrid.Dock = DockStyle.Fill;
this.themeConfigPanel.Controls.AddRange(new Control[] { this.propertiesGrid, this.splitter, this.designerTreeView });
this.themePanel.Paint += new PaintEventHandler(OnThemePanelPaint);
this.previewButton.Click += new EventHandler(OnPreviewClicked);
this.designerTreeView.AfterSelect += new TreeViewEventHandler(OnDesignerSelectionChanged);
this.themeLocationButton.Click += new EventHandler(OnThemeLocationClicked);
this.okButton.Click += new EventHandler(OnOk);
this.propertiesGrid.PropertyValueChanged += new PropertyValueChangedEventHandler(OnThemePropertyChanged);
this.themeNameTextBox.TextChanged += new EventHandler(OnThemeChanged);
this.themeLocationTextBox.TextChanged += new EventHandler(OnThemeChanged);
this.designerTreeView.SelectedNode = (this.designerTreeView.Nodes.Count > 0) ? this.designerTreeView.Nodes[0] : null;
this.designerTreeView.SelectedNode.EnsureVisible();
ShowPreview = true;
}
private void OnThemeChanged(object sender, EventArgs e)
{
this.themeDirty = true;
}
private void OnThemePropertyChanged(object sender, PropertyValueChangedEventArgs e)
{
this.themeDirty = true;
}
private bool ValidateControls(out string error, out Control control)
{
error = String.Empty;
control = null;
if (this.themeNameTextBox.Text == null || this.themeNameTextBox.Text.Trim().Length == 0)
{
error = DR.GetString(DR.ThemeNameNotValid);
control = this.themeNameTextBox;
return false;
}
if (this.themeLocationTextBox.Text == null)
{
error = DR.GetString(DR.ThemePathNotValid);
control = this.themeNameTextBox;
return false;
}
string path = this.themeLocationTextBox.Text.Trim();
if (path.IndexOfAny(Path.GetInvalidPathChars()) >= 0 ||
!Path.IsPathRooted(path) ||
!Path.HasExtension(path))
{
error = DR.GetString(DR.ThemePathNotValid);
control = this.themeLocationTextBox;
return false;
}
string fileName = Path.GetFileNameWithoutExtension(path);
string extension = Path.GetExtension(path);
if (fileName == null || fileName.Trim().Length == 0 ||
extension == null || extension.Trim().Length == 0)
{
error = DR.GetString(DR.ThemePathNotValid);
control = this.themeLocationTextBox;
return false;
}
if (!extension.Equals(WorkflowTheme.DefaultThemeFileExtension.Replace("*", ""), StringComparison.Ordinal))
{
error = DR.GetString(DR.ThemeFileNotXml);
control = this.themeLocationTextBox;
return false;
}
return true;
}
private void OnOk(object sender, EventArgs e)
{
string error = String.Empty;
Control control = null;
if (!ValidateControls(out error, out control))
{
DialogResult = DialogResult.None;
DesignerHelpers.ShowError(this.serviceProvider, error);
if (control != null)
{
TextBox textBox = control as TextBox;
if (textBox != null)
{
textBox.SelectionStart = 0;
textBox.SelectionLength = (textBox.Text != null) ? textBox.Text.Length : 0;
}
control.Focus();
}
return;
}
//Before we try saving show the warning if the user has changed the theme path
if (!this.bufferedTheme.FilePath.Equals(this.themeLocationTextBox.Text.Trim(), StringComparison.OrdinalIgnoreCase))
{
if (DialogResult.No == DesignerHelpers.ShowMessage(this.serviceProvider, DR.GetString(DR.UpdateRelativePaths), DR.GetString(DR.WorkflowDesignerTitle), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1))
{
DialogResult = DialogResult.None;
return;
}
}
if (this.themeDirty)
{
try
{
Cursor.Current = Cursors.WaitCursor;
ThemeConfigHelpers.EnsureDesignerThemes(this.serviceProvider, this.bufferedTheme, ThemeConfigHelpers.GetAllTreeNodes(this.designerTreeView));
this.bufferedTheme.ReadOnly = false;
this.bufferedTheme.Name = this.themeNameTextBox.Text.Trim();
this.bufferedTheme.Description = DR.GetString(DR.ThemeDescription);
this.bufferedTheme.Save(this.themeLocationTextBox.Text.Trim());
this.themeDirty = false;
this.bufferedTheme.ReadOnly = true;
}
catch
{
DesignerHelpers.ShowError(this.serviceProvider, DR.GetString(DR.ThemeFileCreationError));
this.themeLocationTextBox.SelectionStart = 0;
this.themeLocationTextBox.SelectionLength = (this.themeLocationTextBox.Text != null) ? this.themeLocationTextBox.Text.Length : 0;
this.themeLocationTextBox.Focus();
DialogResult = DialogResult.None;
}
finally
{
Cursor.Current = Cursors.Default;
}
}
}
private void OnHelpClicked(object sender, CancelEventArgs e)
{
e.Cancel = true;
ShowHelp();
}
protected override void OnHelpRequested(HelpEventArgs e)
{
ShowHelp();
e.Handled = true;
}
private void ShowHelp()
{
DesignerHelpers.ShowHelpFromKeyword(this.serviceProvider, typeof(ThemeConfigurationDialog).FullName + ".UI");
}
private void OnThemePanelPaint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(SystemPens.ControlDark, 0, 0, this.themePanel.ClientSize.Width - 1, this.themePanel.ClientSize.Height - 2);
if (this.previewShown)
{
Point top = new Point(this.propertiesGrid.Right + (this.dummyPreviewPanel.Left - this.propertiesGrid.Right) / 2, this.themePanel.Margin.Top);
Point bottom = new Point(top.X, this.themePanel.Height - this.themePanel.Margin.Bottom);
e.Graphics.DrawLine(SystemPens.ControlDark, top, bottom);
}
Size margin = new Size(8, 8);
using (Pen framePen = new Pen(Color.Black, 1))
{
framePen.DashStyle = DashStyle.Dot;
e.Graphics.DrawLine(framePen, this.designerPreview.Left - margin.Width, this.designerPreview.Top - 1, this.designerPreview.Right + margin.Width, this.designerPreview.Top - 1);
e.Graphics.DrawLine(framePen, this.designerPreview.Left - margin.Width, this.designerPreview.Bottom + 1, this.designerPreview.Right + margin.Width, this.designerPreview.Bottom + 1);
e.Graphics.DrawLine(framePen, this.designerPreview.Left - 1, this.designerPreview.Top - margin.Height, this.designerPreview.Left - 1, this.designerPreview.Bottom + margin.Height);
e.Graphics.DrawLine(framePen, this.designerPreview.Right + 1, this.designerPreview.Top - margin.Height, this.designerPreview.Right + 1, this.designerPreview.Bottom + margin.Height);
}
}
private void OnDesignerSelectionChanged(object sender, TreeViewEventArgs eventArgs)
{
//We need to select the theme of the selected designer
Type activityType = (eventArgs.Node != null && typeof(Activity).IsAssignableFrom(eventArgs.Node.Tag as System.Type)) ? eventArgs.Node.Tag as System.Type : null;
IDesigner previewedDesigner = this.designerPreview.UpdatePreview(activityType);
object[] selectedObjects = null;
if (activityType == null)
{
if (eventArgs.Node != null)
selectedObjects = (eventArgs.Node.Parent == null) ? new object[] { this.bufferedTheme.AmbientTheme } : ThemeConfigHelpers.GetDesignerThemes(this.serviceProvider, this.bufferedTheme, eventArgs.Node);
}
else
{
selectedObjects = (previewedDesigner != null) ? new object[] { this.bufferedTheme.GetDesignerTheme(previewedDesigner as ActivityDesigner) } : null;
}
this.propertiesGrid.SelectedObjects = selectedObjects;
}
private void OnPreviewClicked(object sender, EventArgs e)
{
ShowPreview = !ShowPreview;
}
private void OnThemeLocationClicked(object sender, EventArgs e)
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.AddExtension = true;
fileDialog.DefaultExt = WorkflowTheme.DefaultThemeFileExtension;
fileDialog.Filter = DR.GetString(DR.ThemeFileFilter);
fileDialog.RestoreDirectory = false;
if (fileDialog.ShowDialog(this) == DialogResult.OK)
{
this.themeLocationTextBox.Text = fileDialog.FileName;
}
}
private bool ShowPreview
{
get
{
return this.previewShown;
}
set
{
this.previewShown = value;
this.previewLabel.Visible = this.previewShown;
this.designerPreview.Visible = this.previewShown;
if (this.previewShown)
{
this.themePanel.Width = this.designerPreview.Right + ((this.designerPreview.Left - this.propertiesGrid.Right) / 2);
this.previewButton.Text = DR.GetString(DR.Preview) + " <<";
}
else
{
this.themePanel.Width = this.themeConfigPanel.Right + this.themeConfigPanel.Left;
this.previewButton.Text = DR.GetString(DR.Preview) + " >>";
}
Width = this.themePanel.Right + this.themePanel.Left + Margin.Left + Margin.Right;
this.themePanel.Invalidate();
}
}
private void OnOperatingSystemSettingsChanged(object sender, UserPreferenceChangedEventArgs e)
{
//
if (e.Category == UserPreferenceCategory.Color || e.Category == UserPreferenceCategory.VisualStyle)
Font = StandardFont;
}
#endregion
#region Class ThemeHelpers
private static class ThemeConfigHelpers
{
internal static void PopulateActivities(IServiceProvider serviceProvider, TreeView treeView)
{
List<Type> activityTypes = new List<Type>();
//***************STOCK TYPES*************
List<String> stockActivityTypeNames = new List<string>();
stockActivityTypeNames.Add(DesignerHelpers.SequentialWorkflowTypeRef);
stockActivityTypeNames.Add(DesignerHelpers.StateMachineWorkflowTypeRef);
stockActivityTypeNames.Add(DesignerHelpers.IfElseBranchTypeRef);
stockActivityTypeNames.Add(typeof(FaultHandlersActivity).AssemblyQualifiedName);
stockActivityTypeNames.Add(DesignerHelpers.EventHandlersTypeRef);
stockActivityTypeNames.Add(typeof(CompensationHandlerActivity).AssemblyQualifiedName);
stockActivityTypeNames.Add(typeof(CancellationHandlerActivity).AssemblyQualifiedName);
foreach (string stockTypeName in stockActivityTypeNames)
{
Type stockType = Type.GetType(stockTypeName, false);
if (stockType == null)
Debug.Assert(false, string.Format(CultureInfo.CurrentCulture, "Could not load type '{0}'", stockTypeName));
else
activityTypes.Add(stockType);
}
//***************NON PREVIWABLE DESIGNER TYPES*************
IList<Type> nonpreviewableDesignerTypes = new List<Type>();
//These designer might be designers such as CADesigner which we eliminated
//We have just kept the code so that in future if this functionality is needed
//we can add it
//Populate the designer combobox
treeView.BeginUpdate();
treeView.Nodes.Clear();
//Work around: ***WE DISPLAY THE COMMON PROPERTIES FOR WORKFLOW AND APPLY THEM RECURSIVELY TO DESIGNERS
TreeNode workflowNode = new TreeNode(DR.GetString(DR.WorkflowDesc));
treeView.Nodes.Add(workflowNode);
//Now we go thru the toolbox items and get all the items which are not in our assembly
IToolboxService toolboxService = serviceProvider.GetService(typeof(IToolboxService)) as IToolboxService;
ITypeProviderCreator typeProviderCreator = serviceProvider.GetService(typeof(ITypeProviderCreator)) as ITypeProviderCreator;
if (toolboxService != null && typeProviderCreator != null)
{
ToolboxItemCollection toolboxItems = toolboxService.GetToolboxItems();
foreach (ToolboxItem toolboxItem in toolboxItems)
{
bool customWinOEActivityType = (toolboxItem is ActivityToolboxItem);
if (!customWinOEActivityType)
{
foreach (ToolboxItemFilterAttribute filter in toolboxItem.Filter)
{
if (filter.FilterString.StartsWith("Microsoft.Workflow.VSDesigner", StringComparison.OrdinalIgnoreCase) ||
filter.FilterString.StartsWith("System.Workflow.ComponentModel", StringComparison.OrdinalIgnoreCase))
{
customWinOEActivityType = true;
break;
}
}
}
if (customWinOEActivityType)
{
Type type = null;
Assembly assembly = typeProviderCreator.GetTransientAssembly(toolboxItem.AssemblyName);
if (assembly != null)
type = assembly.GetType(toolboxItem.TypeName);
if (type != null)
{
ConstructorInfo[] constructors = type.GetConstructors();
foreach (ConstructorInfo constructor in constructors)
{
if (constructor.IsPublic && constructor.GetParameters().GetLength(0) == 0)
activityTypes.Add(type);
}
}
}
}
}
foreach (Type type in activityTypes)
{
Type designerBaseType = (type.FullName.Equals(DesignerHelpers.SequentialWorkflowTypeRef, StringComparison.OrdinalIgnoreCase)) ? typeof(IRootDesigner) : typeof(IDesigner);
Type designerType = ActivityDesigner.GetDesignerType(serviceProvider, type, designerBaseType);
if (designerType != null && !nonpreviewableDesignerTypes.Contains(designerType))
{
object[] attribs = designerType.GetCustomAttributes(typeof(ActivityDesignerThemeAttribute), true);
ActivityDesignerThemeAttribute themeAttrib = (attribs != null && attribs.GetLength(0) > 0) ? attribs[0] as ActivityDesignerThemeAttribute : null;
if (themeAttrib != null)
{
Image image = ActivityToolboxItem.GetToolboxImage(type);
if (treeView.ImageList == null)
{
treeView.ImageList = new ImageList();
treeView.ImageList.ColorDepth = ColorDepth.Depth32Bit;
Image standardImage = DR.GetImage(DR.Activity) as Image;
treeView.ImageList.Images.Add(standardImage, AmbientTheme.TransparentColor);
}
TreeNode parentNode = ThemeConfigHelpers.GetCatagoryNodeForDesigner(designerType, ThemeConfigHelpers.GetAllTreeNodes(treeView));
if (parentNode != null)
{
int imageIndex = (image != null) ? treeView.ImageList.Images.Add(image, AmbientTheme.TransparentColor) : 0;
TreeNode nodeToInsert = (imageIndex >= 0) ? new TreeNode(ActivityToolboxItem.GetToolboxDisplayName(type), imageIndex, imageIndex) : new TreeNode(ActivityToolboxItem.GetToolboxDisplayName(type));
nodeToInsert.Tag = type;
//We always make sure that cata----es are at the end
int index = parentNode.Nodes.Count - 1;
while (index >= 0 && parentNode.Nodes[index].Tag is System.Type)
index = index - 1;
parentNode.Nodes.Insert(index, nodeToInsert);
}
}
}
}
treeView.TreeViewNodeSorter = new ThemeTreeNodeComparer();
treeView.Sort();
treeView.Nodes[0].ExpandAll();
treeView.EndUpdate();
}
internal static TreeNode GetCatagoryNodeForDesigner(Type designerType, TreeNode[] treeNodes)
{
if (designerType == null)
throw new ArgumentNullException("designerType");
if (treeNodes == null)
throw new ArgumentNullException("treeNodes");
if (treeNodes.Length == 0)
throw new ArgumentException(SR.GetString(SR.Error_InvalidArgumentValue), "treeNodes");
CategoryAttribute parentCatagoryAttribute = null;
CategoryAttribute designerCatagoryAttribute = null;
Type baseType = designerType;
while (baseType != typeof(object) && parentCatagoryAttribute == null)
{
object[] attribs = baseType.GetCustomAttributes(typeof(CategoryAttribute), false);
if (attribs != null && attribs.GetLength(0) > 0)
{
if (designerCatagoryAttribute == null)
designerCatagoryAttribute = attribs[0] as CategoryAttribute;
else
parentCatagoryAttribute = attribs[0] as CategoryAttribute;
}
baseType = baseType.BaseType;
}
if (designerCatagoryAttribute == null)
return null;
//Search for the catagory
TreeNode catagoryNode = null;
TreeNode parentCatagoryTreeNode = treeNodes[0];
foreach (TreeNode item in treeNodes)
{
if (parentCatagoryAttribute != null && parentCatagoryAttribute.Category == item.Text && (item.Tag == null || !typeof(Activity).IsAssignableFrom(item.Tag.GetType())))
parentCatagoryTreeNode = item;
//We found the catagory
if (designerCatagoryAttribute.Category == item.Text && (item.Tag == null || !typeof(Activity).IsAssignableFrom(item.Tag.GetType())))
{
catagoryNode = item;
break;
}
}
if (catagoryNode == null)
{
Debug.Assert(parentCatagoryTreeNode != null);
if (parentCatagoryTreeNode != null)
{
//Work around : ***WE DISPLAY THE COMMON PROPERTIES FROM KNOWN DESIGNERCATA----ES
//WE WILL EVENTUALLY REMOVE THIS WHEN WE CREATE AN MECHANISM TO SHARE COMMON
//PROPERTIES IN THEMES
catagoryNode = new TreeNode(designerCatagoryAttribute.Category);
parentCatagoryTreeNode.Nodes.Add(catagoryNode);
}
}
return catagoryNode;
}
internal static DesignerTheme[] GetDesignerThemes(IServiceProvider serviceProvider, WorkflowTheme workflowTheme, TreeNode selectedNode)
{
ArrayList designerThemes = new ArrayList();
Queue<TreeNode> nodes = new Queue<TreeNode>();
nodes.Enqueue(selectedNode);
while (nodes.Count > 0)
{
TreeNode treeNode = nodes.Dequeue();
Type activityType = treeNode.Tag as System.Type;
if (activityType != null)
{
Type designerBaseType = (activityType.FullName.Equals(DesignerHelpers.SequentialWorkflowTypeRef, StringComparison.OrdinalIgnoreCase)) ? typeof(IRootDesigner) : typeof(IDesigner);
Type designerType = ActivityDesigner.GetDesignerType(serviceProvider, activityType, designerBaseType);
if (designerType != null)
{
DesignerTheme designerTheme = workflowTheme.GetTheme(designerType);
if (designerTheme != null)
designerThemes.Add(designerTheme);
}
}
else
{
foreach (TreeNode childNode in treeNode.Nodes)
nodes.Enqueue(childNode);
}
}
return ((DesignerTheme[])designerThemes.ToArray(typeof(DesignerTheme)));
}
internal static TreeNode[] GetAllTreeNodes(TreeView treeView)
{
List<TreeNode> items = new List<TreeNode>();
Queue<TreeNodeCollection> nodeCollections = new Queue<TreeNodeCollection>();
nodeCollections.Enqueue(treeView.Nodes);
while (nodeCollections.Count > 0)
{
TreeNodeCollection nodeCollection = nodeCollections.Dequeue();
foreach (TreeNode treeNode in nodeCollection)
{
items.Add(treeNode);
if (treeNode.Nodes.Count > 0)
nodeCollections.Enqueue(treeNode.Nodes);
}
}
return items.ToArray();
}
internal static void EnsureDesignerThemes(IServiceProvider serviceProvider, WorkflowTheme workflowTheme, TreeNode[] items)
{
//We need to recurse thru the themes and make sure that we have all the designer themes created
foreach (TreeNode item in items)
{
DesignerTheme designerTheme = null;
Type activityType = item.Tag as Type;
if (activityType != null)
{
Type designerBaseType = (activityType.FullName.Equals(DesignerHelpers.SequentialWorkflowTypeRef, StringComparison.OrdinalIgnoreCase)) ? typeof(IRootDesigner) : typeof(IDesigner);
Type designerType = ActivityDesigner.GetDesignerType(serviceProvider, activityType, designerBaseType);
if (designerType != null)
designerTheme = workflowTheme.GetTheme(designerType);
}
}
}
}
#endregion
#region Class ThemeTreeNodeComparer
internal sealed class ThemeTreeNodeComparer : IComparer
{
#region IComparer Members
int IComparer.Compare(object x, object y)
{
TreeNode treeNode1 = x as TreeNode;
TreeNode treeNode2 = y as TreeNode;
if (treeNode1.Nodes.Count > treeNode2.Nodes.Count)
return 1;
else
return String.Compare(treeNode1.Text, treeNode2.Text, StringComparison.CurrentCulture);
}
#endregion
}
#endregion
#region Class DesignerPreview
internal sealed class DesignerPreview : UserControl
{
private ThemeConfigurationDialog parent = null;
private PreviewDesignSurface surface = null;
internal DesignerPreview(ThemeConfigurationDialog parent)
{
BackColor = Color.White;
this.parent = parent;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
SuspendLayout();
this.surface = new PreviewDesignSurface(this.parent.serviceProvider);
PreviewWorkflowDesignerLoader loader = new PreviewWorkflowDesignerLoader();
this.surface.BeginLoad(loader);
//Add the root activity
IDesignerHost host = this.surface.GetService(typeof(IDesignerHost)) as IDesignerHost;
Debug.Assert(host != null);
//
Activity rootDecl = host.CreateComponent(Type.GetType(DesignerHelpers.SequentialWorkflowTypeRef)) as Activity;
rootDecl.Name = "ThemeSequentialWorkflow";
WorkflowDesignerLoader.AddActivityToDesigner(this.surface, rootDecl as Activity);
//Create the readonly workflow
ReadonlyWorkflow workflowView = new ReadonlyWorkflow(this.parent, this.surface as IServiceProvider);
workflowView.TabStop = false;
workflowView.Dock = DockStyle.Fill;
Controls.Add(workflowView);
host.Activate();
ResumeLayout(true);
}
protected override void Dispose(bool disposing)
{
if (disposing && this.surface != null)
{
IDesignerHost host = GetService(typeof(IDesignerHost)) as IDesignerHost;
if (host != null && host.RootComponent != null)
WorkflowDesignerLoader.RemoveActivityFromDesigner(this.surface, host.RootComponent as Activity);
ReadonlyWorkflow workflowView = (Controls.Count > 0) ? Controls[0] as ReadonlyWorkflow : null;
Controls.Clear();
if (workflowView != null)
{
workflowView.Dispose();
workflowView = null;
}
this.surface.Dispose();
this.surface = null;
}
base.Dispose(disposing);
}
internal IDesigner UpdatePreview(Type activityType)
{
bool dummyPreview = false; //if we have a dummy preview activity
IDesignerHost host = this.surface.GetService(typeof(IDesignerHost)) as IDesignerHost;
Debug.Assert(host != null);
CompositeActivity rootDecl = host.RootComponent as CompositeActivity;
Debug.Assert(rootDecl != null);
if (host == null || rootDecl == null)
return null;
IComponent previewActivity = null;
try
{
//Remove earlier activities
while (rootDecl.Activities.Count > 0)
{
Activity declToDelete = rootDecl.Activities[0];
rootDecl.Activities.Remove(declToDelete);
WorkflowDesignerLoader.RemoveActivityFromDesigner(this.surface, declToDelete);
}
//Add new activities to preview
if (activityType == null || activityType.FullName.Equals(DesignerHelpers.SequentialWorkflowTypeRef, StringComparison.OrdinalIgnoreCase))
{
AddDummyActivity(rootDecl as CompositeActivity, Type.GetType(DesignerHelpers.CodeActivityTypeRef));
dummyPreview = true;
}
else
{
IComponent[] components = null;
object[] attribs = activityType.GetCustomAttributes(typeof(ToolboxItemAttribute), false);
ToolboxItemAttribute toolboxItemAttrib = (attribs != null && attribs.GetLength(0) > 0) ? attribs[0] as ToolboxItemAttribute : null;
if (toolboxItemAttrib != null && toolboxItemAttrib.ToolboxItemType != null && typeof(ActivityToolboxItem).IsAssignableFrom(toolboxItemAttrib.ToolboxItemType))
{
ActivityToolboxItem item = Activator.CreateInstance(toolboxItemAttrib.ToolboxItemType, new object[] { activityType }) as ActivityToolboxItem;
components = item.CreateComponents(host);
}
if (components == null)
components = new IComponent[] { Activator.CreateInstance(activityType) as IComponent };
Activity activity = (components != null && components.Length > 0) ? components[0] as Activity : null;
if (activity != null)
{
rootDecl.Activities.Add(activity);
EnsureUniqueId(activity);
WorkflowDesignerLoader.AddActivityToDesigner(this.surface, activity);
CompositeActivityDesigner compositeDesigner = host.GetDesigner(rootDecl) as CompositeActivityDesigner;
ActivityDesigner activityDesigner = host.GetDesigner(activity) as ActivityDesigner;
if (compositeDesigner != null && activityDesigner != null)
compositeDesigner.EnsureVisibleContainedDesigner(activityDesigner);
/*
//
*/
}
}
ISelectionService selectionService = host.GetService(typeof(ISelectionService)) as ISelectionService;
if (selectionService != null)
selectionService.SetSelectedComponents(new IComponent[] { rootDecl });
ReadonlyWorkflow workflowView = (Controls.Count > 0) ? Controls[0] as ReadonlyWorkflow : null;
if (workflowView != null)
workflowView.PerformLayout();
previewActivity = (rootDecl.Activities.Count > 0 && !dummyPreview) ? rootDecl.Activities[0] : rootDecl;
}
catch
{
}
return (previewActivity != null) ? host.GetDesigner(previewActivity) : null;
}
private void AddDummyActivity(CompositeActivity parentActivity, Type activityType)
{
IDesignerHost host = this.surface.GetService(typeof(IDesignerHost)) as IDesignerHost;
Debug.Assert(host != null);
if (host == null)
return;
Activity dummyActivity = Activator.CreateInstance(activityType) as Activity;
Debug.Assert(dummyActivity != null);
if (dummyActivity == null)
return;
parentActivity.Activities.Add(dummyActivity);
EnsureUniqueId(dummyActivity);
WorkflowDesignerLoader.AddActivityToDesigner(this.surface, dummyActivity);
}
private void EnsureUniqueId(Activity addedActivity)
{
Dictionary<string, int> identifiers = new Dictionary<string, int>();
Queue<Activity> Activities = new Queue<Activity>();
Activities.Enqueue(addedActivity);
while (Activities.Count > 0)
{
Activity Activity = Activities.Dequeue();
string fullTypeName = Activity.GetType().FullName;
int id = (identifiers.ContainsKey(fullTypeName)) ? identifiers[fullTypeName] : 1;
Activity.Name = Activity.GetType().Name + id.ToString(CultureInfo.InvariantCulture);
id += 1;
if (identifiers.ContainsKey(fullTypeName))
identifiers[fullTypeName] = id;
else
identifiers.Add(fullTypeName, id);
CompositeActivity compositeActivity = Activity as CompositeActivity;
if (compositeActivity != null)
{
foreach (Activity activity in compositeActivity.Activities)
Activities.Enqueue(activity);
}
}
}
#region Class PreviewDesignSurface
private sealed class PreviewDesignSurface : DesignSurface
{
internal PreviewDesignSurface(IServiceProvider parentProvider)
: base(new PreviewDesignerServiceProvider(parentProvider))
{
ITypeProvider typeProvider = GetService(typeof(ITypeProvider)) as ITypeProvider;
if (typeProvider == null)
{
TypeProvider provider = new TypeProvider(this);
provider.AddAssemblyReference(typeof(string).Assembly.Location);
ServiceContainer.AddService(typeof(ITypeProvider), provider, true);
}
}
protected override IDesigner CreateDesigner(IComponent component, bool rootDesigner)
{
IDesigner designer = base.CreateDesigner(component, rootDesigner);
Activity activity = component as Activity;
if (designer == null && !rootDesigner && activity != null)
designer = ActivityDesigner.CreateDesigner(activity.Site, activity);
return designer;
}
#region Class PreviewDesignerServiceProvider
private sealed class PreviewDesignerServiceProvider : IServiceProvider
{
private IServiceProvider serviceProvider;
internal PreviewDesignerServiceProvider(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
#region IServiceProvider Members
object IServiceProvider.GetService(Type serviceType)
{
if (serviceType == typeof(IPropertyValueUIService))
return null;
return this.serviceProvider.GetService(serviceType);
}
#endregion
}
#endregion
}
#endregion
#region Class PreviewWorkflowDesignerLoader
private class PreviewWorkflowDesignerLoader : WorkflowDesignerLoader
{
public override TextReader GetFileReader(string filePath)
{
return null;
}
public override TextWriter GetFileWriter(string filePath)
{
return null;
}
public override string FileName
{
get
{
return String.Empty;
}
}
}
#endregion
#region Class ReadOnly Workflow
private class ReadonlyWorkflow : WorkflowView
{
private ThemeConfigurationDialog themeConfigDialog = null;
internal ReadonlyWorkflow(ThemeConfigurationDialog themeConfigDialog, IServiceProvider serviceProvider)
: base(serviceProvider)
{
this.themeConfigDialog = themeConfigDialog;
this.themeConfigDialog.propertiesGrid.PropertyValueChanged += new PropertyValueChangedEventHandler(OnThemePropertyChanged);
this.EnableFitToScreen = false;
AddDesignerMessageFilter(new ReadonlyMessageFilter());
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (this.themeConfigDialog != null && this.themeConfigDialog.propertiesGrid != null)
this.themeConfigDialog.propertiesGrid.PropertyValueChanged -= new PropertyValueChangedEventHandler(OnThemePropertyChanged);
}
protected override void OnPaint(PaintEventArgs e)
{
if (this.themeConfigDialog == null)
{
base.OnPaint(e);
return;
}
using (BufferedTheme bufferedTheme = new BufferedTheme(this.themeConfigDialog.bufferedTheme))
base.OnPaint(e);
}
protected override void OnLayout(LayoutEventArgs levent)
{
if (this.themeConfigDialog != null)
{
using (BufferedTheme bufferedTheme = new BufferedTheme(this.themeConfigDialog.bufferedTheme))
base.OnLayout(levent);
Size maxExtent = ActiveLayout.Extent;
Size size = Size;
PointF zoom = new PointF((float)size.Width / (float)maxExtent.Width, (float)size.Height / (float)maxExtent.Height);
Zoom = Convert.ToInt32((Math.Min(zoom.X, zoom.Y) * 100));
}
}
private void OnThemePropertyChanged(object sender, PropertyValueChangedEventArgs e)
{
if (this.themeConfigDialog != null)
{
using (BufferedTheme bufferedTheme = new BufferedTheme(this.themeConfigDialog.bufferedTheme))
base.OnThemeChange(WorkflowTheme.CurrentTheme, EventArgs.Empty);
}
}
#region Class BufferedTheme
private sealed class BufferedTheme : IDisposable
{
private WorkflowTheme oldTheme = null;
internal BufferedTheme(WorkflowTheme themeToApply)
{
if (themeToApply != null && WorkflowTheme.CurrentTheme != themeToApply)
{
WorkflowTheme.EnableChangeNotification = false;
this.oldTheme = WorkflowTheme.CurrentTheme;
WorkflowTheme.CurrentTheme = themeToApply;
}
}
void IDisposable.Dispose()
{
if (this.oldTheme != null && WorkflowTheme.CurrentTheme != this.oldTheme)
{
WorkflowTheme.CurrentTheme.ReadOnly = false; //this was themeToApply passed into constructor, need to make it r/w again
WorkflowTheme.CurrentTheme = this.oldTheme;
WorkflowTheme.EnableChangeNotification = true;
}
}
}
#endregion
}
#endregion
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void OrInt16()
{
var test = new SimpleBinaryOpTest__OrInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__OrInt16
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int Op2ElementCount = VectorSize / sizeof(Int16);
private const int RetElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable;
static SimpleBinaryOpTest__OrInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__OrInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.Or(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.Or(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.Or(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Avx2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__OrInt16();
var result = Avx2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
if ((short)(left[0] | right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(left[i] | right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Or)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Splitter.Panels
{
public partial class MasterPanelContainer : UIViewController
{
public MenuPanelContainer MenuContainer { get; set; }
public SubMenuPanelContainer SubMenuContainer { get; set; }
public DetailPanelContainer DetailContainer { get; set; }
#region Panel Sizing
public RectangleF CreateMenuFrame()
{
return new RectangleF
{
X = View.Frame.X,
Y = View.Frame.Y,
Width = MenuContainer.Width,
Height = View.Frame.Height
};
}
public float SubMenuX()
{
return MenuContainer != null ? MenuContainer.View.Frame.X + MenuContainer.View.Frame.Width : 0;
}
public RectangleF CreateSubMenuFrame()
{
return new RectangleF
{
X = SubMenuX(),
Y = View.Frame.Y,
Width = SubMenuContainer.IsVisible ? SubMenuContainer.Width : 0,
Height = View.Frame.Height
};
}
public RectangleF CreateDetailFrame()
{
var frame = UIScreen.MainScreen.ApplicationFrame;
var bound = UIScreen.MainScreen.Bounds;
var x = SubMenuContainer != null && SubMenuContainer.IsVisible ? SubMenuContainer.View.Frame.X + SubMenuContainer.View.Frame.Width : MenuContainer != null ? MenuContainer.View.Frame.X + MenuContainer.View.Frame.Width : 0;
return new RectangleF
{
X = x,
Y = View.Frame.Y,
Width = View.Frame.Width - x,
Height = View.Frame.Height
};
}
#endregion
#region Construction/Destruction
/// <summary>
/// Initializes a new instance of the <see cref="SplitPanelView"/> class.
/// </summary>
public MasterPanelContainer(float menuMaxWidth, float subMenuMaxWidth)
{
MenuContainer = new MenuPanelContainer(this, new EmptyView(UIColor.Yellow), menuMaxWidth);
SubMenuContainer = new SubMenuPanelContainer(this, new EmptyView(UIColor.Brown), subMenuMaxWidth);
SubMenuContainer.IsVisible = false;
DetailContainer = new DetailPanelContainer(this, new EmptyView(UIColor.Magenta), menuMaxWidth + subMenuMaxWidth);
}
/// <summary>
/// Initializes a new instance of the <see cref="SplitPanelView"/> class.
/// </summary>
/// <param name="menu">Menu</param>
/// <param name="detail">Detail page</param>
public MasterPanelContainer(float menuMaxWidth, float subMenuMaxWidth, MenuPanelContainer menu, SubMenuPanelContainer subMenu, DetailPanelContainer detail)
{
MenuContainer = menu;
SubMenuContainer = subMenu;
//SubMenuContainer.IsVisible = false;
DetailContainer = detail;
}
#endregion
#region Panel Sizing
private RectangleF CreateViewPosition()
{
var orient = UIApplication.SharedApplication.StatusBarOrientation;
switch (orient)
{
case UIInterfaceOrientation.LandscapeLeft:
case UIInterfaceOrientation.LandscapeRight:
return HorizontalViewPosition();
default:
return VerticalViewPosition();
}
}
private RectangleF VerticalViewPosition()
{
var bounds = UIScreen.MainScreen.Bounds;
var navHeight = NavigationController.NavigationBarHidden ? 0 : NavigationController.NavigationBar.Frame.Height;
var pointX = UIScreen.MainScreen.ApplicationFrame.X;
var pointY = navHeight - 12;//UIScreen.MainScreen.ApplicationFrame.Y * 2;// + navHeight + UIApplication.SharedApplication.StatusBarFrame.Height;
var width = UIScreen.MainScreen.ApplicationFrame.Width;
var height = UIScreen.MainScreen.ApplicationFrame.Height - navHeight;// - UIApplication.SharedApplication.StatusBarFrame.Height;
return new RectangleF(new PointF(pointX, pointY), new SizeF(width, height));
}
private RectangleF HorizontalViewPosition()
{
var bounds = UIScreen.MainScreen.Bounds;
var navHeight = NavigationController.NavigationBarHidden ? 0 : NavigationController.NavigationBar.Frame.Height;
var pointX = UIScreen.MainScreen.ApplicationFrame.Y;
var pointY = navHeight - 12;// - UIScreen.MainScreen.ApplicationFrame.X;// + navHeight;// + UIApplication.SharedApplication.StatusBarFrame.Width;
var width = UIScreen.MainScreen.ApplicationFrame.Width + UIScreen.MainScreen.ApplicationFrame.X;
var height = UIScreen.MainScreen.ApplicationFrame.Height - navHeight - UIApplication.SharedApplication.StatusBarFrame.Width;
return new RectangleF(new PointF(pointX, pointY), new SizeF(width, height));
}
#endregion
#region ViewLifecycle
public override void ViewDidLoad()
{
base.ViewDidLoad();
View.Frame = UIScreen.MainScreen.ApplicationFrame;
if (SubMenuContainer != null)
{
AddChildViewController(SubMenuContainer);
View.AddSubview(SubMenuContainer.View);
}
if (MenuContainer != null)
{
AddChildViewController(MenuContainer);
View.AddSubview(MenuContainer.View);
}
if (DetailContainer != null)
{
AddChildViewController(DetailContainer);
View.AddSubview(DetailContainer.View);
}
}
/// <summary>
/// Called every time the Panel is about to be shown
/// </summary>
/// <param name="animated">If set to <c>true</c> animated.</param>
public override void ViewWillAppear(bool animated)
{
View.Frame = CreateViewPosition();
if (MenuContainer != null)
MenuContainer.ViewWillAppear(animated);
if (SubMenuContainer != null)
SubMenuContainer.ViewWillAppear(animated);
if (DetailContainer != null)
DetailContainer.ViewWillAppear(animated);
base.ViewWillAppear(animated);
}
/// <summary>
/// Called every time after the Panel is shown
/// </summary>
/// <param name="animated">If set to <c>true</c> animated.</param>
public override void ViewDidAppear(bool animated)
{
if (MenuContainer != null)
MenuContainer.ViewDidAppear(animated);
if (SubMenuContainer != null)
SubMenuContainer.ViewWillAppear(animated);
if (DetailContainer != null)
DetailContainer.ViewWillAppear(animated);
base.ViewDidAppear(animated);
}
/// <summary>
/// Called whenever the Panel is about to be hidden
/// </summary>
/// <param name="animated">If set to <c>true</c> animated.</param>
public override void ViewWillDisappear(bool animated)
{
if (MenuContainer != null)
MenuContainer.ViewWillDisappear(animated);
if (SubMenuContainer != null)
SubMenuContainer.ViewWillAppear(animated);
if (DetailContainer != null)
DetailContainer.ViewWillAppear(animated);
base.ViewWillDisappear(animated);
}
/// <summary>
/// Called every time after the Panel is hidden
/// </summary>
/// <param name="animated">If set to <c>true</c> animated.</param>
public override void ViewDidDisappear(bool animated)
{
if (MenuContainer != null)
MenuContainer.ViewDidDisappear(animated);
if (SubMenuContainer != null)
SubMenuContainer.ViewWillAppear(animated);
if (DetailContainer != null)
DetailContainer.ViewWillAppear(animated);
base.ViewDidDisappear(animated);
}
#endregion
#region overrides to pass to container
/// <summary>
/// Called when the view will rotate.
/// This override forwards the WillRotate callback on to each of the panel containers
/// </summary>
/// <param name="toInterfaceOrientation">To interface orientation.</param>
/// <param name="duration">Duration.</param>
public override void WillRotate(UIInterfaceOrientation toInterfaceOrientation, double duration)
{
base.WillRotate(toInterfaceOrientation, duration);
if (MenuContainer != null)
MenuContainer.WillRotate(toInterfaceOrientation, duration);
if (SubMenuContainer != null)
SubMenuContainer.WillRotate(toInterfaceOrientation, duration);
if (DetailContainer != null)
DetailContainer.WillRotate(toInterfaceOrientation, duration);
}
/// <summary>
/// Called after the view rotated
/// This override forwards the DidRotate callback on to each of the panel containers
/// </summary>
/// <param name="fromInterfaceOrientation">From interface orientation.</param>
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate(fromInterfaceOrientation);
if (MenuContainer != null)
MenuContainer.DidRotate(fromInterfaceOrientation);
if (SubMenuContainer != null)
SubMenuContainer.DidRotate(fromInterfaceOrientation);
if (DetailContainer != null)
DetailContainer.DidRotate(fromInterfaceOrientation);
}
#endregion
#region Panel stuff
/// <summary>
/// Get the corresponding panel
/// </summary>
/// <param name="type">Type.</param>
private PanelContainer GetPanel(PanelType type)
{
switch (type)
{
case PanelType.MenuPanel:
return MenuContainer;
case PanelType.SubMenuPanel:
return SubMenuContainer;
case PanelType.DetailPanel:
return DetailContainer;
default:
return null;
}
}
public void ChangePanelContents(UIViewController newChildView, PanelType type)
{
var activePanel = GetPanel(type);
if (activePanel != null)
activePanel.SwapChildView(newChildView, type);
else
DisplayNewChildView(newChildView, type);
}
protected void DisplayNewChildView(UIViewController newChildView, PanelType type)
{
PanelContainer newPanel = null;
switch (type)
{
case PanelType.MenuPanel:
newPanel = new MenuPanelContainer(this, newChildView, 150);
break;
case PanelType.SubMenuPanel:
newPanel = new SubMenuPanelContainer(this, newChildView, 200);
break;
case PanelType.DetailPanel:
newPanel = new DetailPanelContainer(this, newChildView, 350);
break;
}
if (newPanel == null)
return;
AddChildViewController(newPanel);
View.AddSubview(newPanel.View);
newPanel.DidMoveToParentViewController(null);
}
public void ShowSubMenu()
{
SubMenuContainer.IsVisible = true;
UIView.Animate(0.3f, () =>
{
SubMenuContainer.View.Frame = CreateSubMenuFrame();
DetailContainer.View.Frame = CreateDetailFrame();
}, () =>
{
});
}
public void HideMenu()
{
SubMenuContainer.IsVisible = false;
UIView.Animate(0.3f, () =>
{
SubMenuContainer.View.Frame = CreateSubMenuFrame();
DetailContainer.View.Frame = CreateDetailFrame();
}, () =>
{
});
}
#endregion
}
}
| |
//! \file ArcDAT.cs
//! \date Thu Jun 16 13:48:04 2016
//! \brief Tinker Bell resource archive.
//
// Copyright (C) 2016-2017 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using GameRes.Compression;
using GameRes.Formats.Strings;
using GameRes.Utility;
namespace GameRes.Formats.Cyberworks
{
internal class BellArchive : ArcFile
{
public readonly AImageScheme Scheme;
public BellArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, AImageScheme scheme)
: base (arc, impl, dir)
{
Scheme = scheme;
}
}
internal abstract class ArchiveNameParser
{
readonly Regex m_regex;
protected ArchiveNameParser (string pattern)
{
m_regex = new Regex (pattern, RegexOptions.IgnoreCase);
}
/// <summary>
/// Returns toc filename and archive index corresponding to <paramref name="arc_name"/>.
/// </summary>
public Tuple<string, int> ParseName (string arc_name)
{
var match = m_regex.Match (arc_name);
if (!match.Success)
return null;
int arc_idx;
var toc_name = ParseMatch (match, out arc_idx);
if (null == toc_name)
return null;
return Tuple.Create (toc_name, arc_idx);
}
protected abstract string ParseMatch (Match match, out int arc_idx);
}
internal class ArcNameParser : ArchiveNameParser
{
public ArcNameParser () : base (@"^.+0?(?<id>(?<num>\d)(?<idx>[a-z])?)(?:|\..*)$") { }
protected override string ParseMatch (Match match, out int arc_idx)
{
arc_idx = 0;
char num = match.Groups["num"].Value[0];
int index_num;
if (num >= '4' && num <= '6')
index_num = num - '3';
else if ('8' == num)
index_num = 7;
else
return null;
if (match.Groups["idx"].Success)
arc_idx = char.ToUpper (match.Groups["idx"].Value[0]) - '@';
var toc_name_builder = new StringBuilder (match.Value);
var num_pos = match.Groups["id"].Index;
toc_name_builder.Remove (num_pos, match.Groups["id"].Length);
toc_name_builder.Insert (num_pos, index_num);
return toc_name_builder.ToString();
}
}
internal class DatNameParser : ArchiveNameParser
{
public DatNameParser () : base (@"^(?<name>d[a-z]+?)(?<idx>[ah])?\.dat$") { }
protected override string ParseMatch (Match match, out int arc_idx)
{
var toc_name_builder = new StringBuilder (match.Groups["name"].Value);
arc_idx = 0;
if (match.Groups["idx"].Success)
{
if ('a' == match.Groups["idx"].Value[0])
{
arc_idx = 1;
toc_name_builder.Append ('h');
}
}
else
toc_name_builder.Append ('h');
toc_name_builder.Append (".dat");
return toc_name_builder.ToString();
}
}
internal class OldArcNameParser : ArchiveNameParser
{
public OldArcNameParser () : base (@"^Arc0(?<num>\d)\..*$") { }
// matches archive body to its index
static readonly IDictionary<char, int> s_arcmap = new Dictionary<char, int> {
{ '2', 0 }, { '3', 1 }, { '5', 4 }
};
protected override string ParseMatch (Match match, out int arc_idx)
{
arc_idx = 0;
char num = match.Groups["num"].Value[0];
int index_num;
if (!s_arcmap.TryGetValue (num, out index_num))
return null;
var toc_name_builder = new StringBuilder (match.Value);
var num_pos = match.Groups["num"].Index;
toc_name_builder.Remove (num_pos, match.Groups["num"].Length);
toc_name_builder.Insert (num_pos, index_num);
return toc_name_builder.ToString();
}
}
internal class PatchNameParser : ArchiveNameParser
{
public PatchNameParser () : base (@"^patch0(?<num>[2468])\.dat$") { }
protected override string ParseMatch (Match match, out int arc_idx)
{
arc_idx = 0;
int index_num = match.Groups["num"].Value[0] - '0' - 1;
var toc_name_builder = new StringBuilder (match.Value);
var num_pos = match.Groups["num"].Index;
toc_name_builder.Remove (num_pos, match.Groups["num"].Length);
toc_name_builder.Insert (num_pos, index_num);
return toc_name_builder.ToString();
}
}
internal class InKyouParser : ArchiveNameParser
{
public InKyouParser () : base (@"^(inyoukyou_kuon|mugen.*)\.app$") { }
protected override string ParseMatch (Match match, out int arc_idx)
{
arc_idx = 0;
return match.Groups[1].Value + ".dat";
}
}
[Export(typeof(ArchiveFormat))]
public class DatOpener : ArchiveFormat
{
public override string Tag { get { return "ARC/Cyberworks"; } }
public override string Description { get { return "Cyberworks/TinkerBell resource archive"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public DatOpener ()
{
Extensions = new string[] { "dat", "04", "05", "06", "app" };
}
public bool BlendOverlayImages = true;
static readonly ArchiveNameParser[] s_name_parsers = {
new ArcNameParser(),
new DatNameParser(),
new PatchNameParser(),
new InKyouParser()
};
public override ArcFile TryOpen (ArcView file)
{
var arc_name = Path.GetFileName (file.Name);
var dir_name = VFS.GetDirectoryName (file.Name);
string game_name = arc_name != "Arc06.dat" ? TryParseMeta (VFS.CombinePath (dir_name, "Arc06.dat")) : null;
Tuple<string, int> parsed = null;
if (string.IsNullOrEmpty (game_name))
parsed = s_name_parsers.Select (p => p.ParseName (arc_name)).FirstOrDefault (p => p != null);
else // Shukujo no Tsuyagoto special case
parsed = OldDatOpener.ArcNameParser.ParseName (arc_name);
if (null == parsed)
return null;
string toc_name = parsed.Item1;
int arc_idx = parsed.Item2;
toc_name = VFS.CombinePath (dir_name, toc_name);
var toc = ReadToc (toc_name, 8);
if (null == toc)
return null;
using (var index = new ArcIndexReader (toc, file, arc_idx))
{
if (!index.Read())
return null;
return ArchiveFromDir (file, index.Dir, index.HasImages);
}
}
internal ArcFile ArchiveFromDir (ArcView file, List<Entry> dir, bool has_images)
{
if (0 == dir.Count)
return null;
if (!has_images)
return new ArcFile (file, this, dir);
var scheme = QueryScheme (file.Name);
return new BellArchive (file, this, dir, scheme);
}
/// <summary>
// Try to parse file containing game meta-information.
/// </summary>
internal string TryParseMeta (string meta_arc_name)
{
if (!VFS.FileExists (meta_arc_name))
return null;
using (var unpacker = new TocUnpacker (meta_arc_name))
{
if (unpacker.Length > 0x1000)
return null;
var data = unpacker.Unpack (8);
if (null == data)
return null;
using (var content = new BinMemoryStream (data))
{
int title_length = content.ReadInt32();
if (title_length <= 0 || title_length > content.Length)
return null;
var title = content.ReadBytes (title_length);
if (title.Length != title_length)
return null;
return Encodings.cp932.GetString (title);
}
}
}
internal byte[] ReadToc (string toc_name, int num_length)
{
if (!VFS.FileExists (toc_name))
return null;
using (var toc_unpacker = new TocUnpacker (toc_name))
return toc_unpacker.Unpack (num_length);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
Stream input = arc.File.CreateStream (entry.Offset, entry.Size);
var pent = entry as PackedEntry;
if (null != pent && pent.IsPacked)
{
input = new LzssStream (input);
}
return input;
}
public override IImageDecoder OpenImage (ArcFile arc, Entry entry)
{
var barc = arc as BellArchive;
if (null == barc || entry.Size < 5)
return base.OpenImage (arc, entry);
var input = arc.OpenBinaryEntry (entry);
try
{
var reader = DecryptImage (input, barc.Scheme);
if (BlendOverlayImages)
{
var overlay = reader as AImageReader;
if (overlay != null)
overlay.ReadBaseline (barc, entry);
}
return reader;
}
catch
{
input.Dispose();
throw;
}
}
protected virtual IImageDecoder DecryptImage (IBinaryStream input, AImageScheme scheme)
{
int type = input.ReadByte();
if ('c' == type || 'b' == type)
{
uint img_size = Binary.BigEndian (input.ReadUInt32());
if (input.Length - 5 == img_size)
{
input = BinaryStream.FromStream (new StreamRegion (input.AsStream, 5, img_size), input.Name);
}
}
else if (scheme != null && ('a' == type || 'd' == type) && input.Length > 21)
{
int id = input.ReadByte();
if (id == scheme.Value2)
{
return new AImageReader (input, scheme, type);
}
}
input.Position = 0;
return new ImageFormatDecoder (input);
}
internal AImageScheme QueryScheme (string arc_name)
{
var title = FormatCatalog.Instance.LookupGame (arc_name);
if (!string.IsNullOrEmpty (title) && KnownSchemes.ContainsKey (title))
return KnownSchemes[title];
var options = Query<BellOptions> (arcStrings.ArcEncryptedNotice);
return options.Scheme;
}
public override ResourceOptions GetDefaultOptions ()
{
return new BellOptions { Scheme = GetScheme (Properties.Settings.Default.BELLTitle) };
}
public override object GetAccessWidget ()
{
return new GUI.WidgetBELL();
}
public static AImageScheme GetScheme (string title)
{
AImageScheme scheme = null;
if (string.IsNullOrEmpty (title) || !KnownSchemes.TryGetValue (title, out scheme))
return null;
return scheme;
}
static SchemeMap DefaultScheme = new SchemeMap {
KnownSchemes = new Dictionary<string, AImageScheme>()
};
public static Dictionary<string, AImageScheme> KnownSchemes { get { return DefaultScheme.KnownSchemes; } }
public override ResourceScheme Scheme
{
get { return DefaultScheme; }
set { DefaultScheme = (SchemeMap)value; }
}
}
[Serializable]
public class AImageScheme
{
public byte Value1;
public byte Value2;
public byte Value3;
public byte[] HeaderOrder;
public bool Flipped;
public AImageScheme ()
{
Flipped = true;
}
}
[Serializable]
public class SchemeMap : ResourceScheme
{
public Dictionary<string, AImageScheme> KnownSchemes;
}
public class BellOptions : ResourceOptions
{
public AImageScheme Scheme;
}
[Export(typeof(ArchiveFormat))]
public class OldDatOpener : DatOpener
{
public override string Tag { get { return "ARC/Csystem"; } }
public override string Description { get { return "TinkerBell resource archive"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public OldDatOpener ()
{
Extensions = new string[] { "dat" };
}
internal static readonly ArchiveNameParser ArcNameParser = new OldArcNameParser();
public override ArcFile TryOpen (ArcView file)
{
var arc_name = Path.GetFileName (file.Name);
var parsed = ArcNameParser.ParseName (arc_name);
if (null == parsed)
return null;
var toc_name = VFS.CombinePath (VFS.GetDirectoryName (file.Name), parsed.Item1);
var toc = ReadToc (toc_name, 4);
if (null == toc)
return null;
bool has_images = false;
var dir = new List<Entry>();
using (var toc_stream = new MemoryStream (toc))
using (var index = new StreamReader (toc_stream))
{
string line;
while ((line = index.ReadLine()) != null)
{
var fields = line.Split (',');
if (fields.Length != 5)
return null;
var name = Path.ChangeExtension (fields[0], fields[4]);
string type = "";
if ("b" == fields[4])
{
type = "image";
has_images = true;
}
else if ("k" == fields[4] || "j" == fields[4])
type = "audio";
var entry = new PackedEntry
{
Name = name,
Type = type,
Offset = UInt32.Parse (fields[3]),
Size = UInt32.Parse (fields[2]),
UnpackedSize = UInt32.Parse (fields[1]),
};
if (!entry.CheckPlacement (file.MaxOffset))
return null;
entry.IsPacked = entry.UnpackedSize != entry.Size;
dir.Add (entry);
}
}
return ArchiveFromDir (file, dir, has_images);
}
protected override IImageDecoder DecryptImage (IBinaryStream input, AImageScheme scheme)
{
int id = input.ReadByte();
if (id == scheme.Value2)
return new AImageReader (input, scheme);
input.Position = 0;
return new ImageFormatDecoder (input);
}
}
[Export(typeof(ArchiveFormat))]
public class OldDatOpener2 : DatOpener
{
public override string Tag { get { return "ARC/Csystem/2"; } }
public override string Description { get { return "TinkerBell resource archive"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public OldDatOpener2 ()
{
Extensions = new string[] { "dat" };
}
public override ArcFile TryOpen (ArcView file)
{
var arc_name = Path.GetFileName (file.Name);
var parsed = OldDatOpener.ArcNameParser.ParseName (arc_name);
if (null == parsed)
return null;
var toc_name = VFS.CombinePath (VFS.GetDirectoryName (file.Name), parsed.Item1);
var toc = ReadToc (toc_name, 4);
if (null == toc)
return null;
using (var index = new DatIndexReader (toc, file))
{
if (!index.Read())
return null;
return ArchiveFromDir (file, index.Dir, index.HasImages);
}
}
}
internal sealed class TocUnpacker : IDisposable
{
ArcView m_file;
bool m_should_dispose;
public long Length { get { return m_file.MaxOffset; } }
public uint PackedSize { get; private set; }
public uint UnpackedSize { get; private set; }
public TocUnpacker (string toc_name) : this (VFS.OpenView (toc_name), true)
{
}
public TocUnpacker (ArcView file, bool should_dispose = false)
{
m_file = file;
m_should_dispose = should_dispose;
}
public byte[] Unpack (int num_length)
{
return Unpack (0, num_length);
}
public byte[] Unpack (long offset, int num_length)
{
long data_offset = offset + num_length*2;
if (m_file.MaxOffset <= data_offset)
return null;
UnpackedSize = DecodeDecimal (offset, num_length);
if (UnpackedSize <= 4 || UnpackedSize > 0x1000000)
return null;
PackedSize = DecodeDecimal (offset+num_length, num_length);
if (PackedSize > m_file.MaxOffset - data_offset || 0 == PackedSize)
return null;
return UnpackAt (data_offset);
}
byte[] UnpackAt (long offset)
{
using (var toc_s = m_file.CreateStream (offset, PackedSize))
using (var lzss = new LzssStream (toc_s))
{
var toc = new byte[UnpackedSize];
if (toc.Length != lzss.Read (toc, 0, toc.Length))
return null;
return toc;
}
}
internal uint DecodeDecimal (long offset, int num_length)
{
uint v = 0;
uint rank = 1;
for (int i = num_length-1; i >= 0; --i, rank *= 10)
{
uint b = m_file.View.ReadByte (offset+i);
if (b != 0xFF)
v += (b ^ 0x7F) * rank;
}
return v;
}
bool _disposed = false;
public void Dispose ()
{
if (m_should_dispose && !_disposed)
{
m_file.Dispose();
_disposed = true;
}
}
}
internal abstract class IndexReader : IDisposable
{
protected IBinaryStream m_index;
readonly long m_max_offset;
private List<Entry> m_dir;
public List<Entry> Dir { get { return m_dir; } }
public long MaxOffset { get { return m_max_offset; } }
public bool HasImages { get; protected set; }
public IndexReader (byte[] toc, ArcView file)
{
m_index = new BinMemoryStream (toc);
m_max_offset = file.MaxOffset;
}
public bool Read ()
{
int entry_size = m_index.ReadInt32();
if (entry_size < 0x11)
return false;
int count = (int)m_index.Length / (entry_size + 4);
if (!ArchiveFormat.IsSaneCount (count))
return false;
long next_pos = 0;
m_dir = new List<Entry> (count);
while (next_pos < m_index.Length)
{
m_index.Position = next_pos;
entry_size = m_index.ReadInt32();
if (entry_size <= 0)
return false;
next_pos += 4 + entry_size;
var entry = ReadEntryInfo();
if (ReadEntryType (entry, entry_size))
{
if (entry.CheckPlacement (MaxOffset))
m_dir.Add (entry);
}
}
return true;
}
internal PackedEntry ReadEntryInfo ()
{
uint id = m_index.ReadUInt32();
var entry = new PackedEntry { Name = id.ToString ("D6") };
entry.UnpackedSize = m_index.ReadUInt32();
entry.Size = m_index.ReadUInt32();
entry.IsPacked = entry.UnpackedSize != entry.Size;
entry.Offset = m_index.ReadUInt32();
return entry;
}
protected abstract bool ReadEntryType (Entry entry, int entry_size);
public void Dispose ()
{
Dispose (true);
}
bool _disposed = false;
protected virtual void Dispose (bool disposing)
{
if (disposing && !_disposed)
{
m_index.Dispose();
_disposed = true;
}
}
}
internal class ArcIndexReader : IndexReader
{
int m_arc_number;
public ArcIndexReader (byte[] toc, ArcView file, int arc_number) : base (toc, file)
{
m_arc_number = arc_number;
}
char[] m_type = new char[2];
protected override bool ReadEntryType (Entry entry, int entry_size)
{
m_type[0] = (char)m_index.ReadByte();
m_type[1] = (char)m_index.ReadByte();
int entry_idx = 0;
if (entry_size >= 0x17)
{
m_index.ReadInt32();
entry_idx = m_index.ReadByte();
}
if (entry_idx != m_arc_number)
return false;
if (m_type[0] > 0x20 && m_type[0] < 0x7F)
{
string ext;
if (m_type[1] > 0x20 && m_type[1] < 0x7F)
ext = new string (m_type);
else
ext = new string (m_type[0], 1);
if ("b0" == ext || "n0" == ext || "o0" == ext || "0b" == ext || "b" == ext)
{
entry.Type = "image";
HasImages = true;
}
else if ("j0" == ext || "k0" == ext || "u0" == ext || "j" == ext || "k" == ext)
entry.Type = "audio";
entry.Name = Path.ChangeExtension (entry.Name, ext);
}
return true;
}
}
internal class DatIndexReader : IndexReader
{
public DatIndexReader (byte[] toc, ArcView file) : base (toc, file)
{
}
protected override bool ReadEntryType (Entry entry, int entry_size)
{
if (entry_size > 0x11)
throw new InvalidFormatException();
char type = (char)m_index.ReadByte();
if (type > 0x20 && type < 0x7F)
{
string ext = new string (type, 1);
if ('b' == type)
{
entry.Type = "image";
HasImages = true;
}
else if ('k' == type || 'j' == type)
entry.Type = "audio";
entry.Name = Path.ChangeExtension (entry.Name, ext);
}
return true;
}
}
}
| |
/*
Matali Physics Demo
Copyright (c) 2013 KOMIRES Sp. z o. o.
*/
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using Komires.MataliPhysics;
namespace MataliPhysicsDemo
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Ragdoll1
{
Demo demo;
PhysicsScene scene;
string instanceIndexName;
public Ragdoll1(Demo demo, int instanceIndex)
{
this.demo = demo;
instanceIndexName = " " + instanceIndex.ToString();
}
public void Initialize(PhysicsScene scene)
{
this.scene = scene;
}
public static void CreateShapes(Demo demo, PhysicsScene scene)
{
}
public void Create(Vector3 objectPosition, Vector3 objectScale, Quaternion objectOrientation, bool enableControl, bool enableControlWithDeformation, float minAngleDeformationVelocity)
{
Shape box = scene.Factory.ShapeManager.Find("Box");
PhysicsObject objectRoot = null;
PhysicsObject objectBase = null;
Vector3 position1 = Vector3.Zero;
Vector3 position2 = Vector3.Zero;
Quaternion orientation1 = Quaternion.Identity;
Quaternion orientation2 = Quaternion.Identity;
objectRoot = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1" + instanceIndexName);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Head" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.InitLocalTransform.SetPosition(0.0f, 42.7f, 20.0f);
objectBase.InitLocalTransform.SetScale(0.7f);
objectBase.Integral.SetDensity(1.64f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Upper Torso" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.CreateSound(true);
objectBase.Sound.HitVolume = 0.25f;
objectBase.Sound.RollVolume = 0.25f;
objectBase.Sound.SlideVolume = 0.25f;
objectBase.Sound.MinFirstImpactForce = 100.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 41.0f, 20.0f);
objectBase.Integral.SetDensity(1.44f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Lower Torso" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.CreateSound(true);
objectBase.Sound.HitVolume = 0.25f;
objectBase.Sound.RollVolume = 0.25f;
objectBase.Sound.SlideVolume = 0.25f;
objectBase.Sound.MinFirstImpactForce = 100.0f;
objectBase.InitLocalTransform.SetPosition(0.0f, 39.0f, 20.0f);
objectBase.Integral.SetDensity(1.84f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Right Upper Arm" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.InitLocalTransform.SetPosition(2.0f, 41.5f, 20.0f);
objectBase.InitLocalTransform.SetScale(1.0f, 0.5f, 0.5f);
objectBase.Integral.SetDensity(2.145f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Right Lower Arm" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.InitLocalTransform.SetPosition(4.0f, 41.5f, 20.0f);
objectBase.InitLocalTransform.SetScale(1.0f, 0.5f, 0.5f);
objectBase.Integral.SetDensity(2.145f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Right Hand" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.CreateSound(true);
objectBase.Sound.HitVolume = 0.25f;
objectBase.Sound.RollVolume = 0.25f;
objectBase.Sound.SlideVolume = 0.25f;
objectBase.Sound.MinFirstImpactForce = 100.0f;
objectBase.InitLocalTransform.SetPosition(5.5f, 41.5f, 20.0f);
objectBase.InitLocalTransform.SetScale(0.5f, 0.4f, 0.2f);
objectBase.Integral.SetDensity(2.145f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Left Upper Arm" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.InitLocalTransform.SetPosition(-2.0f, 41.5f, 20.0f);
objectBase.InitLocalTransform.SetScale(1.0f, 0.5f, 0.5f);
objectBase.Integral.SetDensity(2.145f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Left Lower Arm" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.InitLocalTransform.SetPosition(-4.0f, 41.5f, 20.0f);
objectBase.InitLocalTransform.SetScale(1.0f, 0.5f, 0.5f);
objectBase.Integral.SetDensity(2.145f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Left Hand" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.CreateSound(true);
objectBase.Sound.HitVolume = 0.25f;
objectBase.Sound.RollVolume = 0.25f;
objectBase.Sound.SlideVolume = 0.25f;
objectBase.Sound.MinFirstImpactForce = 100.0f;
objectBase.InitLocalTransform.SetPosition(-5.5f, 41.5f, 20.0f);
objectBase.InitLocalTransform.SetScale(0.5f, 0.4f, 0.2f);
objectBase.Integral.SetDensity(2.145f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Right Upper Leg" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.InitLocalTransform.SetPosition(0.6f, 36.75f, 20.0f);
objectBase.InitLocalTransform.SetScale(0.5f, 1.25f, 0.5f);
objectBase.Integral.SetDensity(2.145f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Right Lower Leg" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.InitLocalTransform.SetPosition(0.6f, 34.25f, 20.0f);
objectBase.InitLocalTransform.SetScale(0.5f, 1.25f, 0.5f);
objectBase.Integral.SetDensity(2.145f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Right Foot" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.CreateSound(true);
objectBase.Sound.HitVolume = 0.25f;
objectBase.Sound.RollVolume = 0.25f;
objectBase.Sound.SlideVolume = 0.25f;
objectBase.Sound.MinFirstImpactForce = 100.0f;
objectBase.InitLocalTransform.SetPosition(0.6f, 32.8f, 19.7f);
objectBase.InitLocalTransform.SetScale(0.4f, 0.2f, 0.8f);
objectBase.Integral.SetDensity(2.145f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Left Upper Leg" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.InitLocalTransform.SetPosition(-0.6f, 36.75f, 20.0f);
objectBase.InitLocalTransform.SetScale(0.5f, 1.25f, 0.5f);
objectBase.Integral.SetDensity(2.145f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Left Lower Leg" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.InitLocalTransform.SetPosition(-0.6f, 34.25f, 20.0f);
objectBase.InitLocalTransform.SetScale(0.5f, 1.25f, 0.5f);
objectBase.Integral.SetDensity(2.145f);
objectBase = scene.Factory.PhysicsObjectManager.Create("Ragdoll 1 Left Foot" + instanceIndexName);
objectRoot.AddChildPhysicsObject(objectBase);
objectBase.Shape = box;
objectBase.UserDataStr = "Box";
objectBase.CreateSound(true);
objectBase.Sound.HitVolume = 0.25f;
objectBase.Sound.RollVolume = 0.25f;
objectBase.Sound.SlideVolume = 0.25f;
objectBase.Sound.MinFirstImpactForce = 100.0f;
objectBase.InitLocalTransform.SetPosition(-0.6f, 32.8f, 19.7f);
objectBase.InitLocalTransform.SetScale(0.4f, 0.2f, 0.8f);
objectBase.Integral.SetDensity(2.145f);
objectRoot.UpdateFromInitLocalTransform();
Constraint constraint = null;
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 1" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Head" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Upper Torso" + instanceIndexName);
constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position1 - new Vector3(0.0f, 0.7f, 0.0f));
constraint.SetAnchor2(position1 - new Vector3(0.0f, 0.7f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleX = -20.0f;
constraint.MaxLimitDegAngleX = 20.0f;
constraint.MinLimitDegAngleY = -60.0f;
constraint.MaxLimitDegAngleY = 60.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 2" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Upper Torso" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Lower Torso" + instanceIndexName);
constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position1 - new Vector3(0.0f, 1.0f, 0.0f));
constraint.SetAnchor2(position1 - new Vector3(0.0f, 1.0f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleX = -10.0f;
constraint.MaxLimitDegAngleX = 45.0f;
constraint.MinLimitDegAngleZ = -10.0f;
constraint.MaxLimitDegAngleZ = 10.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 3" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Upper Torso" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Right Upper Arm" + instanceIndexName);
constraint.PhysicsObject2.MainWorldTransform.GetPosition(ref position2);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position2 - new Vector3(1.0f, 0.0f, 0.0f));
constraint.SetAnchor2(position2 - new Vector3(1.0f, 0.0f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleY = -20.0f;
constraint.MaxLimitDegAngleY = 90.0f;
constraint.MinLimitDegAngleZ = -90.0f;
constraint.MaxLimitDegAngleZ = 45.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 4" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Upper Torso" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Left Upper Arm" + instanceIndexName);
constraint.PhysicsObject2.MainWorldTransform.GetPosition(ref position2);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position2 + new Vector3(1.0f, 0.0f, 0.0f));
constraint.SetAnchor2(position2 + new Vector3(1.0f, 0.0f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleY = -90.0f;
constraint.MaxLimitDegAngleY = 20.0f;
constraint.MinLimitDegAngleZ = -45.0f;
constraint.MaxLimitDegAngleZ = 90.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 5" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Lower Torso" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Right Upper Leg" + instanceIndexName);
constraint.PhysicsObject2.MainWorldTransform.GetPosition(ref position2);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position2 + new Vector3(0.0f, 1.25f, 0.0f));
constraint.SetAnchor2(position2 + new Vector3(0.0f, 1.25f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleX = -10.0f;
constraint.MaxLimitDegAngleX = 100.0f;
constraint.MinLimitDegAngleY = -20.0f;
constraint.MaxLimitDegAngleY = 0.0f;
constraint.MinLimitDegAngleZ = -45.0f;
constraint.MaxLimitDegAngleZ = 45.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 6" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Lower Torso" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Left Upper Leg" + instanceIndexName);
constraint.PhysicsObject2.MainWorldTransform.GetPosition(ref position2);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position2 + new Vector3(0.0f, 1.25f, 0.0f));
constraint.SetAnchor2(position2 + new Vector3(0.0f, 1.25f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleX = -10.0f;
constraint.MaxLimitDegAngleX = 100.0f;
constraint.MinLimitDegAngleY = -20.0f;
constraint.MaxLimitDegAngleY = 0.0f;
constraint.MinLimitDegAngleZ = -45.0f;
constraint.MaxLimitDegAngleZ = 45.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 7" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Right Upper Arm" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Right Lower Arm" + instanceIndexName);
constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position1 + new Vector3(1.0f, 0.0f, 0.0f));
constraint.SetAnchor2(position1 + new Vector3(1.0f, 0.0f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleY = -2.0f;
constraint.MaxLimitDegAngleY = 135.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 8" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Right Lower Arm" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Right Hand" + instanceIndexName);
constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position1 + new Vector3(1.0f, 0.0f, 0.0f));
constraint.SetAnchor2(position1 + new Vector3(1.0f, 0.0f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleY = -20.0f;
constraint.MaxLimitDegAngleY = 60.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 9" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Left Upper Arm" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Left Lower Arm" + instanceIndexName);
constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position1 - new Vector3(1.0f, 0.0f, 0.0f));
constraint.SetAnchor2(position1 - new Vector3(1.0f, 0.0f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleY = -135.0f;
constraint.MaxLimitDegAngleY = 2.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 10" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Left Lower Arm" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Left Hand" + instanceIndexName);
constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position1 - new Vector3(1.0f, 0.0f, 0.0f));
constraint.SetAnchor2(position1 - new Vector3(1.0f, 0.0f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleY = -60.0f;
constraint.MaxLimitDegAngleY = 20.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 11" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Right Upper Leg" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Right Lower Leg" + instanceIndexName);
constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position1 - new Vector3(0.0f, 1.25f, 0.0f));
constraint.SetAnchor2(position1 - new Vector3(0.0f, 1.25f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleX = -135.0f;
constraint.MaxLimitDegAngleX = 2.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 12" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Right Lower Leg" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Right Foot" + instanceIndexName);
constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position1 - new Vector3(0.0f, 1.25f, 0.0f));
constraint.SetAnchor2(position1 - new Vector3(0.0f, 1.25f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleX = -45.0f;
constraint.MaxLimitDegAngleX = 2.0f;
constraint.MinLimitDegAngleZ = -10.0f;
constraint.MaxLimitDegAngleZ = 10.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 13" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Left Upper Leg" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Left Lower Leg" + instanceIndexName);
constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position1 - new Vector3(0.0f, 1.25f, 0.0f));
constraint.SetAnchor2(position1 - new Vector3(0.0f, 1.25f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleX = -135.0f;
constraint.MaxLimitDegAngleX = 2.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
constraint = scene.Factory.ConstraintManager.Create("Ragdoll 1 Constraint 14" + instanceIndexName);
constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Left Lower Leg" + instanceIndexName);
constraint.PhysicsObject2 = scene.Factory.PhysicsObjectManager.Find("Ragdoll 1 Left Foot" + instanceIndexName);
constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);
constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
constraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
constraint.SetAnchor1(position1 - new Vector3(0.0f, 1.25f, 0.0f));
constraint.SetAnchor2(position1 - new Vector3(0.0f, 1.25f, 0.0f));
constraint.SetInitWorldOrientation1(ref orientation1);
constraint.SetInitWorldOrientation2(ref orientation2);
constraint.EnableBreak = true;
constraint.MinBreakVelocity = 300.0f;
constraint.EnableLimitAngleX = true;
constraint.EnableLimitAngleY = true;
constraint.EnableLimitAngleZ = true;
constraint.MinLimitDegAngleX = -45.0f;
constraint.MaxLimitDegAngleX = 2.0f;
constraint.MinLimitDegAngleZ = -10.0f;
constraint.MaxLimitDegAngleZ = 10.0f;
constraint.LimitAngleMode = LimitAngleMode.EulerYZX;
if (enableControl)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
}
else
if (enableControlWithDeformation)
{
constraint.EnableControlAngleX = true;
constraint.EnableControlAngleY = true;
constraint.EnableControlAngleZ = true;
constraint.EnableControlAngleWithDeformation = true;
constraint.MinAngleDeformationVelocity = minAngleDeformationVelocity;
constraint.AngularDamping = 1.0f;
}
constraint.Update();
objectRoot.InitLocalTransform.SetOrientation(ref objectOrientation);
objectRoot.InitLocalTransform.SetScale(ref objectScale);
objectRoot.InitLocalTransform.SetPosition(ref objectPosition);
scene.UpdateFromInitLocalTransform(objectRoot);
}
}
}
| |
// 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: Convenient wrapper for an array, an offset, and
** a count. Ideally used in streams & collections.
** Net Classes will consume an array of these.
**
**
===========================================================*/
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace System
{
// Note: users should make sure they copy the fields out of an ArraySegment onto their stack
// then validate that the fields describe valid bounds within the array. This must be done
// because assignments to value types are not atomic, and also because one thread reading
// three fields from an ArraySegment may not see the same ArraySegment from one call to another
// (ie, users could assign a new value to the old location).
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly struct ArraySegment<T> : IList<T>, IReadOnlyList<T>
{
// Do not replace the array allocation with Array.Empty. We don't want to have the overhead of
// instantiating another generic type in addition to ArraySegment<T> for new type parameters.
public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]);
private readonly T[] _array; // Do not rename (binary serialization)
private readonly int _offset; // Do not rename (binary serialization)
private readonly int _count; // Do not rename (binary serialization)
public ArraySegment(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
_array = array;
_offset = 0;
_count = array.Length;
}
public ArraySegment(T[] array, int offset, int count)
{
// Validate arguments, check is minimal instructions with reduced branching for inlinable fast-path
// Negative values discovered though conversion to high values when converted to unsigned
// Failure should be rare and location determination and message is delegated to failure functions
if (array == null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset))
ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count);
_array = array;
_offset = offset;
_count = count;
}
public T[] Array => _array;
public int Offset => _offset;
public int Count => _count;
public T this[int index]
{
get
{
if ((uint)index >= (uint)_count)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
return _array[_offset + index];
}
set
{
if ((uint)index >= (uint)_count)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
_array[_offset + index] = value;
}
}
public Enumerator GetEnumerator()
{
ThrowInvalidOperationIfDefault();
return new Enumerator(this);
}
public override int GetHashCode()
{
if (_array == null)
{
return 0;
}
int hash = 5381;
hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset);
hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count);
// The array hash is expected to be an evenly-distributed mixture of bits,
// so rather than adding the cost of another rotation we just xor it.
hash ^= _array.GetHashCode();
return hash;
}
public void CopyTo(T[] destination) => CopyTo(destination, 0);
public void CopyTo(T[] destination, int destinationIndex)
{
ThrowInvalidOperationIfDefault();
System.Array.Copy(_array, _offset, destination, destinationIndex, _count);
}
public void CopyTo(ArraySegment<T> destination)
{
ThrowInvalidOperationIfDefault();
destination.ThrowInvalidOperationIfDefault();
if (_count > destination._count)
{
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
System.Array.Copy(_array, _offset, destination._array, destination._offset, _count);
}
public override bool Equals(object obj)
{
if (obj is ArraySegment<T>)
return Equals((ArraySegment<T>)obj);
else
return false;
}
public bool Equals(ArraySegment<T> obj)
{
return obj._array == _array && obj._offset == _offset && obj._count == _count;
}
public ArraySegment<T> Slice(int index)
{
ThrowInvalidOperationIfDefault();
if ((uint)index > (uint)_count)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
return new ArraySegment<T>(_array, _offset + index, _count - index);
}
public ArraySegment<T> Slice(int index, int count)
{
ThrowInvalidOperationIfDefault();
if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index))
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
return new ArraySegment<T>(_array, _offset + index, count);
}
public T[] ToArray()
{
ThrowInvalidOperationIfDefault();
if (_count == 0)
{
return Empty._array;
}
var array = new T[_count];
System.Array.Copy(_array, _offset, array, 0, _count);
return array;
}
public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b)
{
return a.Equals(b);
}
public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b)
{
return !(a == b);
}
public static implicit operator ArraySegment<T>(T[] array) => array != null ? new ArraySegment<T>(array) : default;
#region IList<T>
T IList<T>.this[int index]
{
get
{
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
return _array[_offset + index];
}
set
{
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
_array[_offset + index] = value;
}
}
int IList<T>.IndexOf(T item)
{
ThrowInvalidOperationIfDefault();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0 ? index - _offset : -1;
}
void IList<T>.Insert(int index, T item)
{
ThrowHelper.ThrowNotSupportedException();
}
void IList<T>.RemoveAt(int index)
{
ThrowHelper.ThrowNotSupportedException();
}
#endregion
#region IReadOnlyList<T>
T IReadOnlyList<T>.this[int index]
{
get
{
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
return _array[_offset + index];
}
}
#endregion IReadOnlyList<T>
#region ICollection<T>
bool ICollection<T>.IsReadOnly
{
get
{
// the indexer setter does not throw an exception although IsReadOnly is true.
// This is to match the behavior of arrays.
return true;
}
}
void ICollection<T>.Add(T item)
{
ThrowHelper.ThrowNotSupportedException();
}
void ICollection<T>.Clear()
{
ThrowHelper.ThrowNotSupportedException();
}
bool ICollection<T>.Contains(T item)
{
ThrowInvalidOperationIfDefault();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0;
}
bool ICollection<T>.Remove(T item)
{
ThrowHelper.ThrowNotSupportedException();
return default;
}
#endregion
#region IEnumerable<T>
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
private void ThrowInvalidOperationIfDefault()
{
if (_array == null)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
}
}
public struct Enumerator : IEnumerator<T>
{
private readonly T[] _array;
private readonly int _start;
private readonly int _end; // cache Offset + Count, since it's a little slow
private int _current;
internal Enumerator(ArraySegment<T> arraySegment)
{
Debug.Assert(arraySegment.Array != null);
Debug.Assert(arraySegment.Offset >= 0);
Debug.Assert(arraySegment.Count >= 0);
Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length);
_array = arraySegment.Array;
_start = arraySegment.Offset;
_end = arraySegment.Offset + arraySegment.Count;
_current = arraySegment.Offset - 1;
}
public bool MoveNext()
{
if (_current < _end)
{
_current++;
return (_current < _end);
}
return false;
}
public T Current
{
get
{
if (_current < _start)
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
if (_current >= _end)
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return _array[_current];
}
}
object IEnumerator.Current => Current;
void IEnumerator.Reset()
{
_current = _start - 1;
}
public void Dispose()
{
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace NorthwindAccess
{
/// <summary>
/// Strongly-typed collection for the ProductCategoryMap class.
/// </summary>
[Serializable]
public partial class ProductCategoryMapCollection : ActiveList<ProductCategoryMap, ProductCategoryMapCollection>
{
public ProductCategoryMapCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ProductCategoryMapCollection</returns>
public ProductCategoryMapCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
ProductCategoryMap o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Product_Category_Map table.
/// </summary>
[Serializable]
public partial class ProductCategoryMap : ActiveRecord<ProductCategoryMap>, IActiveRecord
{
#region .ctors and Default Settings
public ProductCategoryMap()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public ProductCategoryMap(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public ProductCategoryMap(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public ProductCategoryMap(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Product_Category_Map", TableType.Table, DataService.GetInstance("NorthwindAccess"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"";
//columns
TableSchema.TableColumn colvarCategoryID = new TableSchema.TableColumn(schema);
colvarCategoryID.ColumnName = "CategoryID";
colvarCategoryID.DataType = DbType.Int32;
colvarCategoryID.MaxLength = 0;
colvarCategoryID.AutoIncrement = false;
colvarCategoryID.IsNullable = false;
colvarCategoryID.IsPrimaryKey = true;
colvarCategoryID.IsForeignKey = true;
colvarCategoryID.IsReadOnly = false;
colvarCategoryID.DefaultSetting = @"";
colvarCategoryID.ForeignKeyTableName = "Categories";
schema.Columns.Add(colvarCategoryID);
TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema);
colvarProductID.ColumnName = "ProductID";
colvarProductID.DataType = DbType.Int32;
colvarProductID.MaxLength = 0;
colvarProductID.AutoIncrement = false;
colvarProductID.IsNullable = false;
colvarProductID.IsPrimaryKey = true;
colvarProductID.IsForeignKey = true;
colvarProductID.IsReadOnly = false;
colvarProductID.DefaultSetting = @"";
colvarProductID.ForeignKeyTableName = "Products";
schema.Columns.Add(colvarProductID);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["NorthwindAccess"].AddSchema("Product_Category_Map",schema);
}
}
#endregion
#region Props
[XmlAttribute("CategoryID")]
[Bindable(true)]
public int CategoryID
{
get { return GetColumnValue<int>(Columns.CategoryID); }
set { SetColumnValue(Columns.CategoryID, value); }
}
[XmlAttribute("ProductID")]
[Bindable(true)]
public int ProductID
{
get { return GetColumnValue<int>(Columns.ProductID); }
set { SetColumnValue(Columns.ProductID, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a Category ActiveRecord object related to this ProductCategoryMap
///
/// </summary>
public NorthwindAccess.Category Category
{
get { return NorthwindAccess.Category.FetchByID(this.CategoryID); }
set { SetColumnValue("CategoryID", value.CategoryID); }
}
/// <summary>
/// Returns a Product ActiveRecord object related to this ProductCategoryMap
///
/// </summary>
public NorthwindAccess.Product Product
{
get { return NorthwindAccess.Product.FetchByID(this.ProductID); }
set { SetColumnValue("ProductID", value.ProductID); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varCategoryID,int varProductID)
{
ProductCategoryMap item = new ProductCategoryMap();
item.CategoryID = varCategoryID;
item.ProductID = varProductID;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varCategoryID,int varProductID)
{
ProductCategoryMap item = new ProductCategoryMap();
item.CategoryID = varCategoryID;
item.ProductID = varProductID;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn CategoryIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn ProductIDColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string CategoryID = @"CategoryID";
public static string ProductID = @"ProductID";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#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.Threading.Tasks;
using System;
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Versioning;
namespace System.Xml
{
// Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents
// that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification.
public abstract partial class XmlWriter : IDisposable
{
// Write methods
// Writes out the XML declaration with the version "1.0".
public virtual Task WriteStartDocumentAsync()
{
throw NotImplemented.ByDesign;
}
//Writes out the XML declaration with the version "1.0" and the speficied standalone attribute.
public virtual Task WriteStartDocumentAsync(bool standalone)
{
throw NotImplemented.ByDesign;
}
//Closes any open elements or attributes and puts the writer back in the Start state.
public virtual Task WriteEndDocumentAsync()
{
throw NotImplemented.ByDesign;
}
// Writes out the DOCTYPE declaration with the specified name and optional attributes.
public virtual Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset)
{
throw NotImplemented.ByDesign;
}
// Writes out the specified start tag and associates it with the given namespace and prefix.
public virtual Task WriteStartElementAsync(string prefix, string localName, string ns)
{
throw NotImplemented.ByDesign;
}
// Closes one element and pops the corresponding namespace scope.
public virtual Task WriteEndElementAsync()
{
throw NotImplemented.ByDesign;
}
// Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>.
public virtual Task WriteFullEndElementAsync()
{
throw NotImplemented.ByDesign;
}
// Writes out the attribute with the specified LocalName, value, and NamespaceURI.
// Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value.
public Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value)
{
Task task = WriteStartAttributeAsync(prefix, localName, ns);
if (task.IsSuccess())
{
return WriteStringAsync(value).CallTaskFuncWhenFinishAsync(thisRef => thisRef.WriteEndAttributeAsync(), this);
}
else
{
return WriteAttributeStringAsyncHelper(task, value);
}
}
private async Task WriteAttributeStringAsyncHelper(Task task, string value)
{
await task.ConfigureAwait(false);
await WriteStringAsync(value).ConfigureAwait(false);
await WriteEndAttributeAsync().ConfigureAwait(false);
}
// Writes the start of an attribute.
protected internal virtual Task WriteStartAttributeAsync(string prefix, string localName, string ns)
{
throw NotImplemented.ByDesign;
}
// Closes the attribute opened by WriteStartAttribute call.
protected internal virtual Task WriteEndAttributeAsync()
{
throw NotImplemented.ByDesign;
}
// Writes out a <![CDATA[...]]>; block containing the specified text.
public virtual Task WriteCDataAsync(string text)
{
throw NotImplemented.ByDesign;
}
// Writes out a comment <!--...-->; containing the specified text.
public virtual Task WriteCommentAsync(string text)
{
throw NotImplemented.ByDesign;
}
// Writes out a processing instruction with a space between the name and text as follows: <?name text?>
public virtual Task WriteProcessingInstructionAsync(string name, string text)
{
throw NotImplemented.ByDesign;
}
// Writes out an entity reference as follows: "&"+name+";".
public virtual Task WriteEntityRefAsync(string name)
{
throw NotImplemented.ByDesign;
}
// Forces the generation of a character entity for the specified Unicode character value.
public virtual Task WriteCharEntityAsync(char ch)
{
throw NotImplemented.ByDesign;
}
// Writes out the given whitespace.
public virtual Task WriteWhitespaceAsync(string ws)
{
throw NotImplemented.ByDesign;
}
// Writes out the specified text content.
public virtual Task WriteStringAsync(string text)
{
throw NotImplemented.ByDesign;
}
// Write out the given surrogate pair as an entity reference.
public virtual Task WriteSurrogateCharEntityAsync(char lowChar, char highChar)
{
throw NotImplemented.ByDesign;
}
// Writes out the specified text content.
public virtual Task WriteCharsAsync(char[] buffer, int index, int count)
{
throw NotImplemented.ByDesign;
}
// Writes raw markup from the given character buffer.
public virtual Task WriteRawAsync(char[] buffer, int index, int count)
{
throw NotImplemented.ByDesign;
}
// Writes raw markup from the given string.
public virtual Task WriteRawAsync(string data)
{
throw NotImplemented.ByDesign;
}
// Encodes the specified binary bytes as base64 and writes out the resulting text.
public virtual Task WriteBase64Async(byte[] buffer, int index, int count)
{
throw NotImplemented.ByDesign;
}
// Encodes the specified binary bytes as binhex and writes out the resulting text.
public virtual Task WriteBinHexAsync(byte[] buffer, int index, int count)
{
return BinHexEncoder.EncodeAsync(buffer, index, count, this);
}
// Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader.
public virtual Task FlushAsync()
{
throw NotImplemented.ByDesign;
}
// Scalar Value Methods
// Writes out the specified name, ensuring it is a valid NmToken according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual Task WriteNmTokenAsync(string name)
{
if (name == null || name.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyName);
}
return WriteStringAsync(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException));
}
// Writes out the specified name, ensuring it is a valid Name according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual Task WriteNameAsync(string name)
{
return WriteStringAsync(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException));
}
// Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
public virtual async Task WriteQualifiedNameAsync(string localName, string ns)
{
if (ns != null && ns.Length > 0)
{
string prefix = LookupPrefix(ns);
if (prefix == null)
{
throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
}
await WriteStringAsync(prefix).ConfigureAwait(false);
await WriteStringAsync(":").ConfigureAwait(false);
}
await WriteStringAsync(localName).ConfigureAwait(false);
}
// XmlReader Helper Methods
// Writes out all the attributes found at the current position in the specified XmlReader.
public virtual async Task WriteAttributesAsync(XmlReader reader, bool defattr)
{
if (null == reader)
{
throw new ArgumentNullException("reader");
}
if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.XmlDeclaration)
{
if (reader.MoveToFirstAttribute())
{
await WriteAttributesAsync(reader, defattr).ConfigureAwait(false);
reader.MoveToElement();
}
}
else if (reader.NodeType != XmlNodeType.Attribute)
{
throw new XmlException(SR.Xml_InvalidPosition, string.Empty);
}
else
{
do
{
// we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault.
// If either of these is true and defattr=false, we should not write the attribute out
if (defattr || !reader.IsDefaultInternal)
{
await WriteStartAttributeAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false);
while (reader.ReadAttributeValue())
{
if (reader.NodeType == XmlNodeType.EntityReference)
{
await WriteEntityRefAsync(reader.Name).ConfigureAwait(false);
}
else
{
await WriteStringAsync(reader.Value).ConfigureAwait(false);
}
}
await WriteEndAttributeAsync().ConfigureAwait(false);
}
}
while (reader.MoveToNextAttribute());
}
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
public virtual Task WriteNodeAsync(XmlReader reader, bool defattr)
{
if (null == reader)
{
throw new ArgumentNullException("reader");
}
if (reader.Settings != null && reader.Settings.Async)
{
return WriteNodeAsync_CallAsyncReader(reader, defattr);
}
else
{
return WriteNodeAsync_CallSyncReader(reader, defattr);
}
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
//use sync methods on the reader
internal async Task WriteNodeAsync_CallSyncReader(XmlReader reader, bool defattr)
{
bool canReadChunk = reader.CanReadValueChunk;
int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth;
do
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
await WriteStartElementAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false);
await WriteAttributesAsync(reader, defattr).ConfigureAwait(false);
if (reader.IsEmptyElement)
{
await WriteEndElementAsync().ConfigureAwait(false);
break;
}
break;
case XmlNodeType.Text:
if (canReadChunk)
{
if (_writeNodeBuffer == null)
{
_writeNodeBuffer = new char[WriteNodeBufferSize];
}
int read;
while ((read = reader.ReadValueChunk(_writeNodeBuffer, 0, WriteNodeBufferSize)) > 0)
{
await this.WriteCharsAsync(_writeNodeBuffer, 0, read).ConfigureAwait(false);
}
}
else
{
await WriteStringAsync(reader.Value).ConfigureAwait(false);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
await WriteWhitespaceAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.CDATA:
await WriteCDataAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.EntityReference:
await WriteEntityRefAsync(reader.Name).ConfigureAwait(false);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
await WriteProcessingInstructionAsync(reader.Name, reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.DocumentType:
await WriteDocTypeAsync(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.Comment:
await WriteCommentAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.EndElement:
await WriteFullEndElementAsync().ConfigureAwait(false);
break;
}
} while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)));
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
//use async methods on the reader
internal async Task WriteNodeAsync_CallAsyncReader(XmlReader reader, bool defattr)
{
bool canReadChunk = reader.CanReadValueChunk;
int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth;
do
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
await WriteStartElementAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false);
await WriteAttributesAsync(reader, defattr).ConfigureAwait(false);
if (reader.IsEmptyElement)
{
await WriteEndElementAsync().ConfigureAwait(false);
break;
}
break;
case XmlNodeType.Text:
if (canReadChunk)
{
if (_writeNodeBuffer == null)
{
_writeNodeBuffer = new char[WriteNodeBufferSize];
}
int read;
while ((read = await reader.ReadValueChunkAsync(_writeNodeBuffer, 0, WriteNodeBufferSize).ConfigureAwait(false)) > 0)
{
await this.WriteCharsAsync(_writeNodeBuffer, 0, read).ConfigureAwait(false);
}
}
else
{
//reader.Value may block on Text or WhiteSpace node, use GetValueAsync
await WriteStringAsync(await reader.GetValueAsync().ConfigureAwait(false)).ConfigureAwait(false);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
await WriteWhitespaceAsync(await reader.GetValueAsync().ConfigureAwait(false)).ConfigureAwait(false);
break;
case XmlNodeType.CDATA:
await WriteCDataAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.EntityReference:
await WriteEntityRefAsync(reader.Name).ConfigureAwait(false);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
await WriteProcessingInstructionAsync(reader.Name, reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.DocumentType:
await WriteDocTypeAsync(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.Comment:
await WriteCommentAsync(reader.Value).ConfigureAwait(false);
break;
case XmlNodeType.EndElement:
await WriteFullEndElementAsync().ConfigureAwait(false);
break;
}
} while (await reader.ReadAsync().ConfigureAwait(false) && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)));
}
// Element Helper Methods
// Writes out an attribute with the specified name, namespace URI, and string value.
public async Task WriteElementStringAsync(string prefix, String localName, String ns, String value)
{
await WriteStartElementAsync(prefix, localName, ns).ConfigureAwait(false);
if (null != value && 0 != value.Length)
{
await WriteStringAsync(value).ConfigureAwait(false);
}
await WriteEndElementAsync().ConfigureAwait(false);
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using AllReady.Models;
namespace AllReady.Migrations
{
[DbContext(typeof(AllReadyContext))]
[Migration("20160624152405_OrgDescFields")]
partial class OrgDescFields
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("AllReady.Models.AllReadyTask", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<DateTimeOffset?>("EndDateTime");
b.Property<int?>("EventId");
b.Property<bool>("IsAllowWaitList");
b.Property<bool>("IsLimitVolunteers");
b.Property<string>("Name")
.IsRequired();
b.Property<int>("NumberOfVolunteersRequired");
b.Property<int?>("OrganizationId");
b.Property<DateTimeOffset?>("StartDateTime");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<string>("FirstName");
b.Property<string>("LastName");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<int?>("OrganizationId");
b.Property<string>("PasswordHash");
b.Property<string>("PendingNewEmail");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<string>("TimeZoneId")
.IsRequired();
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("AllReady.Models.Campaign", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CampaignImpactId");
b.Property<string>("Description");
b.Property<DateTimeOffset>("EndDateTime");
b.Property<string>("ExternalUrl");
b.Property<string>("ExternalUrlText");
b.Property<bool>("Featured");
b.Property<string>("FullDescription");
b.Property<string>("Headline")
.HasAnnotation("MaxLength", 150);
b.Property<string>("ImageUrl");
b.Property<int?>("LocationId");
b.Property<bool>("Locked");
b.Property<int>("ManagingOrganizationId");
b.Property<string>("Name")
.IsRequired();
b.Property<string>("OrganizerId");
b.Property<DateTimeOffset>("StartDateTime");
b.Property<string>("TimeZoneId")
.IsRequired();
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.CampaignContact", b =>
{
b.Property<int>("CampaignId");
b.Property<int>("ContactId");
b.Property<int>("ContactType");
b.HasKey("CampaignId", "ContactId", "ContactType");
});
modelBuilder.Entity("AllReady.Models.CampaignImpact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CurrentImpactLevel");
b.Property<bool>("Display");
b.Property<int>("ImpactType");
b.Property<int>("NumericImpactGoal");
b.Property<string>("TextualImpactGoal");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.CampaignSponsors", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CampaignId");
b.Property<int?>("OrganizationId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ClosestLocation", b =>
{
b.Property<string>("PostalCode");
b.Property<string>("City");
b.Property<double>("Distance");
b.Property<string>("State");
b.HasKey("PostalCode");
});
modelBuilder.Entity("AllReady.Models.Contact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Email");
b.Property<string>("FirstName");
b.Property<string>("LastName");
b.Property<string>("PhoneNumber");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Event", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CampaignId");
b.Property<string>("Description");
b.Property<DateTimeOffset>("EndDateTime");
b.Property<int>("EventType");
b.Property<string>("Headline")
.HasAnnotation("MaxLength", 150);
b.Property<string>("ImageUrl");
b.Property<bool>("IsAllowWaitList");
b.Property<bool>("IsLimitVolunteers");
b.Property<int?>("LocationId");
b.Property<string>("Name")
.IsRequired();
b.Property<int>("NumberOfVolunteersRequired");
b.Property<string>("OrganizerId");
b.Property<DateTimeOffset>("StartDateTime");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.EventSignup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AdditionalInfo");
b.Property<DateTime?>("CheckinDateTime");
b.Property<int?>("EventId");
b.Property<string>("PreferredEmail");
b.Property<string>("PreferredPhoneNumber");
b.Property<DateTime>("SignupDateTime");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.EventSkill", b =>
{
b.Property<int>("EventId");
b.Property<int>("SkillId");
b.HasKey("EventId", "SkillId");
});
modelBuilder.Entity("AllReady.Models.Itinerary", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("Date");
b.Property<int>("EventId");
b.Property<string>("Name");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ItineraryRequest", b =>
{
b.Property<int>("ItineraryId");
b.Property<Guid>("RequestId");
b.Property<DateTime>("DateAssigned");
b.Property<int>("OrderIndex");
b.HasKey("ItineraryId", "RequestId");
});
modelBuilder.Entity("AllReady.Models.Location", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Address1");
b.Property<string>("Address2");
b.Property<string>("City");
b.Property<string>("Country");
b.Property<string>("Name");
b.Property<string>("PhoneNumber");
b.Property<string>("PostalCode");
b.Property<string>("State");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Organization", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("DescriptionHtml");
b.Property<int?>("LocationId");
b.Property<string>("LogoUrl");
b.Property<string>("Name")
.IsRequired();
b.Property<string>("PrivacyPolicy");
b.Property<string>("Summary")
.HasAnnotation("MaxLength", 250);
b.Property<string>("WebUrl");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.OrganizationContact", b =>
{
b.Property<int>("OrganizationId");
b.Property<int>("ContactId");
b.Property<int>("ContactType");
b.HasKey("OrganizationId", "ContactId", "ContactType");
});
modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b =>
{
b.Property<string>("PostalCode");
b.Property<string>("City");
b.Property<string>("State");
b.HasKey("PostalCode");
});
modelBuilder.Entity("AllReady.Models.PostalCodeGeoCoordinate", b =>
{
b.Property<double>("Latitude");
b.Property<double>("Longitude");
b.HasKey("Latitude", "Longitude");
});
modelBuilder.Entity("AllReady.Models.Request", b =>
{
b.Property<Guid>("RequestId")
.ValueGeneratedOnAdd();
b.Property<string>("Address");
b.Property<string>("City");
b.Property<DateTime>("DateAdded");
b.Property<string>("Email");
b.Property<int?>("EventId");
b.Property<double>("Latitude");
b.Property<double>("Longitude");
b.Property<string>("Name");
b.Property<string>("Phone");
b.Property<string>("ProviderData");
b.Property<string>("ProviderId");
b.Property<string>("State");
b.Property<int>("Status");
b.Property<string>("Zip");
b.HasKey("RequestId");
});
modelBuilder.Entity("AllReady.Models.Resource", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("CategoryTag");
b.Property<string>("Description");
b.Property<string>("MediaUrl");
b.Property<string>("Name");
b.Property<DateTime>("PublishDateBegin");
b.Property<DateTime>("PublishDateEnd");
b.Property<string>("ResourceUrl");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Skill", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<string>("Name")
.IsRequired();
b.Property<int?>("OwningOrganizationId");
b.Property<int?>("ParentSkillId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.TaskSignup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AdditionalInfo");
b.Property<int?>("ItineraryId");
b.Property<string>("PreferredEmail");
b.Property<string>("PreferredPhoneNumber");
b.Property<string>("Status");
b.Property<DateTime>("StatusDateTimeUtc");
b.Property<string>("StatusDescription");
b.Property<int>("TaskId");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.TaskSkill", b =>
{
b.Property<int>("TaskId");
b.Property<int>("SkillId");
b.HasKey("TaskId", "SkillId");
});
modelBuilder.Entity("AllReady.Models.UserSkill", b =>
{
b.Property<string>("UserId");
b.Property<int>("SkillId");
b.HasKey("UserId", "SkillId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("AllReady.Models.AllReadyTask", b =>
{
b.HasOne("AllReady.Models.Event")
.WithMany()
.HasForeignKey("EventId");
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OrganizationId");
});
modelBuilder.Entity("AllReady.Models.ApplicationUser", b =>
{
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OrganizationId");
});
modelBuilder.Entity("AllReady.Models.Campaign", b =>
{
b.HasOne("AllReady.Models.CampaignImpact")
.WithMany()
.HasForeignKey("CampaignImpactId");
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("ManagingOrganizationId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("OrganizerId");
});
modelBuilder.Entity("AllReady.Models.CampaignContact", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Contact")
.WithMany()
.HasForeignKey("ContactId");
});
modelBuilder.Entity("AllReady.Models.CampaignSponsors", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OrganizationId");
});
modelBuilder.Entity("AllReady.Models.Event", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("OrganizerId");
});
modelBuilder.Entity("AllReady.Models.EventSignup", b =>
{
b.HasOne("AllReady.Models.Event")
.WithMany()
.HasForeignKey("EventId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("AllReady.Models.EventSkill", b =>
{
b.HasOne("AllReady.Models.Event")
.WithMany()
.HasForeignKey("EventId");
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
});
modelBuilder.Entity("AllReady.Models.Itinerary", b =>
{
b.HasOne("AllReady.Models.Event")
.WithMany()
.HasForeignKey("EventId");
});
modelBuilder.Entity("AllReady.Models.ItineraryRequest", b =>
{
b.HasOne("AllReady.Models.Itinerary")
.WithMany()
.HasForeignKey("ItineraryId");
b.HasOne("AllReady.Models.Request")
.WithMany()
.HasForeignKey("RequestId");
});
modelBuilder.Entity("AllReady.Models.Organization", b =>
{
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
});
modelBuilder.Entity("AllReady.Models.OrganizationContact", b =>
{
b.HasOne("AllReady.Models.Contact")
.WithMany()
.HasForeignKey("ContactId");
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OrganizationId");
});
modelBuilder.Entity("AllReady.Models.Request", b =>
{
b.HasOne("AllReady.Models.Event")
.WithMany()
.HasForeignKey("EventId");
});
modelBuilder.Entity("AllReady.Models.Skill", b =>
{
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OwningOrganizationId");
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("ParentSkillId");
});
modelBuilder.Entity("AllReady.Models.TaskSignup", b =>
{
b.HasOne("AllReady.Models.Itinerary")
.WithMany()
.HasForeignKey("ItineraryId");
b.HasOne("AllReady.Models.AllReadyTask")
.WithMany()
.HasForeignKey("TaskId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("AllReady.Models.TaskSkill", b =>
{
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
b.HasOne("AllReady.Models.AllReadyTask")
.WithMany()
.HasForeignKey("TaskId");
});
modelBuilder.Entity("AllReady.Models.UserSkill", b =>
{
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dccelerator.DataAccess.Ado.Implementation;
using Dccelerator.DataAccess.Infrastructure;
using Dccelerator.UnFastReflection;
using JetBrains.Annotations;
namespace Dccelerator.DataAccess.Ado {
/// <summary>
/// Am <see cref="IAdoNetRepository"/> what defines special names of CRUD-operation stored procedures.
/// </summary>
/// <seealso cref="ReadCommandText"/>
/// <seealso cref="InsertCommandText{TEntity}"/>
/// <seealso cref="UpdateCommandText{TEntity}"/>
/// <seealso cref="DeleteCommandText{TEntity}"/>
public abstract class AdoNetRepository<TCommand, TParameter, TConnection> : IAdoNetRepository
where TCommand : DbCommand
where TParameter : DbParameter
where TConnection : DbConnection {
DbConnection IAdoNetRepository.GetConnection() => GetConnection();
protected internal abstract string DatabaseSpecificNameOf(string parameter);
protected internal virtual string DatabaseSpecificNameOf(IDataCriterion criterion) => DatabaseSpecificNameOf(criterion.Name);
Type _repositoryType;
protected Type RepositoryType => _repositoryType ?? (_repositoryType = GetType());
/// <summary>
/// Get instance of <typeparamref name="TParameter" /> that represents primary key.
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="info">Information about entity</param>
/// <param name="entity">Instance of entity</param>
/// <returns>Return instance of parameter</returns>
protected internal abstract TParameter PrimaryKeyParameterOf<TEntity>(IEntityInfo info, TEntity entity);
/// <summary>
/// Get instance <typeparamref name="TConnection" /> for database.
/// </summary>
/// <remarks>Connection should be instantiated, but unopened.</remarks>
/// <returns>Return instance of connection</returns>
protected internal abstract TConnection GetConnection();
/// <summary>
/// Get instance of <typeparamref name="TParameter" /> for queries based on input info and entity.
/// </summary>
/// <param name="info">Information about entity</param>
/// <param name="criterion">Criterion that should be represented by returned <typeparamref name="TParameter"/></param>
/// <returns>Return instance of <typeparamref name="TParameter"/> </returns>
protected internal abstract TParameter ParameterWith(IEntityInfo info, IDataCriterion criterion);
/// <summary>
/// Represents a command that will be executed against a database.
/// </summary>
/// <param name="commandText">String that represent query for command</param>
/// <param name="args">Database action arguments. Connection and transaction</param>
/// <param name="parameters">List of parameters</param>
/// <param name="type">Type of command</param>
/// <returns>Return instance of command</returns>
protected internal abstract TCommand CommandFor(string commandText, DbActionArgs args, IEnumerable<TParameter> parameters, CommandType type = CommandType.StoredProcedure);
/// <summary>
/// Get text for <typeparamref name="TCommand"/> used for reading data.
/// </summary>
/// <param name="info">Information about entity</param>
/// <param name="criteria">Query criteria</param>
/// <returns>Return string with query</returns>
protected internal virtual string ReadCommandText(IEntityInfo info, IEnumerable<IDataCriterion> criteria) {
return info.UsingQueries
? SelectQuery(info, criteria)
: SelectProcedure(info, criteria);
}
/// <summary>
/// Get text for <typeparamref name="TCommand"/> used for inserting <paramref name="entity"/>.
/// </summary>
/// <typeparam name="TEntity">Type of entity</typeparam>
/// <param name="info">Information about entity</param>
/// <param name="entity">Instance of entity</param>
/// <returns>Return string with query</returns>
protected internal virtual string InsertCommandText<TEntity>(IEntityInfo info, TEntity entity) {
return info.UsingQueries
? InsertQuery(info, entity)
: InsertProcedure(info, entity);
}
/// <summary>
/// Get text for <typeparamref name="TCommand"/> used for updating <paramref name="entity"/>.
/// </summary>
/// <typeparam name="TEntity">Type of entity</typeparam>
/// <param name="info">Information about entity</param>
/// <param name="entity">Instance of entity</param>
/// <returns>Return string with query</returns>
protected internal virtual string UpdateCommandText<TEntity>(IEntityInfo info, TEntity entity) {
return info.UsingQueries
? UpdateQuery(info, entity)
: UpdateProcedure(info, entity);
}
/// <summary>
/// Get text for <typeparamref name="TCommand"/> used for deleting <paramref name="entity"/>.
/// </summary>
/// <typeparam name="TEntity">Type of entity</typeparam>
/// <param name="info">Information about entity</param>
/// <param name="entity">Instance of entity</param>
/// <returns>Return string with query</returns>
protected internal virtual string DeleteCommandText<TEntity>(IEntityInfo info, TEntity entity) {
return info.UsingQueries
? DeleteQuery(info, entity)
: DeleteProcedure(info, entity);
}
protected internal virtual string SelectQuery(IEntityInfo info, IEnumerable<IDataCriterion> criteria) {
var builder = new StringBuilder("select * from ").Append(info.EntityName).Append(" where ");
foreach (var criterion in criteria)
builder.Append(criterion.Name).Append(" = ").Append(DatabaseSpecificNameOf(criterion.Name)).Append(" and ");
return builder.Remove(builder.Length - 5, 5).ToString();
}
protected internal virtual string InsertQuery<TEntity>(IEntityInfo info, TEntity entity) {
var adoInfo = (IAdoEntityInfo) info;
string query;
if (adoInfo.CachedInsertQueries.TryGetValue(RepositoryType.FullName, out query))
return query;
var builder = new StringBuilder("insert into ").Append(info.EntityName).Append(" ( ");
foreach (var property in info.PersistedProperties.Keys)
builder.Append(property).Append(", ");
builder.Remove(builder.Length - 2, 2).Append(" )\n values ( ");
foreach (var property in info.PersistedProperties.Keys)
builder.Append(DatabaseSpecificNameOf(property)).Append(", ");
query = builder.Remove(builder.Length - 2, 1).Append(")").ToString();
adoInfo.CachedInsertQueries.TryAdd(RepositoryType.FullName, query);
return query;
}
protected internal virtual string UpdateQuery<TEntity>(IEntityInfo info, TEntity entity) {
var adoInfo = (IAdoEntityInfo)info;
string query;
if (adoInfo.CachedUpdateQueries.TryGetValue(RepositoryType.FullName, out query))
return query;
var builder = new StringBuilder("update ").Append(info.EntityName).Append(" set ");
var key = PrimaryKeyParameterOf(info, entity);
foreach (var property in info.PersistedProperties.Keys) {
if (property == key.ParameterName) continue;
builder.Append(property).Append(" = ").Append(DatabaseSpecificNameOf(property)).Append(", ");
}
builder.Remove(builder.Length - 2, 2);
builder.Append(" where ").Append(key.ParameterName).Append(" = ").Append(DatabaseSpecificNameOf(key.ParameterName));
query = builder.ToString();
adoInfo.CachedUpdateQueries.TryAdd(RepositoryType.FullName, query);
return query;
}
protected internal virtual string DeleteQuery<TEntity>(IEntityInfo info, TEntity entity) {
var adoInfo = (IAdoEntityInfo)info;
string query;
if (adoInfo.CachedDeleteQueries.TryGetValue(RepositoryType.FullName, out query))
return query;
var builder = new StringBuilder("delete from ").Append(info.EntityName);
var key = PrimaryKeyParameterOf(info, entity);
builder.Append(" where ").Append(key.ParameterName).Append(" = ").Append(DatabaseSpecificNameOf(key.ParameterName));
query = builder.ToString();
adoInfo.CachedDeleteQueries.TryAdd(RepositoryType.FullName, query);
return query;
}
protected internal virtual string SelectProcedure(IEntityInfo info, IEnumerable<IDataCriterion> criteria) {
return string.Concat("obj_", info.EntityName, "_get_by_criteria");
}
protected internal virtual string InsertProcedure<TEntity>(IEntityInfo info, TEntity entity) {
return string.Concat("obj_", info.EntityName, "_insert");
}
protected internal virtual string UpdateProcedure<TEntity>(IEntityInfo info, TEntity entity) {
return string.Concat("obj_", info.EntityName, "_update");
}
protected internal virtual string DeleteProcedure<TEntity>(IEntityInfo info, TEntity entity) {
return string.Concat("obj_", info.EntityName, "_delete");
}
/// <summary>
/// Get <see cref="CommandBehavior"/> for command.
/// </summary>
/// <returns>Instance of CommandBehavior</returns>
protected virtual CommandBehavior GetBehaviorFor(IEntityInfo info) {
if (info.Inclusions?.Any() != true)
return CommandBehavior.SequentialAccess | CommandBehavior.SingleResult;
return CommandBehavior.SequentialAccess;
}
/// <summary>
/// Returns whole <paramref name="entity"/>, represented as sequence of <typeparamref name="TParameter"/>.
/// </summary>
/// <returns>IEnumerable (sequence) of TParameter</returns>
protected virtual IEnumerable<TParameter> ParametersFrom<TEntity>(IEntityInfo info, TEntity entity) where TEntity : class {
return info.PersistedProperties.Select(x => {
object value;
if (!RUtils<TEntity>.TryGet(entity, x.Key, out value))
throw new InvalidOperationException($"Entity of type {entity.GetType()} should contain property '{x.Key}', " +
"but in some reason value or that property could not be getted.");
var criterion = new DataCriterion {Name = x.Key, Type = x.Value.PropertyType, Value = value};
return ParameterWith(info, criterion);
});
}
/// <summary>
/// Returns entities from database, filtered with <paramref name="criteria"/>.
/// </summary>
/// <param name="info">Information about entity</param>
/// <param name="criteria">Filtering criteria</param>
public IEnumerable<object> Read(IEntityInfo info, ICollection<IDataCriterion> criteria) {
return Read((IAdoEntityInfo) info, criteria);
}
/// <summary>
/// Returns entities from database, filtered with <paramref name="criteria"/>.
/// </summary>
/// <param name="info">Information about entity</param>
/// <param name="criteria">Filtering criteria</param>
protected virtual IEnumerable<object> Read(IAdoEntityInfo info, ICollection<IDataCriterion> criteria) {
return info.Inclusions?.Any() == true
? ReadToEnd(info, criteria)
: GetMainEntities(info, criteria);
}
/// <summary>
/// Checks, is database contains any entity (specified by it's <paramref name="info"/>), that satisfying passed filtering <paramref name="criteria"/>.
/// </summary>
/// <exception cref="DbException">The connection-level error that occurred while opening the connection. </exception>
public bool Any(IEntityInfo info, ICollection<IDataCriterion> criteria) {
var parameters = criteria.Select(x => ParameterWith(info, x));
var behavior = GetBehaviorFor(info) | CommandBehavior.SingleRow;
var connection = GetConnection();
try {
using (var command = CommandFor(ReadCommandText(info, criteria), new DbActionArgs(connection), parameters)) {
connection.Open();
using (var reader = command.ExecuteReader(behavior)) {
return reader.Read();
}
}
}
finally {
connection.Close();
connection.Dispose();
}
}
/// <summary>
/// Returns values of one property/column of entities, that satisfying passed filtering <paramref name="criteria"/>.
/// </summary>
public IEnumerable<object> ReadColumn(string columnName, IEntityInfo info, ICollection<IDataCriterion> criteria) {
return ReadColumn(columnName, (IAdoEntityInfo) info, criteria);
}
/// <summary>
/// Returns values of one property/column of entities, that satisfying passed filtering <paramref name="criteria"/>.
/// </summary>
/// <exception cref="DbException">The connection-level error that occurred while opening the connection. </exception>
protected virtual IEnumerable<object> ReadColumn(string columnName, IAdoEntityInfo info, ICollection<IDataCriterion> criteria) {
var parameters = criteria.Select(x => ParameterWith(info, x));
var idx = info.ReaderColumns != null ? info.IndexOf(columnName) : -1;
var behavior = GetBehaviorFor(info);
var connection = GetConnection();
try {
using (var command = CommandFor(ReadCommandText(info, criteria), new DbActionArgs(connection), parameters)) {
connection.Open();
using (var reader = command.ExecuteReader(behavior)) {
if (idx < 0) {
info.InitReaderColumns(reader);
idx = info.IndexOf(columnName);
}
while (reader.Read()) {
yield return reader.GetValue(idx);
}
}
}
}
finally {
connection.Close();
connection.Dispose();
}
}
/// <summary>
/// Get number of entities, that satisfying passed filtering <paramref name="criteria"/>.
/// </summary>
/// <returns>Number of entities</returns>
/// <exception cref="DbException">The connection-level error that occurred while opening the connection. </exception>
public int CountOf(IEntityInfo info, ICollection<IDataCriterion> criteria) {
var parameters = criteria.Select(x => ParameterWith(info, x));
var behavior = GetBehaviorFor(info);
var connection = GetConnection();
try {
using (var command = CommandFor(ReadCommandText(info, criteria), new DbActionArgs(connection), parameters)) {
connection.Open();
using (var reader = command.ExecuteReader(behavior)) {
return RowsCount(reader);
}
}
}
finally {
connection.Close();
connection.Dispose();
}
}
/// <summary>
/// Inserts an <paramref name="entity"/> using it's database-specific <paramref name="entityName"/>.
/// </summary>
/// <returns>Result of operation</returns>
/// <exception cref="DbException">The connection-level error that occurred while opening the connection. </exception>
public virtual bool Insert<TEntity>(IEntityInfo info, TEntity entity, DbActionArgs args) where TEntity : class {
var parameters = ParametersFrom(info, entity);
using (var command = CommandFor(InsertCommandText(info, entity), args, parameters)) {
return command.ExecuteNonQuery() > 0;
}
}
/// <summary>
/// Inserts an <paramref name="entities"/> using they database-specific <paramref name="entityName"/>.
/// </summary>
/// <returns>Result of operation</returns>
/// <exception cref="DbException">The connection-level error that occurred while opening the connection. </exception>
public virtual bool InsertMany<TEntity>(IEntityInfo info, IEnumerable<TEntity> entities, DbActionArgs args) where TEntity : class {
var name = InsertCommandText(info, entities);
foreach (var entity in entities) {
var parameters = ParametersFrom(info, entity);
using (var command = CommandFor(name, args, parameters)) {
if (command.ExecuteNonQuery() <= 0) {
return false;
}
}
}
return true;
}
/// <summary>
/// Updates an <paramref name="entity"/> using it's database-specific <paramref name="entityName"/>.
/// </summary>
/// <returns>Result of operation</returns>
/// <exception cref="DbException">The connection-level error that occurred while opening the connection. </exception>
public virtual bool Update<T>(IEntityInfo info, T entity, DbActionArgs args) where T : class {
var parameters = ParametersFrom(info, entity);
using (var command = CommandFor(UpdateCommandText(info, entity), args, parameters)) {
return command.ExecuteNonQuery() > 0;
}
}
/// <summary>
/// Updates an <paramref name="entities"/> using they database-specific <paramref name="entityName"/>.
/// </summary>
/// <returns>Result of operation</returns>
/// <exception cref="DbException">The connection-level error that occurred while opening the connection. </exception>
public virtual bool UpdateMany<TEntity>(IEntityInfo info, IEnumerable<TEntity> entities, DbActionArgs args) where TEntity : class {
var name = UpdateCommandText(info, entities);
foreach (var entity in entities) {
var parameters = ParametersFrom(info, entity);
using (var command = CommandFor(name, args, parameters)) {
if (command.ExecuteNonQuery() <= 0) {
return false;
}
}
}
return true;
}
/// <summary>
/// Removes an <paramref name="entity"/> using it's database-specific <paramref name="entityName"/>.
/// </summary>
/// <returns>Result of operation</returns>
/// <exception cref="DbException">The connection-level error that occurred while opening the connection. </exception>
public virtual bool Delete<TEntity>(IEntityInfo info, TEntity entity, DbActionArgs args) where TEntity : class {
var parameters = new[] {PrimaryKeyParameterOf(info, entity)};
using (var command = CommandFor(DeleteCommandText(info, entity), args, parameters)) {
return command.ExecuteNonQuery() > 0;
}
}
/// <summary>
/// Removes an <paramref name="entities"/> using they database-specific <paramref name="entityName"/>.
/// </summary>
/// <returns>Result of operation</returns>
/// <exception cref="DbException">The connection-level error that occurred while opening the connection. </exception>
public virtual bool DeleteMany<TEntity>(IEntityInfo info, IEnumerable<TEntity> entities, DbActionArgs args) where TEntity : class {
var name = DeleteCommandText(info, entities);
foreach (var entity in entities) {
var parameters = new[] {PrimaryKeyParameterOf(info, entity)};
using (var command = CommandFor(name, args, parameters)) {
if (command.ExecuteNonQuery() <= 0)
return false;
}
}
return true;
}
/// <summary>
/// Get number of rows in <paramref name="reader"/>.
/// </summary>
protected virtual int RowsCount(DbDataReader reader) {
var count = 0;
while (reader.Read()) {
count++;
}
return count;
}
/// <summary>
/// Returns sequence, containing entities (described by their <paramref name="info"/>)
/// from first result set of data reader, that satisfies to passed filtering <paramref name="criteria"/>.
/// </summary>
/// <exception cref="DbException">The connection-level error that occurred while opening the connection. </exception>
protected virtual IEnumerable<object> GetMainEntities(IAdoEntityInfo info, ICollection<IDataCriterion> criteria) {
var parameters = criteria.Select(x => ParameterWith(info, x));
var connection = GetConnection();
var behavior = GetBehaviorFor(info);
try {
using (var command = CommandFor(ReadCommandText(info, criteria), new DbActionArgs(connection), parameters)) {
connection.Open();
using (var reader = command.ExecuteReader(behavior)) {
info.InitReaderColumns(reader);
while (reader.Read()) {
object keyId;
yield return ReadItem(reader, info, null, out keyId);
}
}
}
}
finally {
connection.Close();
connection.Dispose();
}
}
/// <summary>
/// Returns sequence of entities, that satisfies to passed filtering <paramref name="criteria"/>,
/// including additional result sets, of data reader.
/// See <see cref="IncludeChildrenAttribute"/> and <see cref="IIncludeon"/> for more details.
/// </summary>
/// <exception cref="DbException">The connection-level error that occurred while opening the connection. </exception>
/// <seealso cref="IncludeChildrenAttribute"/>
/// <seealso cref="IIncludeon"/>
protected virtual IEnumerable<object> ReadToEnd(IAdoEntityInfo mainObjectInfo, ICollection<IDataCriterion> criteria) {
var parameters = criteria.Select(x => ParameterWith(mainObjectInfo, x));
var connection = GetConnection();
var behavior = GetBehaviorFor(mainObjectInfo);
try {
using (var command = CommandFor(ReadCommandText(mainObjectInfo, criteria), new DbActionArgs(connection), parameters)) {
connection.Open();
using (var reader = command.ExecuteReader(behavior)) {
mainObjectInfo.InitReaderColumns(reader);
var hasIncludeons = mainObjectInfo.Inclusions.Any();
var mainObjects = hasIncludeons ? new Dictionary<object, object>() : null;
while (reader.Read()) {
object keyId;
var item = ReadItem(reader, mainObjectInfo, null, out keyId);
if (!hasIncludeons)
yield return item;
try {
mainObjects.Add(keyId, item);
}
catch (Exception e) {
Log.TraceEvent(TraceEventType.Critical,
$"On reading '{mainObjectInfo.EntityType}' using special name {mainObjectInfo.EntityName} getted exception, " +
"possibly because reader contains more then one object with same identifier.\n" +
$"Identifier: {keyId}\n" +
$"Exception: {e}");
throw;
}
}
var tableIndex = 0;
while (reader.NextResult()) {
tableIndex++;
Includeon includeon;
if (!mainObjectInfo.Inclusions.TryGetValue(tableIndex, out includeon)) {
Log.TraceEvent(TraceEventType.Warning,
$"Reader for object {mainObjectInfo.EntityType.FullName} returned more than one table, " +
$"but it has not includeon information for table#{tableIndex}.");
continue;
}
var info = includeon.Info;
info.InitReaderColumns(reader);
if (!includeon.IsCollection) {
while (reader.Read()) {
object keyId;
var item = ReadItem(reader, mainObjectInfo, includeon, out keyId);
if (keyId == null) {
Log.TraceEvent(TraceEventType.Error, $"Can't get key id from item with info {info.EntityType}, {includeon.Attribute.TargetPath} (used on entity {mainObjectInfo.EntityType}");
break;
}
var index = tableIndex;
Parallel.ForEach(mainObjects.Values,
mainObject => {
object value;
if (!mainObject.TryGet(includeon.ForeignKeyFromMainEntityToCurrent, out value) || !keyId.Equals(value)) // target path should be ServiceWorkplaceId, but it ServiceWorkPlace
return; //keyId should be just primary key of ServiceWorkPlace
if (!mainObject.TrySet(includeon.Attribute.TargetPath, item))
Log.TraceEvent(TraceEventType.Warning,
$"Can't set property {includeon.Attribute.TargetPath} from '{mainObjectInfo.EntityType.FullName}' context.\nTarget path specified for child item {info.EntityType} in result set #{index}.");
});
}
}
else {
var children = new Dictionary<object, IList>(); //? Key is Main Object Primary Key, Value is children collection of main object's navigation property
while (reader.Read()) {
object keyId;
var item = ReadItem(reader, mainObjectInfo, includeon, out keyId);
if (keyId == null) {
Log.TraceEvent(TraceEventType.Error, $"Can't get key id from item with info {info.EntityType}, {includeon.Attribute.TargetPath} (used on entity {mainObjectInfo.EntityType}");
break;
}
IList collection;
if (!children.TryGetValue(keyId, out collection)) {
collection = (IList) Activator.CreateInstance(includeon.TargetCollectionType);
children.Add(keyId, collection);
}
collection.Add(item);
}
var index = tableIndex;
Parallel.ForEach(children,
child => {
object mainObject;
if (!mainObjects.TryGetValue(child.Key, out mainObject)) {
Log.TraceEvent(TraceEventType.Warning,
$"In result set #{index} finded data row of type {info.EntityType}, that doesn't has owner object in result set #1.\nOwner Id is {child.Key}.\nTarget path is '{includeon.Attribute.TargetPath}'.");
return;
}
if (!mainObject.TrySet(includeon.Attribute.TargetPath, child.Value))
Log.TraceEvent(TraceEventType.Warning,
$"Can't set property {includeon.Attribute.TargetPath} from '{mainObjectInfo.EntityType.FullName}' context.\nTarget path specified for child item {info.EntityType} in result set #{index}.");
if (string.IsNullOrWhiteSpace(includeon.OwnerNavigationReferenceName))
return;
foreach (var item in child.Value) {
if (!item.TrySet(includeon.OwnerNavigationReferenceName, mainObject))
Log.TraceEvent(TraceEventType.Warning,
$"Can't set property {includeon.OwnerNavigationReferenceName} from '{info.EntityType}' context. This should be reference to owner object ({mainObject})");
}
});
}
}
foreach (var item in mainObjects.Values)
yield return item;
}
}
}
finally {
connection.Close();
connection.Dispose();
}
}
/// <summary>
/// Returns one single entity, by reading it's data from <paramref name="reader"/>.
/// It uses <paramref name="includeon"/> if it was specified, otherwise - it uses <paramref name="mainEntityInfo"/>.
/// It also return identifier of entity in <paramref name="keyId"/> outer parameter.
/// </summary>
/// <param name="reader">Reader contained entities data.</param>
/// <param name="mainEntityInfo">Info about entity. Used if <paramref name="includeon"/> is not specified (equals to null).</param>
/// <param name="includeon">Info about includeon. Can be unspecified. See <see cref="IncludeChildrenAttribute"/> for more details.</param>
/// <param name="keyId">
/// Identifier of returned entity.
/// If <paramref name="includeon"/> parameter unspecified, or represents single field includeon - <paramref name="keyId"/> will contain primary key of returned entity.
/// If <paramref name="includeon"/> specified and represents sum-collection of main entity (<see cref="IIncludeon.IsCollection"/>)
/// - <paramref name="keyId"/> will contain key primary key of main entity (not the key of returned one).
/// </param>
/// <returns>Main entity (when <paramref name="includeon"/> unspecified) or entity described by <paramref name="includeon"/>.</returns>
protected virtual object ReadItem(DbDataReader reader, IAdoEntityInfo mainEntityInfo, [CanBeNull] Includeon includeon, out object keyId) {
var entityType = includeon?.Info.EntityType ?? mainEntityInfo.EntityType;
var item = Activator.CreateInstance(entityType);
keyId = null;
var isKey = includeon == null
? IsPrimaryKey
: includeon.IsCollection
? (Func<string, IAdoEntityInfo, Includeon, bool>) IsKeyOfMainEntityInForeign
: IsPrimaryKey;
var columns = includeon?.Info.ReaderColumns ?? mainEntityInfo.ReaderColumns;
for (var i = 0; i < columns.Length; i++) {
var name = columns[i];
var value = reader.GetValue(i);
if (value == null || value.GetType().FullName == "System.DBNull")
continue;
if (isKey(name, mainEntityInfo, includeon))
keyId = value;
if (!item.TrySet(name, value))
Log.TraceEvent(TraceEventType.Warning, $"Can't set property {name} from '{entityType.FullName}' context.");
}
return item;
}
/// <summary>
/// Checks, is property of entity represents it's primary key.
/// </summary>
protected abstract bool IsPrimaryKey([NotNull] string propertyName, [NotNull] IAdoEntityInfo mainEntityInfo, [CanBeNull] Includeon includeon);
/// <summary>
/// Checks, is property represend foreign key to main entity from the included.
/// </summary>
protected virtual bool IsKeyOfMainEntityInForeign([NotNull] string propertyName, [NotNull] IAdoEntityInfo mainEntityInfo, [NotNull] Includeon includeon) {
return propertyName == includeon.ForeignKeyFromCurrentEntityToMain;
}
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using System;
using System.Collections.Generic;
using PlayFab.SharedModels;
namespace PlayFab.EconomyModels
{
[Serializable]
public class CatalogAlternateId : PlayFabBaseModel
{
/// <summary>
/// Type of the alternate ID.
/// </summary>
public string Type;
/// <summary>
/// Value of the alternate ID.
/// </summary>
public string Value;
}
[Serializable]
public class CatalogConfig : PlayFabBaseModel
{
/// <summary>
/// A list of player entity keys that will have admin permissions.
/// </summary>
public List<EntityKey> AdminEntities;
/// <summary>
/// A list of display properties to index.
/// </summary>
public List<DisplayPropertyIndexInfo> DisplayPropertyIndexInfos;
/// <summary>
/// The set of configuration that only applies to Files.
/// </summary>
public FileConfig File;
/// <summary>
/// The set of configuration that only applies to Images.
/// </summary>
public ImageConfig Image;
/// <summary>
/// Flag defining whether catalog is enabled.
/// </summary>
public bool IsCatalogEnabled;
/// <summary>
/// A set of player entity keys that are allowed to review content.
/// </summary>
public List<EntityKey> ReviewerEntities;
/// <summary>
/// The set of configuration that only applies to user generated contents.
/// </summary>
public UserGeneratedContentSpecificConfig UserGeneratedContent;
}
[Serializable]
public class CatalogItem : PlayFabBaseModel
{
/// <summary>
/// The alternate IDs associated with this item.
/// </summary>
public List<CatalogAlternateId> AlternateIds;
/// <summary>
/// The set of contents associated with this item.
/// </summary>
public List<Content> Contents;
/// <summary>
/// The client-defined type of the item.
/// </summary>
public string ContentType;
/// <summary>
/// The date and time when this item was created.
/// </summary>
public DateTime? CreationDate;
/// <summary>
/// The ID of the creator of this catalog item.
/// </summary>
public EntityKey CreatorEntity;
/// <summary>
/// A dictionary of localized descriptions. Key is language code and localized string is the value. The neutral locale is
/// required.
/// </summary>
public Dictionary<string,string> Description;
/// <summary>
/// Game specific properties for display purposes. This is an arbitrary JSON blob.
/// </summary>
public object DisplayProperties;
/// <summary>
/// The user provided version of the item for display purposes.
/// </summary>
public string DisplayVersion;
/// <summary>
/// The date of when the item will cease to be available. If not provided then the product will be available indefinitely.
/// </summary>
public DateTime? EndDate;
/// <summary>
/// The current ETag value that can be used for optimistic concurrency in the If-None-Match header.
/// </summary>
public string ETag;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
/// <summary>
/// The images associated with this item. Images can be thumbnails or screenshots.
/// </summary>
public List<Image> Images;
/// <summary>
/// Indicates if the item is hidden.
/// </summary>
public bool? IsHidden;
/// <summary>
/// A dictionary of localized keywords. Key is language code and localized list of keywords is the value.
/// </summary>
public Dictionary<string,KeywordSet> Keywords;
/// <summary>
/// The date and time this item was last updated.
/// </summary>
public DateTime? LastModifiedDate;
/// <summary>
/// The moderation state for this item.
/// </summary>
public ModerationState Moderation;
/// <summary>
/// Rating summary for this item.
/// </summary>
public Rating Rating;
/// <summary>
/// The date of when the item will be available. If not provided then the product will appear immediately.
/// </summary>
public DateTime? StartDate;
/// <summary>
/// The list of tags that are associated with this item.
/// </summary>
public List<string> Tags;
/// <summary>
/// A dictionary of localized titles. Key is language code and localized string is the value. The neutral locale is
/// required.
/// </summary>
public Dictionary<string,string> Title;
/// <summary>
/// The high-level type of the item.
/// </summary>
public string Type;
}
public enum ConcernCategory
{
None,
OffensiveContent,
ChildExploitation,
MalwareOrVirus,
PrivacyConcerns,
MisleadingApp,
PoorPerformance,
ReviewResponse,
SpamAdvertising,
Profanity
}
[Serializable]
public class Content : PlayFabBaseModel
{
/// <summary>
/// The content unique ID.
/// </summary>
public string Id;
/// <summary>
/// The maximum client version that this content is compatible with.
/// </summary>
public string MaxClientVersion;
/// <summary>
/// The minimum client version that this content is compatible with.
/// </summary>
public string MinClientVersion;
/// <summary>
/// The list of tags that are associated with this content.
/// </summary>
public List<string> Tags;
/// <summary>
/// The client-defined type of the content.
/// </summary>
public string Type;
/// <summary>
/// The Azure CDN URL for retrieval of the catalog item binary content.
/// </summary>
public string Url;
}
/// <summary>
/// The item will not be published to the public catalog until the PublishItem API is called for the item.
/// </summary>
[Serializable]
public class CreateDraftItemRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Metadata describing the new catalog item to be created.
/// </summary>
public CatalogItem Item;
/// <summary>
/// Whether the item should be published immediately.
/// </summary>
public bool Publish;
}
[Serializable]
public class CreateDraftItemResponse : PlayFabResultCommon
{
/// <summary>
/// Updated metadata describing the catalog item just created.
/// </summary>
public CatalogItem Item;
}
/// <summary>
/// Upload URLs point to Azure Blobs; clients must follow the Microsoft Azure Storage Blob Service REST API pattern for
/// uploading content. The response contains upload URLs and IDs for each file. The IDs and URLs returned must be added to
/// the item metadata and committed using the CreateDraftItem or UpdateDraftItem Item APIs.
/// </summary>
[Serializable]
public class CreateUploadUrlsRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Description of the files to be uploaded by the client.
/// </summary>
public List<UploadInfo> Files;
}
[Serializable]
public class CreateUploadUrlsResponse : PlayFabResultCommon
{
/// <summary>
/// List of URLs metadata for the files to be uploaded by the client.
/// </summary>
public List<UploadUrlMetadata> UploadUrls;
}
[Serializable]
public class DeleteEntityItemReviewsRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
}
[Serializable]
public class DeleteEntityItemReviewsResponse : PlayFabResultCommon
{
}
[Serializable]
public class DeleteItemRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
}
[Serializable]
public class DeleteItemResponse : PlayFabResultCommon
{
}
[Serializable]
public class DisplayPropertyIndexInfo : PlayFabBaseModel
{
/// <summary>
/// The property name in the 'DisplayProperties' property to be indexed.
/// </summary>
public string Name;
/// <summary>
/// The type of the property to be indexed.
/// </summary>
public DisplayPropertyType? Type;
}
public enum DisplayPropertyType
{
None,
QueryDateTime,
QueryDouble,
QueryString,
SearchString
}
/// <summary>
/// Combined entity type and ID structure which uniquely identifies a single entity.
/// </summary>
[Serializable]
public class EntityKey : PlayFabBaseModel
{
/// <summary>
/// Unique ID of the entity.
/// </summary>
public string Id;
/// <summary>
/// Entity type. See https://docs.microsoft.com/gaming/playfab/features/data/entities/available-built-in-entity-types
/// </summary>
public string Type;
}
[Serializable]
public class FileConfig : PlayFabBaseModel
{
/// <summary>
/// The set of content types that will be used for validation.
/// </summary>
public List<string> ContentTypes;
/// <summary>
/// The set of tags that will be used for validation.
/// </summary>
public List<string> Tags;
}
[Serializable]
public class GetCatalogConfigRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
}
[Serializable]
public class GetCatalogConfigResponse : PlayFabResultCommon
{
/// <summary>
/// The catalog configuration.
/// </summary>
public CatalogConfig Config;
}
[Serializable]
public class GetDraftItemRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// Whether to fetch metadata of the scan status.
/// </summary>
public bool? ExpandScanningStatus;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
}
[Serializable]
public class GetDraftItemResponse : PlayFabResultCommon
{
/// <summary>
/// Full metadata of the catalog item requested.
/// </summary>
public CatalogItem Item;
}
[Serializable]
public class GetDraftItemsRequest : PlayFabRequestCommon
{
/// <summary>
/// List of item alternate IDs.
/// </summary>
public List<CatalogAlternateId> AlternateIds;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// List of Item Ids.
/// </summary>
public List<string> Ids;
}
[Serializable]
public class GetDraftItemsResponse : PlayFabResultCommon
{
/// <summary>
/// An opaque token used to retrieve the next page of items, if any are available.
/// </summary>
public string ContinuationToken;
/// <summary>
/// A set of items created by the entity.
/// </summary>
public List<CatalogItem> Items;
}
[Serializable]
public class GetEntityDraftItemsRequest : PlayFabRequestCommon
{
/// <summary>
/// An opaque token used to retrieve the next page of items created by the caller, if any are available. Should be null on
/// initial request.
/// </summary>
public string ContinuationToken;
/// <summary>
/// Number of items to retrieve. Maximum page size is 10.
/// </summary>
public int Count;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
}
[Serializable]
public class GetEntityDraftItemsResponse : PlayFabResultCommon
{
/// <summary>
/// An opaque token used to retrieve the next page of items, if any are available.
/// </summary>
public string ContinuationToken;
/// <summary>
/// A set of items created by the entity.
/// </summary>
public List<CatalogItem> Items;
}
[Serializable]
public class GetEntityItemReviewRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
}
[Serializable]
public class GetEntityItemReviewResponse : PlayFabResultCommon
{
/// <summary>
/// The review the entity submitted for the requested item.
/// </summary>
public Review Review;
}
[Serializable]
public class GetItemModerationStateRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
}
[Serializable]
public class GetItemModerationStateResponse : PlayFabResultCommon
{
/// <summary>
/// The current moderation state for the requested item.
/// </summary>
public ModerationState State;
}
[Serializable]
public class GetItemPublishStatusRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
}
[Serializable]
public class GetItemPublishStatusResponse : PlayFabResultCommon
{
/// <summary>
/// Scan results for any items that failed content scans.
/// </summary>
public List<ScanResult> FailedScanResults;
/// <summary>
/// High level status of the published item.
/// </summary>
public PublishResult? Result;
/// <summary>
/// Descriptive message about the current status of the publish.
/// </summary>
public string StatusMessage;
}
[Serializable]
public class GetItemRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
}
/// <summary>
/// Get item result.
/// </summary>
[Serializable]
public class GetItemResponse : PlayFabResultCommon
{
/// <summary>
/// The item result.
/// </summary>
public CatalogItem Item;
}
[Serializable]
public class GetItemReviewsRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// An opaque token used to retrieve the next page of items, if any are available.
/// </summary>
public string ContinuationToken;
/// <summary>
/// Number of items to retrieve. Maximum page size is 200. If not specified, defaults to 10.
/// </summary>
public int Count;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
/// <summary>
/// An OData orderBy used to order the results of the query.
/// </summary>
public string OrderBy;
}
[Serializable]
public class GetItemReviewsResponse : PlayFabResultCommon
{
/// <summary>
/// An opaque token used to retrieve the next page of items, if any are available.
/// </summary>
public string ContinuationToken;
/// <summary>
/// The paginated set of results.
/// </summary>
public List<Review> Reviews;
}
[Serializable]
public class GetItemReviewSummaryRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
}
[Serializable]
public class GetItemReviewSummaryResponse : PlayFabResultCommon
{
/// <summary>
/// The least favorable review for this item.
/// </summary>
public Review LeastFavorableReview;
/// <summary>
/// The most favorable review for this item.
/// </summary>
public Review MostFavorableReview;
/// <summary>
/// The summary of ratings associated with this item.
/// </summary>
public Rating Rating;
/// <summary>
/// The total number of reviews associated with this item.
/// </summary>
public int ReviewsCount;
}
[Serializable]
public class GetItemsRequest : PlayFabRequestCommon
{
/// <summary>
/// List of item alternate IDs.
/// </summary>
public List<CatalogAlternateId> AlternateIds;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// List of Item Ids.
/// </summary>
public List<string> Ids;
}
[Serializable]
public class GetItemsResponse : PlayFabResultCommon
{
/// <summary>
/// Metadata of set of items.
/// </summary>
public List<CatalogItem> Items;
}
public enum HelpfulnessVote
{
None,
UnHelpful,
Helpful
}
[Serializable]
public class Image : PlayFabBaseModel
{
/// <summary>
/// The image unique ID.
/// </summary>
public string Id;
/// <summary>
/// The client-defined tag associated with this image.
/// </summary>
public string Tag;
/// <summary>
/// The client-defined type of this image.
/// </summary>
public string Type;
/// <summary>
/// The URL for retrieval of the image.
/// </summary>
public string Url;
}
[Serializable]
public class ImageConfig : PlayFabBaseModel
{
/// <summary>
/// The set of tags that will be used for validation.
/// </summary>
public List<string> Tags;
}
[Serializable]
public class KeywordSet : PlayFabBaseModel
{
/// <summary>
/// A list of localized keywords.
/// </summary>
public List<string> Values;
}
[Serializable]
public class ModerationState : PlayFabBaseModel
{
/// <summary>
/// The date and time this moderation state was last updated.
/// </summary>
public DateTime? LastModifiedDate;
/// <summary>
/// The current stated reason for the associated item being moderated.
/// </summary>
public string Reason;
/// <summary>
/// The current moderation status for the associated item.
/// </summary>
public ModerationStatus? Status;
}
public enum ModerationStatus
{
Unknown,
AwaitingModeration,
Approved,
Rejected
}
/// <summary>
/// The call kicks off a workflow to publish the item to the public catalog. The Publish Status API should be used to
/// monitor the publish job.
/// </summary>
[Serializable]
public class PublishDraftItemRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// ETag of the catalog item to published from the working catalog to the public catalog. Used for optimistic concurrency.
/// If the provided ETag does not match the ETag in the current working catalog, the request will be rejected. If not
/// provided, the current version of the document in the working catalog will be published.
/// </summary>
public string ETag;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
}
[Serializable]
public class PublishDraftItemResponse : PlayFabResultCommon
{
}
public enum PublishResult
{
Unknown,
Pending,
Succeeded,
Failed,
Canceled
}
[Serializable]
public class Rating : PlayFabBaseModel
{
/// <summary>
/// The average rating for this item.
/// </summary>
public float? Average;
/// <summary>
/// The total count of 1 star ratings for this item.
/// </summary>
public int? Count1Star;
/// <summary>
/// The total count of 2 star ratings for this item.
/// </summary>
public int? Count2Star;
/// <summary>
/// The total count of 3 star ratings for this item.
/// </summary>
public int? Count3Star;
/// <summary>
/// The total count of 4 star ratings for this item.
/// </summary>
public int? Count4Star;
/// <summary>
/// The total count of 5 star ratings for this item.
/// </summary>
public int? Count5Star;
/// <summary>
/// The total count of ratings for this item.
/// </summary>
public int? TotalCount;
}
[Serializable]
public class ReportItemRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// Category of concern for this report.
/// </summary>
public ConcernCategory? ConcernCategory;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
/// <summary>
/// The string reason for this report.
/// </summary>
public string Reason;
}
[Serializable]
public class ReportItemResponse : PlayFabResultCommon
{
}
/// <summary>
/// Submit a report for an inappropriate review, allowing the submitting user to specify their concern.
/// </summary>
[Serializable]
public class ReportItemReviewRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID of the item associated with the review.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The reason this review is being reported.
/// </summary>
public ConcernCategory? ConcernCategory;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The string ID of the item associated with the review.
/// </summary>
public string ItemId;
/// <summary>
/// The string reason for this report.
/// </summary>
public string Reason;
/// <summary>
/// The ID of the review to submit a report for.
/// </summary>
public string ReviewId;
}
[Serializable]
public class ReportItemReviewResponse : PlayFabResultCommon
{
}
[Serializable]
public class Review : PlayFabBaseModel
{
/// <summary>
/// The number of negative helpfulness votes for this review.
/// </summary>
public int HelpfulNegative;
/// <summary>
/// Total number of helpfulness votes for this review.
/// </summary>
public int HelpfulnessVotes;
/// <summary>
/// The number of positive helpfulness votes for this review.
/// </summary>
public int HelpfulPositive;
/// <summary>
/// Indicates whether the review author has the item installed.
/// </summary>
public bool IsInstalled;
/// <summary>
/// The ID of the item being reviewed.
/// </summary>
public string ItemId;
/// <summary>
/// The version of the item being reviewed.
/// </summary>
public string ItemVersion;
/// <summary>
/// The locale for which this review was submitted in.
/// </summary>
public string Locale;
/// <summary>
/// Star rating associated with this review.
/// </summary>
public int Rating;
/// <summary>
/// The ID of the author of the review.
/// </summary>
public string ReviewerId;
/// <summary>
/// The ID of the review.
/// </summary>
public string ReviewId;
/// <summary>
/// The full text of this review.
/// </summary>
public string ReviewText;
/// <summary>
/// The date and time this review was last submitted.
/// </summary>
public DateTime Submitted;
/// <summary>
/// The title of this review.
/// </summary>
public string Title;
}
[Serializable]
public class ReviewItemRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
/// <summary>
/// The review to submit.
/// </summary>
public Review Review;
}
[Serializable]
public class ReviewItemResponse : PlayFabResultCommon
{
}
[Serializable]
public class ReviewTakedown : PlayFabBaseModel
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The ID of the item associated with the review to take down.
/// </summary>
public string ItemId;
/// <summary>
/// The ID of the review to take down.
/// </summary>
public string ReviewId;
}
[Serializable]
public class ScanResult : PlayFabBaseModel
{
/// <summary>
/// The URL of the item which failed the scan.
/// </summary>
public string Url;
}
[Serializable]
public class SearchItemsRequest : PlayFabRequestCommon
{
/// <summary>
/// An opaque token used to retrieve the next page of items, if any are available.
/// </summary>
public string ContinuationToken;
/// <summary>
/// Number of items to retrieve. Maximum page size is 225. Default value is 10.
/// </summary>
public int Count;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// An OData filter used to refine the search query.
/// </summary>
public string Filter;
/// <summary>
/// An OData orderBy used to order the results of the search query.
/// </summary>
public string OrderBy;
/// <summary>
/// The text to search for.
/// </summary>
public string Search;
/// <summary>
/// An OData select query option used to augment the search results. If not defined, the default search result metadata will
/// be returned.
/// </summary>
public string Select;
}
[Serializable]
public class SearchItemsResponse : PlayFabResultCommon
{
/// <summary>
/// An opaque token used to retrieve the next page of items, if any are available.
/// </summary>
public string ContinuationToken;
/// <summary>
/// The paginated set of results for the search query.
/// </summary>
public List<CatalogItem> Items;
}
[Serializable]
public class SetItemModerationStateRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID associated with this item.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The unique ID of the item.
/// </summary>
public string Id;
/// <summary>
/// The reason for the moderation state change for the associated item.
/// </summary>
public string Reason;
/// <summary>
/// The status to set for the associated item.
/// </summary>
public ModerationStatus? Status;
}
[Serializable]
public class SetItemModerationStateResponse : PlayFabResultCommon
{
}
[Serializable]
public class SubmitItemReviewVoteRequest : PlayFabRequestCommon
{
/// <summary>
/// An alternate ID of the item associated with the review.
/// </summary>
public CatalogAlternateId AlternateId;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The string ID of the item associated with the review.
/// </summary>
public string ItemId;
/// <summary>
/// The ID of the review to submit a helpfulness vote for.
/// </summary>
public string ReviewId;
/// <summary>
/// The helpfulness vote of the review.
/// </summary>
public HelpfulnessVote? Vote;
}
[Serializable]
public class SubmitItemReviewVoteResponse : PlayFabResultCommon
{
}
/// <summary>
/// Submit a request to takedown one or more reviews, removing them from public view. Authors will still be able to see
/// their reviews after being taken down.
/// </summary>
[Serializable]
public class TakedownItemReviewsRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The set of reviews to take down.
/// </summary>
public List<ReviewTakedown> Reviews;
}
[Serializable]
public class TakedownItemReviewsResponse : PlayFabResultCommon
{
}
[Serializable]
public class UpdateCatalogConfigRequest : PlayFabRequestCommon
{
/// <summary>
/// The updated catalog configuration.
/// </summary>
public CatalogConfig Config;
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
}
[Serializable]
public class UpdateCatalogConfigResponse : PlayFabResultCommon
{
}
[Serializable]
public class UpdateDraftItemRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Updated metadata describing the catalog item to be updated.
/// </summary>
public CatalogItem Item;
/// <summary>
/// Whether the item should be published immediately.
/// </summary>
public bool Publish;
}
[Serializable]
public class UpdateDraftItemResponse : PlayFabResultCommon
{
/// <summary>
/// Updated metadata describing the catalog item just updated.
/// </summary>
public CatalogItem Item;
}
[Serializable]
public class UploadInfo : PlayFabBaseModel
{
/// <summary>
/// Name of the file to be uploaded.
/// </summary>
public string FileName;
}
[Serializable]
public class UploadUrlMetadata : PlayFabBaseModel
{
/// <summary>
/// Name of the file for which this upload URL was requested.
/// </summary>
public string FileName;
/// <summary>
/// Unique ID for the binary content to be uploaded to the target URL.
/// </summary>
public string Id;
/// <summary>
/// URL for the binary content to be uploaded to.
/// </summary>
public string Url;
}
[Serializable]
public class UserGeneratedContentSpecificConfig : PlayFabBaseModel
{
/// <summary>
/// The set of content types that will be used for validation.
/// </summary>
public List<string> ContentTypes;
/// <summary>
/// The set of tags that will be used for validation.
/// </summary>
public List<string> Tags;
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using Excel.Core;
using Excel.Log;
using ExcelDataReader.Portable.Core;
using ExcelDataReader.Portable.Core.BinaryFormat;
namespace Excel
{
/// <summary>
/// ExcelDataReader Class
/// </summary>
public class ExcelBinaryReader : IExcelDataReader
{
#region Members
private Stream m_file;
private XlsHeader m_hdr;
private List<XlsWorksheet> m_sheets;
private XlsBiffStream m_stream;
private DataSet m_workbookData;
private XlsWorkbookGlobals m_globals;
private ushort m_version;
private bool m_ConvertOADate;
private Encoding m_encoding;
private bool m_isValid;
private bool m_isClosed;
private readonly Encoding m_Default_Encoding = Encoding.UTF8;
private string m_exceptionMessage;
private object[] m_cellsValues;
private uint[] m_dbCellAddrs;
private int m_dbCellAddrsIndex;
private bool m_canRead;
private int m_SheetIndex;
private int m_depth;
private int m_cellOffset;
private int m_maxCol;
private int m_maxRow;
private bool m_noIndex;
private XlsBiffRow m_currentRowRecord;
private readonly ReadOption m_ReadOption = ReadOption.Strict;
private bool m_IsFirstRead;
private bool _isFirstRowAsColumnNames;
private const string WORKBOOK = "Workbook";
private const string BOOK = "Book";
private const string COLUMN = "Column";
private bool disposed;
#endregion
internal ExcelBinaryReader()
{
m_encoding = m_Default_Encoding;
m_version = 0x0600;
m_isValid = true;
m_SheetIndex = -1;
m_IsFirstRead = true;
}
internal ExcelBinaryReader(ReadOption readOption) : this()
{
m_ReadOption = readOption;
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this.disposed)
{
if (disposing)
{
if (m_workbookData != null) m_workbookData.Dispose();
if (m_sheets != null) m_sheets.Clear();
}
m_workbookData = null;
m_sheets = null;
m_stream = null;
m_globals = null;
m_encoding = null;
m_hdr = null;
disposed = true;
}
}
~ExcelBinaryReader()
{
Dispose(false);
}
#endregion
#region Private methods
private int findFirstDataCellOffset(int startOffset)
{
//seek to the first dbcell record
var record = m_stream.ReadAt(startOffset);
while (!(record is XlsBiffDbCell))
{
if (m_stream.Position >= m_stream.Size)
return -1;
if (record is XlsBiffEOF)
return -1;
record = m_stream.Read();
}
XlsBiffDbCell startCell = (XlsBiffDbCell)record;
XlsBiffRow row = null;
int offs = startCell.RowAddress;
do
{
row = m_stream.ReadAt(offs) as XlsBiffRow;
if (row == null) break;
offs += row.Size;
} while (null != row);
return offs;
}
private void readWorkBookGlobals()
{
//Read Header
try
{
m_hdr = XlsHeader.ReadHeader(m_file);
}
catch (Exceptions.HeaderException ex)
{
fail(ex.Message);
return;
}
catch (FormatException ex)
{
fail(ex.Message);
return;
}
XlsRootDirectory dir = new XlsRootDirectory(m_hdr);
XlsDirectoryEntry workbookEntry = dir.FindEntry(WORKBOOK) ?? dir.FindEntry(BOOK);
if (workbookEntry == null)
{ fail(Errors.ErrorStreamWorkbookNotFound); return; }
if (workbookEntry.EntryType != STGTY.STGTY_STREAM)
{ fail(Errors.ErrorWorkbookIsNotStream); return; }
m_stream = new XlsBiffStream(m_hdr, workbookEntry.StreamFirstSector, workbookEntry.IsEntryMiniStream, dir, this);
m_globals = new XlsWorkbookGlobals();
m_stream.Seek(0, SeekOrigin.Begin);
XlsBiffRecord rec = m_stream.Read();
XlsBiffBOF bof = rec as XlsBiffBOF;
if (bof == null || bof.Type != BIFFTYPE.WorkbookGlobals)
{ fail(Errors.ErrorWorkbookGlobalsInvalidData); return; }
bool sst = false;
m_version = bof.Version;
m_sheets = new List<XlsWorksheet>();
while (null != (rec = m_stream.Read()))
{
switch (rec.ID)
{
case BIFFRECORDTYPE.INTERFACEHDR:
m_globals.InterfaceHdr = (XlsBiffInterfaceHdr)rec;
break;
case BIFFRECORDTYPE.BOUNDSHEET:
XlsBiffBoundSheet sheet = (XlsBiffBoundSheet)rec;
if (sheet.Type != XlsBiffBoundSheet.SheetType.Worksheet) break;
sheet.IsV8 = isV8();
//sheet.UseEncoding = m_encoding;
LogManager.Log(this).Debug("BOUNDSHEET IsV8={0}", sheet.IsV8);
m_sheets.Add(new XlsWorksheet(m_globals.Sheets.Count, sheet));
m_globals.Sheets.Add(sheet);
break;
case BIFFRECORDTYPE.MMS:
m_globals.MMS = rec;
break;
case BIFFRECORDTYPE.COUNTRY:
m_globals.Country = rec;
break;
case BIFFRECORDTYPE.CODEPAGE:
m_globals.CodePage = (XlsBiffSimpleValueRecord)rec;
try
{
//workaround: 1200 should actually be UTF-8 for some reason
if (m_globals.CodePage.Value == 1200)
m_encoding = Encoding.GetEncoding(65001);
else
m_encoding = Encoding.GetEncoding(m_globals.CodePage.Value);
}
catch (ArgumentException)
{
// Warning - Password protection
// TODO: Attach to ILog
}
break;
case BIFFRECORDTYPE.FONT:
case BIFFRECORDTYPE.FONT_V34:
m_globals.Fonts.Add(rec);
break;
case BIFFRECORDTYPE.FORMAT_V23:
{
var fmt = (XlsBiffFormatString) rec;
//fmt.UseEncoding = m_encoding;
m_globals.Formats.Add((ushort) m_globals.Formats.Count, fmt);
}
break;
case BIFFRECORDTYPE.FORMAT:
{
var fmt = (XlsBiffFormatString) rec;
m_globals.Formats.Add(fmt.Index, fmt);
}
break;
case BIFFRECORDTYPE.XF:
case BIFFRECORDTYPE.XF_V4:
case BIFFRECORDTYPE.XF_V3:
case BIFFRECORDTYPE.XF_V2:
m_globals.ExtendedFormats.Add(rec);
break;
case BIFFRECORDTYPE.SST:
m_globals.SST = (XlsBiffSST)rec;
sst = true;
break;
case BIFFRECORDTYPE.CONTINUE:
if (!sst) break;
XlsBiffContinue contSST = (XlsBiffContinue)rec;
m_globals.SST.Append(contSST);
break;
case BIFFRECORDTYPE.EXTSST:
m_globals.ExtSST = rec;
sst = false;
break;
case BIFFRECORDTYPE.PROTECT:
case BIFFRECORDTYPE.PASSWORD:
case BIFFRECORDTYPE.PROT4REVPASSWORD:
//IsProtected
break;
case BIFFRECORDTYPE.EOF:
if (m_globals.SST != null)
m_globals.SST.ReadStrings();
return;
default:
continue;
}
}
}
private bool readWorkSheetGlobals(XlsWorksheet sheet, out XlsBiffIndex idx, out XlsBiffRow row)
{
idx = null;
row = null;
m_stream.Seek((int)sheet.DataOffset, SeekOrigin.Begin);
XlsBiffBOF bof = m_stream.Read() as XlsBiffBOF;
if (bof == null || bof.Type != BIFFTYPE.Worksheet) return false;
//DumpBiffRecords();
XlsBiffRecord rec = m_stream.Read();
if (rec == null) return false;
if (rec is XlsBiffIndex)
{
idx = rec as XlsBiffIndex;
}
else if (rec is XlsBiffUncalced)
{
// Sometimes this come before the index...
idx = m_stream.Read() as XlsBiffIndex;
}
//if (null == idx)
//{
// // There is a record before the index! Chech his type and see the MS Biff Documentation
// return false;
//}
if (idx != null)
{
idx.IsV8 = isV8();
LogManager.Log(this).Debug("INDEX IsV8={0}", idx.IsV8);
}
XlsBiffRecord trec;
XlsBiffDimensions dims = null;
do
{
trec = m_stream.Read();
if (trec.ID == BIFFRECORDTYPE.DIMENSIONS)
{
dims = (XlsBiffDimensions)trec;
break;
}
} while (trec != null && trec.ID != BIFFRECORDTYPE.ROW);
//if we are already on row record then set that as the row, otherwise step forward till we get to a row record
if (trec.ID == BIFFRECORDTYPE.ROW)
row = (XlsBiffRow)trec;
XlsBiffRow rowRecord = null;
while (rowRecord == null)
{
if (m_stream.Position >= m_stream.Size)
break;
var thisRec = m_stream.Read();
LogManager.Log(this).Debug("finding rowRecord offset {0}, rec: {1}", thisRec.Offset, thisRec.ID);
if (thisRec is XlsBiffEOF)
break;
rowRecord = thisRec as XlsBiffRow;
}
if (rowRecord != null)
LogManager.Log(this).Debug("Got row {0}, rec: id={1},rowindex={2}, rowColumnStart={3}, rowColumnEnd={4}", rowRecord.Offset, rowRecord.ID, rowRecord.RowIndex, rowRecord.FirstDefinedColumn, rowRecord.LastDefinedColumn);
row = rowRecord;
if (dims != null) {
dims.IsV8 = isV8();
LogManager.Log(this).Debug("dims IsV8={0}", dims.IsV8);
m_maxCol = dims.LastColumn - 1;
//handle case where sheet reports last column is 1 but there are actually more
if (m_maxCol <= 0 && rowRecord != null)
{
m_maxCol = rowRecord.LastDefinedColumn;
}
m_maxRow = (int)dims.LastRow;
sheet.Dimensions = dims;
} else {
m_maxCol = 256;
m_maxRow = (int)idx.LastExistingRow;
}
if (idx != null && idx.LastExistingRow <= idx.FirstExistingRow)
{
return false;
}
else if (row == null)
{
return false;
}
m_depth = 0;
return true;
}
private void DumpBiffRecords()
{
XlsBiffRecord rec = null;
var startPos = m_stream.Position;
do
{
rec = m_stream.Read();
LogManager.Log(this).Debug(rec.ID.ToString());
} while (rec != null && m_stream.Position < m_stream.Size);
m_stream.Seek(startPos, SeekOrigin.Begin);
}
private bool readWorkSheetRow()
{
m_cellsValues = new object[m_maxCol];
while (m_cellOffset < m_stream.Size)
{
XlsBiffRecord rec = m_stream.ReadAt(m_cellOffset);
m_cellOffset += rec.Size;
if ((rec is XlsBiffDbCell) || (rec is XlsBiffMSODrawing)) { break; };//break;
if (rec is XlsBiffEOF) { return false; };
XlsBiffBlankCell cell = rec as XlsBiffBlankCell;
if ((null == cell) || (cell.ColumnIndex >= m_maxCol)) continue;
if (cell.RowIndex != m_depth) { m_cellOffset -= rec.Size; break; };
pushCellValue(cell);
}
m_depth++;
return m_depth < m_maxRow;
}
private DataTable readWholeWorkSheet(XlsWorksheet sheet)
{
XlsBiffIndex idx;
if (!readWorkSheetGlobals(sheet, out idx, out m_currentRowRecord)) return null;
DataTable table = new DataTable(sheet.Name);
bool triggerCreateColumns = true;
if (idx != null)
readWholeWorkSheetWithIndex(idx, triggerCreateColumns, table);
else
readWholeWorkSheetNoIndex(triggerCreateColumns, table);
table.EndLoadData();
return table;
}
//TODO: quite a bit of duplication with the noindex version
private void readWholeWorkSheetWithIndex(XlsBiffIndex idx, bool triggerCreateColumns, DataTable table)
{
m_dbCellAddrs = idx.DbCellAddresses;
for (int index = 0; index < m_dbCellAddrs.Length; index++)
{
if (m_depth == m_maxRow) break;
// init reading data
m_cellOffset = findFirstDataCellOffset((int) m_dbCellAddrs[index]);
if (m_cellOffset < 0)
return;
//DataTable columns
if (triggerCreateColumns)
{
if (_isFirstRowAsColumnNames && readWorkSheetRow() || (_isFirstRowAsColumnNames && m_maxRow == 1))
{
for (int i = 0; i < m_maxCol; i++)
{
if (m_cellsValues[i] != null && m_cellsValues[i].ToString().Length > 0)
Helpers.AddColumnHandleDuplicate(table, m_cellsValues[i].ToString());
else
Helpers.AddColumnHandleDuplicate(table, string.Concat(COLUMN, i));
}
}
else
{
for (int i = 0; i < m_maxCol; i++)
{
table.Columns.Add(null, typeof (Object));
}
}
triggerCreateColumns = false;
table.BeginLoadData();
}
while (readWorkSheetRow())
{
table.Rows.Add(m_cellsValues);
}
//add the row
if (m_depth > 0 && !(_isFirstRowAsColumnNames && m_maxRow == 1))
{
table.Rows.Add(m_cellsValues);
}
}
}
private void readWholeWorkSheetNoIndex(bool triggerCreateColumns, DataTable table)
{
while (Read())
{
if (m_depth == m_maxRow) break;
bool justAddedColumns = false;
//DataTable columns
if (triggerCreateColumns)
{
if (_isFirstRowAsColumnNames || (_isFirstRowAsColumnNames && m_maxRow == 1))
{
for (int i = 0; i < m_maxCol; i++)
{
if (m_cellsValues[i] != null && m_cellsValues[i].ToString().Length > 0)
Helpers.AddColumnHandleDuplicate(table, m_cellsValues[i].ToString());
else
Helpers.AddColumnHandleDuplicate(table, string.Concat(COLUMN, i));
}
justAddedColumns = true;
}
else
{
for (int i = 0; i < m_maxCol; i++)
{
table.Columns.Add(null, typeof(Object));
}
}
triggerCreateColumns = false;
table.BeginLoadData();
}
if (!justAddedColumns && m_depth > 0 && !(_isFirstRowAsColumnNames && m_maxRow == 1))
{
table.Rows.Add(m_cellsValues);
}
}
if (m_depth > 0 && !(_isFirstRowAsColumnNames && m_maxRow == 1))
{
table.Rows.Add(m_cellsValues);
}
}
private void pushCellValue(XlsBiffBlankCell cell)
{
double _dValue;
LogManager.Log(this).Debug("pushCellValue {0}", cell.ID);
switch (cell.ID)
{
case BIFFRECORDTYPE.BOOLERR:
if (cell.ReadByte(7) == 0)
m_cellsValues[cell.ColumnIndex] = cell.ReadByte(6) != 0;
break;
case BIFFRECORDTYPE.BOOLERR_OLD:
if (cell.ReadByte(8) == 0)
m_cellsValues[cell.ColumnIndex] = cell.ReadByte(7) != 0;
break;
case BIFFRECORDTYPE.INTEGER:
case BIFFRECORDTYPE.INTEGER_OLD:
m_cellsValues[cell.ColumnIndex] = ((XlsBiffIntegerCell)cell).Value;
break;
case BIFFRECORDTYPE.NUMBER:
case BIFFRECORDTYPE.NUMBER_OLD:
_dValue = ((XlsBiffNumberCell)cell).Value;
m_cellsValues[cell.ColumnIndex] = !ConvertOaDate ?
_dValue : tryConvertOADateTime(_dValue, cell.XFormat);
LogManager.Log(this).Debug("VALUE: {0}", _dValue);
break;
case BIFFRECORDTYPE.LABEL:
case BIFFRECORDTYPE.LABEL_OLD:
case BIFFRECORDTYPE.RSTRING:
m_cellsValues[cell.ColumnIndex] = ((XlsBiffLabelCell)cell).Value;
LogManager.Log(this).Debug("VALUE: {0}", m_cellsValues[cell.ColumnIndex]);
break;
case BIFFRECORDTYPE.LABELSST:
string tmp = m_globals.SST.GetString(((XlsBiffLabelSSTCell)cell).SSTIndex);
LogManager.Log(this).Debug("VALUE: {0}", tmp);
m_cellsValues[cell.ColumnIndex] = tmp;
break;
case BIFFRECORDTYPE.RK:
_dValue = ((XlsBiffRKCell)cell).Value;
m_cellsValues[cell.ColumnIndex] = !ConvertOaDate ?
_dValue : tryConvertOADateTime(_dValue, cell.XFormat);
LogManager.Log(this).Debug("VALUE: {0}", _dValue);
break;
case BIFFRECORDTYPE.MULRK:
XlsBiffMulRKCell _rkCell = (XlsBiffMulRKCell)cell;
for (ushort j = cell.ColumnIndex; j <= _rkCell.LastColumnIndex; j++)
{
_dValue = _rkCell.GetValue(j);
LogManager.Log(this).Debug("VALUE[{1}]: {0}", _dValue, j);
m_cellsValues[j] = !ConvertOaDate ? _dValue : tryConvertOADateTime(_dValue, _rkCell.GetXF(j));
}
break;
case BIFFRECORDTYPE.BLANK:
case BIFFRECORDTYPE.BLANK_OLD:
case BIFFRECORDTYPE.MULBLANK:
// Skip blank cells
break;
case BIFFRECORDTYPE.FORMULA:
case BIFFRECORDTYPE.FORMULA_OLD:
object _oValue = ((XlsBiffFormulaCell)cell).Value;
if (null != _oValue && _oValue is FORMULAERROR)
{
_oValue = null;
}
else
{
m_cellsValues[cell.ColumnIndex] = !ConvertOaDate ?
_oValue : tryConvertOADateTime(_oValue, (ushort)(cell.XFormat));//date time offset
}
break;
default:
break;
}
}
private bool moveToNextRecord()
{
//if sheet has no index
if (m_noIndex)
{
LogManager.Log(this).Debug("No index");
return moveToNextRecordNoIndex();
}
//if sheet has index
if (null == m_dbCellAddrs ||
m_dbCellAddrsIndex == m_dbCellAddrs.Length ||
m_depth == m_maxRow) return false;
m_canRead = readWorkSheetRow();
//read last row
if (!m_canRead && m_depth > 0) m_canRead = true;
if (!m_canRead && m_dbCellAddrsIndex < (m_dbCellAddrs.Length - 1))
{
m_dbCellAddrsIndex++;
m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]);
if (m_cellOffset < 0)
return false;
m_canRead = readWorkSheetRow();
}
return m_canRead;
}
private bool moveToNextRecordNoIndex()
{
//seek from current row record to start of cell data where that cell relates to the next row record
XlsBiffRow rowRecord = m_currentRowRecord;
if (rowRecord == null)
return false;
if (rowRecord.RowIndex < m_depth)
{
m_stream.Seek(rowRecord.Offset + rowRecord.Size, SeekOrigin.Begin);
do
{
if (m_stream.Position >= m_stream.Size)
return false;
var record = m_stream.Read();
if (record is XlsBiffEOF)
return false;
rowRecord = record as XlsBiffRow;
} while (rowRecord == null || rowRecord.RowIndex < m_depth);
}
m_currentRowRecord = rowRecord;
//m_depth = m_currentRowRecord.RowIndex;
//we have now found the row record for the new row, the we need to seek forward to the first cell record
XlsBiffBlankCell cell = null;
do
{
if (m_stream.Position >= m_stream.Size)
return false;
var record = m_stream.Read();
if (record is XlsBiffEOF)
return false;
if (record.IsCell)
{
var candidateCell = record as XlsBiffBlankCell;
if (candidateCell != null)
{
if (candidateCell.RowIndex == m_currentRowRecord.RowIndex)
cell = candidateCell;
}
}
} while (cell == null);
m_cellOffset = cell.Offset;
m_canRead = readWorkSheetRow();
//read last row
//if (!m_canRead && m_depth > 0) m_canRead = true;
//if (!m_canRead && m_dbCellAddrsIndex < (m_dbCellAddrs.Length - 1))
//{
// m_dbCellAddrsIndex++;
// m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]);
// m_canRead = readWorkSheetRow();
//}
return m_canRead;
}
private void initializeSheetRead()
{
if (m_SheetIndex == ResultsCount) return;
m_dbCellAddrs = null;
m_IsFirstRead = false;
if (m_SheetIndex == -1) m_SheetIndex = 0;
XlsBiffIndex idx;
if (!readWorkSheetGlobals(m_sheets[m_SheetIndex], out idx, out m_currentRowRecord))
{
//read next sheet
m_SheetIndex++;
initializeSheetRead();
return;
};
if (idx == null)
{
//no index, but should have the first row record
m_noIndex = true;
}
else
{
m_dbCellAddrs = idx.DbCellAddresses;
m_dbCellAddrsIndex = 0;
m_cellOffset = findFirstDataCellOffset((int)m_dbCellAddrs[m_dbCellAddrsIndex]);
if (m_cellOffset < 0)
{
fail("Badly formed binary file. Has INDEX but no DBCELL");
return;
}
}
}
private void fail(string message)
{
m_exceptionMessage = message;
m_isValid = false;
m_file.Close();
m_isClosed = true;
m_workbookData = null;
m_sheets = null;
m_stream = null;
m_globals = null;
m_encoding = null;
m_hdr = null;
}
private object tryConvertOADateTime(double value, ushort XFormat)
{
ushort format = 0;
if (XFormat >= 0 && XFormat < m_globals.ExtendedFormats.Count)
{
var rec = m_globals.ExtendedFormats[XFormat];
switch (rec.ID)
{
case BIFFRECORDTYPE.XF_V2:
format = (ushort) (rec.ReadByte(2) & 0x3F);
break;
case BIFFRECORDTYPE.XF_V3:
if ((rec.ReadByte(3) & 4) == 0)
return value;
format = rec.ReadByte(1);
break;
case BIFFRECORDTYPE.XF_V4:
if ((rec.ReadByte(5) & 4) == 0)
return value;
format = rec.ReadByte(1);
break;
default:
if ((rec.ReadByte(m_globals.Sheets[m_globals.Sheets.Count-1].IsV8 ? 9 : 7) & 4) == 0)
return value;
format = rec.ReadUInt16(2);
break;
}
}
else
{
format = XFormat;
}
switch (format)
{
// numeric built in formats
case 0: //"General";
case 1: //"0";
case 2: //"0.00";
case 3: //"#,##0";
case 4: //"#,##0.00";
case 5: //"\"$\"#,##0_);(\"$\"#,##0)";
case 6: //"\"$\"#,##0_);[Red](\"$\"#,##0)";
case 7: //"\"$\"#,##0.00_);(\"$\"#,##0.00)";
case 8: //"\"$\"#,##0.00_);[Red](\"$\"#,##0.00)";
case 9: //"0%";
case 10: //"0.00%";
case 11: //"0.00E+00";
case 12: //"# ?/?";
case 13: //"# ??/??";
case 0x30:// "##0.0E+0";
case 0x25:// "_(#,##0_);(#,##0)";
case 0x26:// "_(#,##0_);[Red](#,##0)";
case 0x27:// "_(#,##0.00_);(#,##0.00)";
case 40:// "_(#,##0.00_);[Red](#,##0.00)";
case 0x29:// "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)";
case 0x2a:// "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)";
case 0x2b:// "_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)";
case 0x2c:// "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)";
return value;
// date formats
case 14: //this.GetDefaultDateFormat();
case 15: //"D-MM-YY";
case 0x10: // "D-MMM";
case 0x11: // "MMM-YY";
case 0x12: // "h:mm AM/PM";
case 0x13: // "h:mm:ss AM/PM";
case 20: // "h:mm";
case 0x15: // "h:mm:ss";
case 0x16: // string.Format("{0} {1}", this.GetDefaultDateFormat(), this.GetDefaultTimeFormat());
case 0x2d: // "mm:ss";
case 0x2e: // "[h]:mm:ss";
case 0x2f: // "mm:ss.0";
return Helpers.ConvertFromOATime(value);
case 0x31:// "@";
return value.ToString();
default:
XlsBiffFormatString fmtString;
if (m_globals.Formats.TryGetValue(format, out fmtString) )
{
var fmt = fmtString.Value;
var formatReader = new FormatReader() {FormatString = fmt};
if (formatReader.IsDateFormatString())
return Helpers.ConvertFromOATime(value);
}
return value;
}
}
private object tryConvertOADateTime(object value, ushort XFormat)
{
double _dValue;
if (double.TryParse(value.ToString(), out _dValue))
return tryConvertOADateTime(_dValue, XFormat);
return value;
}
public bool isV8()
{
return m_version >= 0x600;
}
#endregion
#region IExcelDataReader Members
public void Initialize(Stream fileStream)
{
m_file = fileStream;
readWorkBookGlobals();
// set the sheet index to the index of the first sheet.. this is so that properties such as Name which use m_sheetIndex reflect the first sheet in the file without having to perform a read() operation
m_SheetIndex = 0;
}
public DataSet AsDataSet()
{
return AsDataSet(false);
}
public DataSet AsDataSet(bool convertOADateTime)
{
if (!m_isValid) return null;
if (m_isClosed) return m_workbookData;
ConvertOaDate = convertOADateTime;
m_workbookData = new DataSet();
for (int index = 0; index < ResultsCount; index++)
{
DataTable table = readWholeWorkSheet(m_sheets[index]);
if (null != table)
{
table.ExtendedProperties.Add("visiblestate", m_sheets[index].VisibleState);
m_workbookData.Tables.Add(table);
}
}
m_file.Close();
m_isClosed = true;
m_workbookData.AcceptChanges();
Helpers.FixDataTypes(m_workbookData);
return m_workbookData;
}
public string ExceptionMessage
{
get { return m_exceptionMessage; }
}
public string Name
{
get
{
if (null != m_sheets && m_sheets.Count > 0)
return m_sheets[m_SheetIndex].Name;
else
return null;
}
}
public string VisibleState
{
get
{
if (null != m_sheets && m_sheets.Count > 0)
return m_sheets[m_SheetIndex].VisibleState;
else
return null;
}
}
public bool IsValid
{
get { return m_isValid; }
}
public void Close()
{
m_file.Close();
m_isClosed = true;
}
public int Depth
{
get { return m_depth; }
}
public int ResultsCount
{
get { return m_globals.Sheets.Count; }
}
public bool IsClosed
{
get { return m_isClosed; }
}
public bool NextResult()
{
if (m_SheetIndex >= (this.ResultsCount - 1)) return false;
m_SheetIndex++;
m_IsFirstRead = true;
return true;
}
public bool Read()
{
if (!m_isValid) return false;
if (m_IsFirstRead) initializeSheetRead();
return moveToNextRecord();
}
public int FieldCount
{
get { return m_maxCol; }
}
public bool GetBoolean(int i)
{
if (IsDBNull(i)) return false;
return Boolean.Parse(m_cellsValues[i].ToString());
}
public DateTime GetDateTime(int i)
{
if (IsDBNull(i)) return DateTime.MinValue;
// requested change: 3
object val = m_cellsValues[i];
if (val is DateTime)
{
// if the value is already a datetime.. return it without further conversion
return (DateTime)val;
}
// otherwise proceed with conversion attempts
string valString = val.ToString();
double dVal;
try
{
dVal = double.Parse(valString);
}
catch (FormatException)
{
return DateTime.Parse(valString);
}
return DateTime.FromOADate(dVal);
}
public decimal GetDecimal(int i)
{
if (IsDBNull(i)) return decimal.MinValue;
return decimal.Parse(m_cellsValues[i].ToString());
}
public double GetDouble(int i)
{
if (IsDBNull(i)) return double.MinValue;
return double.Parse(m_cellsValues[i].ToString());
}
public float GetFloat(int i)
{
if (IsDBNull(i)) return float.MinValue;
return float.Parse(m_cellsValues[i].ToString());
}
public short GetInt16(int i)
{
if (IsDBNull(i)) return short.MinValue;
return short.Parse(m_cellsValues[i].ToString());
}
public int GetInt32(int i)
{
if (IsDBNull(i)) return int.MinValue;
return int.Parse(m_cellsValues[i].ToString());
}
public long GetInt64(int i)
{
if (IsDBNull(i)) return long.MinValue;
return long.Parse(m_cellsValues[i].ToString());
}
public string GetString(int i)
{
if (IsDBNull(i)) return null;
return m_cellsValues[i].ToString();
}
public object GetValue(int i)
{
return m_cellsValues[i];
}
public bool IsDBNull(int i)
{
return (null == m_cellsValues[i]) || (DBNull.Value == m_cellsValues[i]);
}
public object this[int i]
{
get { return m_cellsValues[i]; }
}
#endregion
#region Not Supported IDataReader Members
public DataTable GetSchemaTable()
{
throw new NotSupportedException();
}
public int RecordsAffected
{
get { throw new NotSupportedException(); }
}
#endregion
#region Not Supported IDataRecord Members
public byte GetByte(int i)
{
throw new NotSupportedException();
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public char GetChar(int i)
{
throw new NotSupportedException();
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public IDataReader GetData(int i)
{
throw new NotSupportedException();
}
public string GetDataTypeName(int i)
{
throw new NotSupportedException();
}
public Type GetFieldType(int i)
{
throw new NotSupportedException();
}
public Guid GetGuid(int i)
{
throw new NotSupportedException();
}
public string GetName(int i)
{
throw new NotSupportedException();
}
public int GetOrdinal(string name)
{
throw new NotSupportedException();
}
public int GetValues(object[] values)
{
throw new NotSupportedException();
}
public object this[string name]
{
get { throw new NotSupportedException(); }
}
#endregion
#region IExcelDataReader Members
public bool IsFirstRowAsColumnNames
{
get
{
return _isFirstRowAsColumnNames;
}
set
{
_isFirstRowAsColumnNames = value;
}
}
public Encoding Encoding
{
get { return m_encoding; }
}
public Encoding DefaultEncoding
{
get { return m_Default_Encoding; }
}
public bool ConvertOaDate
{
get { return m_ConvertOADate; }
set { m_ConvertOADate = value; }
}
public ReadOption ReadOption
{
get { return m_ReadOption; }
}
#endregion
}
/// <summary>
/// Strict is as normal, Loose is more forgiving and will not cause an exception if a record size takes it beyond the end of the file. It will be trunacted in this case (SQl Reporting Services)
/// </summary>
public enum ReadOption
{
Strict,
Loose
}
}
| |
/**
* LR parser for C# generated by the Syntax tool.
*
* https://www.npmjs.com/package/syntax-cli
*
* npm install -g syntax-cli
*
* syntax-cli --help
*
* To regenerate run:
*
* syntax-cli \
* --grammar ~/path-to-grammar-file \
* --mode <parsing-mode> \
* --output ~/ParserClassName.cs
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
{{{MODULE_INCLUDE}}}
namespace SyntaxParser
{
// --------------------------------------------
// Location object.
public class YyLoc
{
public YyLoc() {}
public int StartOffset;
public int EndOffset;
public int StartLine;
public int EndLine;
public int StartColumn;
public int EndColumn;
public static YyLoc yyloc(dynamic start, dynamic end)
{
// Epsilon doesn't produce location.
if (start == null || end == null)
{
return start == null ? end : start;
}
return new YyLoc()
{
StartOffset = start.StartOffset,
EndOffset = end.EndOffset,
StartLine = start.StartLine,
EndLine = end.EndLine,
StartColumn = start.StartColumn,
EndColumn = end.EndColumn,
};
}
}
// --------------------------------------------
// Parser.
/**
* Entires on the parsing stack are:
*
* - an actual entry {symbol, semanticValue}, implemented by `StackEntry`.
* - a state number
*/
public class StackEntry
{
public int Symbol;
public object SemanticValue;
public YyLoc Loc;
public StackEntry(int symbol, object semanticValue, YyLoc loc)
{
Symbol = symbol;
SemanticValue = semanticValue;
Loc = loc;
}
}
/**
* SyntaxException.
*/
public class SyntaxException : Exception
{
public SyntaxException(string message)
: base(message)
{
}
}
/**
* Base class for the parser. Implements LR parsing algorithm.
*
* Should implement at least the following API:
*
* - parse(string stringToParse): object
* - setTokenizer(Tokenizer tokenizer): void, or equivalent Tokenizer
* accessor property with a setter.
*/
public class yyparse
{
public yyparse()
{
// A tokenizer instance, which is reused for all
// `parse` method calls. The actual string is set
// in the tokenizer.initString("...").
tokenizer = new Tokenizer();
// Run init hook to setup callbacks, etc.
Init.run();
}
/**
* Encoded grammar productions table.
* Format of a record:
* { <Non-Terminal Index>, <RHS.Length>, <handler> }
*
* Non-terminal indices are 0-Last Non-terminal. LR-algorithm uses
* length of RHS to pop symbols from the stack; this length is stored
* as the second element of a record. The last element is an optional
* name of the semantic action handler. The first record is always
* a special marker {-1, -1} entry representing an augmented production.
*
* Example:
*
* {
* new object[] {-1, 1},
* new object[] {0, 3, "_handler1"},
* new object[] {0, 2, "_handler2"},
* }
*
*/
private static object[][] mProductions = {{{PRODUCTIONS}}};
/**
* Actual parsing table. An array of records, where
* index is a state number, and a value is a dictionary
* from an encoded symbol (number) to parsing action.
* The parsing action can be "Shift/s", "Reduce/r", a state
* transition number, or "Accept/acc".
*
* Example:
* {
* // 0
* new Dictionary<int, string>()
* {
* {0, "1"},
* {3, "s8"},
* {4, "s2"},
* },
* // 1
* new Dictionary<int, string>()
* {
* {1, "s3"},
* {2, "s4"},
* {6, "acc"},
* },
* ...
* }
*/
private static Dictionary<int, string>[] mTable = {{{TABLE}}};
/**
* Parsing stack. Stores instances of StackEntry, and state numbers.
*/
Stack<object> mStack = null;
/**
* __ holds a result value from a production
* handler. In the grammar usually used as $$.
*/
private dynamic __ = null;
/**
* __loc holds a result location info. In the grammar
* usually used as @$.
*/
private dynamic __loc = null;
/**
* Whether locations should be captured and propagated.
*/
private bool mShouldCaptureLocations = {{{CAPTURE_LOCATIONS}}};
/**
* On parse begin callback.
*
* Example: parser.onParseBegin = (string code) => { ... };
*/
public static Action<string> onParseBegin {get; set; } = null;
/**
* On parse end callback.
*
* Example: parser.onParseEnd = (object parsed) => { ... };
*/
public static Action<object> onParseEnd {get; set; } = null;
/**
* Tokenizer instance.
*/
public Tokenizer tokenizer { get; set; } = null;
/**
* Global constants used across the tokenizer, and parser.
* The `yytext` stores a matched token value, `yyleng` is its length.
*/
public static string EOF = "$";
public static string yytext = null;
public static int yyleng = 0;
/**
* Production handles. The handlers receive arguments as _1, _2, etc.
* The result is always stored in __.
*
* Example:
*
* public void _handler1(dynamic _1, dynamic _2, dynamic _3)
* {
* __ = _1 + _3;
* }
*/
{{{PRODUCTION_HANDLERS}}}
/**
* Main parsing method which applies LR-algorithm.
*/
public object parse(string str)
{
// On parse begin hook.
if (onParseBegin != null)
{
onParseBegin(str);
}
// Tokenizer should be set prior calling the parse.
if (tokenizer == null)
{
throw new Exception("Tokenizer instance isn't specified.");
}
tokenizer.initString(str);
// Initialize the parsing stack to the initial state 0.
mStack = new Stack<object>();
mStack.Push(0);
Token token = tokenizer.getNextToken();
Token shiftedToken = null;
do
{
if (token == null)
{
unexpectedEndOfInput();
}
var state = Convert.ToInt32(mStack.Peek());
var column = token.Type;
if (!mTable[state].ContainsKey(column))
{
unexpectedToken(token);
break;
}
var entry = mTable[state][column];
// ---------------------------------------------------
// "Shift". Shift-entries always have 's' as their
// first char, after which goes *next state number*, e.g. "s5".
// On shift we push the token, and the next state on the stack.
if (entry[0] == 's')
{
YyLoc loc = null;
if (mShouldCaptureLocations)
{
loc = new YyLoc
{
StartOffset = token.StartOffset,
EndOffset = token.EndOffset,
StartLine = token.StartLine,
EndLine = token.EndLine,
StartColumn = token.StartColumn,
EndColumn = token.EndColumn,
};
}
// Push token.
mStack.Push(new StackEntry(token.Type, token.Value, loc));
// Push next state number: "s5" -> 5
mStack.Push(Convert.ToInt32(entry.Substring(1)));
shiftedToken = token;
token = tokenizer.getNextToken();
}
// ---------------------------------------------------
// "Reduce". Reduce-entries always have 'r' as their
// first char, after which goes *production number* to
// reduce by, e.g. "r3" - reduce by production 3 in the grammar.
// On reduce, we pop of the stack number of symbols on the RHS
// of the production, and their pushed state numbers, i.e.
// total RHS * 2 symbols.
else if (entry[0] == 'r')
{
// "r3" -> 3
var productionNumber = Convert.ToInt32(entry.Substring(1));
var production = mProductions[productionNumber];
// Handler can be optional: {0, 3} - no handler,
// {0, 3, "_handler1"} - has handler.
var hasSemanticAction = production.Length > 2;
var semanticValueArgs = new List<object>();
List<object> locationArgs = null;
if (mShouldCaptureLocations) {
locationArgs = new List<object>();
}
// The length of RHS is stored in the production[1].
var rhsLength = (int)production[1];
if (rhsLength != 0)
{
while (rhsLength-- > 0)
{
// Pop the state number.
mStack.Pop();
// Pop the stack entry.
var stackEntry = (StackEntry)mStack.Pop();
// Collect all semantic values from the stack
// to the arguments list, which is passed to the
// semantic action handler.
if (hasSemanticAction)
{
semanticValueArgs.Insert(0, stackEntry.SemanticValue);
if (mShouldCaptureLocations)
{
locationArgs.Insert(0, stackEntry.Loc);
}
}
}
}
var previousState = Convert.ToInt32(mStack.Peek());
var symbolToReduceWith = (int)production[0];
var reduceStackEntry = new StackEntry(symbolToReduceWith, null, null);
// Execute the semantic action handler.
if (hasSemanticAction)
{
yyparse.yytext = shiftedToken != null ? shiftedToken.Value : null;
yyparse.yyleng = shiftedToken != null ? shiftedToken.Value.Length : 0;
var semanticAction = (string)production[2];
MethodInfo semanticActionHandler = GetType().GetMethod(semanticAction);
var semanticActionArgs = semanticValueArgs;
if (mShouldCaptureLocations)
{
semanticActionArgs.AddRange(locationArgs);
}
// Call the action, the result is in __.
semanticActionHandler.Invoke(this, semanticActionArgs.ToArray());
reduceStackEntry.SemanticValue = __;
if (mShouldCaptureLocations)
{
reduceStackEntry.Loc = __loc;
}
}
// Then push LHS onto the stack.
mStack.Push(reduceStackEntry);
// And the next state number.
var nextState = mTable[previousState][symbolToReduceWith];
mStack.Push(nextState);
}
// ---------------------------------------------------
// Accept. Pop starting production and its state number.
else if (entry == "acc")
{
// Pop state number.
mStack.Pop();
// Pop the parsed value.
var parsed = (StackEntry)mStack.Pop();
if (mStack.Count != 1 ||
(int)mStack.Peek() != 0 ||
tokenizer.hasMoreTokens())
{
unexpectedToken(token);
}
var parsedValue = parsed.SemanticValue;
if (onParseEnd != null)
{
onParseEnd(parsedValue);
}
return parsedValue;
}
} while (tokenizer.hasMoreTokens() || mStack.Count > 1);
return null;
}
private void unexpectedToken(Token token)
{
if (token.Type == Tokenizer.EOF_TOKEN.Type)
{
unexpectedEndOfInput();
}
tokenizer.throwUnexpectedToken(
token.Value,
token.StartLine,
token.StartColumn
);
}
private void unexpectedEndOfInput()
{
parseError("Unexpected end of input.");
}
private void parseError(string message)
{
throw new SyntaxException("Parse error: " + message);
}
}
/**
* An actual parser class.
*/
public class {{{PARSER_CLASS_NAME}}} : yyparse { }
}
/**
* Tokenizer class.
*/
{{{TOKENIZER}}}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2014 Oleg Shilo
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.Linq;
using IO = System.IO;
namespace WixSharp
{
/// <summary>
/// Base class for all Wix# related types
/// </summary>
public class WixObject
{
}
/// <summary>
/// Alias for the <c>Dictionary<string, string> </c> type.
/// </summary>
public class Attributes : Dictionary<string, string>
{
}
/// <summary>
/// Generic <see cref="T:WixSharp.WixEntity"/> container for defining WiX <c>Package</c> element attributes.
/// <para>These attributes are the properties of the package to be placed in the Summary Information Stream. These are visible from COM through the IStream interface, and can be seen in Explorer.</para>
///<example>The following is an example of defining the <c>Package</c> attributes.
///<code>
/// var project =
/// new Project("My Product",
/// new Dir(@"%ProgramFiles%\My Company\My Product",
///
/// ...
///
/// project.Package.AttributesDefinition = @"AdminImage=Yes;
/// Comments=Release Candidate;
/// Description=Fantastic product...";
///
/// Compiler.BuildMsi(project);
/// </code>
/// </example>
/// </summary>
public class Package : WixEntity
{
}
/// <summary>
/// Generic <see cref="T:WixSharp.WixEntity"/> container for defining WiX <c>Media</c> element attributes.
/// <para>These attributes describe a disk that makes up the source media for the installation.</para>
///<example>The following is an example of defining the <c>Media</c> attributes.
///<code>
/// var project =
/// new Project("My Product",
/// new Dir(@"%ProgramFiles%\My Company\My Product",
///
/// ...
///
/// project.Media.AttributesDefinition = @"Id=2;
/// CompressionLevel=mszip";
///
/// Compiler.BuildMsi(project);
/// </code>
/// </example>
/// </summary>
public class Media : WixEntity
{
/// <summary>
/// Initializes a new instance of the <see cref="Media"/> class.
/// </summary>
public Media()
{
AttributesDefinition = "Id=1;EmbedCab=yes";
}
}
/// <summary>
/// Base class for all Wix# types representing WiX XML elements (entities)
/// </summary>
public class WixEntity : WixObject
{
internal void MoveAttributesTo(WixEntity dest)
{
var attrs = this.Attributes;
var attrsDefinition = this.AttributesDefinition;
this.Attributes.Clear();
this.AttributesDefinition = null;
dest.Attributes = attrs;
dest.AttributesDefinition = attrsDefinition;
}
/// <summary>
/// Collection of Attribute/Value pairs for WiX element attributes not supported directly by Wix# objects.
/// <para>You should use <c>Attributes</c> if you want to inject specific XML attributes
/// for a given WiX element.</para>
/// <para>For example <c>Hotkey</c> attribute is not supported by Wix# <see cref="T:WixSharp.Shortcut"/>
/// but if you want them to be set in the WiX source file you may achieve this be setting
/// <c>WixEntity.Attributes</c> member variable:
/// <para> <code>new Shortcut { Attributes= new { {"Hotkey", "0"} }</code> </para>
/// <remarks>
/// You can also inject attributes into WiX components "related" to the <see cref="WixEntity"/> but not directly
/// represented in the Wix# entities family. For example if you need to set a custom attribute for the WiX <c>Component</c>
/// XML element you can use corresponding <see cref="T:WixSharp.File"/> attributes. The only difference from
/// the <c>Hotkey</c> example is the composite (column separated) key name:
/// <para> <code>new File { Attributes= new { {"Component:SharedDllRefCount", "yes"} }</code> </para>
/// The code above will force the Wix# compiler to insert "SharedDllRefCount" attribute into <c>Component</c>
/// XML element, which is automatically generated for the <see cref="T:WixSharp.File"/>.
/// <para>Currently the only supported "related" attribute is <c>Component</c>.</para>
/// </remarks>
/// </para>
/// </summary>
public Dictionary<string, string> Attributes
{
get
{
ProcessAttributesDefinition();
return attributes;
}
set
{
attributes = value;
}
}
internal void AddInclude(string xmlFile, string parentElement)
{
//SetAttributeDefinition("WixSharpCustomAttributes:xml_include:" + xmlFile, parentElement??"<none>");
SetAttributeDefinition("WixSharpCustomAttributes:xml_include", parentElement+"|"+ xmlFile, append:true);
}
Dictionary<string, string> attributes = new Dictionary<string, string>();
/// <summary>
/// Optional attributes of the <c>WiX Element</c> (e.g. Secure:YesNoPath) expressed as a string KeyValue pairs (e.g. "StartOnInstall=Yes; Sequence=1").
/// <para>OptionalAttributes just redirects all access calls to the <see cref="T:WixEntity.Attributes"/> member.</para>
/// <para>You can also use <see cref="T:WixEntity.AttributesDefinition"/> to keep the code cleaner.</para>
/// </summary>
/// <example>
/// <code>
/// var webSite = new WebSite
/// {
/// Description = "MyWebSite",
/// Attributes = new Dictionary<string, string> { { "StartOnInstall", "Yes" }, { "Sequence", "1" } }
/// //or
/// AttributesDefinition = "StartOnInstall=Yes; Sequence=1"
/// ...
/// </code>
/// </example>
public string AttributesDefinition { get; set; }
void ProcessAttributesDefinition()
{
if (!AttributesDefinition.IsEmpty())
{
var attrToAdd = new Dictionary<string, string>();
foreach (string attrDef in AttributesDefinition.Trim().Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
{
try
{
string[] tokens = attrDef.Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string name = tokens[0].Trim();
if (tokens.Length > 1)
{
string value = tokens[1].Trim();
attrToAdd[name] = value;
}
}
catch (Exception e)
{
throw new Exception("Invalid AttributesDefinition", e);
}
}
this.Attributes = attrToAdd;
}
}
internal string GetAttributeDefinition(string name)
{
var preffix = name + "=";
return (AttributesDefinition ?? "").Trim()
.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Where(x => x.StartsWith(preffix))
.Select(x => x.Substring(preffix.Length))
.FirstOrDefault();
}
internal void SetAttributeDefinition(string name, string value, bool append = false)
{
var preffix = name + "=";
var allItems = (AttributesDefinition ?? "").Trim()
.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.ToList();
var items = allItems;
if (value.IsNotEmpty())
{
if (append)
{
//add index to the items with the same key
var similarNamedItems = allItems.Where(x => x.StartsWith(name)).ToArray();
items.Add(name + similarNamedItems.Count() + "=" + value);
}
else
{
//reset items with the same key
items.RemoveAll(x => x.StartsWith(preffix));
items.Add(name + "=" + value);
}
}
AttributesDefinition = string.Join(";", items.ToArray());
}
/// <summary>
/// Name of the <see cref="WixEntity"/>.
/// <para>This value is used as a <c>Name</c> for the corresponding WiX XML element.</para>
/// </summary>
public string Name = "";
/// <summary>
/// Gets or sets the <c>Id</c> value of the <see cref="WixEntity"/>.
/// <para>This value is used as a <c>Id</c> for the corresponding WiX XML element.</para>
/// <para>If the <see cref="Id"/> value is not specified explicitly by the user the Wix# compiler
/// generates it automatically insuring its uniqueness.</para>
/// <remarks>
/// <para>
/// Note: The ID auto-generation is triggered on the first access (evaluation) and in order to make the id
/// allocation deterministic the compiler resets ID generator just before the build starts. However if you
/// accessing any auto-id before the Build*() is called you can it interferes with the ID auto generation and eventually
/// lead to the WiX ID duplications. To prevent this from happening either:\n"
/// - Avoid evaluating the auto-generated IDs values before the call to Build*()
/// - Set the IDs (to be evaluated) explicitly
/// - Prevent resetting auto-ID generator by setting WixEntity.DoNotResetIdGenerator to true";
/// </para>
/// </remarks>
/// </summary>
/// <value>The id.</value>
public string Id
{
get
{
if (id.IsEmpty())
{
if (!idMaps.ContainsKey(GetType()))
idMaps[GetType()] = new Dictionary<string, int>();
var rawName = Name.Expand();
if (GetType() != typeof(Dir) && GetType().BaseType != typeof(Dir))
rawName = IO.Path.GetFileName(Name).Expand();
string rawNameKey = rawName.ToLower();
/*
"bin\Release\similarFiles.txt" and "bin\similarfiles.txt" will produce the following IDs
"Component.similarFiles.txt" and "Component.similariles.txt", which will be treated by Wix compiler as duplication
*/
if (!idMaps[GetType()].ContainsSimilarKey(rawName)) //this Type has not been generated yet
{
idMaps[GetType()][rawNameKey] = 0;
id = rawName;
}
else
{
//The Id has been already generated for this Type with this rawName
//so just increase the index
var index = idMaps[GetType()][rawNameKey] + 1;
id = rawName + "." + index;
idMaps[GetType()][rawNameKey] = index;
}
//Trace.WriteLine(">>> " + GetType() + " >>> " + id);
if (rawName.IsNotEmpty() && char.IsDigit(rawName[0]))
id = "_" + id;
}
return id;
}
set
{
id = value;
isAutoId = false;
}
}
internal bool isAutoId = true;
/// <summary>
/// Backing value of <see cref="Id"/>.
/// </summary>
protected string id;
internal string RawId { get { return id; } }
/// <summary>
/// The do not reset auto-ID generator before starting the build.
/// </summary>
static public bool DoNotResetIdGenerator = true;
static Dictionary<Type, Dictionary<string, int>> idMaps = new Dictionary<Type, Dictionary<string, int>>();
/// <summary>
/// Resets the <see cref="Id"/> generator. This method is exercised by the Wix# compiler before any
/// <c>Build</c> operations to ensure reproducibility of the <see cref="Id"/> set between <c>Build()</c>
/// calls.
/// </summary>
static public void ResetIdGenerator()
{
if (!DoNotResetIdGenerator)
{
if (idMaps.Count > 0)
{
Console.WriteLine("----------------------------");
Console.WriteLine("Warning: Wix# compiler detected that some IDs has been auto-generated before the build started. " +
"This can lead to the WiX ID duplications. To prevent this from happening either:\n" +
" - Avoid evaluating the auto-generated IDs values before the call to Build*\n" +
" - Set the IDs (to be evaluated) explicitly\n" +
" - Prevent resetting auto-ID generator by setting WixEntity.DoNotResetIdGenerator to true");
Console.WriteLine("----------------------------");
}
idMaps.Clear();
}
}
internal bool IsIdSet()
{
return !id.IsEmpty();
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections;
using System;
namespace RootMotion.FinalIK {
/*
* Custom inspector for RotationLimitSpline
* */
[CustomEditor(typeof(RotationLimitSpline))]
[CanEditMultipleObjects]
public class RotationLimitSplineInspector : RotationLimitInspector {
// Determines if we are dragging the handle's limits or angle
public enum ScaleMode {
Limit,
Angle
}
// In Smooth TangentMode, in and out tangents will always be the same, Independent allowes for difference
public enum TangentMode {
Smooth,
Independent
}
private RotationLimitSpline script { get { return target as RotationLimitSpline; }}
private RotationLimitSpline clone;
private ScaleMode scaleMode;
private TangentMode tangentMode;
private int selectedHandle = -1, deleteHandle = -1, addHandle = -1;
#region Inspector
public void OnEnable() {
// Check if RotationLimitspline is properly set up, if not, reset to defaults
if (script.spline == null) {
script.spline = new AnimationCurve(defaultKeys);
EditorUtility.SetDirty(script);
}
else if (script.spline.keys.Length < 4) {
script.spline.keys = defaultKeys;
EditorUtility.SetDirty(script);
}
}
/*
* Returns the default keyframes for the RotationLimitspline
* */
private static Keyframe[] defaultKeys {
get {
Keyframe[] k = new Keyframe[5];
// Values for a simple elliptic spline
k[0].time = 0.01f;
k[0].value = 30;
k[0].inTangent = 0.01f;
k[0].outTangent = 0.01f;
k[1].time = 90;
k[1].value = 45;
k[1].inTangent = 0.01f;
k[1].outTangent = 0.01f;
k[2].time = 180;
k[2].value = 30;
k[2].inTangent = 0.01f;
k[2].outTangent = 0.01f;
k[3].time = 270;
k[3].value = 45;
k[3].inTangent = 0.01f;
k[3].outTangent = 0.01f;
k[4].time = 360;
k[4].value = 30;
k[4].inTangent = 0.01f;
k[4].outTangent = 0.01f;
return k;
}
}
public override void OnInspectorGUI() {
GUI.changed = false;
DrawDefaultInspector();
script.twistLimit = Mathf.Clamp(script.twistLimit, 0, 180);
if (GUI.changed) EditorUtility.SetDirty(script);
}
/*
* Make sure the keyframes and tangents are valid
* */
private void ValidateKeyframes(Keyframe[] keys) {
keys[keys.Length - 1].value = keys[0].value;
keys[keys.Length - 1].time = keys[0].time + 360;
keys[keys.Length - 1].inTangent = keys[0].inTangent;
}
#endregion Inspector
#region Scene
void OnSceneGUI() {
GUI.changed = false;
// Get the keyframes of the AnimationCurve to be manipulated
Keyframe[] keys = script.spline.keys;
// Set defaultLocalRotation so that the initial local rotation will be the zero point for the rotation limit
if (!Application.isPlaying) script.defaultLocalRotation = script.transform.localRotation;
if (script.axis == Vector3.zero) return;
// Make the curve loop
script.spline.postWrapMode = WrapMode.Loop;
script.spline.preWrapMode = WrapMode.Loop;
DrawRotationSphere(script.transform.position);
// Display the main axis
DrawArrow(script.transform.position, Direction(script.axis), colorDefault, "Axis", 0.02f);
Vector3 swing = script.axis.normalized;
// Editing tools GUI
Handles.BeginGUI();
GUILayout.BeginArea(new Rect(10, Screen.height - 140, 440, 90), "Rotation Limit Spline", "Window");
// Scale Mode and Tangent Mode
GUILayout.BeginHorizontal();
scaleMode = (ScaleMode)EditorGUILayout.EnumPopup("Drag Handle", scaleMode);
tangentMode = (TangentMode)EditorGUILayout.EnumPopup("Drag Tangents", tangentMode);
GUILayout.EndHorizontal();
EditorGUILayout.Space();
if (Inspector.Button("Rotate 90 degrees", "Rotate rotation limit around axis.", script, GUILayout.Width(220))) {
if (!Application.isPlaying) Undo.RecordObject(script, "Handle Value");
for (int i = 0; i < keys.Length; i++) keys[i].time += 90;
}
// Cloning values from another RotationLimitSpline
EditorGUILayout.BeginHorizontal();
if (Inspector.Button("Clone From", "Make this rotation limit identical to another", script, GUILayout.Width(220))) {
CloneLimit();
keys = script.spline.keys;
}
clone = (RotationLimitSpline)EditorGUILayout.ObjectField("", clone, typeof(RotationLimitSpline), true);
EditorGUILayout.EndHorizontal();
GUILayout.EndArea();
Handles.EndGUI();
// Draw keyframes
for (int i = 0; i < keys.Length - 1; i++) {
float angle = keys[i].time;
// Start drawing handles
Quaternion offset = Quaternion.AngleAxis(angle, swing);
Quaternion rotation = Quaternion.AngleAxis(keys[i].value, offset * script.crossAxis);
Vector3 position = script.transform.position + Direction(rotation * swing);
Handles.Label(position, " " + i.ToString());
// Dragging Values
if (selectedHandle == i) {
Handles.color = colorHandles;
switch(scaleMode) {
case ScaleMode.Limit:
float inputValue = keys[i].value;
inputValue = Mathf.Clamp(Inspector.ScaleValueHandleSphere(inputValue, position, Quaternion.identity, 0.5f, 0), 0.01f, 180);
if (keys[i].value != inputValue) {
if (!Application.isPlaying) Undo.RecordObject(script, "Handle Value");
keys[i].value = inputValue;
}
break;
case ScaleMode.Angle:
float inputTime = keys[i].time;
inputTime = Inspector.ScaleValueHandleSphere(inputTime, position, Quaternion.identity, 0.5f, 0);
if (keys[i].time != inputTime) {
if (!Application.isPlaying) Undo.RecordObject(script, "Handle Angle");
keys[i].time = inputTime;
}
break;
}
}
// Handle select button
if (selectedHandle != i) {
Handles.color = Color.blue;
if (Inspector.SphereButton(position, script.transform.rotation, 0.05f, 0.05f)) {
selectedHandle = i;
}
}
// Tangents
if (selectedHandle == i) {
// Evaluate positions before and after the key to get the tangent positions
Vector3 prevPosition = GetAnglePosition(keys[i].time - 1);
Vector3 nextPosition = GetAnglePosition(keys[i].time + 1);
// Draw handles for the tangents
Handles.color = Color.white;
Vector3 toNext = (nextPosition - position).normalized * 0.3f;
float outTangent = keys[i].outTangent;
outTangent = Inspector.ScaleValueHandleSphere(outTangent, position + toNext, Quaternion.identity, 0.2f, 0);
Vector3 toPrev = (prevPosition - position).normalized * 0.3f;
float inTangent = keys[i].inTangent;
inTangent = Inspector.ScaleValueHandleSphere(inTangent, position + toPrev, Quaternion.identity, 0.2f, 0);
if (outTangent != keys[i].outTangent || inTangent != keys[i].inTangent) selectedHandle = i;
// Make the other tangent match the dragged tangent (if in "Smooth" TangentMode)
switch(tangentMode) {
case TangentMode.Smooth:
if (outTangent != keys[i].outTangent) {
if (!Application.isPlaying) Undo.RecordObject(script, "Tangents");
keys[i].outTangent = outTangent;
keys[i].inTangent = outTangent;
} else if (inTangent != keys[i].inTangent) {
if (!Application.isPlaying) Undo.RecordObject(script, "Tangents");
keys[i].outTangent = inTangent;
keys[i].inTangent = inTangent;
}
break;
case TangentMode.Independent:
if (outTangent != keys[i].outTangent) {
if (!Application.isPlaying) Undo.RecordObject(script, "Tangents");
keys[i].outTangent = outTangent;
} else if (inTangent != keys[i].inTangent) {
if (!Application.isPlaying) Undo.RecordObject(script, "Tangents");
keys[i].inTangent = inTangent;
}
break;
}
// Draw lines and labels to tangent handles
Handles.color = Color.white;
GUI.color = Color.white;
Handles.DrawLine(position, position + toNext);
Handles.Label(position + toNext, " Out");
Handles.DrawLine(position, position + toPrev);
Handles.Label(position + toPrev, " In");
}
}
// Selected Point GUI
if (selectedHandle != -1) {
Handles.BeginGUI();
GUILayout.BeginArea(new Rect(Screen.width - 240, Screen.height - 200, 230, 150), "Handle " + selectedHandle.ToString(), "Window");
if (Inspector.Button("Delete", "Delete this handle", script)) {
if (keys.Length > 4) {
deleteHandle = selectedHandle;
} else if (!Warning.logged) script.LogWarning("Spline Rotation Limit should have at least 3 handles");
}
if (Inspector.Button("Add Handle", "Add a new handle next to this one", script)) {
addHandle = selectedHandle;
}
// Clamp the key angles to previous and next handle angles
float prevTime = 0, nextTime = 0;
if (selectedHandle < keys.Length - 2) nextTime = keys[selectedHandle + 1].time;
else nextTime = keys[0].time + 360;
if (selectedHandle == 0) prevTime = keys[keys.Length - 2].time - 360;
else prevTime = keys[selectedHandle - 1].time;
// Angles
float inputTime = keys[selectedHandle].time;
inputTime = Mathf.Clamp(EditorGUILayout.FloatField(new GUIContent("Angle", "Angle of the point (0-360)."), inputTime), prevTime, nextTime);
if (keys[selectedHandle].time != inputTime) {
if (!Application.isPlaying) Undo.RecordObject(script, "Handle Angle");
keys[selectedHandle].time = inputTime;
}
// Limits
float inputValue = keys[selectedHandle].value;
inputValue = Mathf.Clamp(EditorGUILayout.FloatField(new GUIContent("Limit", "Max angular limit from Axis at this angle"), inputValue), 0, 180);
if (keys[selectedHandle].value != inputValue) {
if (!Application.isPlaying) Undo.RecordObject(script, "Handle Limit");
keys[selectedHandle].value = inputValue;
}
// In Tangents
float inputInTangent = keys[selectedHandle].inTangent;
inputInTangent = EditorGUILayout.FloatField(new GUIContent("In Tangent", "In tangent of the handle point on the spline"), inputInTangent);
if (keys[selectedHandle].inTangent != inputInTangent) {
if (!Application.isPlaying) Undo.RecordObject(script, "Handle In Tangent");
keys[selectedHandle].inTangent = inputInTangent;
}
// Out tangents
float inputOutTangent = keys[selectedHandle].outTangent;
inputOutTangent = EditorGUILayout.FloatField(new GUIContent("Out Tangent", "Out tangent of the handle point on the spline"), inputOutTangent);
if (keys[selectedHandle].outTangent != inputOutTangent) {
if (!Application.isPlaying) Undo.RecordObject(script, "Handle Out Tangent");
keys[selectedHandle].outTangent = inputOutTangent;
}
GUILayout.EndArea();
Handles.EndGUI();
}
// Make sure the keyframes are valid;
ValidateKeyframes(keys);
// Replace the AnimationCurve keyframes with the manipulated keyframes
script.spline.keys = keys;
// Display limits
for (int i = 0; i < 360; i+= 2) {
float evaluatedLimit = script.spline.Evaluate((float)i);
Quaternion offset = Quaternion.AngleAxis(i, swing);
Quaternion evaluatedRotation = Quaternion.AngleAxis(evaluatedLimit, offset * script.crossAxis);
Quaternion testRotation = Quaternion.AngleAxis(179.9f, offset * script.crossAxis);
Quaternion limitedRotation = script.LimitSwing(testRotation);
Vector3 evaluatedDirection = evaluatedRotation * swing;
Vector3 limitedDirection = limitedRotation * swing;
// Display the limit points in red if they are out of range
bool isValid = Vector3.Distance(evaluatedDirection, limitedDirection) < 0.01f && evaluatedLimit >= 0;
Color color = isValid? colorDefaultTransparent: colorInvalid;
Vector3 limitPoint = script.transform.position + Direction(evaluatedDirection);
Handles.color = color;
if (i == 0) zeroPoint = limitPoint;
Handles.DrawLine(script.transform.position, limitPoint);
if (i > 0) {
Handles.color = isValid? colorDefault: colorInvalid;
Handles.DrawLine(limitPoint, lastPoint);
if (i == 358) Handles.DrawLine(limitPoint, zeroPoint);
}
lastPoint = limitPoint;
}
// Deleting points
if (deleteHandle != -1) {
DeleteHandle(deleteHandle);
selectedHandle = -1;
deleteHandle = -1;
}
// Adding points
if (addHandle != -1) {
AddHandle(addHandle);
addHandle = -1;
}
Handles.color = Color.white;
if (GUI.changed) EditorUtility.SetDirty(script);
}
private Vector3 lastPoint, zeroPoint;
/*
* Return the evaluated position for the specified angle
* */
private Vector3 GetAnglePosition(float angle) {
Vector3 swing = script.axis.normalized;
Quaternion offset = Quaternion.AngleAxis(angle, swing);
Quaternion rotation = Quaternion.AngleAxis(script.spline.Evaluate(angle), offset * script.crossAxis);
return script.transform.position + Direction(rotation * swing);
}
/*
* Converting directions from local space to world space
* */
private Vector3 Direction(Vector3 v) {
if (script.transform.parent == null) return script.defaultLocalRotation * v;
return script.transform.parent.rotation * (script.defaultLocalRotation * v);
}
/*
* Removing Handles
* */
private void DeleteHandle(int p) {
Keyframe[] keys = script.spline.keys;
Keyframe[] newKeys = new Keyframe[0];
for (int i = 0; i < keys.Length; i++) {
if (i != p) {
Array.Resize(ref newKeys, newKeys.Length + 1);
newKeys[newKeys.Length - 1] = keys[i];
}
}
script.spline.keys = newKeys;
}
/*
* Creating new Handles
* */
private void AddHandle(int p) {
Keyframe[] keys = script.spline.keys;
Keyframe[] newKeys = new Keyframe[keys.Length + 1];
for (int i = 0; i < p + 1; i++) newKeys[i] = keys[i];
float nextTime = 0;
if (p < keys.Length - 1) nextTime = keys[p + 1].time;
else nextTime = keys[0].time;
float newTime = Mathf.Lerp(keys[p].time, nextTime, 0.5f);
float newValue = script.spline.Evaluate(newTime);
newKeys[p + 1] = new Keyframe(newTime, newValue);
for (int i = p + 2; i < newKeys.Length; i++) newKeys[i] = keys[i - 1];
script.spline.keys = newKeys;
}
/*
* Clone properties from another RotationLimitSpline
* */
private void CloneLimit() {
if (clone == null) return;
if (clone == script) {
script.LogWarning("Can't clone from self.");
return;
}
script.axis = clone.axis;
script.twistLimit = clone.twistLimit;
script.spline.keys = clone.spline.keys;
}
#endregion Scene
}
}
| |
// ---------------------------------------------------------------------
// Copyright (c) 2015-2016 Microsoft
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ---------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
namespace Obvs.ActiveMQ.RecyclableMemoryStream
{
/// <summary>
/// Manages pools of RecyclableMemoryStream objects.
/// </summary>
/// <remarks>
/// There are two pools managed in here. The small pool contains same-sized buffers that are handed to streams
/// as they write more data.
///
/// For scenarios that need to call GetBuffer(), the large pool contains buffers of various sizes, all
/// multiples of LargeBufferMultiple (1 MB by default). They are split by size to avoid overly-wasteful buffer
/// usage. There should be far fewer 8 MB buffers than 1 MB buffers, for example.
/// </remarks>
public partial class RecyclableMemoryStreamManager
{
/// <summary>
/// Generic delegate for handling events without any arguments.
/// </summary>
public delegate void EventHandler();
/// <summary>
/// Delegate for handling large buffer discard reports.
/// </summary>
/// <param name="reason">Reason the buffer was discarded.</param>
public delegate void LargeBufferDiscardedEventHandler(Events.MemoryStreamDiscardReason reason);
/// <summary>
/// Delegate for handling reports of stream size when streams are allocated
/// </summary>
/// <param name="bytes">Bytes allocated.</param>
public delegate void StreamLengthReportHandler(long bytes);
/// <summary>
/// Delegate for handling periodic reporting of memory use statistics.
/// </summary>
/// <param name="smallPoolInUseBytes">Bytes currently in use in the small pool.</param>
/// <param name="smallPoolFreeBytes">Bytes currently free in the small pool.</param>
/// <param name="largePoolInUseBytes">Bytes currently in use in the large pool.</param>
/// <param name="largePoolFreeBytes">Bytes currently free in the large pool.</param>
public delegate void UsageReportEventHandler(
long smallPoolInUseBytes, long smallPoolFreeBytes, long largePoolInUseBytes, long largePoolFreeBytes);
public const int DefaultBlockSize = 128 * 1024;
public const int DefaultLargeBufferMultiple = 1024 * 1024;
public const int DefaultMaximumBufferSize = 128 * 1024 * 1024;
private readonly int blockSize;
private readonly long[] largeBufferFreeSize;
private readonly long[] largeBufferInUseSize;
private readonly int largeBufferMultiple;
/// <summary>
/// pools[0] = 1x largeBufferMultiple buffers
/// pools[1] = 2x largeBufferMultiple buffers
/// etc., up to maximumBufferSize
/// </summary>
private readonly ConcurrentStack<byte[]>[] largePools;
private readonly int maximumBufferSize;
private readonly ConcurrentStack<byte[]> smallPool;
private long smallPoolFreeSize;
private long smallPoolInUseSize;
/// <summary>
/// Initializes the memory manager with the default block/buffer specifications.
/// </summary>
public RecyclableMemoryStreamManager()
: this(DefaultBlockSize, DefaultLargeBufferMultiple, DefaultMaximumBufferSize) { }
/// <summary>
/// Initializes the memory manager with the given block requiredSize.
/// </summary>
/// <param name="blockSize">Size of each block that is pooled. Must be > 0.</param>
/// <param name="largeBufferMultiple">Each large buffer will be a multiple of this value.</param>
/// <param name="maximumBufferSize">Buffers larger than this are not pooled</param>
/// <exception cref="ArgumentOutOfRangeException">blockSize is not a positive number, or largeBufferMultiple is not a positive number, or maximumBufferSize is less than blockSize.</exception>
/// <exception cref="ArgumentException">maximumBufferSize is not a multiple of largeBufferMultiple</exception>
public RecyclableMemoryStreamManager(int blockSize, int largeBufferMultiple, int maximumBufferSize)
{
if (blockSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(blockSize), blockSize, "blockSize must be a positive number");
}
if (largeBufferMultiple <= 0)
{
throw new ArgumentOutOfRangeException(nameof(largeBufferMultiple),
"largeBufferMultiple must be a positive number");
}
if (maximumBufferSize < blockSize)
{
throw new ArgumentOutOfRangeException(nameof(maximumBufferSize),
"maximumBufferSize must be at least blockSize");
}
this.blockSize = blockSize;
this.largeBufferMultiple = largeBufferMultiple;
this.maximumBufferSize = maximumBufferSize;
if (!this.IsLargeBufferMultiple(maximumBufferSize))
{
throw new ArgumentException("maximumBufferSize is not a multiple of largeBufferMultiple",
nameof(maximumBufferSize));
}
this.smallPool = new ConcurrentStack<byte[]>();
var numLargePools = maximumBufferSize / largeBufferMultiple;
// +1 to store size of bytes in use that are too large to be pooled
this.largeBufferInUseSize = new long[numLargePools + 1];
this.largeBufferFreeSize = new long[numLargePools];
this.largePools = new ConcurrentStack<byte[]>[numLargePools];
for (var i = 0; i < this.largePools.Length; ++i)
{
this.largePools[i] = new ConcurrentStack<byte[]>();
}
Events.Writer.MemoryStreamManagerInitialized(blockSize, largeBufferMultiple, maximumBufferSize);
}
/// <summary>
/// The size of each block. It must be set at creation and cannot be changed.
/// </summary>
public int BlockSize => this.blockSize;
/// <summary>
/// All buffers are multiples of this number. It must be set at creation and cannot be changed.
/// </summary>
public int LargeBufferMultiple => this.largeBufferMultiple;
/// <summary>
/// Gets or sets the maximum buffer size.
/// </summary>
/// <remarks>Any buffer that is returned to the pool that is larger than this will be
/// discarded and garbage collected.</remarks>
public int MaximumBufferSize => this.maximumBufferSize;
/// <summary>
/// Number of bytes in small pool not currently in use
/// </summary>
public long SmallPoolFreeSize => this.smallPoolFreeSize;
/// <summary>
/// Number of bytes currently in use by stream from the small pool
/// </summary>
public long SmallPoolInUseSize => this.smallPoolInUseSize;
/// <summary>
/// Number of bytes in large pool not currently in use
/// </summary>
public long LargePoolFreeSize => this.largeBufferFreeSize.Sum();
/// <summary>
/// Number of bytes currently in use by streams from the large pool
/// </summary>
public long LargePoolInUseSize => this.largeBufferInUseSize.Sum();
/// <summary>
/// How many blocks are in the small pool
/// </summary>
public long SmallBlocksFree => this.smallPool.Count;
/// <summary>
/// How many buffers are in the large pool
/// </summary>
public long LargeBuffersFree
{
get
{
long free = 0;
foreach (var pool in this.largePools)
{
free += pool.Count;
}
return free;
}
}
/// <summary>
/// How many bytes of small free blocks to allow before we start dropping
/// those returned to us.
/// </summary>
public long MaximumFreeSmallPoolBytes { get; set; }
/// <summary>
/// How many bytes of large free buffers to allow before we start dropping
/// those returned to us.
/// </summary>
public long MaximumFreeLargePoolBytes { get; set; }
/// <summary>
/// Maximum stream capacity in bytes. Attempts to set a larger capacity will
/// result in an exception.
/// </summary>
/// <remarks>A value of 0 indicates no limit.</remarks>
public long MaximumStreamCapacity { get; set; }
/// <summary>
/// Whether to save callstacks for stream allocations. This can help in debugging.
/// It should NEVER be turned on generally in production.
/// </summary>
public bool GenerateCallStacks { get; set; }
/// <summary>
/// Whether dirty buffers can be immediately returned to the buffer pool. E.g. when GetBuffer() is called on
/// a stream and creates a single large buffer, if this setting is enabled, the other blocks will be returned
/// to the buffer pool immediately.
/// Note when enabling this setting that the user is responsible for ensuring that any buffer previously
/// retrieved from a stream which is subsequently modified is not used after modification (as it may no longer
/// be valid).
/// </summary>
public bool AggressiveBufferReturn { get; set; }
/// <summary>
/// Removes and returns a single block from the pool.
/// </summary>
/// <returns>A byte[] array</returns>
internal byte[] GetBlock()
{
byte[] block;
if (!this.smallPool.TryPop(out block))
{
// We'll add this back to the pool when the stream is disposed
// (unless our free pool is too large)
block = new byte[this.BlockSize];
Events.Writer.MemoryStreamNewBlockCreated(this.smallPoolInUseSize);
ReportBlockCreated();
}
else
{
Interlocked.Add(ref this.smallPoolFreeSize, -this.BlockSize);
}
Interlocked.Add(ref this.smallPoolInUseSize, this.BlockSize);
return block;
}
/// <summary>
/// Returns a buffer of arbitrary size from the large buffer pool. This buffer
/// will be at least the requiredSize and always be a multiple of largeBufferMultiple.
/// </summary>
/// <param name="requiredSize">The minimum length of the buffer</param>
/// <param name="tag">The tag of the stream returning this buffer, for logging if necessary.</param>
/// <returns>A buffer of at least the required size.</returns>
internal byte[] GetLargeBuffer(int requiredSize, string tag)
{
requiredSize = this.RoundToLargeBufferMultiple(requiredSize);
var poolIndex = requiredSize / this.largeBufferMultiple - 1;
byte[] buffer;
if (poolIndex < this.largePools.Length)
{
if (!this.largePools[poolIndex].TryPop(out buffer))
{
buffer = new byte[requiredSize];
Events.Writer.MemoryStreamNewLargeBufferCreated(requiredSize, this.LargePoolInUseSize);
ReportLargeBufferCreated();
}
else
{
Interlocked.Add(ref this.largeBufferFreeSize[poolIndex], -buffer.Length);
}
}
else
{
// Buffer is too large to pool. They get a new buffer.
// We still want to track the size, though, and we've reserved a slot
// in the end of the inuse array for nonpooled bytes in use.
poolIndex = this.largeBufferInUseSize.Length - 1;
// We still want to round up to reduce heap fragmentation.
buffer = new byte[requiredSize];
string callStack = null;
if (this.GenerateCallStacks)
{
// Grab the stack -- we want to know who requires such large buffers
callStack = Environment.StackTrace;
}
Events.Writer.MemoryStreamNonPooledLargeBufferCreated(requiredSize, tag, callStack);
ReportLargeBufferCreated();
}
Interlocked.Add(ref this.largeBufferInUseSize[poolIndex], buffer.Length);
return buffer;
}
private int RoundToLargeBufferMultiple(int requiredSize)
{
return ((requiredSize + this.LargeBufferMultiple - 1) / this.LargeBufferMultiple) * this.LargeBufferMultiple;
}
private bool IsLargeBufferMultiple(int value)
{
return (value != 0) && (value % this.LargeBufferMultiple) == 0;
}
/// <summary>
/// Returns the buffer to the large pool
/// </summary>
/// <param name="buffer">The buffer to return.</param>
/// <param name="tag">The tag of the stream returning this buffer, for logging if necessary.</param>
/// <exception cref="ArgumentNullException">buffer is null</exception>
/// <exception cref="ArgumentException">buffer.Length is not a multiple of LargeBufferMultiple (it did not originate from this pool)</exception>
internal void ReturnLargeBuffer(byte[] buffer, string tag)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (!this.IsLargeBufferMultiple(buffer.Length))
{
throw new ArgumentException(
"buffer did not originate from this memory manager. The size is not a multiple of " +
this.LargeBufferMultiple);
}
var poolIndex = buffer.Length / this.largeBufferMultiple - 1;
if (poolIndex < this.largePools.Length)
{
if ((this.largePools[poolIndex].Count + 1) * buffer.Length <= this.MaximumFreeLargePoolBytes ||
this.MaximumFreeLargePoolBytes == 0)
{
this.largePools[poolIndex].Push(buffer);
Interlocked.Add(ref this.largeBufferFreeSize[poolIndex], buffer.Length);
}
else
{
Events.Writer.MemoryStreamDiscardBuffer(Events.MemoryStreamBufferType.Large, tag,
Events.MemoryStreamDiscardReason.EnoughFree);
ReportLargeBufferDiscarded(Events.MemoryStreamDiscardReason.EnoughFree);
}
}
else
{
// This is a non-poolable buffer, but we still want to track its size for inuse
// analysis. We have space in the inuse array for this.
poolIndex = this.largeBufferInUseSize.Length - 1;
Events.Writer.MemoryStreamDiscardBuffer(Events.MemoryStreamBufferType.Large, tag,
Events.MemoryStreamDiscardReason.TooLarge);
ReportLargeBufferDiscarded(Events.MemoryStreamDiscardReason.TooLarge);
}
Interlocked.Add(ref this.largeBufferInUseSize[poolIndex], -buffer.Length);
ReportUsageReport(this.smallPoolInUseSize, this.smallPoolFreeSize, this.LargePoolInUseSize,
this.LargePoolFreeSize);
}
/// <summary>
/// Returns the blocks to the pool
/// </summary>
/// <param name="blocks">Collection of blocks to return to the pool</param>
/// <param name="tag">The tag of the stream returning these blocks, for logging if necessary.</param>
/// <exception cref="ArgumentNullException">blocks is null</exception>
/// <exception cref="ArgumentException">blocks contains buffers that are the wrong size (or null) for this memory manager</exception>
internal void ReturnBlocks(ICollection<byte[]> blocks, string tag)
{
if (blocks == null)
{
throw new ArgumentNullException(nameof(blocks));
}
var bytesToReturn = blocks.Count * this.BlockSize;
Interlocked.Add(ref this.smallPoolInUseSize, -bytesToReturn);
foreach (var block in blocks)
{
if (block == null || block.Length != this.BlockSize)
{
throw new ArgumentException("blocks contains buffers that are not BlockSize in length");
}
}
foreach (var block in blocks)
{
if (this.MaximumFreeSmallPoolBytes == 0 || this.SmallPoolFreeSize < this.MaximumFreeSmallPoolBytes)
{
Interlocked.Add(ref this.smallPoolFreeSize, this.BlockSize);
this.smallPool.Push(block);
}
else
{
Events.Writer.MemoryStreamDiscardBuffer(Events.MemoryStreamBufferType.Small, tag,
Events.MemoryStreamDiscardReason.EnoughFree);
ReportBlockDiscarded();
break;
}
}
ReportUsageReport(this.smallPoolInUseSize, this.smallPoolFreeSize, this.LargePoolInUseSize,
this.LargePoolFreeSize);
}
internal void ReportBlockCreated()
{
this.BlockCreated?.Invoke();
}
internal void ReportBlockDiscarded()
{
this.BlockDiscarded?.Invoke();
}
internal void ReportLargeBufferCreated()
{
this.LargeBufferCreated?.Invoke();
}
internal void ReportLargeBufferDiscarded(Events.MemoryStreamDiscardReason reason)
{
this.LargeBufferDiscarded?.Invoke(reason);
}
internal void ReportStreamCreated()
{
this.StreamCreated?.Invoke();
}
internal void ReportStreamDisposed()
{
this.StreamDisposed?.Invoke();
}
internal void ReportStreamFinalized()
{
this.StreamFinalized?.Invoke();
}
internal void ReportStreamLength(long bytes)
{
this.StreamLength?.Invoke(bytes);
}
internal void ReportStreamToArray()
{
this.StreamConvertedToArray?.Invoke();
}
internal void ReportUsageReport(
long smallPoolInUseBytes, long smallPoolFreeBytes, long largePoolInUseBytes, long largePoolFreeBytes)
{
this.UsageReport?.Invoke(smallPoolInUseBytes, smallPoolFreeBytes, largePoolInUseBytes, largePoolFreeBytes);
}
/// <summary>
/// Retrieve a new MemoryStream object with no tag and a default initial capacity.
/// </summary>
/// <returns>A MemoryStream.</returns>
public MemoryStream GetStream()
{
return new RecyclableMemoryStream(this);
}
/// <summary>
/// Retrieve a new MemoryStream object with the given tag and a default initial capacity.
/// </summary>
/// <param name="tag">A tag which can be used to track the source of the stream.</param>
/// <returns>A MemoryStream.</returns>
public MemoryStream GetStream(string tag)
{
return new RecyclableMemoryStream(this, tag);
}
/// <summary>
/// Retrieve a new MemoryStream object with the given tag and at least the given capacity.
/// </summary>
/// <param name="tag">A tag which can be used to track the source of the stream.</param>
/// <param name="requiredSize">The minimum desired capacity for the stream.</param>
/// <returns>A MemoryStream.</returns>
public MemoryStream GetStream(string tag, int requiredSize)
{
return new RecyclableMemoryStream(this, tag, requiredSize);
}
/// <summary>
/// Retrieve a new MemoryStream object with the given tag and at least the given capacity, possibly using
/// a single continugous underlying buffer.
/// </summary>
/// <remarks>Retrieving a MemoryStream which provides a single contiguous buffer can be useful in situations
/// where the initial size is known and it is desirable to avoid copying data between the smaller underlying
/// buffers to a single large one. This is most helpful when you know that you will always call GetBuffer
/// on the underlying stream.</remarks>
/// <param name="tag">A tag which can be used to track the source of the stream.</param>
/// <param name="requiredSize">The minimum desired capacity for the stream.</param>
/// <param name="asContiguousBuffer">Whether to attempt to use a single contiguous buffer.</param>
/// <returns>A MemoryStream.</returns>
public MemoryStream GetStream(string tag, int requiredSize, bool asContiguousBuffer)
{
if (!asContiguousBuffer || requiredSize <= this.BlockSize)
{
return this.GetStream(tag, requiredSize);
}
return new RecyclableMemoryStream(this, tag, requiredSize, this.GetLargeBuffer(requiredSize, tag));
}
/// <summary>
/// Retrieve a new MemoryStream object with the given tag and with contents copied from the provided
/// buffer. The provided buffer is not wrapped or used after construction.
/// </summary>
/// <remarks>The new stream's position is set to the beginning of the stream when returned.</remarks>
/// <param name="tag">A tag which can be used to track the source of the stream.</param>
/// <param name="buffer">The byte buffer to copy data from.</param>
/// <param name="offset">The offset from the start of the buffer to copy from.</param>
/// <param name="count">The number of bytes to copy from the buffer.</param>
/// <returns>A MemoryStream.</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public MemoryStream GetStream(string tag, byte[] buffer, int offset, int count)
{
var stream = new RecyclableMemoryStream(this, tag, count);
stream.Write(buffer, offset, count);
stream.Position = 0;
return stream;
}
/// <summary>
/// Triggered when a new block is created.
/// </summary>
public event EventHandler BlockCreated;
/// <summary>
/// Triggered when a new block is created.
/// </summary>
public event EventHandler BlockDiscarded;
/// <summary>
/// Triggered when a new large buffer is created.
/// </summary>
public event EventHandler LargeBufferCreated;
/// <summary>
/// Triggered when a new stream is created.
/// </summary>
public event EventHandler StreamCreated;
/// <summary>
/// Triggered when a stream is disposed.
/// </summary>
public event EventHandler StreamDisposed;
/// <summary>
/// Triggered when a stream is finalized.
/// </summary>
public event EventHandler StreamFinalized;
/// <summary>
/// Triggered when a stream is finalized.
/// </summary>
public event StreamLengthReportHandler StreamLength;
/// <summary>
/// Triggered when a user converts a stream to array.
/// </summary>
public event EventHandler StreamConvertedToArray;
/// <summary>
/// Triggered when a large buffer is discarded, along with the reason for the discard.
/// </summary>
public event LargeBufferDiscardedEventHandler LargeBufferDiscarded;
/// <summary>
/// Periodically triggered to report usage statistics.
/// </summary>
public event UsageReportEventHandler UsageReport;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using Xunit;
namespace DispatchProxyTests
{
public static class DispatchProxyTests
{
[Fact]
public static void Create_Proxy_Derives_From_DispatchProxy_BaseType()
{
TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>();
Assert.NotNull(proxy);
Assert.IsAssignableFrom<TestDispatchProxy>(proxy);
}
[Fact]
public static void Create_Proxy_Implements_All_Interfaces()
{
TestType_IHelloAndGoodbyeService proxy = DispatchProxy.Create<TestType_IHelloAndGoodbyeService, TestDispatchProxy>();
Assert.NotNull(proxy);
Type[] implementedInterfaces = typeof(TestType_IHelloAndGoodbyeService).GetTypeInfo().ImplementedInterfaces.ToArray();
foreach (Type t in implementedInterfaces)
{
Assert.IsAssignableFrom(t, proxy);
}
}
[Fact]
public static void Create_Proxy_Internal_Interface()
{
TestType_InternalInterfaceService proxy = DispatchProxy.Create<TestType_InternalInterfaceService, TestDispatchProxy>();
Assert.NotNull(proxy);
}
[Fact]
public static void Create_Proxy_Implements_Internal_Interfaces()
{
TestType_InternalInterfaceService proxy = DispatchProxy.Create<TestType_PublicInterfaceService_Implements_Internal, TestDispatchProxy>();
Assert.NotNull(proxy);
}
[Fact]
public static void Create_Same_Proxy_Type_And_Base_Type_Reuses_Same_Generated_Type()
{
TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>();
TestType_IHelloService proxy2 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>();
Assert.NotNull(proxy1);
Assert.NotNull(proxy2);
Assert.IsType(proxy1.GetType(), proxy2);
}
[Fact]
public static void Create_Proxy_Instances_Of_Same_Proxy_And_Base_Type_Are_Unique()
{
TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>();
TestType_IHelloService proxy2 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>();
Assert.NotNull(proxy1);
Assert.NotNull(proxy2);
Assert.False(object.ReferenceEquals(proxy1, proxy2),
String.Format("First and second instance of proxy type {0} were the same instance", proxy1.GetType().ToString()));
}
[Fact]
public static void Create_Same_Proxy_Type_With_Different_BaseType_Uses_Different_Generated_Type()
{
TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>();
TestType_IHelloService proxy2 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy2>();
Assert.NotNull(proxy1);
Assert.NotNull(proxy2);
Assert.False(proxy1.GetType() == proxy2.GetType(),
String.Format("Proxy generated for base type {0} used same for base type {1}", typeof(TestDispatchProxy).Name, typeof(TestDispatchProxy).Name));
}
[Fact]
public static void Created_Proxy_With_Different_Proxy_Type_Use_Different_Generated_Type()
{
TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>();
TestType_IGoodbyeService proxy2 = DispatchProxy.Create<TestType_IGoodbyeService, TestDispatchProxy>();
Assert.NotNull(proxy1);
Assert.NotNull(proxy2);
Assert.False(proxy1.GetType() == proxy2.GetType(),
String.Format("Proxy generated for type {0} used same for type {1}", typeof(TestType_IHelloService).Name, typeof(TestType_IGoodbyeService).Name));
}
[Fact]
[ActiveIssue("https://github.com/dotnet/corert/issues/3637 - wrong exception thrown from DispatchProxy.Create()", TargetFrameworkMonikers.UapAot)]
public static void Create_Using_Concrete_Proxy_Type_Throws_ArgumentException()
{
AssertExtensions.Throws<ArgumentException>("T", () => DispatchProxy.Create<TestType_ConcreteClass, TestDispatchProxy>());
}
[Fact]
[ActiveIssue("https://github.com/dotnet/corert/issues/3637 - wrong exception thrown from DispatchProxy.Create()", TargetFrameworkMonikers.UapAot)]
public static void Create_Using_Sealed_BaseType_Throws_ArgumentException()
{
AssertExtensions.Throws<ArgumentException>("TProxy", () => DispatchProxy.Create<TestType_IHelloService, Sealed_TestDispatchProxy>());
}
[Fact]
[ActiveIssue("https://github.com/dotnet/corert/issues/3637 - wrong exception thrown from DispatchProxy.Create()", TargetFrameworkMonikers.UapAot)]
public static void Create_Using_Abstract_BaseType_Throws_ArgumentException()
{
AssertExtensions.Throws<ArgumentException>("TProxy", () => DispatchProxy.Create<TestType_IHelloService, Abstract_TestDispatchProxy>());
}
[Fact]
[ActiveIssue("https://github.com/dotnet/corert/issues/3637 - wrong exception thrown from DispatchProxy.Create()", TargetFrameworkMonikers.UapAot)]
public static void Create_Using_BaseType_Without_Default_Ctor_Throws_ArgumentException()
{
AssertExtensions.Throws<ArgumentException>("TProxy", () => DispatchProxy.Create<TestType_IHelloService, NoDefaultCtor_TestDispatchProxy>());
}
[Fact]
public static void Invoke_Receives_Correct_MethodInfo_And_Arguments()
{
bool wasInvoked = false;
StringBuilder errorBuilder = new StringBuilder();
// This Func is called whenever we call a method on the proxy.
// This is where we validate it received the correct arguments and methods
Func<MethodInfo, object[], object> invokeCallback = (method, args) =>
{
wasInvoked = true;
if (method == null)
{
string error = String.Format("Proxy for {0} was called with null method", typeof(TestType_IHelloService).Name);
errorBuilder.AppendLine(error);
return null;
}
else
{
MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello");
if (expectedMethod != method)
{
string error = String.Format("Proxy for {0} was called with incorrect method. Expected = {1}, Actual = {2}",
typeof(TestType_IHelloService).Name, expectedMethod, method);
errorBuilder.AppendLine(error);
return null;
}
}
return "success";
};
TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>();
Assert.NotNull(proxy);
TestDispatchProxy dispatchProxy = proxy as TestDispatchProxy;
Assert.NotNull(dispatchProxy);
// Redirect Invoke to our own Func above
dispatchProxy.CallOnInvoke = invokeCallback;
// Calling this method now will invoke the Func above which validates correct method
proxy.Hello("testInput");
Assert.True(wasInvoked, "The invoke method was not called");
Assert.True(errorBuilder.Length == 0, errorBuilder.ToString());
}
[Fact]
public static void Invoke_Receives_Correct_MethodInfo()
{
MethodInfo invokedMethod = null;
TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>();
((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
{
invokedMethod = method;
return String.Empty;
};
proxy.Hello("testInput");
MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello");
Assert.True(invokedMethod != null && expectedMethod == invokedMethod, String.Format("Invoke expected method {0} but actual was {1}", expectedMethod, invokedMethod));
}
[Fact]
public static void Invoke_Receives_Correct_Arguments()
{
object[] actualArgs = null;
TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>();
((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
{
actualArgs = args;
return String.Empty;
};
proxy.Hello("testInput");
object[] expectedArgs = new object[] { "testInput" };
Assert.True(actualArgs != null && actualArgs.Length == expectedArgs.Length,
String.Format("Invoked expected object[] of length {0} but actual was {1}",
expectedArgs.Length, (actualArgs == null ? "null" : actualArgs.Length.ToString())));
for (int i = 0; i < expectedArgs.Length; ++i)
{
Assert.True(expectedArgs[i].Equals(actualArgs[i]),
String.Format("Expected arg[{0}] = '{1}' but actual was '{2}'",
i, expectedArgs[i], actualArgs[i]));
}
}
[Fact]
public static void Invoke_Returns_Correct_Value()
{
TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>();
((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
{
return "testReturn";
};
string expectedResult = "testReturn";
string actualResult = proxy.Hello(expectedResult);
Assert.Equal(expectedResult, actualResult);
}
[Fact]
public static void Invoke_Multiple_Parameters_Receives_Correct_Arguments()
{
object[] invokedArgs = null;
object[] expectedArgs = new object[] { (int)42, "testString", (double)5.0 };
TestType_IMultipleParameterService proxy = DispatchProxy.Create<TestType_IMultipleParameterService, TestDispatchProxy>();
((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
{
invokedArgs = args;
return 0.0;
};
proxy.TestMethod((int)expectedArgs[0], (string)expectedArgs[1], (double)expectedArgs[2]);
Assert.True(invokedArgs != null && invokedArgs.Length == expectedArgs.Length,
String.Format("Expected {0} arguments but actual was {1}",
expectedArgs.Length, invokedArgs == null ? "null" : invokedArgs.Length.ToString()));
for (int i = 0; i < expectedArgs.Length; ++i)
{
Assert.True(expectedArgs[i].Equals(invokedArgs[i]),
String.Format("Expected arg[{0}] = '{1}' but actual was '{2}'",
i, expectedArgs[i], invokedArgs[i]));
}
}
[Fact]
public static void Invoke_Multiple_Parameters_Via_Params_Receives_Correct_Arguments()
{
object[] actualArgs = null;
object[] invokedArgs = null;
object[] expectedArgs = new object[] { 42, "testString", 5.0 };
TestType_IMultipleParameterService proxy = DispatchProxy.Create<TestType_IMultipleParameterService, TestDispatchProxy>();
((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
{
invokedArgs = args;
return String.Empty;
};
proxy.ParamsMethod((int)expectedArgs[0], (string)expectedArgs[1], (double)expectedArgs[2]);
// All separate params should have become a single object[1] array
Assert.True(invokedArgs != null && invokedArgs.Length == 1,
String.Format("Expected single element object[] but actual was {0}",
invokedArgs == null ? "null" : invokedArgs.Length.ToString()));
// That object[1] should contain an object[3] containing the args
actualArgs = invokedArgs[0] as object[];
Assert.True(actualArgs != null && actualArgs.Length == expectedArgs.Length,
String.Format("Invoked expected object[] of length {0} but actual was {1}",
expectedArgs.Length, (actualArgs == null ? "null" : actualArgs.Length.ToString())));
for (int i = 0; i < expectedArgs.Length; ++i)
{
Assert.True(expectedArgs[i].Equals(actualArgs[i]),
String.Format("Expected arg[{0}] = '{1}' but actual was '{2}'",
i, expectedArgs[i], actualArgs[i]));
}
}
[Fact]
public static void Invoke_Void_Returning_Method_Accepts_Null_Return()
{
MethodInfo invokedMethod = null;
TestType_IOneWay proxy = DispatchProxy.Create<TestType_IOneWay, TestDispatchProxy>();
((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
{
invokedMethod = method;
return null;
};
proxy.OneWay();
MethodInfo expectedMethod = typeof(TestType_IOneWay).GetTypeInfo().GetDeclaredMethod("OneWay");
Assert.True(invokedMethod != null && expectedMethod == invokedMethod, String.Format("Invoke expected method {0} but actual was {1}", expectedMethod, invokedMethod));
}
[Fact]
public static void Invoke_Same_Method_Multiple_Interfaces_Calls_Correct_Method()
{
List<MethodInfo> invokedMethods = new List<MethodInfo>();
TestType_IHelloService1And2 proxy = DispatchProxy.Create<TestType_IHelloService1And2, TestDispatchProxy>();
((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
{
invokedMethods.Add(method);
return null;
};
((TestType_IHelloService)proxy).Hello("calling 1");
((TestType_IHelloService2)proxy).Hello("calling 2");
Assert.True(invokedMethods.Count == 2, String.Format("Expected 2 method invocations but received {0}", invokedMethods.Count));
MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello");
Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been TestType_IHelloService.Hello but actual was {0}", invokedMethods[0]));
expectedMethod = typeof(TestType_IHelloService2).GetTypeInfo().GetDeclaredMethod("Hello");
Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been TestType_IHelloService2.Hello but actual was {0}", invokedMethods[1]));
}
[Fact]
public static void Invoke_Thrown_Exception_Rethrown_To_Caller()
{
Exception actualException = null;
InvalidOperationException expectedException = new InvalidOperationException("testException");
TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>();
((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
{
throw expectedException;
};
try
{
proxy.Hello("testCall");
}
catch (Exception e)
{
actualException = e;
}
Assert.Equal(expectedException, actualException);
}
[Fact]
public static void Invoke_Property_Setter_And_Getter_Invokes_Correct_Methods()
{
List<MethodInfo> invokedMethods = new List<MethodInfo>();
TestType_IPropertyService proxy = DispatchProxy.Create<TestType_IPropertyService, TestDispatchProxy>();
((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
{
invokedMethods.Add(method);
return null;
};
proxy.ReadWrite = "testValue";
string actualValue = proxy.ReadWrite;
Assert.True(invokedMethods.Count == 2, String.Format("Expected 2 method invocations but received {0}", invokedMethods.Count));
PropertyInfo propertyInfo = typeof(TestType_IPropertyService).GetTypeInfo().GetDeclaredProperty("ReadWrite");
Assert.NotNull(propertyInfo);
MethodInfo expectedMethod = propertyInfo.SetMethod;
Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been {0} but actual was {1}",
expectedMethod.Name, invokedMethods[0]));
expectedMethod = propertyInfo.GetMethod;
Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been {0} but actual was {1}",
expectedMethod.Name, invokedMethods[1]));
Assert.Null(actualValue);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Reflection on generated dispatch proxy types not allowed.")]
public static void Proxy_Declares_Interface_Properties()
{
TestType_IPropertyService proxy = DispatchProxy.Create<TestType_IPropertyService, TestDispatchProxy>();
PropertyInfo propertyInfo = proxy.GetType().GetTypeInfo().GetDeclaredProperty("ReadWrite");
Assert.NotNull(propertyInfo);
}
#if netcoreapp
[Fact]
public static void Invoke_Event_Add_And_Remove_And_Raise_Invokes_Correct_Methods()
{
// C# cannot emit raise_Xxx method for the event, so we must use System.Reflection.Emit to generate such event.
AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("EventBuilder"), AssemblyBuilderAccess.Run);
ModuleBuilder modb = ab.DefineDynamicModule("mod");
TypeBuilder tb = modb.DefineType("TestType_IEventService", TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract);
EventBuilder eb = tb.DefineEvent("AddRemoveRaise", EventAttributes.None, typeof(EventHandler));
eb.SetAddOnMethod(tb.DefineMethod("add_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventHandler) }));
eb.SetRemoveOnMethod( tb.DefineMethod("remove_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventHandler) }));
eb.SetRaiseMethod(tb.DefineMethod("raise_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventArgs) }));
TypeInfo ieventServiceTypeInfo = tb.CreateTypeInfo();
List<MethodInfo> invokedMethods = new List<MethodInfo>();
object proxy =
typeof(DispatchProxy)
.GetRuntimeMethod("Create", Array.Empty<Type>()).MakeGenericMethod(ieventServiceTypeInfo.AsType(), typeof(TestDispatchProxy))
.Invoke(null, null);
((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
{
invokedMethods.Add(method);
return null;
};
EventHandler handler = new EventHandler((sender, e) => {});
proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "add_AddRemoveRaise").Invoke(proxy, new object[] { handler });
proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "raise_AddRemoveRaise").Invoke(proxy, new object[] { EventArgs.Empty });
proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "remove_AddRemoveRaise").Invoke(proxy, new object[] { handler });
Assert.True(invokedMethods.Count == 3, String.Format("Expected 3 method invocations but received {0}", invokedMethods.Count));
EventInfo eventInfo = ieventServiceTypeInfo.GetDeclaredEvent("AddRemoveRaise");
Assert.NotNull(eventInfo);
MethodInfo expectedMethod = eventInfo.AddMethod;
Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been {0} but actual was {1}",
expectedMethod.Name, invokedMethods[0]));
expectedMethod = eventInfo.RaiseMethod;
Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been {0} but actual was {1}",
expectedMethod.Name, invokedMethods[1]));
expectedMethod = eventInfo.RemoveMethod;
Assert.True(invokedMethods[2] != null && expectedMethod == invokedMethods[2], String.Format("Third invoke should have been {0} but actual was {1}",
expectedMethod.Name, invokedMethods[1]));
}
#endif // netcoreapp
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Reflection on generated dispatch proxy types not allowed.")]
public static void Proxy_Declares_Interface_Events()
{
TestType_IEventService proxy = DispatchProxy.Create<TestType_IEventService, TestDispatchProxy>();
EventInfo eventInfo = proxy.GetType().GetTypeInfo().GetDeclaredEvent("AddRemove");
Assert.NotNull(eventInfo);
}
[Fact]
public static void Invoke_Indexer_Setter_And_Getter_Invokes_Correct_Methods()
{
List<MethodInfo> invokedMethods = new List<MethodInfo>();
TestType_IIndexerService proxy = DispatchProxy.Create<TestType_IIndexerService, TestDispatchProxy>();
((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
{
invokedMethods.Add(method);
return null;
};
proxy["key"] = "testValue";
string actualValue = proxy["key"];
Assert.True(invokedMethods.Count == 2, String.Format("Expected 2 method invocations but received {0}", invokedMethods.Count));
PropertyInfo propertyInfo = typeof(TestType_IIndexerService).GetTypeInfo().GetDeclaredProperty("Item");
Assert.NotNull(propertyInfo);
MethodInfo expectedMethod = propertyInfo.SetMethod;
Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been {0} but actual was {1}",
expectedMethod.Name, invokedMethods[0]));
expectedMethod = propertyInfo.GetMethod;
Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been {0} but actual was {1}",
expectedMethod.Name, invokedMethods[1]));
Assert.Null(actualValue);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Reflection on generated dispatch proxy types not allowed.")]
public static void Proxy_Declares_Interface_Indexers()
{
TestType_IIndexerService proxy = DispatchProxy.Create<TestType_IIndexerService, TestDispatchProxy>();
PropertyInfo propertyInfo = proxy.GetType().GetTypeInfo().GetDeclaredProperty("Item");
Assert.NotNull(propertyInfo);
}
static void testGenericMethodRoundTrip<T>(T testValue)
{
var proxy = DispatchProxy.Create<TypeType_GenericMethod, TestDispatchProxy>();
((TestDispatchProxy)proxy).CallOnInvoke = (mi, a) =>
{
Assert.True(mi.IsGenericMethod);
Assert.False(mi.IsGenericMethodDefinition);
Assert.Equal(1, mi.GetParameters().Length);
Assert.Equal(typeof(T), mi.GetParameters()[0].ParameterType);
Assert.Equal(typeof(T), mi.ReturnType);
return a[0];
};
Assert.Equal(proxy.Echo(testValue), testValue);
}
[Fact]
public static void Invoke_Generic_Method()
{
//string
testGenericMethodRoundTrip("asdf");
//reference type
testGenericMethodRoundTrip(new Version(1, 0, 0, 0));
//value type
testGenericMethodRoundTrip(42);
//enum type
testGenericMethodRoundTrip(DayOfWeek.Monday);
}
}
}
| |
//#define ASTARDEBUG //"BBTree Debug" If enables, some queries to the tree will show debug lines. Turn off multithreading when using this since DrawLine calls cannot be called from a different thread
using System;
using UnityEngine;
namespace Pathfinding {
using Pathfinding.Util;
/** Axis Aligned Bounding Box Tree.
* Holds a bounding box tree of triangles.
*
* \astarpro
*/
public class BBTree : IAstarPooledObject {
/** Holds all tree nodes */
BBTreeBox[] tree = null;
TriangleMeshNode[] nodeLookup = null;
int count;
int leafNodes;
const int MaximumLeafSize = 4;
public Rect Size {
get {
if (count == 0) {
return new Rect(0, 0, 0, 0);
} else {
var rect = tree[0].rect;
return Rect.MinMaxRect(rect.xmin*Int3.PrecisionFactor, rect.ymin*Int3.PrecisionFactor, rect.xmax*Int3.PrecisionFactor, rect.ymax*Int3.PrecisionFactor);
}
}
}
/** Clear the tree.
* Note that references to old nodes will still be intact so the GC cannot immediately collect them.
*/
public void Clear () {
count = 0;
leafNodes = 0;
if (tree != null) ArrayPool<BBTreeBox>.Release(ref tree);
if (nodeLookup != null) {
// Prevent memory leaks as the pool does not clear the array
for (int i = 0; i < nodeLookup.Length; i++) nodeLookup[i] = null;
ArrayPool<TriangleMeshNode>.Release(ref nodeLookup);
}
tree = ArrayPool<BBTreeBox>.Claim(0);
nodeLookup = ArrayPool<TriangleMeshNode>.Claim(0);
}
void IAstarPooledObject.OnEnterPool () {
Clear();
}
void EnsureCapacity (int c) {
if (c > tree.Length) {
var newArr = ArrayPool<BBTreeBox>.Claim(c);
tree.CopyTo(newArr, 0);
ArrayPool<BBTreeBox>.Release(ref tree);
tree = newArr;
}
}
void EnsureNodeCapacity (int c) {
if (c > nodeLookup.Length) {
var newArr = ArrayPool<TriangleMeshNode>.Claim(c);
nodeLookup.CopyTo(newArr, 0);
ArrayPool<TriangleMeshNode>.Release(ref nodeLookup);
nodeLookup = newArr;
}
}
int GetBox (IntRect rect) {
if (count >= tree.Length) EnsureCapacity(count+1);
tree[count] = new BBTreeBox(rect);
count++;
return count-1;
}
/** Rebuilds the tree using the specified nodes */
public void RebuildFrom (TriangleMeshNode[] nodes) {
Clear();
if (nodes.Length == 0) return;
// We will use approximately 2N tree nodes
EnsureCapacity(Mathf.CeilToInt(nodes.Length * 2.1f));
// We will use approximately N node references
EnsureNodeCapacity(Mathf.CeilToInt(nodes.Length * 1.1f));
// This will store the order of the nodes while the tree is being built
// It turns out that it is a lot faster to do this than to actually modify
// the nodes and nodeBounds arrays (presumably since that involves shuffling
// around 20 bytes of memory (sizeof(pointer) + sizeof(IntRect)) per node
// instead of 4 bytes (sizeof(int)).
// It also means we don't have to make a copy of the nodes array since
// we do not modify it
var permutation = ArrayPool<int>.Claim(nodes.Length);
for (int i = 0; i < nodes.Length; i++) {
permutation[i] = i;
}
// Precalculate the bounds of the nodes in XZ space.
// It turns out that calculating the bounds is a bottleneck and precalculating
// the bounds makes it around 3 times faster to build a tree
var nodeBounds = ArrayPool<IntRect>.Claim(nodes.Length);
for (int i = 0; i < nodes.Length; i++) {
Int3 v0, v1, v2;
nodes[i].GetVertices(out v0, out v1, out v2);
var rect = new IntRect(v0.x, v0.z, v0.x, v0.z);
rect = rect.ExpandToContain(v1.x, v1.z);
rect = rect.ExpandToContain(v2.x, v2.z);
nodeBounds[i] = rect;
}
RebuildFromInternal(nodes, permutation, nodeBounds, 0, nodes.Length, false);
ArrayPool<int>.Release(ref permutation);
ArrayPool<IntRect>.Release(ref nodeBounds);
}
static int SplitByX (TriangleMeshNode[] nodes, int[] permutation, int from, int to, int divider) {
int mx = to;
for (int i = from; i < mx; i++) {
if (nodes[permutation[i]].position.x > divider) {
mx--;
// Swap items i and mx
var tmp = permutation[mx];
permutation[mx] = permutation[i];
permutation[i] = tmp;
i--;
}
}
return mx;
}
static int SplitByZ (TriangleMeshNode[] nodes, int[] permutation, int from, int to, int divider) {
int mx = to;
for (int i = from; i < mx; i++) {
if (nodes[permutation[i]].position.z > divider) {
mx--;
// Swap items i and mx
var tmp = permutation[mx];
permutation[mx] = permutation[i];
permutation[i] = tmp;
i--;
}
}
return mx;
}
int RebuildFromInternal (TriangleMeshNode[] nodes, int[] permutation, IntRect[] nodeBounds, int from, int to, bool odd) {
var rect = NodeBounds(permutation, nodeBounds, from, to);
int box = GetBox(rect);
if (to - from <= MaximumLeafSize) {
var nodeOffset = tree[box].nodeOffset = leafNodes*MaximumLeafSize;
EnsureNodeCapacity(nodeOffset + MaximumLeafSize);
leafNodes++;
// Assign all nodes to the array. Note that we also need clear unused slots as the array from the pool may contain any information
for (int i = 0; i < MaximumLeafSize; i++) {
nodeLookup[nodeOffset + i] = i < to - from ? nodes[permutation[from + i]] : null;
}
return box;
}
int splitIndex;
if (odd) {
// X
int divider = (rect.xmin + rect.xmax)/2;
splitIndex = SplitByX(nodes, permutation, from, to, divider);
} else {
// Y/Z
int divider = (rect.ymin + rect.ymax)/2;
splitIndex = SplitByZ(nodes, permutation, from, to, divider);
}
if (splitIndex == from || splitIndex == to) {
// All nodes were on one side of the divider
// Try to split along the other axis
if (!odd) {
// X
int divider = (rect.xmin + rect.xmax)/2;
splitIndex = SplitByX(nodes, permutation, from, to, divider);
} else {
// Y/Z
int divider = (rect.ymin + rect.ymax)/2;
splitIndex = SplitByZ(nodes, permutation, from, to, divider);
}
if (splitIndex == from || splitIndex == to) {
// All nodes were on one side of the divider
// Just pick one half
splitIndex = (from+to)/2;
}
}
tree[box].left = RebuildFromInternal(nodes, permutation, nodeBounds, from, splitIndex, !odd);
tree[box].right = RebuildFromInternal(nodes, permutation, nodeBounds, splitIndex, to, !odd);
return box;
}
/** Calculates the bounding box in XZ space of all nodes between \a from (inclusive) and \a to (exclusive) */
static IntRect NodeBounds (int[] permutation, IntRect[] nodeBounds, int from, int to) {
var rect = nodeBounds[permutation[from]];
for (int j = from + 1; j < to; j++) {
var otherRect = nodeBounds[permutation[j]];
// Equivalent to rect = IntRect.Union(rect, otherRect)
// but manually inlining is approximately
// 25% faster when building an entire tree.
// This code is hot when using navmesh cutting.
rect.xmin = Math.Min(rect.xmin, otherRect.xmin);
rect.ymin = Math.Min(rect.ymin, otherRect.ymin);
rect.xmax = Math.Max(rect.xmax, otherRect.xmax);
rect.ymax = Math.Max(rect.ymax, otherRect.ymax);
}
return rect;
}
[System.Diagnostics.Conditional("ASTARDEBUG")]
static void DrawDebugRect (IntRect rect) {
Debug.DrawLine(new Vector3(rect.xmin, 0, rect.ymin), new Vector3(rect.xmax, 0, rect.ymin), Color.white);
Debug.DrawLine(new Vector3(rect.xmin, 0, rect.ymax), new Vector3(rect.xmax, 0, rect.ymax), Color.white);
Debug.DrawLine(new Vector3(rect.xmin, 0, rect.ymin), new Vector3(rect.xmin, 0, rect.ymax), Color.white);
Debug.DrawLine(new Vector3(rect.xmax, 0, rect.ymin), new Vector3(rect.xmax, 0, rect.ymax), Color.white);
}
[System.Diagnostics.Conditional("ASTARDEBUG")]
static void DrawDebugNode (TriangleMeshNode node, float yoffset, Color color) {
Debug.DrawLine((Vector3)node.GetVertex(1) + Vector3.up*yoffset, (Vector3)node.GetVertex(2) + Vector3.up*yoffset, color);
Debug.DrawLine((Vector3)node.GetVertex(0) + Vector3.up*yoffset, (Vector3)node.GetVertex(1) + Vector3.up*yoffset, color);
Debug.DrawLine((Vector3)node.GetVertex(2) + Vector3.up*yoffset, (Vector3)node.GetVertex(0) + Vector3.up*yoffset, color);
}
/** Queries the tree for the closest node to \a p constrained by the NNConstraint.
* Note that this function will only fill in the constrained node.
* If you want a node not constrained by any NNConstraint, do an additional search with constraint = NNConstraint.None
*/
public NNInfoInternal QueryClosest (Vector3 p, NNConstraint constraint, out float distance) {
distance = float.PositiveInfinity;
return QueryClosest(p, constraint, ref distance, new NNInfoInternal(null));
}
/** Queries the tree for the closest node to \a p constrained by the NNConstraint trying to improve an existing solution.
* Note that this function will only fill in the constrained node.
* If you want a node not constrained by any NNConstraint, do an additional search with constraint = NNConstraint.None
*
* This method will completely ignore any Y-axis differences in positions.
*
* \param p Point to search around
* \param constraint Optionally set to constrain which nodes to return
* \param distance The best distance for the \a previous solution. Will be updated with the best distance
* after this search. Will be positive infinity if no node could be found.
* Set to positive infinity if there was no previous solution.
* \param previous This search will start from the \a previous NNInfo and improve it if possible.
* Even if the search fails on this call, the solution will never be worse than \a previous.
*/
public NNInfoInternal QueryClosestXZ (Vector3 p, NNConstraint constraint, ref float distance, NNInfoInternal previous) {
var sqrDistance = distance*distance;
var origSqrDistance = sqrDistance;
if (count > 0 && SquaredRectPointDistance(tree[0].rect, p) < sqrDistance) {
SearchBoxClosestXZ(0, p, ref sqrDistance, constraint, ref previous);
// Only update the distance if the squared distance changed as otherwise #distance
// might change due to rounding errors even if no better solution was found
if (sqrDistance < origSqrDistance) distance = Mathf.Sqrt(sqrDistance);
}
return previous;
}
void SearchBoxClosestXZ (int boxi, Vector3 p, ref float closestSqrDist, NNConstraint constraint, ref NNInfoInternal nnInfo) {
BBTreeBox box = tree[boxi];
if (box.IsLeaf) {
var nodes = nodeLookup;
for (int i = 0; i < MaximumLeafSize && nodes[box.nodeOffset+i] != null; i++) {
var node = nodes[box.nodeOffset+i];
// Update the NNInfo
DrawDebugNode(node, 0.2f, Color.red);
Vector3 closest = node.ClosestPointOnNodeXZ(p);
if (constraint == null || constraint.Suitable(node)) {
// XZ squared distance
float dist = (closest.x-p.x)*(closest.x-p.x)+(closest.z-p.z)*(closest.z-p.z);
if (nnInfo.constrainedNode == null || dist < closestSqrDist) {
nnInfo.constrainedNode = node;
nnInfo.constClampedPosition = closest;
closestSqrDist = dist;
}
}
}
} else {
DrawDebugRect(box.rect);
int first = box.left, second = box.right;
float firstDist, secondDist;
GetOrderedChildren(ref first, ref second, out firstDist, out secondDist, p);
// Search children (closest box first to improve performance)
if (firstDist < closestSqrDist) {
SearchBoxClosestXZ(first, p, ref closestSqrDist, constraint, ref nnInfo);
}
if (secondDist < closestSqrDist) {
SearchBoxClosestXZ(second, p, ref closestSqrDist, constraint, ref nnInfo);
}
}
}
/** Queries the tree for the closest node to \a p constrained by the NNConstraint trying to improve an existing solution.
* Note that this function will only fill in the constrained node.
* If you want a node not constrained by any NNConstraint, do an additional search with constraint = NNConstraint.None
*
* \param p Point to search around
* \param constraint Optionally set to constrain which nodes to return
* \param distance The best distance for the \a previous solution. Will be updated with the best distance
* after this search. Will be positive infinity if no node could be found.
* Set to positive infinity if there was no previous solution.
* \param previous This search will start from the \a previous NNInfo and improve it if possible.
* Even if the search fails on this call, the solution will never be worse than \a previous.
*/
public NNInfoInternal QueryClosest (Vector3 p, NNConstraint constraint, ref float distance, NNInfoInternal previous) {
var sqrDistance = distance*distance;
var origSqrDistance = sqrDistance;
if (count > 0 && SquaredRectPointDistance(tree[0].rect, p) < sqrDistance) {
SearchBoxClosest(0, p, ref sqrDistance, constraint, ref previous);
// Only update the distance if the squared distance changed as otherwise #distance
// might change due to rounding errors even if no better solution was found
if (sqrDistance < origSqrDistance) distance = Mathf.Sqrt(sqrDistance);
}
return previous;
}
void SearchBoxClosest (int boxi, Vector3 p, ref float closestSqrDist, NNConstraint constraint, ref NNInfoInternal nnInfo) {
BBTreeBox box = tree[boxi];
if (box.IsLeaf) {
var nodes = nodeLookup;
for (int i = 0; i < MaximumLeafSize && nodes[box.nodeOffset+i] != null; i++) {
var node = nodes[box.nodeOffset+i];
Vector3 closest = node.ClosestPointOnNode(p);
float dist = (closest-p).sqrMagnitude;
if (dist < closestSqrDist) {
DrawDebugNode(node, 0.2f, Color.red);
if (constraint == null || constraint.Suitable(node)) {
// Update the NNInfo
nnInfo.constrainedNode = node;
nnInfo.constClampedPosition = closest;
closestSqrDist = dist;
}
} else {
DrawDebugNode(node, 0.0f, Color.blue);
}
}
} else {
DrawDebugRect(box.rect);
int first = box.left, second = box.right;
float firstDist, secondDist;
GetOrderedChildren(ref first, ref second, out firstDist, out secondDist, p);
// Search children (closest box first to improve performance)
if (firstDist < closestSqrDist) {
SearchBoxClosest(first, p, ref closestSqrDist, constraint, ref nnInfo);
}
if (secondDist < closestSqrDist) {
SearchBoxClosest(second, p, ref closestSqrDist, constraint, ref nnInfo);
}
}
}
/** Orders the box indices first and second by the approximate distance to the point p */
void GetOrderedChildren (ref int first, ref int second, out float firstDist, out float secondDist, Vector3 p) {
firstDist = SquaredRectPointDistance(tree[first].rect, p);
secondDist = SquaredRectPointDistance(tree[second].rect, p);
if (secondDist < firstDist) {
// Swap
var tmp = first;
first = second;
second = tmp;
var tmp2 = firstDist;
firstDist = secondDist;
secondDist = tmp2;
}
}
/** Searches for a node which contains the specified point.
* If there are multiple nodes that contain the point any one of them
* may be returned.
*
* \see TriangleMeshNode.ContainsPoint
*/
public TriangleMeshNode QueryInside (Vector3 p, NNConstraint constraint) {
return count != 0 && tree[0].Contains(p) ? SearchBoxInside(0, p, constraint) : null;
}
TriangleMeshNode SearchBoxInside (int boxi, Vector3 p, NNConstraint constraint) {
BBTreeBox box = tree[boxi];
if (box.IsLeaf) {
var nodes = nodeLookup;
for (int i = 0; i < MaximumLeafSize && nodes[box.nodeOffset+i] != null; i++) {
var node = nodes[box.nodeOffset+i];
if (node.ContainsPoint((Int3)p)) {
DrawDebugNode(node, 0.2f, Color.red);
if (constraint == null || constraint.Suitable(node)) {
return node;
}
} else {
DrawDebugNode(node, 0.0f, Color.blue);
}
}
} else {
DrawDebugRect(box.rect);
//Search children
if (tree[box.left].Contains(p)) {
var result = SearchBoxInside(box.left, p, constraint);
if (result != null) return result;
}
if (tree[box.right].Contains(p)) {
var result = SearchBoxInside(box.right, p, constraint);
if (result != null) return result;
}
}
return null;
}
struct BBTreeBox {
public IntRect rect;
public int nodeOffset;
public int left, right;
public bool IsLeaf {
get {
return nodeOffset >= 0;
}
}
public BBTreeBox (IntRect rect) {
nodeOffset = -1;
this.rect = rect;
left = right = -1;
}
public BBTreeBox (int nodeOffset, IntRect rect) {
this.nodeOffset = nodeOffset;
this.rect = rect;
left = right = -1;
}
public bool Contains (Vector3 point) {
var pi = (Int3)point;
return rect.Contains(pi.x, pi.z);
}
}
public void OnDrawGizmos () {
Gizmos.color = new Color(1, 1, 1, 0.5F);
if (count == 0) return;
OnDrawGizmos(0, 0);
}
void OnDrawGizmos (int boxi, int depth) {
BBTreeBox box = tree[boxi];
var min = (Vector3) new Int3(box.rect.xmin, 0, box.rect.ymin);
var max = (Vector3) new Int3(box.rect.xmax, 0, box.rect.ymax);
Vector3 center = (min+max)*0.5F;
Vector3 size = (max-center)*2;
size = new Vector3(size.x, 1, size.z);
center.y += depth * 2;
Gizmos.color = AstarMath.IntToColor(depth, 1f);
Gizmos.DrawCube(center, size);
if (!box.IsLeaf) {
OnDrawGizmos(box.left, depth + 1);
OnDrawGizmos(box.right, depth + 1);
}
}
static bool NodeIntersectsCircle (TriangleMeshNode node, Vector3 p, float radius) {
if (float.IsPositiveInfinity(radius)) return true;
/** \bug Is not correct on the Y axis */
return (p - node.ClosestPointOnNode(p)).sqrMagnitude < radius*radius;
}
/** Returns true if \a p is within \a radius from \a r.
* Correctly handles cases where \a radius is positive infinity.
*/
static bool RectIntersectsCircle (IntRect r, Vector3 p, float radius) {
if (float.IsPositiveInfinity(radius)) return true;
Vector3 po = p;
p.x = Math.Max(p.x, r.xmin*Int3.PrecisionFactor);
p.x = Math.Min(p.x, r.xmax*Int3.PrecisionFactor);
p.z = Math.Max(p.z, r.ymin*Int3.PrecisionFactor);
p.z = Math.Min(p.z, r.ymax*Int3.PrecisionFactor);
// XZ squared magnitude comparison
return (p.x-po.x)*(p.x-po.x) + (p.z-po.z)*(p.z-po.z) < radius*radius;
}
/** Returns distance from \a p to the rectangle \a r */
static float SquaredRectPointDistance (IntRect r, Vector3 p) {
Vector3 po = p;
p.x = Math.Max(p.x, r.xmin*Int3.PrecisionFactor);
p.x = Math.Min(p.x, r.xmax*Int3.PrecisionFactor);
p.z = Math.Max(p.z, r.ymin*Int3.PrecisionFactor);
p.z = Math.Min(p.z, r.ymax*Int3.PrecisionFactor);
// XZ squared magnitude comparison
return (p.x-po.x)*(p.x-po.x) + (p.z-po.z)*(p.z-po.z);
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace WebsitePanel.Providers.HostedSolution
{
[Serializable]
public class ExchangeMailboxPlan
{
int itemId;
int mailboxPlanId;
string mailboxPlan;
public override string ToString()
{
if (mailboxPlan != null)
return mailboxPlan;
return base.ToString();
}
int mailboxSizeMB;
int maxRecipients;
int maxSendMessageSizeKB;
int maxReceiveMessageSizeKB;
bool enablePOP;
bool enableIMAP;
bool enableOWA;
bool enableMAPI;
bool enableActiveSync;
int issueWarningPct;
int prohibitSendPct;
int prohibitSendReceivePct;
int keepDeletedItemsDays;
bool isDefault;
bool hideFromAddressBook;
int mailboxPlanType;
bool allowLitigationHold;
int recoverableItemsWarningPct;
int recoverableItemsSpace;
string litigationHoldUrl;
string litigationHoldMsg;
public int ItemId
{
get { return this.itemId; }
set { this.itemId = value; }
}
[LogProperty("Mailbox Plan ID")]
public int MailboxPlanId
{
get { return this.mailboxPlanId; }
set { this.mailboxPlanId = value; }
}
[LogProperty("Mailbox Plan Name")]
public string MailboxPlan
{
get { return this.mailboxPlan; }
set { this.mailboxPlan = value; }
}
public int MailboxPlanType
{
get { return this.mailboxPlanType; }
set { this.mailboxPlanType = value; }
}
public int MailboxSizeMB
{
get { return this.mailboxSizeMB; }
set { this.mailboxSizeMB = value; }
}
public bool IsDefault
{
get { return this.isDefault; }
set { this.isDefault = value; }
}
public int MaxRecipients
{
get { return this.maxRecipients; }
set { this.maxRecipients = value; }
}
public int MaxSendMessageSizeKB
{
get { return this.maxSendMessageSizeKB; }
set { this.maxSendMessageSizeKB = value; }
}
public int MaxReceiveMessageSizeKB
{
get { return this.maxReceiveMessageSizeKB; }
set { this.maxReceiveMessageSizeKB = value; }
}
public bool EnablePOP
{
get { return this.enablePOP; }
set { this.enablePOP = value; }
}
public bool EnableIMAP
{
get { return this.enableIMAP; }
set { this.enableIMAP = value; }
}
public bool EnableOWA
{
get { return this.enableOWA; }
set { this.enableOWA = value; }
}
public bool EnableMAPI
{
get { return this.enableMAPI; }
set { this.enableMAPI = value; }
}
public bool EnableActiveSync
{
get { return this.enableActiveSync; }
set { this.enableActiveSync = value; }
}
public int IssueWarningPct
{
get { return this.issueWarningPct; }
set { this.issueWarningPct = value; }
}
public int ProhibitSendPct
{
get { return this.prohibitSendPct; }
set { this.prohibitSendPct = value; }
}
public int ProhibitSendReceivePct
{
get { return this.prohibitSendReceivePct; }
set { this.prohibitSendReceivePct = value; }
}
public int KeepDeletedItemsDays
{
get { return this.keepDeletedItemsDays; }
set { this.keepDeletedItemsDays = value; }
}
public bool HideFromAddressBook
{
get { return this.hideFromAddressBook; }
set { this.hideFromAddressBook = value; }
}
public bool AllowLitigationHold
{
get { return this.allowLitigationHold; }
set { this.allowLitigationHold = value; }
}
public int RecoverableItemsWarningPct
{
get { return this.recoverableItemsWarningPct; }
set { this.recoverableItemsWarningPct = value; }
}
public int RecoverableItemsSpace
{
get { return this.recoverableItemsSpace; }
set { this.recoverableItemsSpace = value; }
}
public string LitigationHoldUrl
{
get { return this.litigationHoldUrl; }
set { this.litigationHoldUrl = value; }
}
public string LitigationHoldMsg
{
get { return this.litigationHoldMsg; }
set { this.litigationHoldMsg = value; }
}
bool archiving;
public bool Archiving
{
get { return this.archiving; }
set { this.archiving = value; }
}
bool enableArchiving;
public bool EnableArchiving
{
get { return this.enableArchiving; }
set { this.enableArchiving = value; }
}
int archiveSizeMB;
public int ArchiveSizeMB
{
get { return this.archiveSizeMB; }
set { this.archiveSizeMB = value; }
}
int archiveWarningPct;
public int ArchiveWarningPct
{
get { return this.archiveWarningPct; }
set { this.archiveWarningPct = value; }
}
bool enableForceArchiveDeletion;
public bool EnableForceArchiveDeletion
{
get { return this.enableForceArchiveDeletion; }
set { this.enableForceArchiveDeletion = value; }
}
[LogProperty("Mailbox Plan Unique Name")]
public string WSPUniqueName
{
get
{
Regex r = new Regex(@"[^A-Za-z0-9]");
return "WSPPolicy" + MailboxPlanId.ToString() + "_" + r.Replace(MailboxPlan, "");
}
}
}
}
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using FreneticScript;
using BEPUutilities;
using System.Security.Cryptography;
namespace Voxalia.Shared
{
public class Utilities
{
/// <summary>
/// A UTF-8 without BOM encoding.
/// </summary>
public static Encoding encoding = new UTF8Encoding(false);
/// <summary>
/// A static random object for all non-determistic objects to use.
/// </summary>
public static MTRandom UtilRandom
{
get
{
if (intRandom == null)
{
intRandom = new MTRandom();
}
return intRandom;
}
}
[ThreadStatic]
private static MTRandom intRandom = new MTRandom();
public static SHA512Managed sha512 = new SHA512Managed();
public const string salt1 = "aB123!";
public const string salt2 = "--=123Tt=--";
public const string salt3 = "^&()xyZ";
public static string HashQuick(string username, string password)
{
// TODO: Dynamic hash text maybe?
return Convert.ToBase64String(sha512.ComputeHash(encoding.GetBytes(salt1 + username + salt2 + password + salt3)));
}
public static ushort BytesToUshort(byte[] bytes)
{
return BitConverter.ToUInt16(bytes, 0);
}
public static float BytesToFloat(byte[] bytes)
{
return BitConverter.ToSingle(bytes, 0);
}
public static double BytesToDouble(byte[] bytes)
{
return BitConverter.ToDouble(bytes, 0);
}
public static byte[] UshortToBytes(ushort ush)
{
return BitConverter.GetBytes(ush);
}
public static byte[] FloatToBytes(float flt)
{
return BitConverter.GetBytes(flt);
}
public static byte[] DoubleToBytes(double flt)
{
return BitConverter.GetBytes(flt);
}
public static int BytesToInt(byte[] bytes)
{
return BitConverter.ToInt32(bytes, 0);
}
public static long BytesToLong(byte[] bytes)
{
return BitConverter.ToInt64(bytes, 0);
}
public static byte[] IntToBytes(int intty)
{
return BitConverter.GetBytes(intty);
}
public static byte[] LongToBytes(long intty)
{
return BitConverter.GetBytes(intty);
}
public static void CheckException(Exception ex)
{
if (ex is ThreadAbortException)
{
throw ex;
}
}
// TODO: Reduce need for BytesPartial in packets via adding an index to BytesTo<Type>!
public static byte[] BytesPartial(byte[] full, int start, int length)
{
byte[] data = new byte[length];
Array.Copy(full, start, data, 0, length);
return data;
}
public static double StepTowards(double start, double target, double amount)
{
if (start < target - amount)
{
return start + amount;
}
else if (start > target + amount)
{
return start - amount;
}
else
{
return target;
}
}
public static bool IsCloseTo(double one, double target, double amount)
{
return one > target ? one - amount < target : one + amount > target;
}
/// <summary>
/// Converts a string to a double. Returns 0 if the string is not a valid double.
/// </summary>
/// <param name="input">The string to convert.</param>
/// <returns>The converted double.</returns>
public static float StringToFloat(string input)
{
float output;
if (float.TryParse(input, out output))
{
return output;
}
else
{
return 0f;
}
}
public static Location StringToLocation(string input)
{
return Location.FromString(input);
}
/// <summary>
/// Converts a string to a double. Returns 0 if the string is not a valid double.
/// </summary>
/// <param name="input">The string to convert.</param>
/// <returns>The converted double.</returns>
public static double StringToDouble(string input)
{
double output;
if (double.TryParse(input, out output))
{
return output;
}
else
{
return 0f;
}
}
/// <summary>
/// Converts a string to a ushort. Returns 0 if the string is not a valid ushort.
/// </summary>
/// <param name="input">The string to convert.</param>
/// <returns>The converted ushort.</returns>
public static ushort StringToUShort(string input)
{
ushort output;
if (ushort.TryParse(input, out output))
{
return output;
}
else
{
return 0;
}
}
/// <summary>
/// Converts a string to a int. Returns 0 if the string is not a valid int.
/// </summary>
/// <param name="input">The string to convert.</param>
/// <returns>The converted int.</returns>
public static int StringToInt(string input)
{
int output;
if (int.TryParse(input, out output))
{
return output;
}
else
{
return 0;
}
}
/// <summary>
/// Converts a string to a long. Returns 0 if the string is not a valid long.
/// </summary>
/// <param name="input">The string to convert.</param>
/// <returns>The converted long.</returns>
public static long StringToLong(string input)
{
long output;
if (long.TryParse(input, out output))
{
return output;
}
else
{
return 0;
}
}
/// <summary>
/// Returns a string representation of the specified time.
/// </summary>
/// <returns>The time as a string.</returns>
public static string DateTimeToString(DateTime dt)
{
string utcoffset = "";
DateTime UTC = dt.ToUniversalTime();
if (dt.CompareTo(UTC) < 0)
{
TimeSpan span = UTC.Subtract(dt);
utcoffset = "-" + Pad(((int)Math.Floor(span.TotalHours)).ToString(), '0', 2) + ":" + Pad(span.Minutes.ToString(), '0', 2);
}
else
{
TimeSpan span = dt.Subtract(UTC);
utcoffset = "+" + Pad(((int)Math.Floor(span.TotalHours)).ToString(), '0', 2) + ":" + Pad(span.Minutes.ToString(), '0', 2);
}
return Pad(dt.Year.ToString(), '0', 4) + "/" + Pad(dt.Month.ToString(), '0', 2) + "/" +
Pad(dt.Day.ToString(), '0', 2) + " " + Pad(dt.Hour.ToString(), '0', 2) + ":" +
Pad(dt.Minute.ToString(), '0', 2) + ":" + Pad(dt.Second.ToString(), '0', 2) + " UTC" + utcoffset;
}
/// <summary>
/// Pads a string to a specified length with a specified input, on a specified side.
/// </summary>
/// <param name="input">The original string.</param>
/// <param name="padding">The symbol to pad with.</param>
/// <param name="length">How far to pad it to.</param>
/// <param name="left">Whether to pad left (true), or right (false).</param>
/// <returns>The padded string.</returns>
public static string Pad(string input, char padding, int length, bool left = true)
{
int targetlength = length - input.Length;
StringBuilder pad = new StringBuilder(targetlength <= 0 ? 1 : targetlength);
for (int i = 0; i < targetlength; i++)
{
pad.Append(padding);
}
if (left)
{
return pad + input;
}
else
{
return input + pad;
}
}
/// <summary>
/// Returns a peice of text copied a specified number of times.
/// </summary>
/// <param name="text">What text to copy.</param>
/// <param name="times">How many times to copy it.</param>
/// <returns>.</returns>
public static string CopyText(string text, int times)
{
StringBuilder toret = new StringBuilder(text.Length * times);
for (int i = 0; i < times; i++)
{
toret.Append(text);
}
return toret.ToString();
}
/// <summary>
/// Returns the number of times a character occurs in a string.
/// </summary>
/// <param name="input">The string containing the character.</param>
/// <param name="countme">The character which the string contains.</param>
/// <returns>How many times the character occurs.</returns>
public static int CountCharacter(string input, char countme)
{
int count = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == countme)
{
count++;
}
}
return count;
}
/// <summary>
/// Combines a list of strings into a single string, separated by spaces.
/// </summary>
/// <param name="input">The list of strings to combine.</param>
/// <param name="start">The index to start from.</param>
/// <returns>The combined string.</returns>
public static string Concat(List<string> input, int start = 0)
{
StringBuilder output = new StringBuilder();
for (int i = start; i < input.Count; i++)
{
output.Append(input[i]).Append(" ");
}
return (output.Length > 0 ? output.ToString().Substring(0, output.Length - 1) : "");
}
/// <summary>
/// If raw string data is input by a user, call this function to clean it for tag-safety.
/// </summary>
/// <param name="input">The raw string.</param>
/// <returns>A cleaned string.</returns>
public static string CleanStringInput(string input)
{
// No nulls!
return input.Replace('\0', ' ');
}
/// <summary>
/// Used to identify if an input character is a valid color symbol (generally the character that follows a '^'), for use by RenderColoredText
/// </summary>
/// <param name="c"><paramref name="c"/>The character to check.</param>
/// <returns>whether the character is a valid color symbol.</returns>
public static bool IsColorSymbol(char c)
{
return ((c >= '0' && c <= '9') /* 0123456789 */ ||
(c >= 'a' && c <= 'b') /* ab */ ||
(c >= 'd' && c <= 'f') /* def */ ||
(c >= 'h' && c <= 'l') /* hijkl */ ||
(c >= 'n' && c <= 'u') /* nopqrstu */ ||
(c >= 'R' && c <= 'T') /* RST */ ||
(c >= '#' && c <= '&') /* #$%& */ || // 35 - 38
(c >= '(' && c <= '*') /* ()* */ || // 40 - 42
(c == 'A') ||
(c == 'O') ||
(c == '-') || // 45
(c == '!') || // 33
(c == '@') // 64
);
}
public static double PI180 = Math.PI / 180;
/// <summary>
/// Returns a one-length vector of the Yaw/Pitch angle input.
/// </summary>
/// <param name="yaw">The yaw angle, in radians.</param>
/// <param name="pitch">The pitch angle, in radians.</param>
/// <returns>.</returns>
public static Location ForwardVector(double yaw, double pitch)
{
double cp = Math.Cos(pitch);
return new Location(-(cp * Math.Cos(yaw)), -(cp * Math.Sin(yaw)), (Math.Sin(pitch)));
}
/// <summary>
/// Returns a one-length vector of the Yaw/Pitch angle input in degrees
/// </summary>
/// <param name="yaw">The yaw angle, in radians.</param>
/// <param name="pitch">The pitch angle, in radians.</param>
/// <returns>.</returns>
public static Location ForwardVector_Deg(double yaw, double pitch)
{
double pitchdeg = pitch * PI180;
double yawdeg = yaw * PI180;
double cp = Math.Cos(pitchdeg);
return new Location(-(cp * Math.Cos(yawdeg)), -(cp * Math.Sin(yawdeg)), (Math.Sin(pitchdeg)));
}
/// <summary>
/// Rotates a vector by a certain yaw.
/// </summary>
/// <param name="vec">The original vector.</param>
/// <param name="yaw">The yaw to rotate by.</param>
/// <returns>The rotated vector.</returns>
public static Location RotateVector(Location vec, double yaw)
{
double cos = Math.Cos(yaw);
double sin = Math.Sin(yaw);
return new Location((vec.X * cos) - (vec.Y * sin), (vec.X * sin) + (vec.Y * cos), vec.Z);
}
/// <summary>
/// Rotates a vector by a certain yaw and pitch.
/// </summary>
/// <param name="vec">The original vector.</param>
/// <param name="yaw">The yaw to rotate by.</param>
/// <param name="pitch">The pitch to rotate by.</param>
/// <returns>The rotated vector.</returns>
public static Location RotateVector(Location vec, double yaw, double pitch)
{
double cosyaw = Math.Cos(yaw);
double cospitch = Math.Cos(pitch);
double sinyaw = Math.Sin(yaw);
double sinpitch = Math.Sin(pitch);
double bX = vec.Z * sinpitch + vec.X * cospitch;
double bZ = vec.Z * cospitch - vec.X * sinpitch;
return new Location(bX * cosyaw - vec.Y * sinyaw, bX * sinyaw + vec.Y * cosyaw, bZ);
}
public static Quaternion StringToQuat(string input)
{
string[] data = input.Replace('(', ' ').Replace(')', ' ').Replace(" ", "").SplitFast(',');
if (data.Length != 4)
{
return Quaternion.Identity;
}
return new Quaternion(StringToFloat(data[0]), StringToFloat(data[1]), StringToFloat(data[2]), StringToFloat(data[3]));
}
public static string QuatToString(Quaternion quat)
{
return "(" + quat.X + ", " + quat.Y + ", " + quat.Z + ", " + quat.W + ")";
}
public static byte[] QuaternionToBytes(Quaternion quat)
{
byte[] dat = new byte[4 + 4 + 4 + 4];
Utilities.FloatToBytes((float)quat.X).CopyTo(dat, 0);
Utilities.FloatToBytes((float)quat.Y).CopyTo(dat, 4);
Utilities.FloatToBytes((float)quat.Z).CopyTo(dat, 4 + 4);
Utilities.FloatToBytes((float)quat.W).CopyTo(dat, 4 + 4 + 4);
return dat;
}
public static Quaternion BytesToQuaternion(byte[] dat, int offset)
{
return new Quaternion(BytesToFloat(BytesPartial(dat, offset, 4)), BytesToFloat(BytesPartial(dat, offset + 4, 4)),
BytesToFloat(BytesPartial(dat, offset + 4 + 4, 4)), BytesToFloat(BytesPartial(dat, offset + 4 + 4 + 4, 4)));
}
public static Matrix LookAtLH(Location start, Location end, Location up)
{
Location zAxis = (end - start).Normalize();
Location xAxis = up.CrossProduct(zAxis).Normalize();
Location yAxis = zAxis.CrossProduct(xAxis);
return new Matrix((double)xAxis.X, (double)yAxis.X, (double)zAxis.X, 0, (double)xAxis.Y,
(double)yAxis.Y, (double)zAxis.Y, 0, (double)xAxis.Z, (double)yAxis.Z, (double)zAxis.Z, 0,
(double)-xAxis.Dot(start), (double)-yAxis.Dot(start), (double)-zAxis.Dot(start), 1);
}
public static Location MatrixToAngles(Matrix WorldTransform)
{
Location rot;
rot.X = Math.Atan2(WorldTransform.M32, WorldTransform.M33) * 180 / Math.PI;
rot.Y = -Math.Asin(WorldTransform.M31) * 180 / Math.PI;
rot.Z = Math.Atan2(WorldTransform.M21, WorldTransform.M11) * 180 / Math.PI;
return rot;
}
public static Matrix AnglesToMatrix(Location rot)
{
// TODO: better method?
return Matrix.CreateFromAxisAngle(new BEPUutilities.Vector3(1, 0, 0), (double)(rot.X * Utilities.PI180))
* Matrix.CreateFromAxisAngle(new BEPUutilities.Vector3(0, 1, 0), (double)(rot.Y * Utilities.PI180))
* Matrix.CreateFromAxisAngle(new BEPUutilities.Vector3(0, 0, 1), (double)(rot.Z * Utilities.PI180));
}
/// <summary>
/// Converts a forward vector to yaw/pitch angles.
/// </summary>
/// <param name="input">The forward vector.</param>
/// <returns>The yaw/pitch angle vector.</returns>
public static Location VectorToAngles(Location input)
{
if (input.X == 0 && input.Y == 0)
{
if (input.Z > 0)
{
return new Location(0, 90, 0);
}
else
{
return new Location(0, 270, 0);
}
}
else
{
double yaw;
double pitch;
if (input.X != 0)
{
yaw = (Math.Atan2(input.Y, input.X) * (180.0 / Math.PI)) + 180.0;
}
else if (input.Y > 0)
{
yaw = 90;
}
else
{
yaw = 270;
}
pitch = (Math.Atan2(input.Z, Math.Sqrt(input.X * input.X + input.Y * input.Y)) * (180.0 / Math.PI));
while (pitch < -180)
{
pitch += 360;
}
while (pitch > 180)
{
pitch -= 360;
}
while (yaw < 0)
{
yaw += 360;
}
while (yaw > 360)
{
yaw -= 360;
}
Location loc = new Location();
loc.Yaw = yaw;
loc.Pitch = pitch;
return loc;
}
}
/// <summary>
/// Validates a username as correctly formatted.
/// </summary>
/// <param name="str">The username to validate.</param>
/// <returns>Whether the username is valid.</returns>
public static bool ValidateUsername(string str)
{
if (str == null)
{
return false;
}
// Length = 4-15
if (str.Length < 4 || str.Length > 15)
{
return false;
}
// Starts A-Z
if (!(str[0] >= 'a' && str[0] <= 'z') && !(str[0] >= 'A' && str[0] <= 'Z'))
{
return false;
}
// All symbols are A-Z, 0-9, _
for (int i = 0; i < str.Length; i++)
{
if (!(str[i] >= 'a' && str[i] <= 'z') && !(str[i] >= 'A' && str[i] <= 'Z')
&& !(str[i] >= '0' && str[i] <= '9') && !(str[i] == '_'))
{
return false;
}
}
// Valid if all tests above passed
return true;
}
/// <summary>
/// Calculates a Halton Sequence result.
/// </summary>
/// <param name="basen">Should be prime.</param>
static double HaltonSequence(int index, int basen)
{
if (basen <= 1)
{
return 0;
}
double res = 0;
double f = 1;
int i = index;
while (i > 0)
{
f = f / basen;
res = res + f * (i % basen);
i = (int)Math.Floor((double)i / basen);
}
return res;
}
public static string FormatNumber(long input)
{
string basinp = input.ToString();
string creation = "";
int c = 0;
for (int i = basinp.Length - 1; i >= 0; i--)
{
if ((c % 3) == 0 && c != 0)
{
creation = basinp[i] + "," + creation;
}
else
{
creation = basinp[i] + creation;
}
c++;
}
return creation;
}
public static Vector3 Project(Vector3 a, Vector3 b)
{
return b * (Vector3.Dot(a, b) / b.LengthSquared());
}
}
public class IntHolder
{
public volatile int Value = 0;
}
}
|
Subsets and Splits